sqlite3.c 6.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037186038186039186040186041186042186043186044186045186046186047186048186049186050186051186052186053186054186055186056186057186058186059186060186061186062186063186064186065186066186067186068186069186070186071186072186073186074186075186076186077186078186079186080186081186082186083186084186085186086186087186088186089186090186091186092186093186094186095186096186097186098186099186100186101186102186103186104186105186106186107186108186109186110186111186112186113186114186115186116186117186118186119186120186121186122186123186124186125186126186127186128186129186130186131186132186133186134186135186136186137186138186139186140186141186142186143186144186145186146186147186148186149186150186151186152186153186154186155186156186157186158186159186160186161186162186163186164186165186166186167186168186169186170186171186172186173186174186175186176186177186178186179186180186181186182186183186184186185186186186187186188186189186190186191186192186193186194186195186196186197186198186199186200186201186202186203186204186205186206186207186208186209186210186211186212186213186214186215186216186217186218186219186220186221186222186223186224186225186226186227186228186229186230186231186232186233186234186235186236186237186238186239186240186241186242186243186244186245186246186247186248186249186250186251186252186253186254186255186256186257186258186259186260186261186262186263186264186265186266186267186268186269186270186271186272186273186274186275186276186277186278186279186280186281186282186283186284186285186286186287186288186289186290186291186292186293186294186295186296186297186298186299186300186301186302186303186304186305186306186307186308186309186310186311186312186313186314186315186316186317186318186319186320186321186322186323186324186325186326186327186328186329186330186331186332186333186334186335186336186337186338186339186340186341186342186343186344186345186346186347186348186349186350186351186352186353186354186355186356186357186358186359186360186361186362186363186364186365186366186367186368186369186370186371186372186373186374186375186376186377186378186379186380186381186382186383186384186385186386186387186388186389186390186391186392186393186394186395186396186397186398186399186400186401186402186403186404186405186406186407186408186409186410186411186412186413186414186415186416186417186418186419186420186421186422186423186424186425186426186427186428186429186430186431186432186433186434186435186436186437186438186439186440186441186442186443186444186445186446186447186448186449186450186451186452186453186454186455186456186457186458186459186460186461186462186463186464186465186466186467186468186469186470186471186472186473186474186475186476186477186478186479186480186481186482186483186484186485186486186487186488186489186490186491186492186493186494186495186496186497186498186499186500186501186502186503186504186505186506186507186508186509186510186511186512186513186514186515186516186517186518186519186520186521186522186523186524186525186526186527186528186529186530186531186532186533186534186535186536186537186538186539186540186541186542186543186544186545186546186547186548186549186550186551186552186553186554186555186556186557186558186559186560186561186562186563186564186565186566186567186568186569186570186571186572186573186574186575186576186577186578186579186580186581186582186583186584186585186586186587186588186589186590186591186592186593186594186595186596186597186598186599186600186601186602186603186604186605186606186607186608186609186610186611186612186613186614186615186616186617186618186619186620186621186622186623186624186625186626186627186628186629186630186631186632186633186634186635186636186637186638186639186640186641186642186643186644186645186646186647186648186649186650186651186652186653186654186655186656186657186658186659186660186661186662186663186664186665186666186667186668186669186670186671186672186673186674186675186676186677186678186679186680186681186682186683186684186685186686186687186688186689186690186691186692186693186694186695186696186697186698186699186700186701186702186703186704186705186706186707186708186709186710186711186712186713186714186715186716186717186718186719186720186721186722186723186724186725186726186727186728186729186730186731186732186733186734186735186736186737186738186739186740186741186742186743186744186745186746186747186748186749186750186751186752186753186754186755186756186757186758186759186760186761186762186763186764186765186766186767186768186769186770186771186772186773186774186775186776186777186778186779186780186781186782186783186784186785186786186787186788186789186790186791186792186793186794186795186796186797186798186799186800186801186802186803186804186805186806186807186808186809186810186811186812186813186814186815186816186817186818186819186820186821186822186823186824186825186826186827186828186829186830186831186832186833186834186835186836186837186838186839186840186841186842186843186844186845186846186847186848186849186850186851186852186853186854186855186856186857186858186859186860186861186862186863186864186865186866186867186868186869186870186871186872186873186874186875186876186877186878186879186880186881186882186883186884186885186886186887186888186889186890186891186892186893186894186895186896186897186898186899186900186901186902186903186904186905186906186907186908186909186910186911186912186913186914186915186916186917186918186919186920186921186922186923186924186925186926186927186928186929186930186931186932186933186934186935186936186937186938186939186940186941186942186943186944186945186946186947186948186949186950186951186952186953186954186955186956186957186958186959186960186961186962186963186964186965186966186967186968186969186970186971186972186973186974186975186976186977186978186979186980186981186982186983186984186985186986186987186988186989186990186991186992186993186994186995186996186997186998186999187000187001187002187003187004187005187006187007187008187009187010187011187012187013187014187015187016187017187018187019187020187021187022187023187024187025187026187027187028187029187030187031187032187033187034187035187036187037187038187039187040187041187042187043187044187045187046187047187048187049187050187051187052187053187054187055187056187057187058187059187060187061187062187063187064187065187066187067187068187069187070187071187072187073187074187075187076187077187078187079187080187081187082187083187084187085187086187087187088187089187090187091187092187093187094187095187096187097187098187099187100187101187102187103187104187105187106187107187108187109187110187111187112187113187114187115187116187117187118187119187120187121187122187123187124187125187126187127187128187129187130187131187132187133187134187135187136187137187138187139187140187141187142187143187144187145187146187147187148187149187150187151187152187153187154187155187156187157187158187159187160187161187162187163187164187165187166187167187168187169187170187171187172187173187174187175187176187177187178187179187180187181187182187183187184187185187186187187187188187189187190187191187192187193187194187195187196187197187198187199187200187201187202187203187204187205187206187207187208187209187210187211187212187213187214187215187216187217187218187219187220187221187222187223187224187225187226187227187228187229187230187231187232187233187234187235187236187237187238187239187240187241187242187243187244187245187246187247187248187249187250187251187252187253187254187255187256187257187258187259187260187261187262187263187264187265187266187267187268187269187270187271187272187273187274187275187276187277187278187279187280187281187282187283187284187285187286187287187288187289187290187291187292187293187294187295187296187297187298187299187300187301187302187303187304187305187306187307187308187309187310187311187312187313187314187315187316187317187318187319187320187321187322187323187324187325187326187327187328187329187330187331187332187333187334187335187336187337187338187339187340187341187342187343187344187345187346187347187348187349187350187351187352187353187354187355187356187357187358187359187360187361187362187363187364187365187366187367187368187369187370187371187372187373187374187375187376187377187378187379187380187381187382187383187384187385187386187387187388187389187390187391187392187393187394187395187396187397187398187399187400187401187402187403187404187405187406187407187408187409187410187411187412187413187414187415187416187417187418187419187420187421187422187423187424187425187426187427187428187429187430187431187432187433187434187435187436187437187438187439187440187441187442187443187444187445187446187447187448187449187450187451187452187453187454187455187456187457187458187459187460187461187462187463187464187465187466187467187468187469187470187471187472187473187474187475187476187477187478187479187480187481187482187483187484187485187486187487187488187489187490187491187492187493187494187495187496187497187498187499187500187501187502187503187504187505187506187507187508187509187510187511187512187513187514187515187516187517187518187519187520187521187522187523187524187525187526187527187528187529187530187531187532187533187534187535187536187537187538187539187540187541187542187543187544187545187546187547187548187549187550187551187552187553187554187555187556187557187558187559187560187561187562187563187564187565187566187567187568187569187570187571187572187573187574187575187576187577187578187579187580187581187582187583187584187585187586187587187588187589187590187591187592187593187594187595187596187597187598187599187600187601187602187603187604187605187606187607187608187609187610187611187612187613187614187615187616187617187618187619187620187621187622187623187624187625187626187627187628187629187630187631187632187633187634187635187636187637187638187639187640187641187642187643187644187645187646187647187648187649187650187651187652187653187654187655187656187657187658187659187660187661187662187663187664187665187666187667187668187669187670187671187672187673187674187675187676187677187678187679187680187681187682187683187684187685187686187687187688187689187690187691187692187693187694187695187696187697187698187699187700187701187702187703187704187705187706187707187708187709187710187711187712187713187714187715187716187717187718187719187720187721187722187723187724187725187726187727187728187729187730187731187732187733187734187735187736187737187738187739187740187741187742187743187744187745187746187747187748187749187750187751187752187753187754187755187756187757187758187759187760187761187762187763187764187765187766187767187768187769187770187771187772187773187774187775187776187777187778187779187780187781187782187783187784187785187786187787187788187789187790187791187792187793187794187795187796187797187798187799187800187801187802187803187804187805187806187807187808187809187810187811187812187813187814187815187816187817187818187819187820187821187822187823187824187825187826187827187828187829187830187831187832187833187834187835187836187837187838187839187840187841187842187843187844187845187846187847187848187849187850187851187852187853187854187855187856187857187858187859187860187861187862187863187864187865187866187867187868187869187870187871187872187873187874187875187876187877187878187879187880187881187882187883187884187885187886187887187888187889187890187891187892187893187894187895187896187897187898187899187900187901187902187903187904187905187906187907187908187909187910187911187912187913187914187915187916187917187918187919187920187921187922187923187924187925187926187927187928187929187930187931187932187933187934187935187936187937187938187939187940187941187942187943187944187945187946187947187948187949187950187951187952187953187954187955187956187957187958187959187960187961187962187963187964187965187966187967187968187969187970187971187972187973187974187975187976187977187978187979187980187981187982187983187984187985187986187987187988187989187990187991187992187993187994187995187996187997187998187999188000188001188002188003188004188005188006188007188008188009188010188011188012188013188014188015188016188017188018188019188020188021188022188023188024188025188026188027188028188029188030188031188032188033188034188035188036188037188038188039188040188041188042188043188044188045188046188047188048188049188050188051188052188053188054188055188056188057188058188059188060188061188062188063188064188065188066188067188068188069188070188071188072188073188074188075188076188077188078188079188080188081188082188083188084188085188086188087188088188089188090188091188092188093188094188095188096188097188098188099188100188101188102188103188104188105188106188107188108188109188110188111188112188113188114188115188116188117188118188119188120188121188122188123188124188125188126188127188128188129188130188131188132188133188134188135188136188137188138188139188140188141188142188143188144188145188146188147188148188149188150188151188152188153188154188155188156188157188158188159188160188161188162188163188164188165188166188167188168188169188170188171188172188173188174188175188176188177188178188179188180188181188182188183188184188185188186188187188188188189188190188191188192188193188194188195188196188197188198188199188200188201188202188203188204188205188206188207188208188209188210188211188212188213188214188215188216188217188218188219188220188221188222188223188224188225188226188227188228188229188230188231188232188233188234188235188236188237188238188239188240188241188242188243188244188245188246188247188248188249188250188251188252188253188254188255188256188257188258188259188260188261188262188263188264188265188266188267188268188269188270188271188272188273188274188275188276188277188278188279188280188281188282188283188284188285188286188287188288188289188290188291188292188293188294188295188296188297188298188299188300188301188302188303188304188305188306188307188308188309188310188311188312188313188314188315188316188317188318188319188320188321188322188323188324188325188326188327188328188329188330188331188332188333188334188335188336188337188338188339188340188341188342188343188344188345188346188347188348188349188350188351188352188353188354188355188356188357188358188359188360188361188362188363188364188365188366188367188368188369188370188371188372188373188374188375188376188377188378188379188380188381188382188383188384188385188386188387188388188389188390188391188392188393188394188395188396188397188398188399188400188401188402188403188404188405188406188407188408188409188410188411188412188413188414188415188416188417188418188419188420188421188422188423188424188425188426188427188428188429188430188431188432188433188434188435188436188437188438188439188440188441188442188443188444188445188446188447188448188449188450188451188452188453188454188455188456188457188458188459188460188461188462188463188464188465188466188467188468188469188470188471188472188473188474188475188476188477188478188479188480188481188482188483188484188485188486188487188488188489188490188491188492188493188494188495188496188497188498188499188500188501188502188503188504188505188506188507188508188509188510188511188512188513188514188515188516188517188518188519188520188521188522188523188524188525188526188527188528188529188530188531188532188533188534188535188536188537188538188539188540188541188542188543188544188545188546188547188548188549188550188551188552188553188554188555188556188557188558188559188560188561188562188563188564188565188566188567188568188569188570188571188572188573188574188575188576188577188578188579188580188581188582188583188584188585188586188587188588188589188590188591188592188593188594188595188596188597188598188599188600188601188602188603188604188605188606188607188608188609188610188611188612188613188614188615188616188617188618188619188620188621188622188623188624188625188626188627188628188629188630188631188632188633188634188635188636188637188638188639188640188641188642188643188644188645188646188647188648188649188650188651188652188653188654188655188656188657188658188659188660188661188662188663188664188665188666188667188668188669188670188671188672188673188674188675188676188677188678188679188680188681188682188683188684188685188686188687188688188689188690188691188692188693188694188695188696188697188698188699188700188701188702188703188704188705188706188707188708188709188710188711188712188713188714188715188716188717188718188719188720188721188722188723188724188725188726188727188728188729188730188731188732188733188734188735188736188737188738188739188740188741188742188743188744188745188746188747188748188749188750188751188752188753188754188755188756188757188758188759188760188761188762188763188764188765188766188767188768188769188770188771188772188773188774188775188776188777188778188779188780188781188782188783188784188785188786188787188788188789188790188791188792188793188794188795188796188797188798188799188800188801188802188803188804188805188806188807188808188809188810188811188812188813188814188815188816188817188818188819188820188821188822188823188824188825188826188827188828188829188830188831188832188833188834188835188836188837188838188839188840188841188842188843188844188845188846188847188848188849188850188851188852188853188854188855188856188857188858188859188860188861188862188863188864188865188866188867188868188869188870188871188872188873188874188875188876188877188878188879188880188881188882188883188884188885188886188887188888188889188890188891188892188893188894188895188896188897188898188899188900188901188902188903188904188905188906188907188908188909188910188911188912188913188914188915188916188917188918188919188920188921188922188923188924188925188926188927188928188929188930188931188932188933188934188935188936188937188938188939188940188941188942188943188944188945188946188947188948188949188950188951188952188953188954188955188956188957188958188959188960188961188962188963188964188965188966188967188968188969188970188971188972188973188974188975188976188977188978188979188980188981188982188983188984188985188986188987188988188989188990188991188992188993188994188995188996188997188998188999189000189001189002189003189004189005189006189007189008189009189010189011189012189013189014189015189016189017189018189019189020189021189022189023189024189025189026189027189028189029189030189031189032189033189034189035189036189037189038189039189040189041189042189043189044189045189046189047189048189049189050189051189052189053189054189055189056189057189058189059189060189061189062189063189064189065189066189067189068189069189070189071189072189073189074189075189076189077189078189079189080189081189082189083189084189085189086189087189088189089189090189091189092189093189094189095189096189097189098189099189100189101189102189103189104189105189106189107189108189109189110189111189112189113189114189115189116189117189118189119189120189121189122189123189124189125189126189127189128189129189130189131189132189133189134189135189136189137189138189139189140189141189142189143189144189145189146189147189148189149189150189151189152189153189154189155189156189157189158189159189160189161189162189163189164189165189166189167189168189169189170189171189172189173189174189175189176189177189178189179189180189181189182189183189184189185189186189187189188189189189190189191189192189193189194189195189196189197189198189199189200189201189202189203189204189205189206189207189208189209189210189211189212189213189214189215189216189217189218189219189220189221189222189223189224189225189226189227189228189229189230189231189232189233189234189235189236189237189238189239189240189241189242189243189244189245189246189247189248189249189250189251189252189253189254189255189256189257189258189259189260189261189262189263189264189265189266189267189268189269189270189271189272189273189274189275189276189277189278189279189280189281189282189283189284189285189286189287189288189289189290189291189292189293189294189295189296189297189298189299189300189301189302189303189304189305189306189307189308189309189310189311189312189313189314189315189316189317189318189319189320189321189322189323189324189325189326189327189328189329189330189331189332189333189334189335189336189337189338189339189340189341189342189343189344189345189346189347189348189349189350189351189352189353189354189355189356189357189358189359189360189361189362189363189364189365189366189367189368189369189370189371189372189373189374189375189376189377189378189379189380189381189382189383189384189385189386189387189388189389189390189391189392189393189394189395189396189397189398189399189400189401189402189403189404189405189406189407189408189409189410189411189412189413189414189415189416189417189418189419189420189421189422189423189424189425189426189427189428189429189430189431189432189433189434189435189436189437189438189439189440189441189442189443189444189445189446189447189448189449189450189451189452189453189454189455189456189457189458189459189460189461189462189463189464189465189466189467189468189469189470189471189472189473189474189475189476189477189478189479189480189481189482189483189484189485189486189487189488189489189490189491189492189493189494189495189496189497189498189499189500189501189502189503189504189505189506189507189508189509189510189511189512189513189514189515189516189517189518189519189520189521189522189523189524189525189526189527189528189529189530189531189532189533189534189535189536189537189538189539189540189541189542189543189544189545189546189547189548189549189550189551189552189553189554189555189556189557189558189559189560189561189562189563189564189565189566189567189568189569189570189571189572189573189574189575189576189577189578189579189580189581189582189583189584189585189586189587189588189589189590189591189592189593189594189595189596189597189598189599189600189601189602189603189604189605189606189607189608189609189610189611189612189613189614189615189616189617189618189619189620189621189622189623189624189625189626189627189628189629189630189631189632189633189634189635189636189637189638189639189640189641189642189643189644189645189646189647189648189649189650189651189652189653189654189655189656189657189658189659189660189661189662189663189664189665189666189667189668189669189670189671189672189673189674189675189676189677189678189679189680189681189682189683189684189685189686189687189688189689189690189691189692189693189694189695189696189697189698189699189700189701189702189703189704189705189706189707189708189709189710189711189712189713189714189715189716189717189718189719189720189721189722189723189724189725189726189727189728189729189730189731189732189733189734189735189736189737189738189739189740189741189742189743189744189745189746189747189748189749189750189751189752189753189754189755189756189757189758189759189760189761189762189763189764189765189766189767189768189769189770189771189772189773189774189775189776189777189778189779189780189781189782189783189784189785189786189787189788189789189790189791189792189793189794189795189796189797189798189799189800189801189802189803189804189805189806189807189808189809189810189811189812189813189814189815189816189817189818189819189820189821189822189823189824189825189826189827189828189829189830189831189832189833189834189835189836189837189838189839189840189841189842189843189844189845189846189847189848189849189850189851189852189853189854189855189856189857189858189859189860189861189862189863189864189865189866189867189868189869189870189871189872189873189874189875189876189877189878189879189880189881189882189883189884189885189886189887189888189889189890189891189892189893189894189895189896189897189898189899189900189901189902189903189904189905189906189907189908189909189910189911189912189913189914189915189916189917189918189919189920189921189922189923189924189925189926189927189928189929189930189931189932189933189934189935189936189937189938189939189940189941189942189943189944189945189946189947189948189949189950189951189952189953189954189955189956189957189958189959189960189961189962189963189964189965189966189967189968189969189970189971189972189973189974189975189976189977189978189979189980189981189982189983189984189985189986189987189988189989189990189991189992189993189994189995189996189997189998189999190000190001190002190003190004190005190006190007190008190009190010190011190012190013190014190015190016190017190018190019190020190021190022190023190024190025190026190027190028190029190030190031190032190033190034190035190036190037190038190039190040190041190042190043190044190045190046190047190048190049190050190051190052190053190054190055190056190057190058190059190060190061190062190063190064190065190066190067190068190069190070190071190072190073190074190075190076190077190078190079190080190081190082190083190084190085190086190087190088190089190090190091190092190093190094190095190096190097190098190099190100190101190102190103190104190105190106190107190108190109190110190111190112190113190114190115190116190117190118190119190120190121190122190123190124190125190126190127190128190129190130190131190132190133190134190135190136190137190138190139190140190141190142190143190144190145190146190147190148190149190150190151190152190153190154190155190156190157190158190159190160190161190162190163190164190165190166190167190168190169190170190171190172190173190174190175190176190177190178190179190180190181190182190183190184190185190186190187190188190189190190190191190192190193190194190195190196190197190198190199190200190201190202190203190204190205190206190207190208190209190210190211190212190213190214190215190216190217190218190219190220190221190222190223190224190225190226190227190228190229190230190231190232190233190234190235190236190237190238190239190240190241190242190243190244190245190246190247190248190249190250190251190252190253190254190255190256190257190258190259190260190261190262190263190264190265190266190267190268190269190270190271190272190273190274190275190276190277190278190279190280190281190282190283190284190285190286190287190288190289190290190291190292190293190294190295190296190297190298190299190300190301190302190303190304190305190306190307190308190309190310190311190312190313190314190315190316190317190318190319190320190321190322190323190324190325190326190327190328190329190330190331190332190333190334190335190336190337190338190339190340190341190342190343190344190345190346190347190348190349190350190351190352190353190354190355190356190357190358190359190360190361190362190363190364190365190366190367190368190369190370190371190372190373190374190375190376190377190378190379190380190381190382190383190384190385190386190387190388190389190390190391190392190393190394190395190396190397190398190399190400190401190402190403190404190405190406190407190408190409190410190411190412190413190414190415190416190417190418190419190420190421190422190423190424190425190426190427190428190429190430190431190432190433190434190435190436190437190438190439190440190441190442190443190444190445190446190447190448190449190450190451190452190453190454190455190456190457190458190459190460190461190462190463190464190465190466190467190468190469190470190471190472190473190474190475190476190477190478190479190480190481190482190483190484190485190486190487190488190489190490190491190492190493190494190495190496190497190498190499190500190501190502190503190504190505190506190507190508190509190510190511190512190513190514190515190516190517190518190519190520190521190522190523190524190525190526190527190528190529190530190531190532190533190534190535190536190537190538190539190540190541190542190543190544190545190546190547190548190549190550190551190552190553190554190555190556190557190558190559190560190561190562190563190564190565190566190567190568190569190570190571190572190573190574190575190576190577190578190579190580190581190582190583190584190585190586190587190588190589190590190591190592190593190594190595190596190597190598190599190600190601190602190603190604190605190606190607190608190609190610190611190612190613190614190615190616190617190618190619190620190621190622190623190624190625190626190627190628190629190630190631190632190633190634190635190636190637190638190639190640190641190642190643190644190645190646190647190648190649190650190651190652190653190654190655190656190657190658190659190660190661190662190663190664190665190666190667190668190669190670190671190672190673190674190675190676190677190678190679190680190681190682190683190684190685190686190687190688190689190690190691190692190693190694190695190696190697190698190699190700190701190702190703190704190705190706190707190708190709190710190711190712190713190714190715190716190717190718190719190720190721190722190723190724190725190726190727190728190729190730190731190732190733190734190735190736190737190738190739190740190741190742190743190744190745190746190747190748190749190750190751190752190753190754190755190756190757190758190759190760190761190762190763190764190765190766190767190768190769190770190771190772190773190774190775190776190777190778190779190780190781190782190783190784190785190786190787190788190789190790190791190792190793190794190795190796190797190798190799190800190801190802190803190804190805190806190807190808190809190810190811190812190813190814190815190816190817190818190819190820190821190822190823190824190825190826190827190828190829190830190831190832190833190834190835190836190837190838190839190840190841190842190843190844190845190846190847190848190849190850190851190852190853190854190855190856190857190858190859190860190861190862190863190864190865190866190867190868190869190870190871190872190873190874190875190876190877190878190879190880190881190882190883190884190885190886190887190888190889190890190891190892190893190894190895190896190897190898190899190900190901190902190903190904190905190906190907190908190909190910190911190912190913190914190915190916190917190918190919190920190921190922190923190924190925190926190927190928190929190930190931190932190933190934190935190936190937190938190939190940190941190942190943190944190945190946190947190948190949190950190951190952190953190954190955190956190957190958190959190960190961190962190963190964190965190966190967190968190969190970190971190972190973190974190975190976190977190978190979190980190981190982190983190984190985190986190987190988190989190990190991190992190993190994190995190996190997190998190999191000191001191002191003191004191005191006191007191008191009191010191011191012191013191014191015191016191017191018191019191020191021191022191023191024191025191026191027191028191029191030191031191032191033191034191035191036191037191038191039191040191041191042191043191044191045191046191047191048191049191050191051191052191053191054191055191056191057191058191059191060191061191062191063191064191065191066191067191068191069191070191071191072191073191074191075191076191077191078191079191080191081191082191083191084191085191086191087191088191089191090191091191092191093191094191095191096191097191098191099191100191101191102191103191104191105191106191107191108191109191110191111191112191113191114191115191116191117191118191119191120191121191122191123191124191125191126191127191128191129191130191131191132191133191134191135191136191137191138191139191140191141191142191143191144191145191146191147191148191149191150191151191152191153191154191155191156191157191158191159191160191161191162191163191164191165191166191167191168191169191170191171191172191173191174191175191176191177191178191179191180191181191182191183191184191185191186191187191188191189191190191191191192191193191194191195191196191197191198191199191200191201191202191203191204191205191206191207191208191209191210191211191212191213191214191215191216191217191218191219191220191221191222191223191224191225191226191227191228191229191230191231191232191233191234191235191236191237191238191239191240191241191242191243191244191245191246191247191248191249191250191251191252191253191254191255191256191257191258191259191260191261191262191263191264191265191266191267191268191269191270191271191272191273191274191275191276191277191278191279191280191281191282191283191284191285191286191287191288191289191290191291191292191293191294191295191296191297191298191299191300191301191302191303191304191305191306191307191308191309191310191311191312191313191314191315191316191317191318191319191320191321191322191323191324191325191326191327191328191329191330191331191332191333191334191335191336191337191338191339191340191341191342191343191344191345191346191347191348191349191350191351191352191353191354191355191356191357191358191359191360191361191362191363191364191365191366191367191368191369191370191371191372191373191374191375191376191377191378191379191380191381191382191383191384191385191386191387191388191389191390191391191392191393191394191395191396191397191398191399191400191401191402191403191404191405191406191407191408191409191410191411191412191413191414191415191416191417191418191419191420191421191422191423191424191425191426191427191428191429191430191431191432191433191434191435191436191437191438191439191440191441191442191443191444191445191446191447191448191449191450191451191452191453191454191455191456191457191458191459191460191461191462191463191464191465191466191467191468191469191470191471191472191473191474191475191476191477191478191479191480191481191482191483191484191485191486191487191488191489191490191491191492191493191494191495191496191497191498191499191500191501191502191503191504191505191506191507191508191509191510191511191512191513191514191515191516191517191518191519191520191521191522191523191524191525191526191527191528191529191530191531191532191533191534191535191536191537191538191539191540191541191542191543191544191545191546191547191548191549191550191551191552191553191554191555191556191557191558191559191560191561191562191563191564191565191566191567191568191569191570191571191572191573191574191575191576191577191578191579191580191581191582191583191584191585191586191587191588191589191590191591191592191593191594191595191596191597191598191599191600191601191602191603191604191605191606191607191608191609191610191611191612191613191614191615191616191617191618191619191620191621191622191623191624191625191626191627191628191629191630191631191632191633191634191635191636191637191638191639191640191641191642191643191644191645191646191647191648191649191650191651191652191653191654191655191656191657191658191659191660191661191662191663191664191665191666191667191668191669191670191671191672191673191674191675191676191677191678191679191680191681191682191683191684191685191686191687191688191689191690191691191692191693191694191695191696191697191698191699191700191701191702191703191704191705191706191707191708191709191710191711191712191713191714191715191716191717191718191719191720191721191722191723191724191725191726191727191728191729191730191731191732191733191734191735191736191737191738191739191740191741191742191743191744191745191746191747191748191749191750191751191752191753191754191755191756191757191758191759191760191761191762191763191764191765191766191767191768191769191770191771191772191773191774191775191776191777191778191779191780191781191782191783191784191785191786191787191788191789191790191791191792191793191794191795191796191797191798191799191800191801191802191803191804191805191806191807191808191809191810191811191812191813191814191815191816191817191818191819191820191821191822191823191824191825191826191827191828191829191830191831191832191833191834191835191836191837191838191839191840191841191842191843191844191845191846191847191848191849191850191851191852191853191854191855191856191857191858191859191860191861191862191863191864191865191866191867191868191869191870191871191872191873191874191875191876191877191878191879191880191881191882191883191884191885191886191887191888191889191890191891191892191893191894191895191896191897191898191899191900191901191902191903191904191905191906191907191908191909191910191911191912191913191914191915191916191917191918191919191920191921191922191923191924191925191926191927191928191929191930191931191932191933191934191935191936191937191938191939191940191941191942191943191944191945191946191947191948191949191950191951191952191953191954191955191956191957191958191959191960191961191962191963191964191965191966191967191968191969191970191971191972191973191974191975191976191977191978191979191980191981191982191983191984191985191986191987191988191989191990191991191992191993191994191995191996191997191998191999192000192001192002192003192004192005192006192007192008192009192010192011192012192013192014192015192016192017192018192019192020192021192022192023192024192025192026192027192028192029192030192031192032192033192034192035192036192037192038192039192040192041192042192043192044192045192046192047192048192049192050192051192052192053192054192055192056192057192058192059192060192061192062192063192064192065192066192067192068192069192070192071192072192073192074192075192076192077192078192079192080192081192082192083192084192085192086192087192088192089192090192091192092192093192094192095192096192097192098192099192100192101192102192103192104192105192106192107192108192109192110192111192112192113192114192115192116192117192118192119192120192121192122192123192124192125192126192127192128192129192130192131192132192133192134192135192136192137192138192139192140192141192142192143192144192145192146192147192148192149192150192151192152192153192154192155192156192157192158192159192160192161192162192163192164192165192166192167192168192169192170192171192172192173192174192175192176192177192178192179192180192181192182192183192184192185192186192187192188192189192190192191192192192193192194192195192196192197192198192199192200192201192202192203192204192205192206192207192208192209192210192211192212192213192214192215192216192217192218192219192220192221192222192223192224192225192226192227192228192229192230192231192232192233192234192235192236192237192238192239192240192241192242192243192244192245192246192247192248192249192250192251192252192253192254192255192256192257192258192259192260192261192262192263192264192265192266192267192268192269192270192271192272192273192274192275192276192277192278192279192280192281192282192283192284192285192286192287192288192289192290192291192292192293192294192295192296192297192298192299192300192301192302192303192304192305192306192307192308192309192310192311192312192313192314192315192316192317192318192319192320192321192322192323192324192325192326192327192328192329192330192331192332192333192334192335192336192337192338192339192340192341192342192343192344192345192346192347192348192349192350192351192352192353192354192355192356192357192358192359192360192361192362192363192364192365192366192367192368192369192370192371192372192373192374192375192376192377192378192379192380192381192382192383192384192385192386192387192388192389192390192391192392192393192394192395192396192397192398192399192400192401192402192403192404192405192406192407192408192409192410192411192412192413192414192415192416192417192418192419192420192421192422192423192424192425192426192427192428192429192430192431192432192433192434192435192436192437192438192439192440192441192442192443192444192445192446192447192448192449192450192451192452192453192454192455192456192457192458192459192460192461192462192463192464192465192466192467192468192469192470192471192472192473192474192475192476192477192478192479192480192481192482192483192484192485192486192487192488192489192490192491192492192493192494192495192496192497192498192499192500192501192502192503192504192505192506192507192508192509192510192511192512192513192514192515192516192517192518192519192520192521192522192523192524192525192526192527192528192529192530192531192532192533192534192535192536192537192538192539192540192541192542192543192544192545192546192547192548192549192550192551192552192553192554192555192556192557192558192559192560192561192562192563192564192565192566192567192568192569192570192571192572192573192574192575192576192577192578192579192580192581192582192583192584192585192586192587192588192589192590192591192592192593192594192595192596192597192598192599192600192601192602192603192604192605192606192607192608192609192610192611192612192613192614192615192616192617192618192619192620192621192622192623192624192625192626192627192628192629192630192631192632192633192634192635192636192637192638192639192640192641192642192643192644192645192646192647192648192649192650192651192652192653192654192655192656192657192658192659192660192661192662192663192664192665192666192667192668192669192670192671192672192673192674192675192676192677192678192679192680192681192682192683192684192685192686192687192688192689192690192691192692192693192694192695192696192697192698192699192700192701192702192703192704192705192706192707192708192709192710192711192712192713192714192715192716192717192718192719192720192721192722192723192724192725192726192727192728192729192730192731192732192733192734192735192736192737192738192739192740192741192742192743192744192745192746192747192748192749192750192751192752192753192754192755192756192757192758192759192760192761192762192763192764192765192766192767192768192769192770192771192772192773192774192775192776192777192778192779192780192781192782192783192784192785192786192787192788192789192790192791192792192793192794192795192796192797192798192799192800192801192802192803192804192805192806192807192808192809192810192811192812192813192814192815192816192817192818192819192820192821192822192823192824192825192826192827192828192829192830192831192832192833192834192835192836192837192838192839192840192841192842192843192844192845192846192847192848192849192850192851192852192853192854192855192856192857192858192859192860192861192862192863192864192865192866192867192868192869192870192871192872192873192874192875192876192877192878192879192880192881192882192883192884192885192886192887192888192889192890192891192892192893192894192895192896192897192898192899192900192901192902192903192904192905192906192907192908192909192910192911192912192913192914192915192916192917192918192919192920192921192922192923192924192925192926192927192928192929192930192931192932192933192934192935192936192937192938192939192940192941192942192943192944192945192946192947192948192949192950192951192952192953192954192955192956192957192958192959192960192961192962192963192964192965192966192967192968192969192970192971192972192973192974192975192976192977192978192979192980192981192982192983192984192985192986192987192988192989192990192991192992192993192994192995192996192997192998192999193000193001193002193003193004193005193006193007193008193009193010193011193012193013193014193015193016193017193018193019193020193021193022193023193024193025193026193027193028193029193030193031193032193033193034193035193036193037193038193039193040193041193042193043193044193045193046193047193048193049193050193051193052193053193054193055193056193057193058193059193060193061193062193063193064193065193066193067193068193069193070193071193072193073193074193075193076193077193078193079193080193081193082193083193084193085193086193087193088193089193090193091193092193093193094193095193096193097193098193099193100193101193102193103193104193105193106193107193108193109193110193111193112193113193114193115193116193117193118193119193120193121193122193123193124193125193126193127193128193129193130193131193132193133193134193135193136193137193138193139193140193141193142193143193144193145193146193147193148193149193150193151193152193153193154193155193156193157193158193159193160193161193162193163193164193165193166193167193168193169193170193171193172193173193174193175193176193177193178193179193180193181193182193183193184193185193186193187193188193189193190193191193192193193193194193195193196193197193198193199193200193201193202193203193204193205193206193207193208193209193210193211193212193213193214193215193216193217193218193219193220193221193222193223193224193225193226193227193228193229193230193231193232193233193234193235193236193237193238193239193240193241193242193243193244193245193246193247193248193249193250193251193252193253193254193255193256193257193258193259193260193261193262193263193264193265193266193267193268193269193270193271193272193273193274193275193276193277193278193279193280193281193282193283193284193285193286193287193288193289193290193291193292193293193294193295193296193297193298193299193300193301193302193303193304193305193306193307193308193309193310193311193312193313193314193315193316193317193318193319193320193321193322193323193324193325193326193327193328193329193330193331193332193333193334193335193336193337193338193339193340193341193342193343193344193345193346193347193348193349193350193351193352193353193354193355193356193357193358193359193360193361193362193363193364193365193366193367193368193369193370193371193372193373193374193375193376193377193378193379193380193381193382193383193384193385193386193387193388193389193390193391193392193393193394193395193396193397193398193399193400193401193402193403193404193405193406193407193408193409193410193411193412193413193414193415193416193417193418193419193420193421193422193423193424193425193426193427193428193429193430193431193432193433193434193435193436193437193438193439193440193441193442193443193444193445193446193447193448193449193450193451193452193453193454193455193456193457193458193459193460193461193462193463193464193465193466193467193468193469193470193471193472193473193474193475193476193477193478193479193480193481193482193483193484193485193486193487193488193489193490193491193492193493193494193495193496193497193498193499193500193501193502193503193504193505193506193507193508193509193510193511193512193513193514193515193516193517193518193519193520193521193522193523193524193525193526193527193528193529193530193531193532193533193534193535193536193537193538193539193540193541193542193543193544193545193546193547193548193549193550193551193552193553193554193555193556193557193558193559193560193561193562193563193564193565193566193567193568193569193570193571193572193573193574193575193576193577193578193579193580193581193582193583193584193585193586193587193588193589193590193591193592193593193594193595193596193597193598193599193600193601193602193603193604193605193606193607193608193609193610193611193612193613193614193615193616193617193618193619193620193621193622193623193624193625193626193627193628193629193630193631193632193633193634193635193636193637193638193639193640193641193642193643193644193645193646193647193648193649193650193651193652193653193654193655193656193657193658193659193660193661193662193663193664193665193666193667193668193669193670193671193672193673193674193675193676193677193678193679193680193681193682193683193684193685193686193687193688193689193690193691193692193693193694193695193696193697193698193699193700193701193702193703193704193705193706193707193708193709193710193711193712193713193714193715193716193717193718193719193720193721193722193723193724193725193726193727193728193729193730193731193732193733193734193735193736193737193738193739193740193741193742193743193744193745193746193747193748193749193750193751193752193753193754193755193756193757193758193759193760193761193762193763193764193765193766193767193768193769193770193771193772193773193774193775193776193777193778193779193780193781193782193783193784193785193786193787193788193789193790193791193792193793193794193795193796193797193798193799193800193801193802193803193804193805193806193807193808193809193810193811193812193813193814193815193816193817193818193819193820193821193822193823193824193825193826193827193828193829193830193831193832193833193834193835193836193837193838193839193840193841193842193843193844193845193846193847193848193849193850193851193852193853193854193855193856193857193858193859193860193861193862193863193864193865193866193867193868193869193870193871193872193873193874193875193876193877193878193879193880193881193882193883193884193885193886193887193888193889193890193891193892193893193894193895193896193897193898193899193900193901193902193903193904193905193906193907193908193909193910193911193912193913193914193915193916193917193918193919193920193921193922193923193924193925193926193927193928193929193930193931193932193933193934193935193936193937193938193939193940193941193942193943193944193945193946193947193948193949193950193951193952193953193954193955193956193957193958193959193960193961193962193963193964193965193966193967193968193969193970193971193972193973193974193975193976193977193978193979193980193981193982193983193984193985193986193987193988193989193990193991193992193993193994193995193996193997193998193999194000194001194002194003194004194005194006194007194008194009194010194011194012194013194014194015194016194017194018194019194020194021194022194023194024194025194026194027194028194029194030194031194032194033194034194035194036194037194038194039194040194041194042194043194044194045194046194047194048194049194050194051194052194053194054194055194056194057194058194059194060194061194062194063194064194065194066194067194068194069194070194071194072194073194074194075194076194077194078194079194080194081194082194083194084194085194086194087194088194089194090194091194092194093194094194095194096194097194098194099194100194101194102194103194104194105194106194107194108194109194110194111194112194113194114194115194116194117194118194119194120194121194122194123194124194125194126194127194128194129194130194131194132194133194134194135194136194137194138194139194140194141194142194143194144194145194146194147194148194149194150194151194152194153194154194155194156194157194158194159194160194161194162194163194164194165194166194167194168194169194170194171194172194173194174194175194176194177194178194179194180194181194182194183194184194185194186194187194188194189194190194191194192194193194194194195194196194197194198194199194200194201194202194203194204194205194206194207194208194209194210194211194212194213194214194215194216194217194218194219194220194221194222194223194224194225194226194227194228194229194230194231194232194233194234194235194236194237194238194239194240194241194242194243194244194245194246194247194248194249194250194251194252194253194254194255194256194257194258194259194260194261194262194263194264194265194266194267194268194269194270194271194272194273194274194275194276194277194278194279194280194281194282194283194284194285194286194287194288194289194290194291194292194293194294194295194296194297194298194299194300194301194302194303194304194305194306194307194308194309194310194311194312194313194314194315194316194317194318194319194320194321194322194323194324194325194326194327194328194329194330194331194332194333194334194335194336194337194338194339194340194341194342194343194344194345194346194347194348194349194350194351194352194353194354194355194356194357194358194359194360194361194362194363194364194365194366194367194368194369194370194371194372194373194374194375194376194377194378194379194380194381194382194383194384194385194386194387194388194389194390194391194392194393194394194395194396194397194398194399194400194401194402194403194404194405194406194407194408194409194410194411194412194413194414194415194416194417194418194419194420194421194422194423194424194425194426194427194428194429194430194431194432194433194434194435194436194437194438194439194440194441194442194443194444194445194446194447194448194449194450194451194452194453194454194455194456194457194458194459194460194461194462194463194464194465194466194467194468194469194470194471194472194473194474194475194476194477194478194479194480194481194482194483194484194485194486194487194488194489194490194491194492194493194494194495194496194497194498194499194500194501194502194503194504194505194506194507194508194509194510194511194512194513194514194515194516194517194518194519194520194521194522194523194524194525194526194527194528194529194530194531194532194533194534194535194536194537194538194539194540194541194542194543194544194545194546194547194548194549194550194551194552194553194554194555194556194557194558194559194560194561194562194563194564194565194566194567194568194569194570194571194572194573194574194575194576194577194578194579194580194581194582194583194584194585194586194587194588194589194590194591194592194593194594194595194596194597194598194599194600194601194602194603194604194605194606194607194608194609194610194611194612194613194614194615194616194617194618194619194620194621194622194623194624194625194626194627194628194629194630194631194632194633194634194635194636194637194638194639194640194641194642194643194644194645194646194647194648194649194650194651194652194653194654194655194656194657194658194659194660194661194662194663194664194665194666194667194668194669194670194671194672194673194674194675194676194677194678194679194680194681194682194683194684194685194686194687194688194689194690194691194692194693194694194695194696194697194698194699194700194701194702194703194704194705194706194707194708194709194710194711194712194713194714194715194716194717194718194719194720194721194722194723194724194725194726194727194728194729194730194731194732194733194734194735194736194737194738194739194740194741194742194743194744194745194746194747194748194749194750194751194752194753194754194755194756194757194758194759194760194761194762194763194764194765194766194767194768194769194770194771194772194773194774194775194776194777194778194779194780194781194782194783194784194785194786194787194788194789194790194791194792194793194794194795194796194797194798194799194800194801194802194803194804194805194806194807194808194809194810194811194812194813194814194815194816194817194818194819194820194821194822194823194824194825194826194827194828194829194830194831194832194833194834194835194836194837194838194839194840194841194842194843194844194845194846194847194848194849194850194851194852194853194854194855194856194857194858194859194860194861194862194863194864194865194866194867194868194869194870194871194872194873194874194875194876194877194878194879194880194881194882194883194884194885194886194887194888194889194890194891194892194893194894194895194896194897194898194899194900194901194902194903194904194905194906194907194908194909194910194911194912194913194914194915194916194917194918194919194920194921194922194923194924194925194926194927194928194929194930194931194932194933194934194935194936194937194938194939194940194941194942194943194944194945194946194947194948194949194950194951194952194953194954194955194956194957194958194959194960194961194962194963194964194965194966194967194968194969194970194971194972194973194974194975194976194977194978194979194980194981194982194983194984194985194986194987194988194989194990194991194992194993194994194995194996194997194998194999195000195001195002195003195004195005195006195007195008195009195010195011195012195013195014195015195016195017195018195019195020195021195022195023195024195025195026195027195028195029195030195031195032195033195034195035195036195037195038195039195040195041195042195043195044195045195046195047195048195049195050195051195052195053195054195055195056195057195058195059195060195061195062195063195064195065195066195067195068195069195070195071195072195073195074195075195076195077195078195079195080195081195082195083195084195085195086195087195088195089195090195091195092195093195094195095195096195097195098195099195100195101195102195103195104195105195106195107195108195109195110195111195112195113195114195115195116195117195118195119195120195121195122195123195124195125195126195127195128195129195130195131195132195133195134195135195136195137195138195139195140195141195142195143195144195145195146195147195148195149195150195151195152195153195154195155195156195157195158195159195160195161195162195163195164195165195166195167195168195169195170195171195172195173195174195175195176195177195178195179195180195181195182195183195184195185195186195187195188195189195190195191195192195193195194195195195196195197195198195199195200195201195202195203195204195205195206195207195208195209195210195211195212195213195214195215195216195217195218195219195220195221195222195223195224195225195226195227195228195229195230195231195232195233195234195235195236195237195238195239195240195241195242195243195244195245195246195247195248195249195250195251195252195253195254195255195256195257195258195259195260195261195262195263195264195265195266195267195268195269195270195271195272195273195274195275195276195277195278195279195280195281195282195283195284195285195286195287195288195289195290195291195292195293195294195295195296195297195298195299195300195301195302195303195304195305195306195307195308195309195310195311195312195313195314195315195316195317195318195319195320195321195322195323195324195325195326195327195328195329195330195331195332195333195334195335195336195337195338195339195340195341195342195343195344195345195346195347195348195349195350195351195352195353195354195355195356195357195358195359195360195361195362195363195364195365195366195367195368195369195370195371195372195373195374195375195376195377195378195379195380195381195382195383195384195385195386195387195388195389195390195391195392195393195394195395195396195397195398195399195400195401195402195403195404195405195406195407195408195409195410195411195412195413195414195415195416195417195418195419195420195421195422195423195424195425195426195427195428195429195430195431195432195433195434195435195436195437195438195439195440195441195442195443195444195445195446195447195448195449195450195451195452195453195454195455195456195457195458195459195460195461195462195463195464195465195466195467195468195469195470195471195472195473195474195475195476195477195478195479195480195481195482195483195484195485195486195487195488195489195490195491195492195493195494195495195496195497195498195499195500195501195502195503195504195505195506195507195508195509195510195511195512195513195514195515195516195517195518195519195520195521195522195523195524195525195526195527195528195529195530195531195532195533195534195535195536195537195538195539195540195541195542195543195544195545195546195547195548195549195550195551195552195553195554195555195556195557195558195559195560195561195562195563195564195565195566195567195568195569195570195571195572195573195574195575195576195577195578195579195580195581195582195583195584195585195586195587195588195589195590195591195592195593195594195595195596195597195598195599195600195601195602195603195604195605195606195607195608195609195610195611195612195613195614195615195616195617195618195619195620195621195622195623195624195625195626195627195628195629195630195631195632195633195634195635195636195637195638195639195640195641195642195643195644195645195646195647195648195649195650195651195652195653195654195655195656195657195658195659195660195661195662195663195664195665195666195667195668195669195670195671195672195673195674195675195676195677195678195679195680195681195682195683195684195685195686195687195688195689195690195691195692195693195694195695195696195697195698195699195700195701195702195703195704195705195706195707195708195709195710195711195712195713195714195715195716195717195718195719195720195721195722195723195724195725195726195727195728195729195730195731195732195733195734195735195736195737195738195739195740195741195742195743195744195745195746195747195748195749195750195751195752195753195754195755195756195757195758195759195760195761195762195763195764195765195766195767195768195769195770195771195772195773195774195775195776195777195778195779195780195781195782195783195784195785195786195787195788195789195790195791195792195793195794195795195796195797195798195799195800195801195802195803195804195805195806195807195808195809195810195811195812195813195814195815195816195817195818195819195820195821195822195823195824195825195826195827195828195829195830195831195832195833195834195835195836195837195838195839195840195841195842195843195844195845195846195847195848195849195850195851195852195853195854195855195856195857195858195859195860195861195862195863195864195865195866195867195868195869195870195871195872195873195874195875195876195877195878195879195880195881195882195883195884195885195886195887195888195889195890195891195892195893195894195895195896195897195898195899195900195901195902195903195904195905195906195907195908195909195910195911195912195913195914195915195916195917195918195919195920195921195922195923195924195925195926195927195928195929195930195931195932195933195934195935195936195937195938195939195940195941195942195943195944195945195946195947195948195949195950195951195952195953195954195955195956195957195958195959195960195961195962195963195964195965195966195967195968195969195970195971195972195973195974195975195976195977195978195979195980195981195982195983195984195985195986195987195988195989195990195991195992195993195994195995195996195997195998195999196000196001196002196003196004196005196006196007196008196009196010196011196012196013196014196015196016196017196018196019196020196021196022196023196024196025196026196027196028196029196030196031196032196033196034196035196036196037196038196039196040196041196042196043196044196045196046196047196048196049196050196051196052196053196054196055196056196057196058196059196060196061196062196063196064196065196066196067196068196069196070196071196072196073196074196075196076196077196078196079196080196081196082196083196084196085196086196087196088196089196090196091196092196093196094196095196096196097196098196099196100196101196102196103196104196105196106196107196108196109196110196111196112196113196114196115196116196117196118196119196120196121196122196123196124196125196126196127196128196129196130196131196132196133196134196135196136196137196138196139196140196141196142196143196144196145196146196147196148196149196150196151196152196153196154196155196156196157196158196159196160196161196162196163196164196165196166196167196168196169196170196171196172196173196174196175196176196177196178196179196180196181196182196183196184196185196186196187196188196189196190196191196192196193196194196195196196196197196198196199196200196201196202196203196204196205196206196207196208196209196210196211196212196213196214196215196216196217196218196219196220196221196222196223196224196225196226196227196228196229196230196231196232196233196234196235196236196237196238196239196240196241196242196243196244196245196246196247196248196249196250196251196252196253196254196255196256196257196258196259196260196261196262196263196264196265196266196267196268196269196270196271196272196273196274196275196276196277196278196279196280196281196282196283196284196285196286196287196288196289196290196291196292196293196294196295196296196297196298196299196300196301196302196303196304196305196306196307196308196309196310196311196312196313196314196315196316196317196318196319196320196321196322196323196324196325196326196327196328196329196330196331196332196333196334196335196336196337196338196339196340196341196342196343196344196345196346196347196348196349196350196351196352196353196354196355196356196357196358196359196360196361196362196363196364196365196366196367196368196369196370196371196372196373196374196375196376196377196378196379196380196381196382196383196384196385196386196387196388196389196390196391196392196393196394196395196396196397196398196399196400196401196402196403196404196405196406196407196408196409196410196411196412196413196414196415196416196417196418196419196420196421196422196423196424196425196426196427196428196429196430196431196432196433196434196435196436196437196438196439196440196441196442196443196444196445196446196447196448196449196450196451196452196453196454196455196456196457196458196459196460196461196462196463196464196465196466196467196468196469196470196471196472196473196474196475196476196477196478196479196480196481196482196483196484196485196486196487196488196489196490196491196492196493196494196495196496196497196498196499196500196501196502196503196504196505196506196507196508196509196510196511196512196513196514196515196516196517196518196519196520196521196522196523196524196525196526196527196528196529196530196531196532196533196534196535196536196537196538196539196540196541196542196543196544196545196546196547196548196549196550196551196552196553196554196555196556196557196558196559196560196561196562196563196564196565196566196567196568196569196570196571196572196573196574196575196576196577196578196579196580196581196582196583196584196585196586196587196588196589196590196591196592196593196594196595196596196597196598196599196600196601196602196603196604196605196606196607196608196609196610196611196612196613196614196615196616196617196618196619196620196621196622196623196624196625196626196627196628196629196630196631196632196633196634196635196636196637196638196639196640196641196642196643196644196645196646196647196648196649196650196651196652196653196654196655196656196657196658196659196660196661196662196663196664196665196666196667196668196669196670196671196672196673196674196675196676196677196678196679196680196681196682196683196684196685196686196687196688196689196690196691196692196693196694196695196696196697196698196699196700196701196702196703196704196705196706196707196708196709196710196711196712196713196714196715196716196717196718196719196720196721196722196723196724196725196726196727196728196729196730196731196732196733196734196735196736196737196738196739196740196741196742196743196744196745196746196747196748196749196750196751196752196753196754196755196756196757196758196759196760196761196762196763196764196765196766196767196768196769196770196771196772196773196774196775196776196777196778196779196780196781196782196783196784196785196786196787196788196789196790196791196792196793196794196795196796196797196798196799196800196801196802196803196804196805196806196807196808196809196810196811196812196813196814196815196816196817196818196819196820196821196822196823196824196825196826196827196828196829196830196831196832196833196834196835196836196837196838196839196840196841196842196843196844196845196846196847196848196849196850196851196852196853196854196855196856196857196858196859196860196861196862196863196864196865196866196867196868196869196870196871196872196873196874196875196876196877196878196879196880196881196882196883196884196885196886196887196888196889196890196891196892196893196894196895196896196897196898196899196900196901196902196903196904196905196906196907196908196909196910196911196912196913196914196915196916196917196918196919196920196921196922196923196924196925196926196927196928196929196930196931196932196933196934196935196936196937196938196939196940196941196942196943196944196945196946196947196948196949196950196951196952196953196954196955196956196957196958196959196960196961196962196963196964196965196966196967196968196969196970196971196972196973196974196975196976196977196978196979196980196981196982196983196984196985196986196987196988196989196990196991196992196993196994196995196996196997196998196999197000197001197002197003197004197005197006197007197008197009197010197011197012197013197014197015197016197017197018197019197020197021197022197023197024197025197026197027197028197029197030197031197032197033197034197035197036197037197038197039197040197041197042197043197044197045197046197047197048197049197050197051197052197053197054197055197056197057197058197059197060197061197062197063197064197065197066197067197068197069197070197071197072197073197074197075197076197077197078197079197080197081197082197083197084197085197086197087197088197089197090197091197092197093197094197095197096197097197098197099197100197101197102197103197104197105197106197107197108197109197110197111197112197113197114197115197116197117197118197119197120197121197122197123197124197125197126197127197128197129197130197131197132197133197134197135197136197137197138197139197140197141197142197143197144197145197146197147197148197149197150197151197152197153197154197155197156197157197158197159197160197161197162197163197164197165197166197167197168197169197170197171197172197173197174197175197176197177197178197179197180197181197182197183197184197185197186197187197188197189197190197191197192197193197194197195197196197197197198197199197200197201197202197203197204197205197206197207197208197209197210197211197212197213197214197215197216197217197218197219197220197221197222197223197224197225197226197227197228197229197230197231197232197233197234197235197236197237197238197239197240197241197242197243197244197245197246197247197248197249197250197251197252197253197254197255197256197257197258197259197260197261197262197263197264197265197266197267197268197269197270197271197272197273197274197275197276197277197278197279197280197281197282197283197284197285197286197287197288197289197290197291197292197293197294197295197296197297197298197299197300197301197302197303197304197305197306197307197308197309197310197311197312197313197314197315197316197317197318197319197320197321197322197323197324197325197326197327197328197329197330197331197332197333197334197335197336197337197338197339197340197341197342197343197344197345197346197347197348197349197350197351197352197353197354197355197356197357197358197359197360197361197362197363197364197365197366197367197368197369197370197371197372197373197374197375197376197377197378197379197380197381197382197383197384197385197386197387197388197389197390197391197392197393197394197395197396197397197398197399197400197401197402197403197404197405197406197407197408197409197410197411197412197413197414197415197416197417197418197419197420197421197422197423197424197425197426197427197428197429197430197431197432197433197434197435197436197437197438197439197440197441197442197443197444197445197446197447197448197449197450197451197452197453197454197455197456197457197458197459197460197461197462197463197464197465197466197467197468197469197470197471197472197473197474197475197476197477197478197479197480197481197482197483197484197485197486197487197488197489197490197491197492197493197494197495197496197497197498197499197500197501197502197503197504197505197506197507197508197509197510197511197512197513197514197515197516197517197518197519197520197521197522197523197524197525197526197527197528197529197530197531197532197533197534197535197536197537197538197539197540197541197542197543197544197545197546197547197548197549197550197551197552197553197554197555197556197557197558197559197560197561197562197563197564197565197566197567197568197569197570197571197572197573197574197575197576197577197578197579197580197581197582197583197584197585197586197587197588197589197590197591197592197593197594197595197596197597197598197599197600197601197602197603197604197605197606197607197608197609197610197611197612197613197614197615197616197617197618197619197620197621197622197623197624197625197626197627197628197629197630197631197632197633197634197635197636197637197638197639197640197641197642197643197644197645197646197647197648197649197650197651197652197653197654197655197656197657197658197659197660197661197662197663197664197665197666197667197668197669197670197671197672197673197674197675197676197677197678197679197680197681197682197683197684197685197686197687197688197689197690197691197692197693197694197695197696197697197698197699197700197701197702197703197704197705197706197707197708197709197710197711197712197713197714197715197716197717197718197719197720197721197722197723197724197725197726197727197728197729197730197731197732197733197734197735197736197737197738197739197740197741197742197743197744197745197746197747197748197749197750197751197752197753197754197755197756197757197758197759197760197761197762197763197764197765197766197767197768197769197770197771197772197773197774197775197776197777197778197779197780197781197782197783197784197785197786197787197788197789197790197791197792197793197794197795197796197797197798197799197800197801197802197803197804197805197806197807197808197809197810197811197812197813197814197815197816197817197818197819197820197821197822197823197824197825197826197827197828197829197830197831197832197833197834197835197836197837197838197839197840197841197842197843197844197845197846197847197848197849197850197851197852197853197854197855197856197857197858197859197860197861197862197863197864197865197866197867197868197869197870197871197872197873197874197875197876197877197878197879197880197881197882197883197884197885197886197887197888197889197890197891197892197893197894197895197896197897197898197899197900197901197902197903197904197905197906197907197908197909197910197911197912197913197914197915197916197917197918197919197920197921197922197923197924197925197926197927197928197929197930197931197932197933197934197935197936197937197938197939197940197941197942197943197944197945197946197947197948197949197950197951197952197953197954197955197956197957197958197959197960197961197962197963197964197965197966197967197968197969197970197971197972197973197974197975197976197977197978197979197980197981197982197983197984197985197986197987197988197989197990197991197992197993197994197995197996197997197998197999198000198001198002198003198004198005198006198007198008198009198010198011198012198013198014198015198016198017198018198019198020198021198022198023198024198025198026198027198028198029198030198031198032198033198034198035198036198037198038198039198040198041198042198043198044198045198046198047198048198049198050198051198052198053198054198055198056198057198058198059198060198061198062198063198064198065198066198067198068198069198070198071198072198073198074198075198076198077198078198079198080198081198082198083198084198085198086198087198088198089198090198091198092198093198094198095198096198097198098198099198100198101198102198103198104198105198106198107198108198109198110198111198112198113198114198115198116198117198118198119198120198121198122198123198124198125198126198127198128198129198130198131198132198133198134198135198136198137198138198139198140198141198142198143198144198145198146198147198148198149198150198151198152198153198154198155198156198157198158198159198160198161198162198163198164198165198166198167198168198169198170198171198172198173198174198175198176198177198178198179198180198181198182198183198184198185198186198187198188198189198190198191198192198193198194198195198196198197198198198199198200198201198202198203198204198205198206198207198208198209198210198211198212198213198214198215198216198217198218198219198220198221198222198223198224198225198226198227198228198229198230198231198232198233198234198235198236198237198238198239198240198241198242198243198244198245198246198247198248198249198250198251198252198253198254198255198256198257198258198259198260198261198262198263198264198265198266198267198268198269198270198271198272198273198274198275198276198277198278198279198280198281198282198283198284198285198286198287198288198289198290198291198292198293198294198295198296198297198298198299198300198301198302198303198304198305198306198307198308198309198310198311198312198313198314198315198316198317198318198319198320198321198322198323198324198325198326198327198328198329198330198331198332198333198334198335198336198337198338198339198340198341198342198343198344198345198346198347198348198349198350198351198352198353198354198355198356198357198358198359198360198361198362198363198364198365198366198367198368198369198370198371198372198373198374198375198376198377198378198379198380198381198382198383198384198385198386198387198388198389198390198391198392198393198394198395198396198397198398198399198400198401198402198403198404198405198406198407198408198409198410198411198412198413198414198415198416198417198418198419198420198421198422198423198424198425198426198427198428198429198430198431198432198433198434198435198436198437198438198439198440198441198442198443198444198445198446198447198448198449198450198451198452198453198454198455198456198457198458198459198460198461198462198463198464198465198466198467198468198469198470198471198472198473198474198475198476198477198478198479198480198481198482198483198484198485198486198487198488198489198490198491198492198493198494198495198496198497198498198499198500198501198502198503198504198505198506198507198508198509198510198511198512198513198514198515198516198517198518198519198520198521198522198523198524198525198526198527198528198529198530198531198532198533198534198535198536198537198538198539198540198541198542198543198544198545198546198547198548198549198550198551198552198553198554198555198556198557198558198559198560198561198562198563198564198565198566198567198568198569198570198571198572198573198574198575198576198577198578198579198580198581198582198583198584198585198586198587198588198589198590198591198592198593198594198595198596198597198598198599198600198601198602198603198604198605198606198607198608198609198610198611198612198613198614198615198616198617198618198619198620198621198622198623198624198625198626198627198628198629198630198631198632198633198634198635198636198637198638198639198640198641198642198643198644198645198646198647198648198649198650198651198652198653198654198655198656198657198658198659198660198661198662198663198664198665198666198667198668198669198670198671198672198673198674198675198676198677198678198679198680198681198682198683198684198685198686198687198688198689198690198691198692198693198694198695198696198697198698198699198700198701198702198703198704198705198706198707198708198709198710198711198712198713198714198715198716198717198718198719198720198721198722198723198724198725198726198727198728198729198730198731198732198733198734198735198736198737198738198739198740198741198742198743198744198745198746198747198748198749198750198751198752198753198754198755198756198757198758198759198760198761198762198763198764198765198766198767198768198769198770198771198772198773198774198775198776198777198778198779198780198781198782198783198784198785198786198787198788198789198790198791198792198793198794198795198796198797198798198799198800198801198802198803198804198805198806198807198808198809198810198811198812198813198814198815198816198817198818198819198820198821198822198823198824198825198826198827198828198829198830198831198832198833198834198835198836198837198838198839198840198841198842198843198844198845198846198847198848198849198850198851198852198853198854198855198856198857198858198859198860198861198862198863198864198865198866198867198868198869198870198871198872198873198874198875198876198877198878198879198880198881198882198883198884198885198886198887198888198889198890198891198892198893198894198895198896198897198898198899198900198901198902198903198904198905198906198907198908198909198910198911198912198913198914198915198916198917198918198919198920198921198922198923198924198925198926198927198928198929198930198931198932198933198934198935198936198937198938198939198940198941198942198943198944198945198946198947198948198949198950198951198952198953198954198955198956198957198958198959198960198961198962198963198964198965198966198967198968198969198970198971198972198973198974198975198976198977198978198979198980198981198982198983198984198985198986198987198988198989198990198991198992198993198994198995198996198997198998198999199000199001199002199003199004199005199006199007199008199009199010199011199012199013199014199015199016199017199018199019199020199021199022199023199024199025199026199027199028199029199030199031199032199033199034199035199036199037199038199039199040199041199042199043199044199045199046199047199048199049199050199051199052199053199054199055199056199057199058199059199060199061199062199063199064199065199066199067199068199069199070199071199072199073199074199075199076199077199078199079199080199081199082199083199084199085199086199087199088199089199090199091199092199093199094199095199096199097199098199099199100199101199102199103199104199105199106199107199108199109199110199111199112199113199114199115199116199117199118199119199120199121199122199123199124199125199126199127199128199129199130199131199132199133199134199135199136199137199138199139199140199141199142199143199144199145199146199147199148199149199150199151199152199153199154199155199156199157199158199159199160199161199162199163199164199165199166199167199168199169199170199171199172199173199174199175199176199177199178199179199180199181199182199183199184199185199186199187199188199189199190199191199192199193199194199195199196199197199198199199199200199201199202199203199204199205199206199207199208199209199210199211199212199213199214199215199216199217199218199219199220199221199222199223199224199225199226199227199228199229199230199231199232199233199234199235199236199237199238199239199240199241199242199243199244199245199246199247199248199249199250199251199252199253199254199255199256199257199258199259199260199261199262199263199264199265199266199267199268199269199270199271199272199273199274199275199276199277199278199279199280199281199282199283199284199285199286199287199288199289199290199291199292199293199294199295199296199297199298199299199300199301199302199303199304199305199306199307199308199309199310199311199312199313199314199315199316199317199318199319199320199321199322199323199324199325199326199327199328199329199330199331199332199333199334199335199336199337199338199339199340199341199342199343199344199345199346199347199348199349199350199351199352199353199354199355199356199357199358199359199360199361199362199363199364199365199366199367199368199369199370199371199372199373199374199375199376199377199378199379199380199381199382199383199384199385199386199387199388199389199390199391199392199393199394199395199396199397199398199399199400199401199402199403199404199405199406199407199408199409199410199411199412199413199414199415199416199417199418199419199420199421199422199423199424199425199426199427199428199429199430199431199432199433199434199435199436199437199438199439199440199441199442199443199444199445199446199447199448199449199450199451199452199453199454199455199456199457199458199459199460199461199462199463199464199465199466199467199468199469199470199471199472199473199474199475199476199477199478199479199480199481199482199483199484199485199486199487199488199489199490199491199492199493199494199495199496199497199498199499199500199501199502199503199504199505199506199507199508199509199510199511199512199513199514199515199516199517199518199519199520199521199522199523199524199525199526199527199528199529199530199531199532199533199534199535199536199537199538199539199540199541199542199543199544199545199546199547199548199549199550199551199552199553199554199555199556199557199558199559199560199561199562199563199564199565199566199567199568199569199570199571199572199573199574199575199576199577199578199579199580199581199582199583199584199585199586199587199588199589199590199591199592199593199594199595199596199597199598199599199600199601199602199603199604199605199606199607199608199609199610199611199612199613199614199615199616199617199618199619199620199621199622199623199624199625199626199627199628199629199630199631199632199633199634199635199636199637199638199639199640199641199642199643199644199645199646199647199648199649199650199651199652199653199654199655199656199657199658199659199660199661199662199663199664199665199666199667199668199669199670199671199672199673199674199675199676199677199678199679199680199681199682199683199684199685199686199687199688199689199690199691199692199693199694199695199696199697199698199699199700199701199702199703199704199705199706199707199708199709199710199711199712199713199714199715199716199717199718199719199720199721199722199723199724199725199726199727199728199729199730199731199732199733199734199735199736199737199738199739199740199741199742199743199744199745199746199747199748199749199750199751199752199753199754199755199756199757199758199759199760199761199762199763199764199765199766199767199768199769199770199771199772199773199774199775199776199777199778199779199780199781199782199783199784199785199786199787199788199789199790199791199792199793199794199795199796199797199798199799199800199801199802199803199804199805199806199807199808199809199810199811199812199813199814199815199816199817199818199819199820199821199822199823199824199825199826199827199828199829199830199831199832199833199834199835199836199837199838199839199840199841199842199843199844199845199846199847199848199849199850199851199852199853199854199855199856199857199858199859199860199861199862199863199864199865199866199867199868199869199870199871199872199873199874199875199876199877199878199879199880199881199882199883199884199885199886199887199888199889199890199891199892199893199894199895199896199897199898199899199900199901199902199903199904199905199906199907199908199909199910199911199912199913199914199915199916199917199918199919199920199921199922199923199924199925199926199927199928199929199930199931199932199933199934199935199936199937199938199939199940199941199942199943199944199945199946199947199948199949199950199951199952199953199954199955199956199957199958199959199960199961199962199963199964199965199966199967199968199969199970199971199972199973199974199975199976199977199978199979199980199981199982199983199984199985199986199987199988199989199990199991199992199993199994199995199996199997199998199999200000200001200002200003200004200005200006200007200008200009200010200011200012200013200014200015200016200017200018200019200020200021200022200023200024200025200026200027200028200029200030200031200032200033200034200035200036200037200038200039200040200041200042200043200044200045200046200047200048200049200050200051200052200053200054200055200056200057200058200059200060200061200062200063200064200065200066200067200068200069200070200071200072200073200074200075200076200077200078200079200080200081200082200083200084200085200086200087200088200089200090200091200092200093200094200095200096200097200098200099200100200101200102200103200104200105200106200107200108200109200110200111200112200113200114200115200116200117200118200119200120200121200122200123200124200125200126200127200128200129200130200131200132200133200134200135200136200137200138200139200140200141200142200143200144200145200146200147200148200149200150200151200152200153200154200155200156200157200158200159200160200161200162200163200164200165200166200167200168200169200170200171200172200173200174200175200176200177200178200179200180200181200182200183200184200185200186200187200188200189200190200191200192200193200194200195200196200197200198200199200200200201200202200203200204200205200206200207200208200209200210200211200212200213200214200215200216200217200218200219200220200221200222200223200224200225200226200227200228200229200230200231200232200233200234200235200236200237200238200239200240200241200242200243200244200245200246200247200248200249200250200251200252200253200254200255200256200257200258200259200260200261200262200263200264200265200266200267200268200269200270200271200272200273200274200275200276200277200278200279200280200281200282200283200284200285200286200287200288200289200290200291200292200293200294200295200296200297200298200299200300200301200302200303200304200305200306200307200308200309200310200311200312200313200314200315200316200317200318200319200320200321200322200323200324200325200326200327200328200329200330200331200332200333200334200335200336200337200338200339200340200341200342200343200344200345200346200347200348200349200350200351200352200353200354200355200356200357200358200359200360200361200362200363200364200365200366200367200368200369200370200371200372200373200374200375200376200377200378200379200380200381200382200383200384200385200386200387200388200389200390200391200392200393200394200395200396200397200398200399200400200401200402200403200404200405200406200407200408200409200410200411200412200413200414200415200416200417200418200419200420200421200422200423200424200425200426200427200428200429200430200431200432200433200434200435200436200437200438200439200440200441200442200443200444200445200446200447200448200449200450200451200452200453200454200455200456200457200458200459200460200461200462200463200464200465200466200467200468200469200470200471200472200473200474200475200476200477200478200479200480200481200482200483200484200485200486200487200488200489200490200491200492200493200494200495200496200497200498200499200500200501200502200503200504200505200506200507200508200509200510200511200512200513200514200515200516200517200518200519200520200521200522200523200524200525200526200527200528200529200530200531200532200533200534200535200536200537200538200539200540200541200542200543200544200545200546200547200548200549200550200551200552200553200554200555200556200557200558200559200560200561200562200563200564200565200566200567200568200569200570200571200572200573200574200575200576200577200578200579200580200581200582200583200584200585200586200587200588200589200590200591200592200593200594200595200596200597200598200599200600200601200602200603200604200605200606200607200608200609200610200611200612200613200614200615200616200617200618200619200620200621200622200623200624200625200626200627200628200629200630200631200632200633200634200635200636200637200638200639200640200641200642200643200644200645200646200647200648200649200650200651200652200653200654200655200656200657200658200659200660200661200662200663200664200665200666200667200668200669200670200671200672200673200674200675200676200677200678200679200680200681200682200683200684200685200686200687200688200689200690200691200692200693200694200695200696200697200698200699200700200701200702200703200704200705200706200707200708200709200710200711200712200713200714200715200716200717200718200719200720200721200722200723200724200725200726200727200728200729200730200731200732200733200734200735200736200737200738200739200740200741200742200743200744200745200746200747200748200749200750200751200752200753200754200755200756200757200758200759200760200761200762200763200764200765200766200767200768200769200770200771200772200773200774200775200776200777200778200779200780200781200782200783200784200785200786200787200788200789200790200791200792200793200794200795200796200797200798200799200800200801200802200803200804200805200806200807200808200809200810200811200812200813200814200815200816200817200818200819200820200821200822200823200824200825200826200827200828200829200830200831200832200833200834200835200836200837200838200839200840200841200842200843200844200845200846200847200848200849200850200851200852200853200854200855200856200857200858200859200860200861200862200863200864200865200866200867200868200869200870200871200872200873200874200875200876200877200878200879200880200881200882200883200884200885200886200887200888200889200890200891200892200893200894200895200896200897200898200899200900200901200902200903200904200905200906200907200908200909200910200911200912200913200914200915200916200917200918200919200920200921200922200923200924200925200926200927200928200929200930200931200932200933200934200935200936200937200938200939200940200941200942200943200944200945200946200947200948200949200950200951200952200953200954200955200956200957200958200959200960200961200962200963200964200965200966200967200968200969200970200971200972200973200974200975200976200977200978200979200980200981200982200983200984200985200986200987200988200989200990200991200992200993200994200995200996200997200998200999201000201001201002201003201004201005201006201007201008201009201010201011201012201013201014201015201016201017201018201019201020201021201022201023201024201025201026201027201028201029201030201031201032201033201034201035201036201037201038201039201040201041201042201043201044201045201046201047201048201049201050201051201052201053201054201055201056201057201058201059201060201061201062201063201064201065201066201067201068201069201070201071201072201073201074201075201076201077201078201079201080201081201082201083201084201085201086201087201088201089201090201091201092201093201094201095201096201097201098201099201100201101201102201103201104201105201106201107201108201109201110201111201112201113201114201115201116201117201118201119201120201121201122201123201124201125201126201127201128201129201130201131201132201133201134201135201136201137201138201139201140201141201142201143201144201145201146201147201148201149201150201151201152201153201154201155201156201157201158201159201160201161201162201163201164201165201166201167201168201169201170201171201172201173201174201175201176201177201178201179201180201181201182201183201184201185201186201187201188201189201190201191201192201193201194201195201196201197201198201199201200201201201202201203201204201205201206201207201208201209201210201211201212201213201214201215201216201217201218201219201220201221201222201223201224201225201226201227201228201229201230201231201232201233201234201235201236201237201238201239201240201241201242201243201244201245201246201247201248201249201250201251201252201253201254201255201256201257201258201259201260201261201262201263201264201265201266201267201268201269201270201271201272201273201274201275201276201277201278201279201280201281201282201283201284201285201286201287201288201289201290201291201292201293201294201295201296201297201298201299201300201301201302201303201304201305201306201307201308201309201310201311201312201313201314201315201316201317201318201319201320201321201322201323201324201325201326201327201328201329201330201331201332201333201334201335201336201337201338201339201340201341201342201343201344201345201346201347201348201349201350201351201352201353201354201355201356201357201358201359201360201361201362201363201364201365201366201367201368201369201370201371201372201373201374201375201376201377201378201379201380201381201382201383201384201385201386201387201388201389201390201391201392201393201394201395201396201397201398201399201400201401201402201403201404201405201406201407201408201409201410201411201412201413201414201415201416201417201418201419201420201421201422201423201424201425201426201427201428201429201430201431201432201433201434201435201436201437201438201439201440201441201442201443201444201445201446201447201448201449201450201451201452201453201454201455201456201457201458201459201460201461201462201463201464201465201466201467201468201469201470201471201472201473201474201475201476201477201478201479201480201481201482201483201484201485201486201487201488201489201490201491201492201493201494201495201496201497201498201499201500201501201502201503201504201505201506201507201508201509201510201511201512201513201514201515201516201517201518201519201520201521201522201523201524201525201526201527201528201529201530201531201532201533201534201535201536201537201538201539201540201541201542201543201544201545201546201547201548201549201550201551201552201553201554201555201556201557201558201559201560201561201562201563201564201565201566201567201568201569201570201571201572201573201574201575201576201577201578201579201580201581201582201583201584201585201586201587201588201589201590201591201592201593201594201595201596201597201598201599201600201601201602201603201604201605201606201607201608201609201610201611201612201613201614201615201616201617201618201619201620201621201622201623201624201625201626201627201628201629201630201631201632201633201634201635201636201637201638201639201640201641201642201643201644201645201646201647201648201649201650201651201652201653201654201655201656201657201658201659201660201661201662201663201664201665201666201667201668201669201670201671201672201673201674201675201676201677201678201679201680201681201682201683201684201685201686201687201688201689201690201691201692201693201694201695201696201697201698201699201700201701201702201703201704201705201706201707201708201709201710201711201712201713201714201715201716201717201718201719201720201721201722201723201724201725201726201727201728201729201730201731201732201733201734201735201736201737201738201739201740201741201742201743201744201745201746201747201748201749201750201751201752201753201754201755201756201757201758201759201760201761201762201763201764201765201766201767201768201769201770201771201772201773201774201775201776201777201778201779201780201781201782201783201784201785201786201787201788201789201790201791201792201793201794201795201796201797201798201799201800201801201802201803201804201805201806201807201808201809201810201811201812201813201814201815201816201817201818201819201820201821201822201823201824201825201826201827201828201829201830201831201832201833201834201835201836201837201838201839201840201841201842201843201844201845201846201847201848201849201850201851201852201853201854201855201856201857201858201859201860201861201862201863201864201865201866201867201868201869201870201871201872201873201874201875201876201877201878201879201880201881201882201883201884201885201886201887201888201889201890201891201892201893201894201895201896201897201898201899201900201901201902201903201904201905201906201907201908201909201910201911201912201913201914201915201916201917201918201919201920201921201922201923201924201925201926201927201928201929201930201931201932201933201934201935201936201937201938201939201940201941201942201943201944201945201946201947201948201949201950201951201952201953201954201955201956201957201958201959201960201961201962201963201964201965201966201967201968201969201970201971201972201973201974201975201976201977201978201979201980201981201982201983201984201985201986201987201988201989201990201991201992201993201994201995201996201997201998201999202000202001202002202003202004202005202006202007202008202009202010202011202012202013202014202015202016202017202018202019202020202021202022202023202024202025202026202027202028202029202030202031202032202033202034202035202036202037202038202039202040202041202042202043202044202045202046202047202048202049202050202051202052202053202054202055202056202057202058202059202060202061202062202063202064202065202066202067202068202069202070202071202072202073202074202075202076202077202078202079202080202081202082202083202084202085202086202087202088202089202090202091202092202093202094202095202096202097202098202099202100202101202102202103202104202105202106202107202108202109202110202111202112202113202114202115202116202117202118202119202120202121202122202123202124202125202126202127202128202129202130202131202132202133202134202135202136202137202138202139202140202141202142202143202144202145202146202147202148202149202150202151202152202153202154202155202156202157202158202159202160202161202162202163202164202165202166202167202168202169202170202171202172202173202174202175202176202177202178202179202180202181202182202183202184202185202186202187202188202189202190202191202192202193202194202195202196202197202198202199202200202201202202202203202204202205202206202207202208202209202210202211202212202213202214202215202216202217202218202219202220202221202222202223202224202225202226202227202228202229202230202231202232202233202234202235202236202237202238202239202240202241202242202243202244202245202246202247202248202249202250202251202252202253202254202255202256202257202258202259202260202261202262202263202264202265202266202267202268202269202270202271202272202273202274202275202276202277202278202279202280202281202282202283202284202285202286202287202288202289202290202291202292202293202294202295202296202297202298202299202300202301202302202303202304202305202306202307202308202309202310202311202312202313202314202315202316202317202318202319202320202321202322202323202324202325202326202327202328202329202330202331202332202333202334202335202336202337202338202339202340202341202342202343202344202345202346202347202348202349202350202351202352202353202354202355202356202357202358202359202360202361202362202363202364202365202366202367202368202369202370202371202372202373202374202375202376202377202378202379202380202381202382202383202384202385202386202387202388202389202390202391202392202393202394202395202396202397202398202399202400202401202402202403202404202405202406202407202408202409202410202411202412202413202414202415202416202417202418202419202420202421202422202423202424202425202426202427202428202429202430202431202432202433202434202435202436202437202438202439202440202441202442202443202444202445202446202447202448202449202450202451202452202453202454202455202456202457202458202459202460202461202462202463202464202465202466202467202468202469202470202471202472202473202474202475202476202477202478202479202480202481202482202483202484202485202486202487202488202489202490202491202492202493202494202495202496202497202498202499202500202501202502202503202504202505202506202507202508202509202510202511202512202513202514202515202516202517202518202519202520202521202522202523202524202525202526202527202528202529202530202531202532202533202534202535202536202537202538202539202540202541202542202543202544202545202546202547202548202549202550202551202552202553202554202555202556202557202558202559202560202561202562202563202564202565202566202567202568202569202570202571202572202573202574202575202576202577202578202579202580202581202582202583202584202585202586202587202588202589202590202591202592202593202594202595202596202597202598202599202600202601202602202603202604202605202606202607202608202609202610202611202612202613202614202615202616202617202618202619202620202621202622202623202624202625202626202627202628202629202630202631202632202633202634202635202636202637202638202639202640202641202642202643202644202645202646202647202648202649202650202651202652202653202654202655202656202657202658202659202660202661202662202663202664202665202666202667202668202669202670202671202672202673202674202675202676202677202678202679202680202681202682202683202684202685202686202687202688202689202690202691202692202693202694202695202696202697202698202699202700202701202702202703202704202705202706202707202708202709202710202711202712202713202714202715202716202717202718202719202720202721202722202723202724202725202726202727202728202729202730202731202732202733202734202735202736202737202738202739202740202741202742202743202744202745202746202747202748202749202750202751202752202753202754202755202756202757202758202759202760202761202762202763202764202765202766202767202768202769202770202771202772202773202774202775202776202777202778202779202780202781202782202783202784202785202786202787202788202789202790202791202792202793202794202795202796202797202798202799202800202801202802202803202804202805202806202807202808202809202810202811202812202813202814202815202816202817202818202819202820202821202822202823202824202825202826202827202828202829202830202831202832202833202834202835202836202837202838202839202840202841202842202843202844202845202846202847202848202849202850202851202852202853202854202855202856202857202858202859202860202861202862202863202864202865202866202867202868202869202870202871202872202873202874202875202876202877202878202879202880202881202882202883202884202885202886202887202888202889202890202891202892202893202894202895202896202897202898202899202900202901202902202903202904202905202906202907202908202909202910202911202912202913202914202915202916202917202918
  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. /************** Begin file msvc.h ********************************************/
  90. /*
  91. ** 2015 January 12
  92. **
  93. ** The author disclaims copyright to this source code. In place of
  94. ** a legal notice, here is a blessing:
  95. **
  96. ** May you do good and not evil.
  97. ** May you find forgiveness for yourself and forgive others.
  98. ** May you share freely, never taking more than you give.
  99. **
  100. ******************************************************************************
  101. **
  102. ** This file contains code that is specific to MSVC.
  103. */
  104. #ifndef SQLITE_MSVC_H
  105. #define SQLITE_MSVC_H
  106. #if defined(_MSC_VER)
  107. #pragma warning(disable : 4054)
  108. #pragma warning(disable : 4055)
  109. #pragma warning(disable : 4100)
  110. #pragma warning(disable : 4127)
  111. #pragma warning(disable : 4130)
  112. #pragma warning(disable : 4152)
  113. #pragma warning(disable : 4189)
  114. #pragma warning(disable : 4206)
  115. #pragma warning(disable : 4210)
  116. #pragma warning(disable : 4232)
  117. #pragma warning(disable : 4244)
  118. #pragma warning(disable : 4305)
  119. #pragma warning(disable : 4306)
  120. #pragma warning(disable : 4702)
  121. #pragma warning(disable : 4706)
  122. #endif /* defined(_MSC_VER) */
  123. #endif /* SQLITE_MSVC_H */
  124. /************** End of msvc.h ************************************************/
  125. /************** Continuing where we left off in sqliteInt.h ******************/
  126. /*
  127. ** Special setup for VxWorks
  128. */
  129. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  130. /************** Begin file vxworks.h *****************************************/
  131. /*
  132. ** 2015-03-02
  133. **
  134. ** The author disclaims copyright to this source code. In place of
  135. ** a legal notice, here is a blessing:
  136. **
  137. ** May you do good and not evil.
  138. ** May you find forgiveness for yourself and forgive others.
  139. ** May you share freely, never taking more than you give.
  140. **
  141. ******************************************************************************
  142. **
  143. ** This file contains code that is specific to Wind River's VxWorks
  144. */
  145. #if defined(__RTP__) || defined(_WRS_KERNEL)
  146. /* This is VxWorks. Set up things specially for that OS
  147. */
  148. #include <vxWorks.h>
  149. #include <pthread.h> /* amalgamator: dontcache */
  150. #define OS_VXWORKS 1
  151. #define SQLITE_OS_OTHER 0
  152. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  153. #define SQLITE_OMIT_LOAD_EXTENSION 1
  154. #define SQLITE_ENABLE_LOCKING_STYLE 0
  155. #define HAVE_UTIME 1
  156. #else
  157. /* This is not VxWorks. */
  158. #define OS_VXWORKS 0
  159. #define HAVE_FCHOWN 1
  160. #define HAVE_READLINK 1
  161. #define HAVE_LSTAT 1
  162. #endif /* defined(_WRS_KERNEL) */
  163. /************** End of vxworks.h *********************************************/
  164. /************** Continuing where we left off in sqliteInt.h ******************/
  165. /*
  166. ** These #defines should enable >2GB file support on POSIX if the
  167. ** underlying operating system supports it. If the OS lacks
  168. ** large file support, or if the OS is windows, these should be no-ops.
  169. **
  170. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  171. ** system #includes. Hence, this block of code must be the very first
  172. ** code in all source files.
  173. **
  174. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  175. ** on the compiler command line. This is necessary if you are compiling
  176. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  177. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  178. ** without this option, LFS is enable. But LFS does not exist in the kernel
  179. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  180. ** portability you should omit LFS.
  181. **
  182. ** The previous paragraph was written in 2005. (This paragraph is written
  183. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  184. ** you should probably leave LFS enabled. But some embedded platforms might
  185. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  186. **
  187. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  188. */
  189. #ifndef SQLITE_DISABLE_LFS
  190. # define _LARGE_FILE 1
  191. # ifndef _FILE_OFFSET_BITS
  192. # define _FILE_OFFSET_BITS 64
  193. # endif
  194. # define _LARGEFILE_SOURCE 1
  195. #endif
  196. /* The GCC_VERSION and MSVC_VERSION macros are used to
  197. ** conditionally include optimizations for each of these compilers. A
  198. ** value of 0 means that compiler is not being used. The
  199. ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  200. ** optimizations, and hence set all compiler macros to 0
  201. **
  202. ** There was once also a CLANG_VERSION macro. However, we learn that the
  203. ** version numbers in clang are for "marketing" only and are inconsistent
  204. ** and unreliable. Fortunately, all versions of clang also recognize the
  205. ** gcc version numbers and have reasonable settings for gcc version numbers,
  206. ** so the GCC_VERSION macro will be set to a correct non-zero value even
  207. ** when compiling with clang.
  208. */
  209. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  210. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  211. #else
  212. # define GCC_VERSION 0
  213. #endif
  214. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  215. # define MSVC_VERSION _MSC_VER
  216. #else
  217. # define MSVC_VERSION 0
  218. #endif
  219. /* Needed for various definitions... */
  220. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  221. # define _GNU_SOURCE
  222. #endif
  223. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  224. # define _BSD_SOURCE
  225. #endif
  226. /*
  227. ** For MinGW, check to see if we can include the header file containing its
  228. ** version information, among other things. Normally, this internal MinGW
  229. ** header file would [only] be included automatically by other MinGW header
  230. ** files; however, the contained version information is now required by this
  231. ** header file to work around binary compatibility issues (see below) and
  232. ** this is the only known way to reliably obtain it. This entire #if block
  233. ** would be completely unnecessary if there was any other way of detecting
  234. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  235. ** some MinGW-specific macros). When compiling for MinGW, either the
  236. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  237. ** defined; otherwise, detection of conditions specific to MinGW will be
  238. ** disabled.
  239. */
  240. #if defined(_HAVE_MINGW_H)
  241. # include "mingw.h"
  242. #elif defined(_HAVE__MINGW_H)
  243. # include "_mingw.h"
  244. #endif
  245. /*
  246. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  247. ** define is required to maintain binary compatibility with the MSVC runtime
  248. ** library in use (e.g. for Windows XP).
  249. */
  250. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  251. defined(_WIN32) && !defined(_WIN64) && \
  252. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  253. defined(__MSVCRT__)
  254. # define _USE_32BIT_TIME_T
  255. #endif
  256. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  257. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  258. ** MinGW.
  259. */
  260. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  261. /************** Begin file sqlite3.h *****************************************/
  262. /*
  263. ** 2001 September 15
  264. **
  265. ** The author disclaims copyright to this source code. In place of
  266. ** a legal notice, here is a blessing:
  267. **
  268. ** May you do good and not evil.
  269. ** May you find forgiveness for yourself and forgive others.
  270. ** May you share freely, never taking more than you give.
  271. **
  272. *************************************************************************
  273. ** This header file defines the interface that the SQLite library
  274. ** presents to client programs. If a C-function, structure, datatype,
  275. ** or constant definition does not appear in this file, then it is
  276. ** not a published API of SQLite, is subject to change without
  277. ** notice, and should not be referenced by programs that use SQLite.
  278. **
  279. ** Some of the definitions that are in this file are marked as
  280. ** "experimental". Experimental interfaces are normally new
  281. ** features recently added to SQLite. We do not anticipate changes
  282. ** to experimental interfaces but reserve the right to make minor changes
  283. ** if experience from use "in the wild" suggest such changes are prudent.
  284. **
  285. ** The official C-language API documentation for SQLite is derived
  286. ** from comments in this file. This file is the authoritative source
  287. ** on how SQLite interfaces are supposed to operate.
  288. **
  289. ** The name of this file under configuration management is "sqlite.h.in".
  290. ** The makefile makes some minor changes to this file (such as inserting
  291. ** the version number) and changes its name to "sqlite3.h" as
  292. ** part of the build process.
  293. */
  294. #ifndef SQLITE3_H
  295. #define SQLITE3_H
  296. #include <stdarg.h> /* Needed for the definition of va_list */
  297. /*
  298. ** Make sure we can call this stuff from C++.
  299. */
  300. #if 0
  301. extern "C" {
  302. #endif
  303. /*
  304. ** Provide the ability to override linkage features of the interface.
  305. */
  306. #ifndef SQLITE_EXTERN
  307. # define SQLITE_EXTERN extern
  308. #endif
  309. #ifndef SQLITE_API
  310. # define SQLITE_API
  311. #endif
  312. #ifndef SQLITE_CDECL
  313. # define SQLITE_CDECL
  314. #endif
  315. #ifndef SQLITE_APICALL
  316. # define SQLITE_APICALL
  317. #endif
  318. #ifndef SQLITE_STDCALL
  319. # define SQLITE_STDCALL SQLITE_APICALL
  320. #endif
  321. #ifndef SQLITE_CALLBACK
  322. # define SQLITE_CALLBACK
  323. #endif
  324. #ifndef SQLITE_SYSAPI
  325. # define SQLITE_SYSAPI
  326. #endif
  327. /*
  328. ** These no-op macros are used in front of interfaces to mark those
  329. ** interfaces as either deprecated or experimental. New applications
  330. ** should not use deprecated interfaces - they are supported for backwards
  331. ** compatibility only. Application writers should be aware that
  332. ** experimental interfaces are subject to change in point releases.
  333. **
  334. ** These macros used to resolve to various kinds of compiler magic that
  335. ** would generate warning messages when they were used. But that
  336. ** compiler magic ended up generating such a flurry of bug reports
  337. ** that we have taken it all out and gone back to using simple
  338. ** noop macros.
  339. */
  340. #define SQLITE_DEPRECATED
  341. #define SQLITE_EXPERIMENTAL
  342. /*
  343. ** Ensure these symbols were not defined by some previous header file.
  344. */
  345. #ifdef SQLITE_VERSION
  346. # undef SQLITE_VERSION
  347. #endif
  348. #ifdef SQLITE_VERSION_NUMBER
  349. # undef SQLITE_VERSION_NUMBER
  350. #endif
  351. /*
  352. ** CAPI3REF: Compile-Time Library Version Numbers
  353. **
  354. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  355. ** evaluates to a string literal that is the SQLite version in the
  356. ** format "X.Y.Z" where X is the major version number (always 3 for
  357. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  358. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  359. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  360. ** numbers used in [SQLITE_VERSION].)^
  361. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  362. ** be larger than the release from which it is derived. Either Y will
  363. ** be held constant and Z will be incremented or else Y will be incremented
  364. ** and Z will be reset to zero.
  365. **
  366. ** Since [version 3.6.18] ([dateof:3.6.18]),
  367. ** SQLite source code has been stored in the
  368. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  369. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  370. ** a string which identifies a particular check-in of SQLite
  371. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  372. ** string contains the date and time of the check-in (UTC) and a SHA1
  373. ** or SHA3-256 hash of the entire source tree.
  374. **
  375. ** See also: [sqlite3_libversion()],
  376. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  377. ** [sqlite_version()] and [sqlite_source_id()].
  378. */
  379. #define SQLITE_VERSION "3.19.3"
  380. #define SQLITE_VERSION_NUMBER 3019003
  381. #define SQLITE_SOURCE_ID "2017-06-08 14:26:16 0ee482a1e0eae22e08edc8978c9733a96603d4509645f348ebf55b579e89636b"
  382. /*
  383. ** CAPI3REF: Run-Time Library Version Numbers
  384. ** KEYWORDS: sqlite3_version sqlite3_sourceid
  385. **
  386. ** These interfaces provide the same information as the [SQLITE_VERSION],
  387. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  388. ** but are associated with the library instead of the header file. ^(Cautious
  389. ** programmers might include assert() statements in their application to
  390. ** verify that values returned by these interfaces match the macros in
  391. ** the header, and thus ensure that the application is
  392. ** compiled with matching library and header files.
  393. **
  394. ** <blockquote><pre>
  395. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  396. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  397. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  398. ** </pre></blockquote>)^
  399. **
  400. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  401. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  402. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  403. ** function is provided for use in DLLs since DLL users usually do not have
  404. ** direct access to string constants within the DLL. ^The
  405. ** sqlite3_libversion_number() function returns an integer equal to
  406. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  407. ** a pointer to a string constant whose value is the same as the
  408. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  409. **
  410. ** See also: [sqlite_version()] and [sqlite_source_id()].
  411. */
  412. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  413. SQLITE_API const char *sqlite3_libversion(void);
  414. SQLITE_API const char *sqlite3_sourceid(void);
  415. SQLITE_API int sqlite3_libversion_number(void);
  416. /*
  417. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  418. **
  419. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  420. ** indicating whether the specified option was defined at
  421. ** compile time. ^The SQLITE_ prefix may be omitted from the
  422. ** option name passed to sqlite3_compileoption_used().
  423. **
  424. ** ^The sqlite3_compileoption_get() function allows iterating
  425. ** over the list of options that were defined at compile time by
  426. ** returning the N-th compile time option string. ^If N is out of range,
  427. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  428. ** prefix is omitted from any strings returned by
  429. ** sqlite3_compileoption_get().
  430. **
  431. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  432. ** and sqlite3_compileoption_get() may be omitted by specifying the
  433. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  434. **
  435. ** See also: SQL functions [sqlite_compileoption_used()] and
  436. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  437. */
  438. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  439. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  440. SQLITE_API const char *sqlite3_compileoption_get(int N);
  441. #endif
  442. /*
  443. ** CAPI3REF: Test To See If The Library Is Threadsafe
  444. **
  445. ** ^The sqlite3_threadsafe() function returns zero if and only if
  446. ** SQLite was compiled with mutexing code omitted due to the
  447. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  448. **
  449. ** SQLite can be compiled with or without mutexes. When
  450. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  451. ** are enabled and SQLite is threadsafe. When the
  452. ** [SQLITE_THREADSAFE] macro is 0,
  453. ** the mutexes are omitted. Without the mutexes, it is not safe
  454. ** to use SQLite concurrently from more than one thread.
  455. **
  456. ** Enabling mutexes incurs a measurable performance penalty.
  457. ** So if speed is of utmost importance, it makes sense to disable
  458. ** the mutexes. But for maximum safety, mutexes should be enabled.
  459. ** ^The default behavior is for mutexes to be enabled.
  460. **
  461. ** This interface can be used by an application to make sure that the
  462. ** version of SQLite that it is linking against was compiled with
  463. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  464. **
  465. ** This interface only reports on the compile-time mutex setting
  466. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  467. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  468. ** can be fully or partially disabled using a call to [sqlite3_config()]
  469. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  470. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  471. ** sqlite3_threadsafe() function shows only the compile-time setting of
  472. ** thread safety, not any run-time changes to that setting made by
  473. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  474. ** is unchanged by calls to sqlite3_config().)^
  475. **
  476. ** See the [threading mode] documentation for additional information.
  477. */
  478. SQLITE_API int sqlite3_threadsafe(void);
  479. /*
  480. ** CAPI3REF: Database Connection Handle
  481. ** KEYWORDS: {database connection} {database connections}
  482. **
  483. ** Each open SQLite database is represented by a pointer to an instance of
  484. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  485. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  486. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  487. ** and [sqlite3_close_v2()] are its destructors. There are many other
  488. ** interfaces (such as
  489. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  490. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  491. ** sqlite3 object.
  492. */
  493. typedef struct sqlite3 sqlite3;
  494. /*
  495. ** CAPI3REF: 64-Bit Integer Types
  496. ** KEYWORDS: sqlite_int64 sqlite_uint64
  497. **
  498. ** Because there is no cross-platform way to specify 64-bit integer types
  499. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  500. **
  501. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  502. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  503. ** compatibility only.
  504. **
  505. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  506. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  507. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  508. ** between 0 and +18446744073709551615 inclusive.
  509. */
  510. #ifdef SQLITE_INT64_TYPE
  511. typedef SQLITE_INT64_TYPE sqlite_int64;
  512. # ifdef SQLITE_UINT64_TYPE
  513. typedef SQLITE_UINT64_TYPE sqlite_uint64;
  514. # else
  515. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  516. # endif
  517. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  518. typedef __int64 sqlite_int64;
  519. typedef unsigned __int64 sqlite_uint64;
  520. #else
  521. typedef long long int sqlite_int64;
  522. typedef unsigned long long int sqlite_uint64;
  523. #endif
  524. typedef sqlite_int64 sqlite3_int64;
  525. typedef sqlite_uint64 sqlite3_uint64;
  526. /*
  527. ** If compiling for a processor that lacks floating point support,
  528. ** substitute integer for floating-point.
  529. */
  530. #ifdef SQLITE_OMIT_FLOATING_POINT
  531. # define double sqlite3_int64
  532. #endif
  533. /*
  534. ** CAPI3REF: Closing A Database Connection
  535. ** DESTRUCTOR: sqlite3
  536. **
  537. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  538. ** for the [sqlite3] object.
  539. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  540. ** the [sqlite3] object is successfully destroyed and all associated
  541. ** resources are deallocated.
  542. **
  543. ** ^If the database connection is associated with unfinalized prepared
  544. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  545. ** will leave the database connection open and return [SQLITE_BUSY].
  546. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  547. ** and/or unfinished sqlite3_backups, then the database connection becomes
  548. ** an unusable "zombie" which will automatically be deallocated when the
  549. ** last prepared statement is finalized or the last sqlite3_backup is
  550. ** finished. The sqlite3_close_v2() interface is intended for use with
  551. ** host languages that are garbage collected, and where the order in which
  552. ** destructors are called is arbitrary.
  553. **
  554. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  555. ** [sqlite3_blob_close | close] all [BLOB handles], and
  556. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  557. ** with the [sqlite3] object prior to attempting to close the object. ^If
  558. ** sqlite3_close_v2() is called on a [database connection] that still has
  559. ** outstanding [prepared statements], [BLOB handles], and/or
  560. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  561. ** of resources is deferred until all [prepared statements], [BLOB handles],
  562. ** and [sqlite3_backup] objects are also destroyed.
  563. **
  564. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  565. ** the transaction is automatically rolled back.
  566. **
  567. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  568. ** must be either a NULL
  569. ** pointer or an [sqlite3] object pointer obtained
  570. ** from [sqlite3_open()], [sqlite3_open16()], or
  571. ** [sqlite3_open_v2()], and not previously closed.
  572. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  573. ** argument is a harmless no-op.
  574. */
  575. SQLITE_API int sqlite3_close(sqlite3*);
  576. SQLITE_API int sqlite3_close_v2(sqlite3*);
  577. /*
  578. ** The type for a callback function.
  579. ** This is legacy and deprecated. It is included for historical
  580. ** compatibility and is not documented.
  581. */
  582. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  583. /*
  584. ** CAPI3REF: One-Step Query Execution Interface
  585. ** METHOD: sqlite3
  586. **
  587. ** The sqlite3_exec() interface is a convenience wrapper around
  588. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  589. ** that allows an application to run multiple statements of SQL
  590. ** without having to use a lot of C code.
  591. **
  592. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  593. ** semicolon-separate SQL statements passed into its 2nd argument,
  594. ** in the context of the [database connection] passed in as its 1st
  595. ** argument. ^If the callback function of the 3rd argument to
  596. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  597. ** coming out of the evaluated SQL statements. ^The 4th argument to
  598. ** sqlite3_exec() is relayed through to the 1st argument of each
  599. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  600. ** is NULL, then no callback is ever invoked and result rows are
  601. ** ignored.
  602. **
  603. ** ^If an error occurs while evaluating the SQL statements passed into
  604. ** sqlite3_exec(), then execution of the current statement stops and
  605. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  606. ** is not NULL then any error message is written into memory obtained
  607. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  608. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  609. ** on error message strings returned through the 5th parameter of
  610. ** sqlite3_exec() after the error message string is no longer needed.
  611. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  612. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  613. ** NULL before returning.
  614. **
  615. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  616. ** routine returns SQLITE_ABORT without invoking the callback again and
  617. ** without running any subsequent SQL statements.
  618. **
  619. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  620. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  621. ** callback is an array of pointers to strings obtained as if from
  622. ** [sqlite3_column_text()], one for each column. ^If an element of a
  623. ** result row is NULL then the corresponding string pointer for the
  624. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  625. ** sqlite3_exec() callback is an array of pointers to strings where each
  626. ** entry represents the name of corresponding result column as obtained
  627. ** from [sqlite3_column_name()].
  628. **
  629. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  630. ** to an empty string, or a pointer that contains only whitespace and/or
  631. ** SQL comments, then no SQL statements are evaluated and the database
  632. ** is not changed.
  633. **
  634. ** Restrictions:
  635. **
  636. ** <ul>
  637. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  638. ** is a valid and open [database connection].
  639. ** <li> The application must not close the [database connection] specified by
  640. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  641. ** <li> The application must not modify the SQL statement text passed into
  642. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  643. ** </ul>
  644. */
  645. SQLITE_API int sqlite3_exec(
  646. sqlite3*, /* An open database */
  647. const char *sql, /* SQL to be evaluated */
  648. int (*callback)(void*,int,char**,char**), /* Callback function */
  649. void *, /* 1st argument to callback */
  650. char **errmsg /* Error msg written here */
  651. );
  652. /*
  653. ** CAPI3REF: Result Codes
  654. ** KEYWORDS: {result code definitions}
  655. **
  656. ** Many SQLite functions return an integer result code from the set shown
  657. ** here in order to indicate success or failure.
  658. **
  659. ** New error codes may be added in future versions of SQLite.
  660. **
  661. ** See also: [extended result code definitions]
  662. */
  663. #define SQLITE_OK 0 /* Successful result */
  664. /* beginning-of-error-codes */
  665. #define SQLITE_ERROR 1 /* SQL error or missing database */
  666. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  667. #define SQLITE_PERM 3 /* Access permission denied */
  668. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  669. #define SQLITE_BUSY 5 /* The database file is locked */
  670. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  671. #define SQLITE_NOMEM 7 /* A malloc() failed */
  672. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  673. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  674. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  675. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  676. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  677. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  678. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  679. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  680. #define SQLITE_EMPTY 16 /* Database is empty */
  681. #define SQLITE_SCHEMA 17 /* The database schema changed */
  682. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  683. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  684. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  685. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  686. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  687. #define SQLITE_AUTH 23 /* Authorization denied */
  688. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  689. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  690. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  691. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  692. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  693. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  694. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  695. /* end-of-error-codes */
  696. /*
  697. ** CAPI3REF: Extended Result Codes
  698. ** KEYWORDS: {extended result code definitions}
  699. **
  700. ** In its default configuration, SQLite API routines return one of 30 integer
  701. ** [result codes]. However, experience has shown that many of
  702. ** these result codes are too coarse-grained. They do not provide as
  703. ** much information about problems as programmers might like. In an effort to
  704. ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  705. ** and later) include
  706. ** support for additional result codes that provide more detailed information
  707. ** about errors. These [extended result codes] are enabled or disabled
  708. ** on a per database connection basis using the
  709. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  710. ** the most recent error can be obtained using
  711. ** [sqlite3_extended_errcode()].
  712. */
  713. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  714. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  715. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  716. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  717. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  718. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  719. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  720. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  721. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  722. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  723. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  724. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  725. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  726. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  727. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  728. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  729. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  730. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  731. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  732. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  733. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  734. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  735. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  736. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  737. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  738. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  739. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  740. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  741. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  742. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  743. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  744. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  745. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  746. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  747. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  748. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  749. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  750. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  751. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  752. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  753. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  754. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  755. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  756. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  757. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  758. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  759. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  760. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  761. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  762. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  763. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  764. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  765. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  766. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  767. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  768. #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
  769. /*
  770. ** CAPI3REF: Flags For File Open Operations
  771. **
  772. ** These bit values are intended for use in the
  773. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  774. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  775. */
  776. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  777. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  778. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  779. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  780. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  781. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  782. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  783. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  784. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  785. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  786. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  787. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  788. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  789. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  790. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  791. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  792. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  793. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  794. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  795. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  796. /* Reserved: 0x00F00000 */
  797. /*
  798. ** CAPI3REF: Device Characteristics
  799. **
  800. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  801. ** object returns an integer which is a vector of these
  802. ** bit values expressing I/O characteristics of the mass storage
  803. ** device that holds the file that the [sqlite3_io_methods]
  804. ** refers to.
  805. **
  806. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  807. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  808. ** mean that writes of blocks that are nnn bytes in size and
  809. ** are aligned to an address which is an integer multiple of
  810. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  811. ** that when data is appended to a file, the data is appended
  812. ** first then the size of the file is extended, never the other
  813. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  814. ** information is written to disk in the same order as calls
  815. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  816. ** after reboot following a crash or power loss, the only bytes in a
  817. ** file that were written at the application level might have changed
  818. ** and that adjacent bytes, even bytes within the same sector are
  819. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  820. ** flag indicates that a file cannot be deleted when open. The
  821. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  822. ** read-only media and cannot be changed even by processes with
  823. ** elevated privileges.
  824. */
  825. #define SQLITE_IOCAP_ATOMIC 0x00000001
  826. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  827. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  828. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  829. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  830. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  831. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  832. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  833. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  834. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  835. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  836. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  837. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  838. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  839. /*
  840. ** CAPI3REF: File Locking Levels
  841. **
  842. ** SQLite uses one of these integer values as the second
  843. ** argument to calls it makes to the xLock() and xUnlock() methods
  844. ** of an [sqlite3_io_methods] object.
  845. */
  846. #define SQLITE_LOCK_NONE 0
  847. #define SQLITE_LOCK_SHARED 1
  848. #define SQLITE_LOCK_RESERVED 2
  849. #define SQLITE_LOCK_PENDING 3
  850. #define SQLITE_LOCK_EXCLUSIVE 4
  851. /*
  852. ** CAPI3REF: Synchronization Type Flags
  853. **
  854. ** When SQLite invokes the xSync() method of an
  855. ** [sqlite3_io_methods] object it uses a combination of
  856. ** these integer values as the second argument.
  857. **
  858. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  859. ** sync operation only needs to flush data to mass storage. Inode
  860. ** information need not be flushed. If the lower four bits of the flag
  861. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  862. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  863. ** to use Mac OS X style fullsync instead of fsync().
  864. **
  865. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  866. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  867. ** settings. The [synchronous pragma] determines when calls to the
  868. ** xSync VFS method occur and applies uniformly across all platforms.
  869. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  870. ** energetic or rigorous or forceful the sync operations are and
  871. ** only make a difference on Mac OSX for the default SQLite code.
  872. ** (Third-party VFS implementations might also make the distinction
  873. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  874. ** operating systems natively supported by SQLite, only Mac OSX
  875. ** cares about the difference.)
  876. */
  877. #define SQLITE_SYNC_NORMAL 0x00002
  878. #define SQLITE_SYNC_FULL 0x00003
  879. #define SQLITE_SYNC_DATAONLY 0x00010
  880. /*
  881. ** CAPI3REF: OS Interface Open File Handle
  882. **
  883. ** An [sqlite3_file] object represents an open file in the
  884. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  885. ** implementations will
  886. ** want to subclass this object by appending additional fields
  887. ** for their own use. The pMethods entry is a pointer to an
  888. ** [sqlite3_io_methods] object that defines methods for performing
  889. ** I/O operations on the open file.
  890. */
  891. typedef struct sqlite3_file sqlite3_file;
  892. struct sqlite3_file {
  893. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  894. };
  895. /*
  896. ** CAPI3REF: OS Interface File Virtual Methods Object
  897. **
  898. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  899. ** [sqlite3_file] object (or, more commonly, a subclass of the
  900. ** [sqlite3_file] object) with a pointer to an instance of this object.
  901. ** This object defines the methods used to perform various operations
  902. ** against the open file represented by the [sqlite3_file] object.
  903. **
  904. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  905. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  906. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  907. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  908. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  909. ** to NULL.
  910. **
  911. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  912. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  913. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  914. ** flag may be ORed in to indicate that only the data of the file
  915. ** and not its inode needs to be synced.
  916. **
  917. ** The integer values to xLock() and xUnlock() are one of
  918. ** <ul>
  919. ** <li> [SQLITE_LOCK_NONE],
  920. ** <li> [SQLITE_LOCK_SHARED],
  921. ** <li> [SQLITE_LOCK_RESERVED],
  922. ** <li> [SQLITE_LOCK_PENDING], or
  923. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  924. ** </ul>
  925. ** xLock() increases the lock. xUnlock() decreases the lock.
  926. ** The xCheckReservedLock() method checks whether any database connection,
  927. ** either in this process or in some other process, is holding a RESERVED,
  928. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  929. ** if such a lock exists and false otherwise.
  930. **
  931. ** The xFileControl() method is a generic interface that allows custom
  932. ** VFS implementations to directly control an open file using the
  933. ** [sqlite3_file_control()] interface. The second "op" argument is an
  934. ** integer opcode. The third argument is a generic pointer intended to
  935. ** point to a structure that may contain arguments or space in which to
  936. ** write return values. Potential uses for xFileControl() might be
  937. ** functions to enable blocking locks with timeouts, to change the
  938. ** locking strategy (for example to use dot-file locks), to inquire
  939. ** about the status of a lock, or to break stale locks. The SQLite
  940. ** core reserves all opcodes less than 100 for its own use.
  941. ** A [file control opcodes | list of opcodes] less than 100 is available.
  942. ** Applications that define a custom xFileControl method should use opcodes
  943. ** greater than 100 to avoid conflicts. VFS implementations should
  944. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  945. ** recognize.
  946. **
  947. ** The xSectorSize() method returns the sector size of the
  948. ** device that underlies the file. The sector size is the
  949. ** minimum write that can be performed without disturbing
  950. ** other bytes in the file. The xDeviceCharacteristics()
  951. ** method returns a bit vector describing behaviors of the
  952. ** underlying device:
  953. **
  954. ** <ul>
  955. ** <li> [SQLITE_IOCAP_ATOMIC]
  956. ** <li> [SQLITE_IOCAP_ATOMIC512]
  957. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  958. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  959. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  960. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  961. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  962. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  963. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  964. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  965. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  966. ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  967. ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  968. ** <li> [SQLITE_IOCAP_IMMUTABLE]
  969. ** </ul>
  970. **
  971. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  972. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  973. ** mean that writes of blocks that are nnn bytes in size and
  974. ** are aligned to an address which is an integer multiple of
  975. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  976. ** that when data is appended to a file, the data is appended
  977. ** first then the size of the file is extended, never the other
  978. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  979. ** information is written to disk in the same order as calls
  980. ** to xWrite().
  981. **
  982. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  983. ** in the unread portions of the buffer with zeros. A VFS that
  984. ** fails to zero-fill short reads might seem to work. However,
  985. ** failure to zero-fill short reads will eventually lead to
  986. ** database corruption.
  987. */
  988. typedef struct sqlite3_io_methods sqlite3_io_methods;
  989. struct sqlite3_io_methods {
  990. int iVersion;
  991. int (*xClose)(sqlite3_file*);
  992. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  993. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  994. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  995. int (*xSync)(sqlite3_file*, int flags);
  996. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  997. int (*xLock)(sqlite3_file*, int);
  998. int (*xUnlock)(sqlite3_file*, int);
  999. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1000. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1001. int (*xSectorSize)(sqlite3_file*);
  1002. int (*xDeviceCharacteristics)(sqlite3_file*);
  1003. /* Methods above are valid for version 1 */
  1004. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1005. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1006. void (*xShmBarrier)(sqlite3_file*);
  1007. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1008. /* Methods above are valid for version 2 */
  1009. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1010. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1011. /* Methods above are valid for version 3 */
  1012. /* Additional methods may be added in future releases */
  1013. };
  1014. /*
  1015. ** CAPI3REF: Standard File Control Opcodes
  1016. ** KEYWORDS: {file control opcodes} {file control opcode}
  1017. **
  1018. ** These integer constants are opcodes for the xFileControl method
  1019. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1020. ** interface.
  1021. **
  1022. ** <ul>
  1023. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1024. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1025. ** opcode causes the xFileControl method to write the current state of
  1026. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1027. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1028. ** into an integer that the pArg argument points to. This capability
  1029. ** is used during testing and is only available when the SQLITE_TEST
  1030. ** compile-time option is used.
  1031. **
  1032. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1033. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1034. ** layer a hint of how large the database file will grow to be during the
  1035. ** current transaction. This hint is not guaranteed to be accurate but it
  1036. ** is often close. The underlying VFS might choose to preallocate database
  1037. ** file space based on this hint in order to help writes to the database
  1038. ** file run faster.
  1039. **
  1040. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1041. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1042. ** extends and truncates the database file in chunks of a size specified
  1043. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1044. ** point to an integer (type int) containing the new chunk-size to use
  1045. ** for the nominated database. Allocating database file space in large
  1046. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1047. ** improve performance on some systems.
  1048. **
  1049. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1050. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1051. ** to the [sqlite3_file] object associated with a particular database
  1052. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1053. **
  1054. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1055. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1056. ** to the [sqlite3_file] object associated with the journal file (either
  1057. ** the [rollback journal] or the [write-ahead log]) for a particular database
  1058. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  1059. **
  1060. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1061. ** No longer in use.
  1062. **
  1063. ** <li>[[SQLITE_FCNTL_SYNC]]
  1064. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1065. ** sent to the VFS immediately before the xSync method is invoked on a
  1066. ** database file descriptor. Or, if the xSync method is not invoked
  1067. ** because the user has configured SQLite with
  1068. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1069. ** of the xSync method. In most cases, the pointer argument passed with
  1070. ** this file-control is NULL. However, if the database file is being synced
  1071. ** as part of a multi-database commit, the argument points to a nul-terminated
  1072. ** string containing the transactions master-journal file name. VFSes that
  1073. ** do not need this signal should silently ignore this opcode. Applications
  1074. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1075. ** disrupt the operation of the specialized VFSes that do require it.
  1076. **
  1077. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1078. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1079. ** and sent to the VFS after a transaction has been committed immediately
  1080. ** but before the database is unlocked. VFSes that do not need this signal
  1081. ** should silently ignore this opcode. Applications should not call
  1082. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1083. ** operation of the specialized VFSes that do require it.
  1084. **
  1085. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1086. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1087. ** retry counts and intervals for certain disk I/O operations for the
  1088. ** windows [VFS] in order to provide robustness in the presence of
  1089. ** anti-virus programs. By default, the windows VFS will retry file read,
  1090. ** file write, and file delete operations up to 10 times, with a delay
  1091. ** of 25 milliseconds before the first retry and with the delay increasing
  1092. ** by an additional 25 milliseconds with each subsequent retry. This
  1093. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1094. ** to be adjusted. The values are changed for all database connections
  1095. ** within the same process. The argument is a pointer to an array of two
  1096. ** integers where the first integer is the new retry count and the second
  1097. ** integer is the delay. If either integer is negative, then the setting
  1098. ** is not changed but instead the prior value of that setting is written
  1099. ** into the array entry, allowing the current retry settings to be
  1100. ** interrogated. The zDbName parameter is ignored.
  1101. **
  1102. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1103. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1104. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1105. ** write ahead log and shared memory files used for transaction control
  1106. ** are automatically deleted when the latest connection to the database
  1107. ** closes. Setting persistent WAL mode causes those files to persist after
  1108. ** close. Persisting the files is useful when other processes that do not
  1109. ** have write permission on the directory containing the database file want
  1110. ** to read the database file, as the WAL and shared memory files must exist
  1111. ** in order for the database to be readable. The fourth parameter to
  1112. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1113. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1114. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1115. ** WAL persistence setting.
  1116. **
  1117. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1118. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1119. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1120. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1121. ** xDeviceCharacteristics methods. The fourth parameter to
  1122. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1123. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1124. ** mode. If the integer is -1, then it is overwritten with the current
  1125. ** zero-damage mode setting.
  1126. **
  1127. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1128. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1129. ** a write transaction to indicate that, unless it is rolled back for some
  1130. ** reason, the entire database file will be overwritten by the current
  1131. ** transaction. This is used by VACUUM operations.
  1132. **
  1133. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1134. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1135. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1136. ** final bottom-level VFS are written into memory obtained from
  1137. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1138. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1139. ** The caller is responsible for freeing the memory when done. As with
  1140. ** all file-control actions, there is no guarantee that this will actually
  1141. ** do anything. Callers should initialize the char* variable to a NULL
  1142. ** pointer in case this file-control is not implemented. This file-control
  1143. ** is intended for diagnostic use only.
  1144. **
  1145. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1146. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1147. ** [VFSes] currently in use. ^(The argument X in
  1148. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1149. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1150. ** to a pointer to the top-level VFS.)^
  1151. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1152. ** upper-most shim only.
  1153. **
  1154. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1155. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1156. ** file control is sent to the open [sqlite3_file] object corresponding
  1157. ** to the database file to which the pragma statement refers. ^The argument
  1158. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1159. ** pointers to strings (char**) in which the second element of the array
  1160. ** is the name of the pragma and the third element is the argument to the
  1161. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1162. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1163. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1164. ** or the equivalent and that string will become the result of the pragma or
  1165. ** the error message if the pragma fails. ^If the
  1166. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1167. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1168. ** file control returns [SQLITE_OK], then the parser assumes that the
  1169. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1170. ** prepared statement if result string is NULL, or that returns a copy
  1171. ** of the result string if the string is non-NULL.
  1172. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1173. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1174. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1175. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1176. ** file control occurs at the beginning of pragma statement analysis and so
  1177. ** it is able to override built-in [PRAGMA] statements.
  1178. **
  1179. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1180. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1181. ** file-control may be invoked by SQLite on the database file handle
  1182. ** shortly after it is opened in order to provide a custom VFS with access
  1183. ** to the connections busy-handler callback. The argument is of type (void **)
  1184. ** - an array of two (void *) values. The first (void *) actually points
  1185. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1186. ** busy-handler, this function should be invoked with the second (void *) in
  1187. ** the array as the only argument. If it returns non-zero, then the operation
  1188. ** should be retried. If it returns zero, the custom VFS should abandon the
  1189. ** current operation.
  1190. **
  1191. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1192. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1193. ** to have SQLite generate a
  1194. ** temporary filename using the same algorithm that is followed to generate
  1195. ** temporary filenames for TEMP tables and other internal uses. The
  1196. ** argument should be a char** which will be filled with the filename
  1197. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1198. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1199. **
  1200. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1201. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1202. ** maximum number of bytes that will be used for memory-mapped I/O.
  1203. ** The argument is a pointer to a value of type sqlite3_int64 that
  1204. ** is an advisory maximum number of bytes in the file to memory map. The
  1205. ** pointer is overwritten with the old value. The limit is not changed if
  1206. ** the value originally pointed to is negative, and so the current limit
  1207. ** can be queried by passing in a pointer to a negative number. This
  1208. ** file-control is used internally to implement [PRAGMA mmap_size].
  1209. **
  1210. ** <li>[[SQLITE_FCNTL_TRACE]]
  1211. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1212. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1213. ** This file control is used by some VFS activity tracing [shims].
  1214. ** The argument is a zero-terminated string. Higher layers in the
  1215. ** SQLite stack may generate instances of this file control if
  1216. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1217. **
  1218. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1219. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1220. ** pointer to an integer and it writes a boolean into that integer depending
  1221. ** on whether or not the file has been renamed, moved, or deleted since it
  1222. ** was first opened.
  1223. **
  1224. ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  1225. ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  1226. ** underlying native file handle associated with a file handle. This file
  1227. ** control interprets its argument as a pointer to a native file handle and
  1228. ** writes the resulting value there.
  1229. **
  1230. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1231. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1232. ** opcode causes the xFileControl method to swap the file handle with the one
  1233. ** pointed to by the pArg argument. This capability is used during testing
  1234. ** and only needs to be supported when SQLITE_TEST is defined.
  1235. **
  1236. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  1237. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  1238. ** be advantageous to block on the next WAL lock if the lock is not immediately
  1239. ** available. The WAL subsystem issues this signal during rare
  1240. ** circumstances in order to fix a problem with priority inversion.
  1241. ** Applications should <em>not</em> use this file-control.
  1242. **
  1243. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  1244. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  1245. ** VFS should return SQLITE_NOTFOUND for this opcode.
  1246. **
  1247. ** <li>[[SQLITE_FCNTL_RBU]]
  1248. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  1249. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  1250. ** this opcode.
  1251. ** </ul>
  1252. */
  1253. #define SQLITE_FCNTL_LOCKSTATE 1
  1254. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  1255. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  1256. #define SQLITE_FCNTL_LAST_ERRNO 4
  1257. #define SQLITE_FCNTL_SIZE_HINT 5
  1258. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1259. #define SQLITE_FCNTL_FILE_POINTER 7
  1260. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1261. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1262. #define SQLITE_FCNTL_PERSIST_WAL 10
  1263. #define SQLITE_FCNTL_OVERWRITE 11
  1264. #define SQLITE_FCNTL_VFSNAME 12
  1265. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1266. #define SQLITE_FCNTL_PRAGMA 14
  1267. #define SQLITE_FCNTL_BUSYHANDLER 15
  1268. #define SQLITE_FCNTL_TEMPFILENAME 16
  1269. #define SQLITE_FCNTL_MMAP_SIZE 18
  1270. #define SQLITE_FCNTL_TRACE 19
  1271. #define SQLITE_FCNTL_HAS_MOVED 20
  1272. #define SQLITE_FCNTL_SYNC 21
  1273. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  1274. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  1275. #define SQLITE_FCNTL_WAL_BLOCK 24
  1276. #define SQLITE_FCNTL_ZIPVFS 25
  1277. #define SQLITE_FCNTL_RBU 26
  1278. #define SQLITE_FCNTL_VFS_POINTER 27
  1279. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  1280. #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
  1281. #define SQLITE_FCNTL_PDB 30
  1282. /* deprecated names */
  1283. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  1284. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  1285. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  1286. /*
  1287. ** CAPI3REF: Mutex Handle
  1288. **
  1289. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1290. ** abstract type for a mutex object. The SQLite core never looks
  1291. ** at the internal representation of an [sqlite3_mutex]. It only
  1292. ** deals with pointers to the [sqlite3_mutex] object.
  1293. **
  1294. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1295. */
  1296. typedef struct sqlite3_mutex sqlite3_mutex;
  1297. /*
  1298. ** CAPI3REF: Loadable Extension Thunk
  1299. **
  1300. ** A pointer to the opaque sqlite3_api_routines structure is passed as
  1301. ** the third parameter to entry points of [loadable extensions]. This
  1302. ** structure must be typedefed in order to work around compiler warnings
  1303. ** on some platforms.
  1304. */
  1305. typedef struct sqlite3_api_routines sqlite3_api_routines;
  1306. /*
  1307. ** CAPI3REF: OS Interface Object
  1308. **
  1309. ** An instance of the sqlite3_vfs object defines the interface between
  1310. ** the SQLite core and the underlying operating system. The "vfs"
  1311. ** in the name of the object stands for "virtual file system". See
  1312. ** the [VFS | VFS documentation] for further information.
  1313. **
  1314. ** The value of the iVersion field is initially 1 but may be larger in
  1315. ** future versions of SQLite. Additional fields may be appended to this
  1316. ** object when the iVersion value is increased. Note that the structure
  1317. ** of the sqlite3_vfs object changes in the transaction between
  1318. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1319. ** modified.
  1320. **
  1321. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1322. ** structure used by this VFS. mxPathname is the maximum length of
  1323. ** a pathname in this VFS.
  1324. **
  1325. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1326. ** the pNext pointer. The [sqlite3_vfs_register()]
  1327. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1328. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1329. ** searches the list. Neither the application code nor the VFS
  1330. ** implementation should use the pNext pointer.
  1331. **
  1332. ** The pNext field is the only field in the sqlite3_vfs
  1333. ** structure that SQLite will ever modify. SQLite will only access
  1334. ** or modify this field while holding a particular static mutex.
  1335. ** The application should never modify anything within the sqlite3_vfs
  1336. ** object once the object has been registered.
  1337. **
  1338. ** The zName field holds the name of the VFS module. The name must
  1339. ** be unique across all VFS modules.
  1340. **
  1341. ** [[sqlite3_vfs.xOpen]]
  1342. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1343. ** is either a NULL pointer or string obtained
  1344. ** from xFullPathname() with an optional suffix added.
  1345. ** ^If a suffix is added to the zFilename parameter, it will
  1346. ** consist of a single "-" character followed by no more than
  1347. ** 11 alphanumeric and/or "-" characters.
  1348. ** ^SQLite further guarantees that
  1349. ** the string will be valid and unchanged until xClose() is
  1350. ** called. Because of the previous sentence,
  1351. ** the [sqlite3_file] can safely store a pointer to the
  1352. ** filename if it needs to remember the filename for some reason.
  1353. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1354. ** must invent its own temporary name for the file. ^Whenever the
  1355. ** xFilename parameter is NULL it will also be the case that the
  1356. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1357. **
  1358. ** The flags argument to xOpen() includes all bits set in
  1359. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1360. ** or [sqlite3_open16()] is used, then flags includes at least
  1361. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1362. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1363. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1364. **
  1365. ** ^(SQLite will also add one of the following flags to the xOpen()
  1366. ** call, depending on the object being opened:
  1367. **
  1368. ** <ul>
  1369. ** <li> [SQLITE_OPEN_MAIN_DB]
  1370. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1371. ** <li> [SQLITE_OPEN_TEMP_DB]
  1372. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1373. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1374. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1375. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1376. ** <li> [SQLITE_OPEN_WAL]
  1377. ** </ul>)^
  1378. **
  1379. ** The file I/O implementation can use the object type flags to
  1380. ** change the way it deals with files. For example, an application
  1381. ** that does not care about crash recovery or rollback might make
  1382. ** the open of a journal file a no-op. Writes to this journal would
  1383. ** also be no-ops, and any attempt to read the journal would return
  1384. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1385. ** file will be doing page-aligned sector reads and writes in a random
  1386. ** order and set up its I/O subsystem accordingly.
  1387. **
  1388. ** SQLite might also add one of the following flags to the xOpen method:
  1389. **
  1390. ** <ul>
  1391. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1392. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1393. ** </ul>
  1394. **
  1395. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1396. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1397. ** will be set for TEMP databases and their journals, transient
  1398. ** databases, and subjournals.
  1399. **
  1400. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1401. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1402. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1403. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1404. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1405. ** be created, and that it is an error if it already exists.
  1406. ** It is <i>not</i> used to indicate the file should be opened
  1407. ** for exclusive access.
  1408. **
  1409. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1410. ** to hold the [sqlite3_file] structure passed as the third
  1411. ** argument to xOpen. The xOpen method does not have to
  1412. ** allocate the structure; it should just fill it in. Note that
  1413. ** the xOpen method must set the sqlite3_file.pMethods to either
  1414. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1415. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1416. ** element will be valid after xOpen returns regardless of the success
  1417. ** or failure of the xOpen call.
  1418. **
  1419. ** [[sqlite3_vfs.xAccess]]
  1420. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1421. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1422. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1423. ** to test whether a file is at least readable. The file can be a
  1424. ** directory.
  1425. **
  1426. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1427. ** output buffer xFullPathname. The exact size of the output buffer
  1428. ** is also passed as a parameter to both methods. If the output buffer
  1429. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1430. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1431. ** to prevent this by setting mxPathname to a sufficiently large value.
  1432. **
  1433. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1434. ** interfaces are not strictly a part of the filesystem, but they are
  1435. ** included in the VFS structure for completeness.
  1436. ** The xRandomness() function attempts to return nBytes bytes
  1437. ** of good-quality randomness into zOut. The return value is
  1438. ** the actual number of bytes of randomness obtained.
  1439. ** The xSleep() method causes the calling thread to sleep for at
  1440. ** least the number of microseconds given. ^The xCurrentTime()
  1441. ** method returns a Julian Day Number for the current date and time as
  1442. ** a floating point value.
  1443. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1444. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1445. ** a 24-hour day).
  1446. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1447. ** date and time if that method is available (if iVersion is 2 or
  1448. ** greater and the function pointer is not NULL) and will fall back
  1449. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1450. **
  1451. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1452. ** are not used by the SQLite core. These optional interfaces are provided
  1453. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1454. ** system calls with functions under its control, a test program can
  1455. ** simulate faults and error conditions that would otherwise be difficult
  1456. ** or impossible to induce. The set of system calls that can be overridden
  1457. ** varies from one VFS to another, and from one version of the same VFS to the
  1458. ** next. Applications that use these interfaces must be prepared for any
  1459. ** or all of these interfaces to be NULL or for their behavior to change
  1460. ** from one release to the next. Applications must not attempt to access
  1461. ** any of these methods if the iVersion of the VFS is less than 3.
  1462. */
  1463. typedef struct sqlite3_vfs sqlite3_vfs;
  1464. typedef void (*sqlite3_syscall_ptr)(void);
  1465. struct sqlite3_vfs {
  1466. int iVersion; /* Structure version number (currently 3) */
  1467. int szOsFile; /* Size of subclassed sqlite3_file */
  1468. int mxPathname; /* Maximum file pathname length */
  1469. sqlite3_vfs *pNext; /* Next registered VFS */
  1470. const char *zName; /* Name of this virtual file system */
  1471. void *pAppData; /* Pointer to application-specific data */
  1472. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1473. int flags, int *pOutFlags);
  1474. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1475. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1476. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1477. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1478. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1479. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1480. void (*xDlClose)(sqlite3_vfs*, void*);
  1481. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1482. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1483. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1484. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1485. /*
  1486. ** The methods above are in version 1 of the sqlite_vfs object
  1487. ** definition. Those that follow are added in version 2 or later
  1488. */
  1489. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1490. /*
  1491. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1492. ** Those below are for version 3 and greater.
  1493. */
  1494. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1495. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1496. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1497. /*
  1498. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1499. ** New fields may be appended in future versions. The iVersion
  1500. ** value will increment whenever this happens.
  1501. */
  1502. };
  1503. /*
  1504. ** CAPI3REF: Flags for the xAccess VFS method
  1505. **
  1506. ** These integer constants can be used as the third parameter to
  1507. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1508. ** what kind of permissions the xAccess method is looking for.
  1509. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1510. ** simply checks whether the file exists.
  1511. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1512. ** checks whether the named directory is both readable and writable
  1513. ** (in other words, if files can be added, removed, and renamed within
  1514. ** the directory).
  1515. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1516. ** [temp_store_directory pragma], though this could change in a future
  1517. ** release of SQLite.
  1518. ** With SQLITE_ACCESS_READ, the xAccess method
  1519. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1520. ** currently unused, though it might be used in a future release of
  1521. ** SQLite.
  1522. */
  1523. #define SQLITE_ACCESS_EXISTS 0
  1524. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1525. #define SQLITE_ACCESS_READ 2 /* Unused */
  1526. /*
  1527. ** CAPI3REF: Flags for the xShmLock VFS method
  1528. **
  1529. ** These integer constants define the various locking operations
  1530. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1531. ** following are the only legal combinations of flags to the
  1532. ** xShmLock method:
  1533. **
  1534. ** <ul>
  1535. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1536. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1537. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1538. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1539. ** </ul>
  1540. **
  1541. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1542. ** was given on the corresponding lock.
  1543. **
  1544. ** The xShmLock method can transition between unlocked and SHARED or
  1545. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1546. ** and EXCLUSIVE.
  1547. */
  1548. #define SQLITE_SHM_UNLOCK 1
  1549. #define SQLITE_SHM_LOCK 2
  1550. #define SQLITE_SHM_SHARED 4
  1551. #define SQLITE_SHM_EXCLUSIVE 8
  1552. /*
  1553. ** CAPI3REF: Maximum xShmLock index
  1554. **
  1555. ** The xShmLock method on [sqlite3_io_methods] may use values
  1556. ** between 0 and this upper bound as its "offset" argument.
  1557. ** The SQLite core will never attempt to acquire or release a
  1558. ** lock outside of this range
  1559. */
  1560. #define SQLITE_SHM_NLOCK 8
  1561. /*
  1562. ** CAPI3REF: Initialize The SQLite Library
  1563. **
  1564. ** ^The sqlite3_initialize() routine initializes the
  1565. ** SQLite library. ^The sqlite3_shutdown() routine
  1566. ** deallocates any resources that were allocated by sqlite3_initialize().
  1567. ** These routines are designed to aid in process initialization and
  1568. ** shutdown on embedded systems. Workstation applications using
  1569. ** SQLite normally do not need to invoke either of these routines.
  1570. **
  1571. ** A call to sqlite3_initialize() is an "effective" call if it is
  1572. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1573. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1574. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1575. ** of sqlite3_initialize() does any initialization. All other calls
  1576. ** are harmless no-ops.)^
  1577. **
  1578. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1579. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1580. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1581. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1582. **
  1583. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1584. ** is not. The sqlite3_shutdown() interface must only be called from a
  1585. ** single thread. All open [database connections] must be closed and all
  1586. ** other SQLite resources must be deallocated prior to invoking
  1587. ** sqlite3_shutdown().
  1588. **
  1589. ** Among other things, ^sqlite3_initialize() will invoke
  1590. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1591. ** will invoke sqlite3_os_end().
  1592. **
  1593. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1594. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1595. ** the library (perhaps it is unable to allocate a needed resource such
  1596. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1597. **
  1598. ** ^The sqlite3_initialize() routine is called internally by many other
  1599. ** SQLite interfaces so that an application usually does not need to
  1600. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1601. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1602. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1603. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1604. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1605. ** are omitted and the application must call sqlite3_initialize() directly
  1606. ** prior to using any other SQLite interface. For maximum portability,
  1607. ** it is recommended that applications always invoke sqlite3_initialize()
  1608. ** directly prior to using any other SQLite interface. Future releases
  1609. ** of SQLite may require this. In other words, the behavior exhibited
  1610. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1611. ** default behavior in some future release of SQLite.
  1612. **
  1613. ** The sqlite3_os_init() routine does operating-system specific
  1614. ** initialization of the SQLite library. The sqlite3_os_end()
  1615. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1616. ** performed by these routines include allocation or deallocation
  1617. ** of static resources, initialization of global variables,
  1618. ** setting up a default [sqlite3_vfs] module, or setting up
  1619. ** a default configuration using [sqlite3_config()].
  1620. **
  1621. ** The application should never invoke either sqlite3_os_init()
  1622. ** or sqlite3_os_end() directly. The application should only invoke
  1623. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1624. ** interface is called automatically by sqlite3_initialize() and
  1625. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1626. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1627. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1628. ** When [custom builds | built for other platforms]
  1629. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1630. ** option) the application must supply a suitable implementation for
  1631. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1632. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1633. ** must return [SQLITE_OK] on success and some other [error code] upon
  1634. ** failure.
  1635. */
  1636. SQLITE_API int sqlite3_initialize(void);
  1637. SQLITE_API int sqlite3_shutdown(void);
  1638. SQLITE_API int sqlite3_os_init(void);
  1639. SQLITE_API int sqlite3_os_end(void);
  1640. /*
  1641. ** CAPI3REF: Configuring The SQLite Library
  1642. **
  1643. ** The sqlite3_config() interface is used to make global configuration
  1644. ** changes to SQLite in order to tune SQLite to the specific needs of
  1645. ** the application. The default configuration is recommended for most
  1646. ** applications and so this routine is usually not necessary. It is
  1647. ** provided to support rare applications with unusual needs.
  1648. **
  1649. ** <b>The sqlite3_config() interface is not threadsafe. The application
  1650. ** must ensure that no other SQLite interfaces are invoked by other
  1651. ** threads while sqlite3_config() is running.</b>
  1652. **
  1653. ** The sqlite3_config() interface
  1654. ** may only be invoked prior to library initialization using
  1655. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1656. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1657. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1658. ** Note, however, that ^sqlite3_config() can be called as part of the
  1659. ** implementation of an application-defined [sqlite3_os_init()].
  1660. **
  1661. ** The first argument to sqlite3_config() is an integer
  1662. ** [configuration option] that determines
  1663. ** what property of SQLite is to be configured. Subsequent arguments
  1664. ** vary depending on the [configuration option]
  1665. ** in the first argument.
  1666. **
  1667. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1668. ** ^If the option is unknown or SQLite is unable to set the option
  1669. ** then this routine returns a non-zero [error code].
  1670. */
  1671. SQLITE_API int sqlite3_config(int, ...);
  1672. /*
  1673. ** CAPI3REF: Configure database connections
  1674. ** METHOD: sqlite3
  1675. **
  1676. ** The sqlite3_db_config() interface is used to make configuration
  1677. ** changes to a [database connection]. The interface is similar to
  1678. ** [sqlite3_config()] except that the changes apply to a single
  1679. ** [database connection] (specified in the first argument).
  1680. **
  1681. ** The second argument to sqlite3_db_config(D,V,...) is the
  1682. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1683. ** that indicates what aspect of the [database connection] is being configured.
  1684. ** Subsequent arguments vary depending on the configuration verb.
  1685. **
  1686. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1687. ** the call is considered successful.
  1688. */
  1689. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1690. /*
  1691. ** CAPI3REF: Memory Allocation Routines
  1692. **
  1693. ** An instance of this object defines the interface between SQLite
  1694. ** and low-level memory allocation routines.
  1695. **
  1696. ** This object is used in only one place in the SQLite interface.
  1697. ** A pointer to an instance of this object is the argument to
  1698. ** [sqlite3_config()] when the configuration option is
  1699. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1700. ** By creating an instance of this object
  1701. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1702. ** during configuration, an application can specify an alternative
  1703. ** memory allocation subsystem for SQLite to use for all of its
  1704. ** dynamic memory needs.
  1705. **
  1706. ** Note that SQLite comes with several [built-in memory allocators]
  1707. ** that are perfectly adequate for the overwhelming majority of applications
  1708. ** and that this object is only useful to a tiny minority of applications
  1709. ** with specialized memory allocation requirements. This object is
  1710. ** also used during testing of SQLite in order to specify an alternative
  1711. ** memory allocator that simulates memory out-of-memory conditions in
  1712. ** order to verify that SQLite recovers gracefully from such
  1713. ** conditions.
  1714. **
  1715. ** The xMalloc, xRealloc, and xFree methods must work like the
  1716. ** malloc(), realloc() and free() functions from the standard C library.
  1717. ** ^SQLite guarantees that the second argument to
  1718. ** xRealloc is always a value returned by a prior call to xRoundup.
  1719. **
  1720. ** xSize should return the allocated size of a memory allocation
  1721. ** previously obtained from xMalloc or xRealloc. The allocated size
  1722. ** is always at least as big as the requested size but may be larger.
  1723. **
  1724. ** The xRoundup method returns what would be the allocated size of
  1725. ** a memory allocation given a particular requested size. Most memory
  1726. ** allocators round up memory allocations at least to the next multiple
  1727. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1728. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1729. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1730. ** that causes the corresponding memory allocation to fail.
  1731. **
  1732. ** The xInit method initializes the memory allocator. For example,
  1733. ** it might allocate any require mutexes or initialize internal data
  1734. ** structures. The xShutdown method is invoked (indirectly) by
  1735. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1736. ** by xInit. The pAppData pointer is used as the only parameter to
  1737. ** xInit and xShutdown.
  1738. **
  1739. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1740. ** the xInit method, so the xInit method need not be threadsafe. The
  1741. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1742. ** not need to be threadsafe either. For all other methods, SQLite
  1743. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1744. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1745. ** it is by default) and so the methods are automatically serialized.
  1746. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1747. ** methods must be threadsafe or else make their own arrangements for
  1748. ** serialization.
  1749. **
  1750. ** SQLite will never invoke xInit() more than once without an intervening
  1751. ** call to xShutdown().
  1752. */
  1753. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1754. struct sqlite3_mem_methods {
  1755. void *(*xMalloc)(int); /* Memory allocation function */
  1756. void (*xFree)(void*); /* Free a prior allocation */
  1757. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1758. int (*xSize)(void*); /* Return the size of an allocation */
  1759. int (*xRoundup)(int); /* Round up request size to allocation size */
  1760. int (*xInit)(void*); /* Initialize the memory allocator */
  1761. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1762. void *pAppData; /* Argument to xInit() and xShutdown() */
  1763. };
  1764. /*
  1765. ** CAPI3REF: Configuration Options
  1766. ** KEYWORDS: {configuration option}
  1767. **
  1768. ** These constants are the available integer configuration options that
  1769. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1770. **
  1771. ** New configuration options may be added in future releases of SQLite.
  1772. ** Existing configuration options might be discontinued. Applications
  1773. ** should check the return code from [sqlite3_config()] to make sure that
  1774. ** the call worked. The [sqlite3_config()] interface will return a
  1775. ** non-zero [error code] if a discontinued or unsupported configuration option
  1776. ** is invoked.
  1777. **
  1778. ** <dl>
  1779. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1780. ** <dd>There are no arguments to this option. ^This option sets the
  1781. ** [threading mode] to Single-thread. In other words, it disables
  1782. ** all mutexing and puts SQLite into a mode where it can only be used
  1783. ** by a single thread. ^If SQLite is compiled with
  1784. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1785. ** it is not possible to change the [threading mode] from its default
  1786. ** value of Single-thread and so [sqlite3_config()] will return
  1787. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1788. ** configuration option.</dd>
  1789. **
  1790. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1791. ** <dd>There are no arguments to this option. ^This option sets the
  1792. ** [threading mode] to Multi-thread. In other words, it disables
  1793. ** mutexing on [database connection] and [prepared statement] objects.
  1794. ** The application is responsible for serializing access to
  1795. ** [database connections] and [prepared statements]. But other mutexes
  1796. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1797. ** environment as long as no two threads attempt to use the same
  1798. ** [database connection] at the same time. ^If SQLite is compiled with
  1799. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1800. ** it is not possible to set the Multi-thread [threading mode] and
  1801. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1802. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1803. **
  1804. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1805. ** <dd>There are no arguments to this option. ^This option sets the
  1806. ** [threading mode] to Serialized. In other words, this option enables
  1807. ** all mutexes including the recursive
  1808. ** mutexes on [database connection] and [prepared statement] objects.
  1809. ** In this mode (which is the default when SQLite is compiled with
  1810. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1811. ** to [database connections] and [prepared statements] so that the
  1812. ** application is free to use the same [database connection] or the
  1813. ** same [prepared statement] in different threads at the same time.
  1814. ** ^If SQLite is compiled with
  1815. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1816. ** it is not possible to set the Serialized [threading mode] and
  1817. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1818. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1819. **
  1820. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1821. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  1822. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  1823. ** The argument specifies
  1824. ** alternative low-level memory allocation routines to be used in place of
  1825. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1826. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1827. ** before the [sqlite3_config()] call returns.</dd>
  1828. **
  1829. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1830. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  1831. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  1832. ** The [sqlite3_mem_methods]
  1833. ** structure is filled with the currently defined memory allocation routines.)^
  1834. ** This option can be used to overload the default memory allocation
  1835. ** routines with a wrapper that simulations memory allocation failure or
  1836. ** tracks memory usage, for example. </dd>
  1837. **
  1838. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1839. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  1840. ** interpreted as a boolean, which enables or disables the collection of
  1841. ** memory allocation statistics. ^(When memory allocation statistics are
  1842. ** disabled, the following SQLite interfaces become non-operational:
  1843. ** <ul>
  1844. ** <li> [sqlite3_memory_used()]
  1845. ** <li> [sqlite3_memory_highwater()]
  1846. ** <li> [sqlite3_soft_heap_limit64()]
  1847. ** <li> [sqlite3_status64()]
  1848. ** </ul>)^
  1849. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1850. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1851. ** allocation statistics are disabled by default.
  1852. ** </dd>
  1853. **
  1854. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1855. ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
  1856. ** that SQLite can use for scratch memory. ^(There are three arguments
  1857. ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
  1858. ** aligned memory buffer from which the scratch allocations will be
  1859. ** drawn, the size of each scratch allocation (sz),
  1860. ** and the maximum number of scratch allocations (N).)^
  1861. ** The first argument must be a pointer to an 8-byte aligned buffer
  1862. ** of at least sz*N bytes of memory.
  1863. ** ^SQLite will not use more than one scratch buffers per thread.
  1864. ** ^SQLite will never request a scratch buffer that is more than 6
  1865. ** times the database page size.
  1866. ** ^If SQLite needs needs additional
  1867. ** scratch memory beyond what is provided by this configuration option, then
  1868. ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
  1869. ** ^When the application provides any amount of scratch memory using
  1870. ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
  1871. ** [sqlite3_malloc|heap allocations].
  1872. ** This can help [Robson proof|prevent memory allocation failures] due to heap
  1873. ** fragmentation in low-memory embedded systems.
  1874. ** </dd>
  1875. **
  1876. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1877. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  1878. ** that SQLite can use for the database page cache with the default page
  1879. ** cache implementation.
  1880. ** This configuration option is a no-op if an application-define page
  1881. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  1882. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  1883. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  1884. ** and the number of cache lines (N).
  1885. ** The sz argument should be the size of the largest database page
  1886. ** (a power of two between 512 and 65536) plus some extra bytes for each
  1887. ** page header. ^The number of extra bytes needed by the page header
  1888. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  1889. ** ^It is harmless, apart from the wasted memory,
  1890. ** for the sz parameter to be larger than necessary. The pMem
  1891. ** argument must be either a NULL pointer or a pointer to an 8-byte
  1892. ** aligned block of memory of at least sz*N bytes, otherwise
  1893. ** subsequent behavior is undefined.
  1894. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  1895. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  1896. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  1897. ** is exhausted.
  1898. ** ^If pMem is NULL and N is non-zero, then each database connection
  1899. ** does an initial bulk allocation for page cache memory
  1900. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  1901. ** of -1024*N bytes if N is negative, . ^If additional
  1902. ** page cache memory is needed beyond what is provided by the initial
  1903. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  1904. ** additional cache line. </dd>
  1905. **
  1906. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1907. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  1908. ** that SQLite will use for all of its dynamic memory allocation needs
  1909. ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
  1910. ** [SQLITE_CONFIG_PAGECACHE].
  1911. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  1912. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  1913. ** [SQLITE_ERROR] if invoked otherwise.
  1914. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  1915. ** An 8-byte aligned pointer to the memory,
  1916. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1917. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1918. ** to using its default memory allocator (the system malloc() implementation),
  1919. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1920. ** memory pointer is not NULL then the alternative memory
  1921. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1922. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1923. ** boundary or subsequent behavior of SQLite will be undefined.
  1924. ** The minimum allocation size is capped at 2**12. Reasonable values
  1925. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1926. **
  1927. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1928. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  1929. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  1930. ** The argument specifies alternative low-level mutex routines to be used
  1931. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  1932. ** the content of the [sqlite3_mutex_methods] structure before the call to
  1933. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1934. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1935. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1936. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1937. ** return [SQLITE_ERROR].</dd>
  1938. **
  1939. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1940. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  1941. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  1942. ** [sqlite3_mutex_methods]
  1943. ** structure is filled with the currently defined mutex routines.)^
  1944. ** This option can be used to overload the default mutex allocation
  1945. ** routines with a wrapper used to track mutex usage for performance
  1946. ** profiling or testing, for example. ^If SQLite is compiled with
  1947. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1948. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1949. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1950. ** return [SQLITE_ERROR].</dd>
  1951. **
  1952. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1953. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  1954. ** the default size of lookaside memory on each [database connection].
  1955. ** The first argument is the
  1956. ** size of each lookaside buffer slot and the second is the number of
  1957. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  1958. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1959. ** option to [sqlite3_db_config()] can be used to change the lookaside
  1960. ** configuration on individual connections.)^ </dd>
  1961. **
  1962. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1963. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  1964. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  1965. ** the interface to a custom page cache implementation.)^
  1966. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  1967. **
  1968. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1969. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  1970. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  1971. ** the current page cache implementation into that object.)^ </dd>
  1972. **
  1973. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1974. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1975. ** global [error log].
  1976. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1977. ** function with a call signature of void(*)(void*,int,const char*),
  1978. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1979. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1980. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1981. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1982. ** passed through as the first parameter to the application-defined logger
  1983. ** function whenever that function is invoked. ^The second parameter to
  1984. ** the logger function is a copy of the first parameter to the corresponding
  1985. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1986. ** [extended result code]. ^The third parameter passed to the logger is
  1987. ** log message after formatting via [sqlite3_snprintf()].
  1988. ** The SQLite logging interface is not reentrant; the logger function
  1989. ** supplied by the application must not invoke any SQLite interface.
  1990. ** In a multi-threaded application, the application-defined logger
  1991. ** function must be threadsafe. </dd>
  1992. **
  1993. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1994. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  1995. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  1996. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  1997. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  1998. ** [sqlite3_open16()] or
  1999. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2000. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2001. ** connection is opened. ^If it is globally disabled, filenames are
  2002. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2003. ** database connection is opened. ^(By default, URI handling is globally
  2004. ** disabled. The default value may be changed by compiling with the
  2005. ** [SQLITE_USE_URI] symbol defined.)^
  2006. **
  2007. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2008. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2009. ** argument which is interpreted as a boolean in order to enable or disable
  2010. ** the use of covering indices for full table scans in the query optimizer.
  2011. ** ^The default setting is determined
  2012. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2013. ** if that compile-time option is omitted.
  2014. ** The ability to disable the use of covering indices for full table scans
  2015. ** is because some incorrectly coded legacy applications might malfunction
  2016. ** when the optimization is enabled. Providing the ability to
  2017. ** disable the optimization allows the older, buggy application code to work
  2018. ** without change even with newer versions of SQLite.
  2019. **
  2020. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2021. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2022. ** <dd> These options are obsolete and should not be used by new code.
  2023. ** They are retained for backwards compatibility but are now no-ops.
  2024. ** </dd>
  2025. **
  2026. ** [[SQLITE_CONFIG_SQLLOG]]
  2027. ** <dt>SQLITE_CONFIG_SQLLOG
  2028. ** <dd>This option is only available if sqlite is compiled with the
  2029. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2030. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2031. ** The second should be of type (void*). The callback is invoked by the library
  2032. ** in three separate circumstances, identified by the value passed as the
  2033. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2034. ** passed as the second argument has just been opened. The third argument
  2035. ** points to a buffer containing the name of the main database file. If the
  2036. ** fourth parameter is 1, then the SQL statement that the third parameter
  2037. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2038. ** the connection being passed as the second parameter is being closed. The
  2039. ** third parameter is passed NULL In this case. An example of using this
  2040. ** configuration option can be seen in the "test_sqllog.c" source file in
  2041. ** the canonical SQLite source tree.</dd>
  2042. **
  2043. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2044. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2045. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2046. ** that are the default mmap size limit (the default setting for
  2047. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2048. ** ^The default setting can be overridden by each database connection using
  2049. ** either the [PRAGMA mmap_size] command, or by using the
  2050. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  2051. ** will be silently truncated if necessary so that it does not exceed the
  2052. ** compile-time maximum mmap size set by the
  2053. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2054. ** ^If either argument to this option is negative, then that argument is
  2055. ** changed to its compile-time default.
  2056. **
  2057. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2058. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2059. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2060. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2061. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2062. ** that specifies the maximum size of the created heap.
  2063. **
  2064. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2065. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2066. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2067. ** is a pointer to an integer and writes into that integer the number of extra
  2068. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2069. ** The amount of extra space required can change depending on the compiler,
  2070. ** target platform, and SQLite version.
  2071. **
  2072. ** [[SQLITE_CONFIG_PMASZ]]
  2073. ** <dt>SQLITE_CONFIG_PMASZ
  2074. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2075. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2076. ** sorter to that integer. The default minimum PMA Size is set by the
  2077. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  2078. ** to help with sort operations when multithreaded sorting
  2079. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2080. ** to be sorted exceeds the page size times the minimum of the
  2081. ** [PRAGMA cache_size] setting and this value.
  2082. **
  2083. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2084. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2085. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2086. ** becomes the [statement journal] spill-to-disk threshold.
  2087. ** [Statement journals] are held in memory until their size (in bytes)
  2088. ** exceeds this threshold, at which point they are written to disk.
  2089. ** Or if the threshold is -1, statement journals are always held
  2090. ** exclusively in memory.
  2091. ** Since many statement journals never become large, setting the spill
  2092. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2093. ** I/O required to support statement rollback.
  2094. ** The default value for this setting is controlled by the
  2095. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2096. ** </dl>
  2097. */
  2098. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2099. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2100. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2101. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2102. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2103. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  2104. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2105. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2106. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2107. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2108. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2109. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2110. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2111. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2112. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2113. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2114. #define SQLITE_CONFIG_URI 17 /* int */
  2115. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2116. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2117. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2118. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2119. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2120. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  2121. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  2122. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  2123. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  2124. /*
  2125. ** CAPI3REF: Database Connection Configuration Options
  2126. **
  2127. ** These constants are the available integer configuration options that
  2128. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2129. **
  2130. ** New configuration options may be added in future releases of SQLite.
  2131. ** Existing configuration options might be discontinued. Applications
  2132. ** should check the return code from [sqlite3_db_config()] to make sure that
  2133. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2134. ** non-zero [error code] if a discontinued or unsupported configuration option
  2135. ** is invoked.
  2136. **
  2137. ** <dl>
  2138. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2139. ** <dd> ^This option takes three additional arguments that determine the
  2140. ** [lookaside memory allocator] configuration for the [database connection].
  2141. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2142. ** pointer to a memory buffer to use for lookaside memory.
  2143. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2144. ** may be NULL in which case SQLite will allocate the
  2145. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2146. ** size of each lookaside buffer slot. ^The third argument is the number of
  2147. ** slots. The size of the buffer in the first argument must be greater than
  2148. ** or equal to the product of the second and third arguments. The buffer
  2149. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2150. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2151. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2152. ** configuration for a database connection can only be changed when that
  2153. ** connection is not currently using lookaside memory, or in other words
  2154. ** when the "current value" returned by
  2155. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2156. ** Any attempt to change the lookaside memory configuration when lookaside
  2157. ** memory is in use leaves the configuration unchanged and returns
  2158. ** [SQLITE_BUSY].)^</dd>
  2159. **
  2160. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2161. ** <dd> ^This option is used to enable or disable the enforcement of
  2162. ** [foreign key constraints]. There should be two additional arguments.
  2163. ** The first argument is an integer which is 0 to disable FK enforcement,
  2164. ** positive to enable FK enforcement or negative to leave FK enforcement
  2165. ** unchanged. The second parameter is a pointer to an integer into which
  2166. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2167. ** following this call. The second parameter may be a NULL pointer, in
  2168. ** which case the FK enforcement setting is not reported back. </dd>
  2169. **
  2170. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2171. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2172. ** There should be two additional arguments.
  2173. ** The first argument is an integer which is 0 to disable triggers,
  2174. ** positive to enable triggers or negative to leave the setting unchanged.
  2175. ** The second parameter is a pointer to an integer into which
  2176. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2177. ** following this call. The second parameter may be a NULL pointer, in
  2178. ** which case the trigger setting is not reported back. </dd>
  2179. **
  2180. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  2181. ** <dd> ^This option is used to enable or disable the two-argument
  2182. ** version of the [fts3_tokenizer()] function which is part of the
  2183. ** [FTS3] full-text search engine extension.
  2184. ** There should be two additional arguments.
  2185. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  2186. ** positive to enable fts3_tokenizer() or negative to leave the setting
  2187. ** unchanged.
  2188. ** The second parameter is a pointer to an integer into which
  2189. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  2190. ** following this call. The second parameter may be a NULL pointer, in
  2191. ** which case the new setting is not reported back. </dd>
  2192. **
  2193. ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  2194. ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  2195. ** interface independently of the [load_extension()] SQL function.
  2196. ** The [sqlite3_enable_load_extension()] API enables or disables both the
  2197. ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  2198. ** There should be two additional arguments.
  2199. ** When the first argument to this interface is 1, then only the C-API is
  2200. ** enabled and the SQL function remains disabled. If the first argument to
  2201. ** this interface is 0, then both the C-API and the SQL function are disabled.
  2202. ** If the first argument is -1, then no changes are made to state of either the
  2203. ** C-API or the SQL function.
  2204. ** The second parameter is a pointer to an integer into which
  2205. ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  2206. ** is disabled or enabled following this call. The second parameter may
  2207. ** be a NULL pointer, in which case the new setting is not reported back.
  2208. ** </dd>
  2209. **
  2210. ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  2211. ** <dd> ^This option is used to change the name of the "main" database
  2212. ** schema. ^The sole argument is a pointer to a constant UTF8 string
  2213. ** which will become the new schema name in place of "main". ^SQLite
  2214. ** does not make a copy of the new main schema name string, so the application
  2215. ** must ensure that the argument passed into this DBCONFIG option is unchanged
  2216. ** until after the database connection closes.
  2217. ** </dd>
  2218. **
  2219. ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  2220. ** <dd> Usually, when a database in wal mode is closed or detached from a
  2221. ** database handle, SQLite checks if this will mean that there are now no
  2222. ** connections at all to the database. If so, it performs a checkpoint
  2223. ** operation before closing the connection. This option may be used to
  2224. ** override this behaviour. The first parameter passed to this operation
  2225. ** is an integer - non-zero to disable checkpoints-on-close, or zero (the
  2226. ** default) to enable them. The second parameter is a pointer to an integer
  2227. ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  2228. ** have been disabled - 0 if they are not disabled, 1 if they are.
  2229. ** </dd>
  2230. **
  2231. ** </dl>
  2232. */
  2233. #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
  2234. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2235. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2236. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2237. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  2238. #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  2239. #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
  2240. /*
  2241. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2242. ** METHOD: sqlite3
  2243. **
  2244. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2245. ** [extended result codes] feature of SQLite. ^The extended result
  2246. ** codes are disabled by default for historical compatibility.
  2247. */
  2248. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  2249. /*
  2250. ** CAPI3REF: Last Insert Rowid
  2251. ** METHOD: sqlite3
  2252. **
  2253. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  2254. ** has a unique 64-bit signed
  2255. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2256. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2257. ** names are not also used by explicitly declared columns. ^If
  2258. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2259. ** is another alias for the rowid.
  2260. **
  2261. ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  2262. ** the most recent successful [INSERT] into a rowid table or [virtual table]
  2263. ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  2264. ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
  2265. ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
  2266. ** zero.
  2267. **
  2268. ** As well as being set automatically as rows are inserted into database
  2269. ** tables, the value returned by this function may be set explicitly by
  2270. ** [sqlite3_set_last_insert_rowid()]
  2271. **
  2272. ** Some virtual table implementations may INSERT rows into rowid tables as
  2273. ** part of committing a transaction (e.g. to flush data accumulated in memory
  2274. ** to disk). In this case subsequent calls to this function return the rowid
  2275. ** associated with these internal INSERT operations, which leads to
  2276. ** unintuitive results. Virtual table implementations that do write to rowid
  2277. ** tables in this way can avoid this problem by restoring the original
  2278. ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
  2279. ** control to the user.
  2280. **
  2281. ** ^(If an [INSERT] occurs within a trigger then this routine will
  2282. ** return the [rowid] of the inserted row as long as the trigger is
  2283. ** running. Once the trigger program ends, the value returned
  2284. ** by this routine reverts to what it was before the trigger was fired.)^
  2285. **
  2286. ** ^An [INSERT] that fails due to a constraint violation is not a
  2287. ** successful [INSERT] and does not change the value returned by this
  2288. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2289. ** and INSERT OR ABORT make no changes to the return value of this
  2290. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2291. ** encounters a constraint violation, it does not fail. The
  2292. ** INSERT continues to completion after deleting rows that caused
  2293. ** the constraint problem so INSERT OR REPLACE will always change
  2294. ** the return value of this interface.)^
  2295. **
  2296. ** ^For the purposes of this routine, an [INSERT] is considered to
  2297. ** be successful even if it is subsequently rolled back.
  2298. **
  2299. ** This function is accessible to SQL statements via the
  2300. ** [last_insert_rowid() SQL function].
  2301. **
  2302. ** If a separate thread performs a new [INSERT] on the same
  2303. ** database connection while the [sqlite3_last_insert_rowid()]
  2304. ** function is running and thus changes the last insert [rowid],
  2305. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2306. ** unpredictable and might not equal either the old or the new
  2307. ** last insert [rowid].
  2308. */
  2309. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  2310. /*
  2311. ** CAPI3REF: Set the Last Insert Rowid value.
  2312. ** METHOD: sqlite3
  2313. **
  2314. ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  2315. ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
  2316. ** without inserting a row into the database.
  2317. */
  2318. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  2319. /*
  2320. ** CAPI3REF: Count The Number Of Rows Modified
  2321. ** METHOD: sqlite3
  2322. **
  2323. ** ^This function returns the number of rows modified, inserted or
  2324. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  2325. ** statement on the database connection specified by the only parameter.
  2326. ** ^Executing any other type of SQL statement does not modify the value
  2327. ** returned by this function.
  2328. **
  2329. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  2330. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  2331. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  2332. **
  2333. ** Changes to a view that are intercepted by
  2334. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  2335. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  2336. ** DELETE statement run on a view is always zero. Only changes made to real
  2337. ** tables are counted.
  2338. **
  2339. ** Things are more complicated if the sqlite3_changes() function is
  2340. ** executed while a trigger program is running. This may happen if the
  2341. ** program uses the [changes() SQL function], or if some other callback
  2342. ** function invokes sqlite3_changes() directly. Essentially:
  2343. **
  2344. ** <ul>
  2345. ** <li> ^(Before entering a trigger program the value returned by
  2346. ** sqlite3_changes() function is saved. After the trigger program
  2347. ** has finished, the original value is restored.)^
  2348. **
  2349. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  2350. ** statement sets the value returned by sqlite3_changes()
  2351. ** upon completion as normal. Of course, this value will not include
  2352. ** any changes performed by sub-triggers, as the sqlite3_changes()
  2353. ** value will be saved and restored after each sub-trigger has run.)^
  2354. ** </ul>
  2355. **
  2356. ** ^This means that if the changes() SQL function (or similar) is used
  2357. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  2358. ** returns the value as set when the calling statement began executing.
  2359. ** ^If it is used by the second or subsequent such statement within a trigger
  2360. ** program, the value returned reflects the number of rows modified by the
  2361. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  2362. **
  2363. ** See also the [sqlite3_total_changes()] interface, the
  2364. ** [count_changes pragma], and the [changes() SQL function].
  2365. **
  2366. ** If a separate thread makes changes on the same database connection
  2367. ** while [sqlite3_changes()] is running then the value returned
  2368. ** is unpredictable and not meaningful.
  2369. */
  2370. SQLITE_API int sqlite3_changes(sqlite3*);
  2371. /*
  2372. ** CAPI3REF: Total Number Of Rows Modified
  2373. ** METHOD: sqlite3
  2374. **
  2375. ** ^This function returns the total number of rows inserted, modified or
  2376. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  2377. ** since the database connection was opened, including those executed as
  2378. ** part of trigger programs. ^Executing any other type of SQL statement
  2379. ** does not affect the value returned by sqlite3_total_changes().
  2380. **
  2381. ** ^Changes made as part of [foreign key actions] are included in the
  2382. ** count, but those made as part of REPLACE constraint resolution are
  2383. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  2384. ** are not counted.
  2385. **
  2386. ** See also the [sqlite3_changes()] interface, the
  2387. ** [count_changes pragma], and the [total_changes() SQL function].
  2388. **
  2389. ** If a separate thread makes changes on the same database connection
  2390. ** while [sqlite3_total_changes()] is running then the value
  2391. ** returned is unpredictable and not meaningful.
  2392. */
  2393. SQLITE_API int sqlite3_total_changes(sqlite3*);
  2394. /*
  2395. ** CAPI3REF: Interrupt A Long-Running Query
  2396. ** METHOD: sqlite3
  2397. **
  2398. ** ^This function causes any pending database operation to abort and
  2399. ** return at its earliest opportunity. This routine is typically
  2400. ** called in response to a user action such as pressing "Cancel"
  2401. ** or Ctrl-C where the user wants a long query operation to halt
  2402. ** immediately.
  2403. **
  2404. ** ^It is safe to call this routine from a thread different from the
  2405. ** thread that is currently running the database operation. But it
  2406. ** is not safe to call this routine with a [database connection] that
  2407. ** is closed or might close before sqlite3_interrupt() returns.
  2408. **
  2409. ** ^If an SQL operation is very nearly finished at the time when
  2410. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2411. ** to be interrupted and might continue to completion.
  2412. **
  2413. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2414. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2415. ** that is inside an explicit transaction, then the entire transaction
  2416. ** will be rolled back automatically.
  2417. **
  2418. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2419. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2420. ** that are started after the sqlite3_interrupt() call and before the
  2421. ** running statements reaches zero are interrupted as if they had been
  2422. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2423. ** that are started after the running statement count reaches zero are
  2424. ** not effected by the sqlite3_interrupt().
  2425. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2426. ** SQL statements is a no-op and has no effect on SQL statements
  2427. ** that are started after the sqlite3_interrupt() call returns.
  2428. */
  2429. SQLITE_API void sqlite3_interrupt(sqlite3*);
  2430. /*
  2431. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2432. **
  2433. ** These routines are useful during command-line input to determine if the
  2434. ** currently entered text seems to form a complete SQL statement or
  2435. ** if additional input is needed before sending the text into
  2436. ** SQLite for parsing. ^These routines return 1 if the input string
  2437. ** appears to be a complete SQL statement. ^A statement is judged to be
  2438. ** complete if it ends with a semicolon token and is not a prefix of a
  2439. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2440. ** string literals or quoted identifier names or comments are not
  2441. ** independent tokens (they are part of the token in which they are
  2442. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2443. ** and comments that follow the final semicolon are ignored.
  2444. **
  2445. ** ^These routines return 0 if the statement is incomplete. ^If a
  2446. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2447. **
  2448. ** ^These routines do not parse the SQL statements thus
  2449. ** will not detect syntactically incorrect SQL.
  2450. **
  2451. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2452. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2453. ** automatically by sqlite3_complete16(). If that initialization fails,
  2454. ** then the return value from sqlite3_complete16() will be non-zero
  2455. ** regardless of whether or not the input SQL is complete.)^
  2456. **
  2457. ** The input to [sqlite3_complete()] must be a zero-terminated
  2458. ** UTF-8 string.
  2459. **
  2460. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2461. ** UTF-16 string in native byte order.
  2462. */
  2463. SQLITE_API int sqlite3_complete(const char *sql);
  2464. SQLITE_API int sqlite3_complete16(const void *sql);
  2465. /*
  2466. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2467. ** KEYWORDS: {busy-handler callback} {busy handler}
  2468. ** METHOD: sqlite3
  2469. **
  2470. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  2471. ** that might be invoked with argument P whenever
  2472. ** an attempt is made to access a database table associated with
  2473. ** [database connection] D when another thread
  2474. ** or process has the table locked.
  2475. ** The sqlite3_busy_handler() interface is used to implement
  2476. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2477. **
  2478. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2479. ** is returned immediately upon encountering the lock. ^If the busy callback
  2480. ** is not NULL, then the callback might be invoked with two arguments.
  2481. **
  2482. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2483. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2484. ** the busy handler callback is the number of times that the busy handler has
  2485. ** been invoked previously for the same locking event. ^If the
  2486. ** busy callback returns 0, then no additional attempts are made to
  2487. ** access the database and [SQLITE_BUSY] is returned
  2488. ** to the application.
  2489. ** ^If the callback returns non-zero, then another attempt
  2490. ** is made to access the database and the cycle repeats.
  2491. **
  2492. ** The presence of a busy handler does not guarantee that it will be invoked
  2493. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2494. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2495. ** to the application instead of invoking the
  2496. ** busy handler.
  2497. ** Consider a scenario where one process is holding a read lock that
  2498. ** it is trying to promote to a reserved lock and
  2499. ** a second process is holding a reserved lock that it is trying
  2500. ** to promote to an exclusive lock. The first process cannot proceed
  2501. ** because it is blocked by the second and the second process cannot
  2502. ** proceed because it is blocked by the first. If both processes
  2503. ** invoke the busy handlers, neither will make any progress. Therefore,
  2504. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2505. ** will induce the first process to release its read lock and allow
  2506. ** the second process to proceed.
  2507. **
  2508. ** ^The default busy callback is NULL.
  2509. **
  2510. ** ^(There can only be a single busy handler defined for each
  2511. ** [database connection]. Setting a new busy handler clears any
  2512. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2513. ** or evaluating [PRAGMA busy_timeout=N] will change the
  2514. ** busy handler and thus clear any previously set busy handler.
  2515. **
  2516. ** The busy callback should not take any actions which modify the
  2517. ** database connection that invoked the busy handler. In other words,
  2518. ** the busy handler is not reentrant. Any such actions
  2519. ** result in undefined behavior.
  2520. **
  2521. ** A busy handler must not close the database connection
  2522. ** or [prepared statement] that invoked the busy handler.
  2523. */
  2524. SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  2525. /*
  2526. ** CAPI3REF: Set A Busy Timeout
  2527. ** METHOD: sqlite3
  2528. **
  2529. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2530. ** for a specified amount of time when a table is locked. ^The handler
  2531. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2532. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2533. ** the handler returns 0 which causes [sqlite3_step()] to return
  2534. ** [SQLITE_BUSY].
  2535. **
  2536. ** ^Calling this routine with an argument less than or equal to zero
  2537. ** turns off all busy handlers.
  2538. **
  2539. ** ^(There can only be a single busy handler for a particular
  2540. ** [database connection] at any given moment. If another busy handler
  2541. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2542. ** this routine, that other busy handler is cleared.)^
  2543. **
  2544. ** See also: [PRAGMA busy_timeout]
  2545. */
  2546. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2547. /*
  2548. ** CAPI3REF: Convenience Routines For Running Queries
  2549. ** METHOD: sqlite3
  2550. **
  2551. ** This is a legacy interface that is preserved for backwards compatibility.
  2552. ** Use of this interface is not recommended.
  2553. **
  2554. ** Definition: A <b>result table</b> is memory data structure created by the
  2555. ** [sqlite3_get_table()] interface. A result table records the
  2556. ** complete query results from one or more queries.
  2557. **
  2558. ** The table conceptually has a number of rows and columns. But
  2559. ** these numbers are not part of the result table itself. These
  2560. ** numbers are obtained separately. Let N be the number of rows
  2561. ** and M be the number of columns.
  2562. **
  2563. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2564. ** There are (N+1)*M elements in the array. The first M pointers point
  2565. ** to zero-terminated strings that contain the names of the columns.
  2566. ** The remaining entries all point to query results. NULL values result
  2567. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2568. ** string representation as returned by [sqlite3_column_text()].
  2569. **
  2570. ** A result table might consist of one or more memory allocations.
  2571. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2572. ** A result table should be deallocated using [sqlite3_free_table()].
  2573. **
  2574. ** ^(As an example of the result table format, suppose a query result
  2575. ** is as follows:
  2576. **
  2577. ** <blockquote><pre>
  2578. ** Name | Age
  2579. ** -----------------------
  2580. ** Alice | 43
  2581. ** Bob | 28
  2582. ** Cindy | 21
  2583. ** </pre></blockquote>
  2584. **
  2585. ** There are two column (M==2) and three rows (N==3). Thus the
  2586. ** result table has 8 entries. Suppose the result table is stored
  2587. ** in an array names azResult. Then azResult holds this content:
  2588. **
  2589. ** <blockquote><pre>
  2590. ** azResult&#91;0] = "Name";
  2591. ** azResult&#91;1] = "Age";
  2592. ** azResult&#91;2] = "Alice";
  2593. ** azResult&#91;3] = "43";
  2594. ** azResult&#91;4] = "Bob";
  2595. ** azResult&#91;5] = "28";
  2596. ** azResult&#91;6] = "Cindy";
  2597. ** azResult&#91;7] = "21";
  2598. ** </pre></blockquote>)^
  2599. **
  2600. ** ^The sqlite3_get_table() function evaluates one or more
  2601. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2602. ** string of its 2nd parameter and returns a result table to the
  2603. ** pointer given in its 3rd parameter.
  2604. **
  2605. ** After the application has finished with the result from sqlite3_get_table(),
  2606. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2607. ** release the memory that was malloced. Because of the way the
  2608. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2609. ** function must not try to call [sqlite3_free()] directly. Only
  2610. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2611. **
  2612. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2613. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2614. ** to any internal data structures of SQLite. It uses only the public
  2615. ** interface defined here. As a consequence, errors that occur in the
  2616. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2617. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2618. ** [sqlite3_errmsg()].
  2619. */
  2620. SQLITE_API int sqlite3_get_table(
  2621. sqlite3 *db, /* An open database */
  2622. const char *zSql, /* SQL to be evaluated */
  2623. char ***pazResult, /* Results of the query */
  2624. int *pnRow, /* Number of result rows written here */
  2625. int *pnColumn, /* Number of result columns written here */
  2626. char **pzErrmsg /* Error msg written here */
  2627. );
  2628. SQLITE_API void sqlite3_free_table(char **result);
  2629. /*
  2630. ** CAPI3REF: Formatted String Printing Functions
  2631. **
  2632. ** These routines are work-alikes of the "printf()" family of functions
  2633. ** from the standard C library.
  2634. ** These routines understand most of the common K&R formatting options,
  2635. ** plus some additional non-standard formats, detailed below.
  2636. ** Note that some of the more obscure formatting options from recent
  2637. ** C-library standards are omitted from this implementation.
  2638. **
  2639. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2640. ** results into memory obtained from [sqlite3_malloc()].
  2641. ** The strings returned by these two routines should be
  2642. ** released by [sqlite3_free()]. ^Both routines return a
  2643. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2644. ** memory to hold the resulting string.
  2645. **
  2646. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2647. ** the standard C library. The result is written into the
  2648. ** buffer supplied as the second parameter whose size is given by
  2649. ** the first parameter. Note that the order of the
  2650. ** first two parameters is reversed from snprintf().)^ This is an
  2651. ** historical accident that cannot be fixed without breaking
  2652. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2653. ** returns a pointer to its buffer instead of the number of
  2654. ** characters actually written into the buffer.)^ We admit that
  2655. ** the number of characters written would be a more useful return
  2656. ** value but we cannot change the implementation of sqlite3_snprintf()
  2657. ** now without breaking compatibility.
  2658. **
  2659. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2660. ** guarantees that the buffer is always zero-terminated. ^The first
  2661. ** parameter "n" is the total size of the buffer, including space for
  2662. ** the zero terminator. So the longest string that can be completely
  2663. ** written will be n-1 characters.
  2664. **
  2665. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2666. **
  2667. ** These routines all implement some additional formatting
  2668. ** options that are useful for constructing SQL statements.
  2669. ** All of the usual printf() formatting options apply. In addition, there
  2670. ** is are "%q", "%Q", "%w" and "%z" options.
  2671. **
  2672. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2673. ** string from the argument list. But %q also doubles every '\'' character.
  2674. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2675. ** character it escapes that character and allows it to be inserted into
  2676. ** the string.
  2677. **
  2678. ** For example, assume the string variable zText contains text as follows:
  2679. **
  2680. ** <blockquote><pre>
  2681. ** char *zText = "It's a happy day!";
  2682. ** </pre></blockquote>
  2683. **
  2684. ** One can use this text in an SQL statement as follows:
  2685. **
  2686. ** <blockquote><pre>
  2687. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2688. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2689. ** sqlite3_free(zSQL);
  2690. ** </pre></blockquote>
  2691. **
  2692. ** Because the %q format string is used, the '\'' character in zText
  2693. ** is escaped and the SQL generated is as follows:
  2694. **
  2695. ** <blockquote><pre>
  2696. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2697. ** </pre></blockquote>
  2698. **
  2699. ** This is correct. Had we used %s instead of %q, the generated SQL
  2700. ** would have looked like this:
  2701. **
  2702. ** <blockquote><pre>
  2703. ** INSERT INTO table1 VALUES('It's a happy day!');
  2704. ** </pre></blockquote>
  2705. **
  2706. ** This second example is an SQL syntax error. As a general rule you should
  2707. ** always use %q instead of %s when inserting text into a string literal.
  2708. **
  2709. ** ^(The %Q option works like %q except it also adds single quotes around
  2710. ** the outside of the total string. Additionally, if the parameter in the
  2711. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2712. ** single quotes).)^ So, for example, one could say:
  2713. **
  2714. ** <blockquote><pre>
  2715. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2716. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2717. ** sqlite3_free(zSQL);
  2718. ** </pre></blockquote>
  2719. **
  2720. ** The code above will render a correct SQL statement in the zSQL
  2721. ** variable even if the zText variable is a NULL pointer.
  2722. **
  2723. ** ^(The "%w" formatting option is like "%q" except that it expects to
  2724. ** be contained within double-quotes instead of single quotes, and it
  2725. ** escapes the double-quote character instead of the single-quote
  2726. ** character.)^ The "%w" formatting option is intended for safely inserting
  2727. ** table and column names into a constructed SQL statement.
  2728. **
  2729. ** ^(The "%z" formatting option works like "%s" but with the
  2730. ** addition that after the string has been read and copied into
  2731. ** the result, [sqlite3_free()] is called on the input string.)^
  2732. */
  2733. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2734. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2735. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2736. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2737. /*
  2738. ** CAPI3REF: Memory Allocation Subsystem
  2739. **
  2740. ** The SQLite core uses these three routines for all of its own
  2741. ** internal memory allocation needs. "Core" in the previous sentence
  2742. ** does not include operating-system specific VFS implementation. The
  2743. ** Windows VFS uses native malloc() and free() for some operations.
  2744. **
  2745. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2746. ** of memory at least N bytes in length, where N is the parameter.
  2747. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2748. ** memory, it returns a NULL pointer. ^If the parameter N to
  2749. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2750. ** a NULL pointer.
  2751. **
  2752. ** ^The sqlite3_malloc64(N) routine works just like
  2753. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  2754. ** of a signed 32-bit integer.
  2755. **
  2756. ** ^Calling sqlite3_free() with a pointer previously returned
  2757. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2758. ** that it might be reused. ^The sqlite3_free() routine is
  2759. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2760. ** to sqlite3_free() is harmless. After being freed, memory
  2761. ** should neither be read nor written. Even reading previously freed
  2762. ** memory might result in a segmentation fault or other severe error.
  2763. ** Memory corruption, a segmentation fault, or other severe error
  2764. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2765. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2766. **
  2767. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  2768. ** prior memory allocation X to be at least N bytes.
  2769. ** ^If the X parameter to sqlite3_realloc(X,N)
  2770. ** is a NULL pointer then its behavior is identical to calling
  2771. ** sqlite3_malloc(N).
  2772. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  2773. ** negative then the behavior is exactly the same as calling
  2774. ** sqlite3_free(X).
  2775. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  2776. ** of at least N bytes in size or NULL if insufficient memory is available.
  2777. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2778. ** of the prior allocation are copied into the beginning of buffer returned
  2779. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  2780. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  2781. ** prior allocation is not freed.
  2782. **
  2783. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  2784. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  2785. ** of a 32-bit signed integer.
  2786. **
  2787. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  2788. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  2789. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  2790. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  2791. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  2792. ** sqlite3_msize(X) returns zero. If X points to something that is not
  2793. ** the beginning of memory allocation, or if it points to a formerly
  2794. ** valid memory allocation that has now been freed, then the behavior
  2795. ** of sqlite3_msize(X) is undefined and possibly harmful.
  2796. **
  2797. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  2798. ** sqlite3_malloc64(), and sqlite3_realloc64()
  2799. ** is always aligned to at least an 8 byte boundary, or to a
  2800. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2801. ** option is used.
  2802. **
  2803. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2804. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2805. ** implementation of these routines to be omitted. That capability
  2806. ** is no longer provided. Only built-in memory allocators can be used.
  2807. **
  2808. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2809. ** the system malloc() and free() directly when converting
  2810. ** filenames between the UTF-8 encoding used by SQLite
  2811. ** and whatever filename encoding is used by the particular Windows
  2812. ** installation. Memory allocation errors were detected, but
  2813. ** they were reported back as [SQLITE_CANTOPEN] or
  2814. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2815. **
  2816. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2817. ** must be either NULL or else pointers obtained from a prior
  2818. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2819. ** not yet been released.
  2820. **
  2821. ** The application must not read or write any part of
  2822. ** a block of memory after it has been released using
  2823. ** [sqlite3_free()] or [sqlite3_realloc()].
  2824. */
  2825. SQLITE_API void *sqlite3_malloc(int);
  2826. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  2827. SQLITE_API void *sqlite3_realloc(void*, int);
  2828. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  2829. SQLITE_API void sqlite3_free(void*);
  2830. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  2831. /*
  2832. ** CAPI3REF: Memory Allocator Statistics
  2833. **
  2834. ** SQLite provides these two interfaces for reporting on the status
  2835. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2836. ** routines, which form the built-in memory allocation subsystem.
  2837. **
  2838. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2839. ** of memory currently outstanding (malloced but not freed).
  2840. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2841. ** value of [sqlite3_memory_used()] since the high-water mark
  2842. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2843. ** [sqlite3_memory_highwater()] include any overhead
  2844. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2845. ** but not overhead added by the any underlying system library
  2846. ** routines that [sqlite3_malloc()] may call.
  2847. **
  2848. ** ^The memory high-water mark is reset to the current value of
  2849. ** [sqlite3_memory_used()] if and only if the parameter to
  2850. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2851. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2852. ** prior to the reset.
  2853. */
  2854. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2855. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2856. /*
  2857. ** CAPI3REF: Pseudo-Random Number Generator
  2858. **
  2859. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2860. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2861. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2862. ** the build-in random() and randomblob() SQL functions. This interface allows
  2863. ** applications to access the same PRNG for other purposes.
  2864. **
  2865. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2866. ** ^The P parameter can be a NULL pointer.
  2867. **
  2868. ** ^If this routine has not been previously called or if the previous
  2869. ** call had N less than one or a NULL pointer for P, then the PRNG is
  2870. ** seeded using randomness obtained from the xRandomness method of
  2871. ** the default [sqlite3_vfs] object.
  2872. ** ^If the previous call to this routine had an N of 1 or more and a
  2873. ** non-NULL P then the pseudo-randomness is generated
  2874. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2875. ** method.
  2876. */
  2877. SQLITE_API void sqlite3_randomness(int N, void *P);
  2878. /*
  2879. ** CAPI3REF: Compile-Time Authorization Callbacks
  2880. ** METHOD: sqlite3
  2881. ** KEYWORDS: {authorizer callback}
  2882. **
  2883. ** ^This routine registers an authorizer callback with a particular
  2884. ** [database connection], supplied in the first argument.
  2885. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2886. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2887. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2888. ** points during the compilation process, as logic is being created
  2889. ** to perform various actions, the authorizer callback is invoked to
  2890. ** see if those actions are allowed. ^The authorizer callback should
  2891. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2892. ** specific action but allow the SQL statement to continue to be
  2893. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2894. ** rejected with an error. ^If the authorizer callback returns
  2895. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2896. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2897. ** the authorizer will fail with an error message.
  2898. **
  2899. ** When the callback returns [SQLITE_OK], that means the operation
  2900. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2901. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2902. ** authorizer will fail with an error message explaining that
  2903. ** access is denied.
  2904. **
  2905. ** ^The first parameter to the authorizer callback is a copy of the third
  2906. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2907. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2908. ** the particular action to be authorized. ^The third through sixth parameters
  2909. ** to the callback are either NULL pointers or zero-terminated strings
  2910. ** that contain additional details about the action to be authorized.
  2911. ** Applications must always be prepared to encounter a NULL pointer in any
  2912. ** of the third through the sixth parameters of the authorization callback.
  2913. **
  2914. ** ^If the action code is [SQLITE_READ]
  2915. ** and the callback returns [SQLITE_IGNORE] then the
  2916. ** [prepared statement] statement is constructed to substitute
  2917. ** a NULL value in place of the table column that would have
  2918. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2919. ** return can be used to deny an untrusted user access to individual
  2920. ** columns of a table.
  2921. ** ^When a table is referenced by a [SELECT] but no column values are
  2922. ** extracted from that table (for example in a query like
  2923. ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  2924. ** is invoked once for that table with a column name that is an empty string.
  2925. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2926. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2927. ** [truncate optimization] is disabled and all rows are deleted individually.
  2928. **
  2929. ** An authorizer is used when [sqlite3_prepare | preparing]
  2930. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2931. ** do not try to access data they are not allowed to see, or that they do not
  2932. ** try to execute malicious statements that damage the database. For
  2933. ** example, an application may allow a user to enter arbitrary
  2934. ** SQL queries for evaluation by a database. But the application does
  2935. ** not want the user to be able to make arbitrary changes to the
  2936. ** database. An authorizer could then be put in place while the
  2937. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2938. ** disallows everything except [SELECT] statements.
  2939. **
  2940. ** Applications that need to process SQL from untrusted sources
  2941. ** might also consider lowering resource limits using [sqlite3_limit()]
  2942. ** and limiting database size using the [max_page_count] [PRAGMA]
  2943. ** in addition to using an authorizer.
  2944. **
  2945. ** ^(Only a single authorizer can be in place on a database connection
  2946. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2947. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2948. ** The authorizer is disabled by default.
  2949. **
  2950. ** The authorizer callback must not do anything that will modify
  2951. ** the database connection that invoked the authorizer callback.
  2952. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2953. ** database connections for the meaning of "modify" in this paragraph.
  2954. **
  2955. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2956. ** statement might be re-prepared during [sqlite3_step()] due to a
  2957. ** schema change. Hence, the application should ensure that the
  2958. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2959. **
  2960. ** ^Note that the authorizer callback is invoked only during
  2961. ** [sqlite3_prepare()] or its variants. Authorization is not
  2962. ** performed during statement evaluation in [sqlite3_step()], unless
  2963. ** as stated in the previous paragraph, sqlite3_step() invokes
  2964. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2965. */
  2966. SQLITE_API int sqlite3_set_authorizer(
  2967. sqlite3*,
  2968. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2969. void *pUserData
  2970. );
  2971. /*
  2972. ** CAPI3REF: Authorizer Return Codes
  2973. **
  2974. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2975. ** return either [SQLITE_OK] or one of these two constants in order
  2976. ** to signal SQLite whether or not the action is permitted. See the
  2977. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2978. ** information.
  2979. **
  2980. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  2981. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  2982. */
  2983. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2984. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2985. /*
  2986. ** CAPI3REF: Authorizer Action Codes
  2987. **
  2988. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2989. ** that is invoked to authorize certain SQL statement actions. The
  2990. ** second parameter to the callback is an integer code that specifies
  2991. ** what action is being authorized. These are the integer action codes that
  2992. ** the authorizer callback may be passed.
  2993. **
  2994. ** These action code values signify what kind of operation is to be
  2995. ** authorized. The 3rd and 4th parameters to the authorization
  2996. ** callback function will be parameters or NULL depending on which of these
  2997. ** codes is used as the second parameter. ^(The 5th parameter to the
  2998. ** authorizer callback is the name of the database ("main", "temp",
  2999. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  3000. ** is the name of the inner-most trigger or view that is responsible for
  3001. ** the access attempt or NULL if this access attempt is directly from
  3002. ** top-level SQL code.
  3003. */
  3004. /******************************************* 3rd ************ 4th ***********/
  3005. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  3006. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  3007. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  3008. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  3009. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  3010. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  3011. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  3012. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  3013. #define SQLITE_DELETE 9 /* Table Name NULL */
  3014. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  3015. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  3016. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  3017. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  3018. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  3019. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  3020. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  3021. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  3022. #define SQLITE_INSERT 18 /* Table Name NULL */
  3023. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  3024. #define SQLITE_READ 20 /* Table Name Column Name */
  3025. #define SQLITE_SELECT 21 /* NULL NULL */
  3026. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  3027. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  3028. #define SQLITE_ATTACH 24 /* Filename NULL */
  3029. #define SQLITE_DETACH 25 /* Database Name NULL */
  3030. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  3031. #define SQLITE_REINDEX 27 /* Index Name NULL */
  3032. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  3033. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  3034. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  3035. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  3036. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  3037. #define SQLITE_COPY 0 /* No longer used */
  3038. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  3039. /*
  3040. ** CAPI3REF: Tracing And Profiling Functions
  3041. ** METHOD: sqlite3
  3042. **
  3043. ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  3044. ** instead of the routines described here.
  3045. **
  3046. ** These routines register callback functions that can be used for
  3047. ** tracing and profiling the execution of SQL statements.
  3048. **
  3049. ** ^The callback function registered by sqlite3_trace() is invoked at
  3050. ** various times when an SQL statement is being run by [sqlite3_step()].
  3051. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  3052. ** SQL statement text as the statement first begins executing.
  3053. ** ^(Additional sqlite3_trace() callbacks might occur
  3054. ** as each triggered subprogram is entered. The callbacks for triggers
  3055. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  3056. **
  3057. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  3058. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  3059. **
  3060. ** ^The callback function registered by sqlite3_profile() is invoked
  3061. ** as each SQL statement finishes. ^The profile callback contains
  3062. ** the original statement text and an estimate of wall-clock time
  3063. ** of how long that statement took to run. ^The profile callback
  3064. ** time is in units of nanoseconds, however the current implementation
  3065. ** is only capable of millisecond resolution so the six least significant
  3066. ** digits in the time are meaningless. Future versions of SQLite
  3067. ** might provide greater resolution on the profiler callback. The
  3068. ** sqlite3_profile() function is considered experimental and is
  3069. ** subject to change in future versions of SQLite.
  3070. */
  3071. SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  3072. void(*xTrace)(void*,const char*), void*);
  3073. SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  3074. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  3075. /*
  3076. ** CAPI3REF: SQL Trace Event Codes
  3077. ** KEYWORDS: SQLITE_TRACE
  3078. **
  3079. ** These constants identify classes of events that can be monitored
  3080. ** using the [sqlite3_trace_v2()] tracing logic. The third argument
  3081. ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
  3082. ** the following constants. ^The first argument to the trace callback
  3083. ** is one of the following constants.
  3084. **
  3085. ** New tracing constants may be added in future releases.
  3086. **
  3087. ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  3088. ** ^The T argument is one of the integer type codes above.
  3089. ** ^The C argument is a copy of the context pointer passed in as the
  3090. ** fourth argument to [sqlite3_trace_v2()].
  3091. ** The P and X arguments are pointers whose meanings depend on T.
  3092. **
  3093. ** <dl>
  3094. ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  3095. ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  3096. ** first begins running and possibly at other times during the
  3097. ** execution of the prepared statement, such as at the start of each
  3098. ** trigger subprogram. ^The P argument is a pointer to the
  3099. ** [prepared statement]. ^The X argument is a pointer to a string which
  3100. ** is the unexpanded SQL text of the prepared statement or an SQL comment
  3101. ** that indicates the invocation of a trigger. ^The callback can compute
  3102. ** the same text that would have been returned by the legacy [sqlite3_trace()]
  3103. ** interface by using the X argument when X begins with "--" and invoking
  3104. ** [sqlite3_expanded_sql(P)] otherwise.
  3105. **
  3106. ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  3107. ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  3108. ** information as is provided by the [sqlite3_profile()] callback.
  3109. ** ^The P argument is a pointer to the [prepared statement] and the
  3110. ** X argument points to a 64-bit integer which is the estimated of
  3111. ** the number of nanosecond that the prepared statement took to run.
  3112. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  3113. **
  3114. ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  3115. ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  3116. ** statement generates a single row of result.
  3117. ** ^The P argument is a pointer to the [prepared statement] and the
  3118. ** X argument is unused.
  3119. **
  3120. ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  3121. ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  3122. ** connection closes.
  3123. ** ^The P argument is a pointer to the [database connection] object
  3124. ** and the X argument is unused.
  3125. ** </dl>
  3126. */
  3127. #define SQLITE_TRACE_STMT 0x01
  3128. #define SQLITE_TRACE_PROFILE 0x02
  3129. #define SQLITE_TRACE_ROW 0x04
  3130. #define SQLITE_TRACE_CLOSE 0x08
  3131. /*
  3132. ** CAPI3REF: SQL Trace Hook
  3133. ** METHOD: sqlite3
  3134. **
  3135. ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  3136. ** function X against [database connection] D, using property mask M
  3137. ** and context pointer P. ^If the X callback is
  3138. ** NULL or if the M mask is zero, then tracing is disabled. The
  3139. ** M argument should be the bitwise OR-ed combination of
  3140. ** zero or more [SQLITE_TRACE] constants.
  3141. **
  3142. ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
  3143. ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  3144. **
  3145. ** ^The X callback is invoked whenever any of the events identified by
  3146. ** mask M occur. ^The integer return value from the callback is currently
  3147. ** ignored, though this may change in future releases. Callback
  3148. ** implementations should return zero to ensure future compatibility.
  3149. **
  3150. ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  3151. ** ^The T argument is one of the [SQLITE_TRACE]
  3152. ** constants to indicate why the callback was invoked.
  3153. ** ^The C argument is a copy of the context pointer.
  3154. ** The P and X arguments are pointers whose meanings depend on T.
  3155. **
  3156. ** The sqlite3_trace_v2() interface is intended to replace the legacy
  3157. ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  3158. ** are deprecated.
  3159. */
  3160. SQLITE_API int sqlite3_trace_v2(
  3161. sqlite3*,
  3162. unsigned uMask,
  3163. int(*xCallback)(unsigned,void*,void*,void*),
  3164. void *pCtx
  3165. );
  3166. /*
  3167. ** CAPI3REF: Query Progress Callbacks
  3168. ** METHOD: sqlite3
  3169. **
  3170. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  3171. ** function X to be invoked periodically during long running calls to
  3172. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  3173. ** database connection D. An example use for this
  3174. ** interface is to keep a GUI updated during a large query.
  3175. **
  3176. ** ^The parameter P is passed through as the only parameter to the
  3177. ** callback function X. ^The parameter N is the approximate number of
  3178. ** [virtual machine instructions] that are evaluated between successive
  3179. ** invocations of the callback X. ^If N is less than one then the progress
  3180. ** handler is disabled.
  3181. **
  3182. ** ^Only a single progress handler may be defined at one time per
  3183. ** [database connection]; setting a new progress handler cancels the
  3184. ** old one. ^Setting parameter X to NULL disables the progress handler.
  3185. ** ^The progress handler is also disabled by setting N to a value less
  3186. ** than 1.
  3187. **
  3188. ** ^If the progress callback returns non-zero, the operation is
  3189. ** interrupted. This feature can be used to implement a
  3190. ** "Cancel" button on a GUI progress dialog box.
  3191. **
  3192. ** The progress handler callback must not do anything that will modify
  3193. ** the database connection that invoked the progress handler.
  3194. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3195. ** database connections for the meaning of "modify" in this paragraph.
  3196. **
  3197. */
  3198. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  3199. /*
  3200. ** CAPI3REF: Opening A New Database Connection
  3201. ** CONSTRUCTOR: sqlite3
  3202. **
  3203. ** ^These routines open an SQLite database file as specified by the
  3204. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  3205. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  3206. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  3207. ** returned in *ppDb, even if an error occurs. The only exception is that
  3208. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  3209. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  3210. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  3211. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  3212. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  3213. ** an English language description of the error following a failure of any
  3214. ** of the sqlite3_open() routines.
  3215. **
  3216. ** ^The default encoding will be UTF-8 for databases created using
  3217. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  3218. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  3219. **
  3220. ** Whether or not an error occurs when it is opened, resources
  3221. ** associated with the [database connection] handle should be released by
  3222. ** passing it to [sqlite3_close()] when it is no longer required.
  3223. **
  3224. ** The sqlite3_open_v2() interface works like sqlite3_open()
  3225. ** except that it accepts two additional parameters for additional control
  3226. ** over the new database connection. ^(The flags parameter to
  3227. ** sqlite3_open_v2() can take one of
  3228. ** the following three values, optionally combined with the
  3229. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  3230. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  3231. **
  3232. ** <dl>
  3233. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  3234. ** <dd>The database is opened in read-only mode. If the database does not
  3235. ** already exist, an error is returned.</dd>)^
  3236. **
  3237. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  3238. ** <dd>The database is opened for reading and writing if possible, or reading
  3239. ** only if the file is write protected by the operating system. In either
  3240. ** case the database must already exist, otherwise an error is returned.</dd>)^
  3241. **
  3242. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  3243. ** <dd>The database is opened for reading and writing, and is created if
  3244. ** it does not already exist. This is the behavior that is always used for
  3245. ** sqlite3_open() and sqlite3_open16().</dd>)^
  3246. ** </dl>
  3247. **
  3248. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  3249. ** combinations shown above optionally combined with other
  3250. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  3251. ** then the behavior is undefined.
  3252. **
  3253. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  3254. ** opens in the multi-thread [threading mode] as long as the single-thread
  3255. ** mode has not been set at compile-time or start-time. ^If the
  3256. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  3257. ** in the serialized [threading mode] unless single-thread was
  3258. ** previously selected at compile-time or start-time.
  3259. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  3260. ** eligible to use [shared cache mode], regardless of whether or not shared
  3261. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  3262. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  3263. ** participate in [shared cache mode] even if it is enabled.
  3264. **
  3265. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  3266. ** [sqlite3_vfs] object that defines the operating system interface that
  3267. ** the new database connection should use. ^If the fourth parameter is
  3268. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  3269. **
  3270. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  3271. ** is created for the connection. ^This in-memory database will vanish when
  3272. ** the database connection is closed. Future versions of SQLite might
  3273. ** make use of additional special filenames that begin with the ":" character.
  3274. ** It is recommended that when a database filename actually does begin with
  3275. ** a ":" character you should prefix the filename with a pathname such as
  3276. ** "./" to avoid ambiguity.
  3277. **
  3278. ** ^If the filename is an empty string, then a private, temporary
  3279. ** on-disk database will be created. ^This private database will be
  3280. ** automatically deleted as soon as the database connection is closed.
  3281. **
  3282. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  3283. **
  3284. ** ^If [URI filename] interpretation is enabled, and the filename argument
  3285. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  3286. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  3287. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  3288. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  3289. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  3290. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  3291. ** by default, but future releases of SQLite might enable URI filename
  3292. ** interpretation by default. See "[URI filenames]" for additional
  3293. ** information.
  3294. **
  3295. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  3296. ** authority, then it must be either an empty string or the string
  3297. ** "localhost". ^If the authority is not an empty string or "localhost", an
  3298. ** error is returned to the caller. ^The fragment component of a URI, if
  3299. ** present, is ignored.
  3300. **
  3301. ** ^SQLite uses the path component of the URI as the name of the disk file
  3302. ** which contains the database. ^If the path begins with a '/' character,
  3303. ** then it is interpreted as an absolute path. ^If the path does not begin
  3304. ** with a '/' (meaning that the authority section is omitted from the URI)
  3305. ** then the path is interpreted as a relative path.
  3306. ** ^(On windows, the first component of an absolute path
  3307. ** is a drive specification (e.g. "C:").)^
  3308. **
  3309. ** [[core URI query parameters]]
  3310. ** The query component of a URI may contain parameters that are interpreted
  3311. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  3312. ** SQLite and its built-in [VFSes] interpret the
  3313. ** following query parameters:
  3314. **
  3315. ** <ul>
  3316. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  3317. ** a VFS object that provides the operating system interface that should
  3318. ** be used to access the database file on disk. ^If this option is set to
  3319. ** an empty string the default VFS object is used. ^Specifying an unknown
  3320. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  3321. ** present, then the VFS specified by the option takes precedence over
  3322. ** the value passed as the fourth parameter to sqlite3_open_v2().
  3323. **
  3324. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  3325. ** "rwc", or "memory". Attempting to set it to any other value is
  3326. ** an error)^.
  3327. ** ^If "ro" is specified, then the database is opened for read-only
  3328. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  3329. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  3330. ** "rw", then the database is opened for read-write (but not create)
  3331. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  3332. ** been set. ^Value "rwc" is equivalent to setting both
  3333. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  3334. ** set to "memory" then a pure [in-memory database] that never reads
  3335. ** or writes from disk is used. ^It is an error to specify a value for
  3336. ** the mode parameter that is less restrictive than that specified by
  3337. ** the flags passed in the third parameter to sqlite3_open_v2().
  3338. **
  3339. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3340. ** "private". ^Setting it to "shared" is equivalent to setting the
  3341. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3342. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3343. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3344. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3345. ** a URI filename, its value overrides any behavior requested by setting
  3346. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3347. **
  3348. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  3349. ** [powersafe overwrite] property does or does not apply to the
  3350. ** storage media on which the database file resides.
  3351. **
  3352. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  3353. ** which if set disables file locking in rollback journal modes. This
  3354. ** is useful for accessing a database on a filesystem that does not
  3355. ** support locking. Caution: Database corruption might result if two
  3356. ** or more processes write to the same database and any one of those
  3357. ** processes uses nolock=1.
  3358. **
  3359. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  3360. ** parameter that indicates that the database file is stored on
  3361. ** read-only media. ^When immutable is set, SQLite assumes that the
  3362. ** database file cannot be changed, even by a process with higher
  3363. ** privilege, and so the database is opened read-only and all locking
  3364. ** and change detection is disabled. Caution: Setting the immutable
  3365. ** property on a database file that does in fact change can result
  3366. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  3367. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  3368. **
  3369. ** </ul>
  3370. **
  3371. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3372. ** error. Future versions of SQLite might understand additional query
  3373. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3374. ** additional information.
  3375. **
  3376. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3377. **
  3378. ** <table border="1" align=center cellpadding=5>
  3379. ** <tr><th> URI filenames <th> Results
  3380. ** <tr><td> file:data.db <td>
  3381. ** Open the file "data.db" in the current directory.
  3382. ** <tr><td> file:/home/fred/data.db<br>
  3383. ** file:///home/fred/data.db <br>
  3384. ** file://localhost/home/fred/data.db <br> <td>
  3385. ** Open the database file "/home/fred/data.db".
  3386. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3387. ** An error. "darkstar" is not a recognized authority.
  3388. ** <tr><td style="white-space:nowrap">
  3389. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3390. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3391. ** C:. Note that the %20 escaping in this example is not strictly
  3392. ** necessary - space characters can be used literally
  3393. ** in URI filenames.
  3394. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3395. ** Open file "data.db" in the current directory for read-only access.
  3396. ** Regardless of whether or not shared-cache mode is enabled by
  3397. ** default, use a private cache.
  3398. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  3399. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  3400. ** that uses dot-files in place of posix advisory locking.
  3401. ** <tr><td> file:data.db?mode=readonly <td>
  3402. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3403. ** </table>
  3404. **
  3405. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3406. ** query components of a URI. A hexadecimal escape sequence consists of a
  3407. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3408. ** specifying an octet value. ^Before the path or query components of a
  3409. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3410. ** hexadecimal escape sequences replaced by a single byte containing the
  3411. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3412. ** the results are undefined.
  3413. **
  3414. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3415. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3416. ** codepage is currently defined. Filenames containing international
  3417. ** characters must be converted to UTF-8 prior to passing them into
  3418. ** sqlite3_open() or sqlite3_open_v2().
  3419. **
  3420. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  3421. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  3422. ** features that require the use of temporary files may fail.
  3423. **
  3424. ** See also: [sqlite3_temp_directory]
  3425. */
  3426. SQLITE_API int sqlite3_open(
  3427. const char *filename, /* Database filename (UTF-8) */
  3428. sqlite3 **ppDb /* OUT: SQLite db handle */
  3429. );
  3430. SQLITE_API int sqlite3_open16(
  3431. const void *filename, /* Database filename (UTF-16) */
  3432. sqlite3 **ppDb /* OUT: SQLite db handle */
  3433. );
  3434. SQLITE_API int sqlite3_open_v2(
  3435. const char *filename, /* Database filename (UTF-8) */
  3436. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3437. int flags, /* Flags */
  3438. const char *zVfs /* Name of VFS module to use */
  3439. );
  3440. /*
  3441. ** CAPI3REF: Obtain Values For URI Parameters
  3442. **
  3443. ** These are utility routines, useful to VFS implementations, that check
  3444. ** to see if a database file was a URI that contained a specific query
  3445. ** parameter, and if so obtains the value of that query parameter.
  3446. **
  3447. ** If F is the database filename pointer passed into the xOpen() method of
  3448. ** a VFS implementation when the flags parameter to xOpen() has one or
  3449. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3450. ** P is the name of the query parameter, then
  3451. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3452. ** parameter if it exists or a NULL pointer if P does not appear as a
  3453. ** query parameter on F. If P is a query parameter of F
  3454. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3455. ** a pointer to an empty string.
  3456. **
  3457. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3458. ** parameter and returns true (1) or false (0) according to the value
  3459. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  3460. ** value of query parameter P is one of "yes", "true", or "on" in any
  3461. ** case or if the value begins with a non-zero number. The
  3462. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  3463. ** query parameter P is one of "no", "false", or "off" in any case or
  3464. ** if the value begins with a numeric zero. If P is not a query
  3465. ** parameter on F or if the value of P is does not match any of the
  3466. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3467. **
  3468. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3469. ** 64-bit signed integer and returns that integer, or D if P does not
  3470. ** exist. If the value of P is something other than an integer, then
  3471. ** zero is returned.
  3472. **
  3473. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3474. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3475. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3476. ** VFS method, then the behavior of this routine is undefined and probably
  3477. ** undesirable.
  3478. */
  3479. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3480. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3481. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3482. /*
  3483. ** CAPI3REF: Error Codes And Messages
  3484. ** METHOD: sqlite3
  3485. **
  3486. ** ^If the most recent sqlite3_* API call associated with
  3487. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  3488. ** returns the numeric [result code] or [extended result code] for that
  3489. ** API call.
  3490. ** If the most recent API call was successful,
  3491. ** then the return value from sqlite3_errcode() is undefined.
  3492. ** ^The sqlite3_extended_errcode()
  3493. ** interface is the same except that it always returns the
  3494. ** [extended result code] even when extended result codes are
  3495. ** disabled.
  3496. **
  3497. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3498. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3499. ** ^(Memory to hold the error message string is managed internally.
  3500. ** The application does not need to worry about freeing the result.
  3501. ** However, the error string might be overwritten or deallocated by
  3502. ** subsequent calls to other SQLite interface functions.)^
  3503. **
  3504. ** ^The sqlite3_errstr() interface returns the English-language text
  3505. ** that describes the [result code], as UTF-8.
  3506. ** ^(Memory to hold the error message string is managed internally
  3507. ** and must not be freed by the application)^.
  3508. **
  3509. ** When the serialized [threading mode] is in use, it might be the
  3510. ** case that a second error occurs on a separate thread in between
  3511. ** the time of the first error and the call to these interfaces.
  3512. ** When that happens, the second error will be reported since these
  3513. ** interfaces always report the most recent result. To avoid
  3514. ** this, each thread can obtain exclusive use of the [database connection] D
  3515. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3516. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3517. ** all calls to the interfaces listed here are completed.
  3518. **
  3519. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3520. ** was invoked incorrectly by the application. In that case, the
  3521. ** error code and message may or may not be set.
  3522. */
  3523. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  3524. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  3525. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  3526. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  3527. SQLITE_API const char *sqlite3_errstr(int);
  3528. /*
  3529. ** CAPI3REF: Prepared Statement Object
  3530. ** KEYWORDS: {prepared statement} {prepared statements}
  3531. **
  3532. ** An instance of this object represents a single SQL statement that
  3533. ** has been compiled into binary form and is ready to be evaluated.
  3534. **
  3535. ** Think of each SQL statement as a separate computer program. The
  3536. ** original SQL text is source code. A prepared statement object
  3537. ** is the compiled object code. All SQL must be converted into a
  3538. ** prepared statement before it can be run.
  3539. **
  3540. ** The life-cycle of a prepared statement object usually goes like this:
  3541. **
  3542. ** <ol>
  3543. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  3544. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  3545. ** interfaces.
  3546. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3547. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  3548. ** to step 2. Do this zero or more times.
  3549. ** <li> Destroy the object using [sqlite3_finalize()].
  3550. ** </ol>
  3551. */
  3552. typedef struct sqlite3_stmt sqlite3_stmt;
  3553. /*
  3554. ** CAPI3REF: Run-time Limits
  3555. ** METHOD: sqlite3
  3556. **
  3557. ** ^(This interface allows the size of various constructs to be limited
  3558. ** on a connection by connection basis. The first parameter is the
  3559. ** [database connection] whose limit is to be set or queried. The
  3560. ** second parameter is one of the [limit categories] that define a
  3561. ** class of constructs to be size limited. The third parameter is the
  3562. ** new limit for that construct.)^
  3563. **
  3564. ** ^If the new limit is a negative number, the limit is unchanged.
  3565. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3566. ** [limits | hard upper bound]
  3567. ** set at compile-time by a C preprocessor macro called
  3568. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3569. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3570. ** ^Attempts to increase a limit above its hard upper bound are
  3571. ** silently truncated to the hard upper bound.
  3572. **
  3573. ** ^Regardless of whether or not the limit was changed, the
  3574. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3575. ** ^Hence, to find the current value of a limit without changing it,
  3576. ** simply invoke this interface with the third parameter set to -1.
  3577. **
  3578. ** Run-time limits are intended for use in applications that manage
  3579. ** both their own internal database and also databases that are controlled
  3580. ** by untrusted external sources. An example application might be a
  3581. ** web browser that has its own databases for storing history and
  3582. ** separate databases controlled by JavaScript applications downloaded
  3583. ** off the Internet. The internal databases can be given the
  3584. ** large, default limits. Databases managed by external sources can
  3585. ** be given much smaller limits designed to prevent a denial of service
  3586. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3587. ** interface to further control untrusted SQL. The size of the database
  3588. ** created by an untrusted script can be contained using the
  3589. ** [max_page_count] [PRAGMA].
  3590. **
  3591. ** New run-time limit categories may be added in future releases.
  3592. */
  3593. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  3594. /*
  3595. ** CAPI3REF: Run-Time Limit Categories
  3596. ** KEYWORDS: {limit category} {*limit categories}
  3597. **
  3598. ** These constants define various performance limits
  3599. ** that can be lowered at run-time using [sqlite3_limit()].
  3600. ** The synopsis of the meanings of the various limits is shown below.
  3601. ** Additional information is available at [limits | Limits in SQLite].
  3602. **
  3603. ** <dl>
  3604. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3605. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3606. **
  3607. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3608. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3609. **
  3610. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3611. ** <dd>The maximum number of columns in a table definition or in the
  3612. ** result set of a [SELECT] or the maximum number of columns in an index
  3613. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3614. **
  3615. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3616. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3617. **
  3618. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3619. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3620. **
  3621. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3622. ** <dd>The maximum number of instructions in a virtual machine program
  3623. ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
  3624. ** the equivalent tries to allocate space for more than this many opcodes
  3625. ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  3626. **
  3627. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3628. ** <dd>The maximum number of arguments on a function.</dd>)^
  3629. **
  3630. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3631. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3632. **
  3633. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3634. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3635. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3636. ** [GLOB] operators.</dd>)^
  3637. **
  3638. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3639. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3640. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3641. **
  3642. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3643. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3644. **
  3645. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  3646. ** <dd>The maximum number of auxiliary worker threads that a single
  3647. ** [prepared statement] may start.</dd>)^
  3648. ** </dl>
  3649. */
  3650. #define SQLITE_LIMIT_LENGTH 0
  3651. #define SQLITE_LIMIT_SQL_LENGTH 1
  3652. #define SQLITE_LIMIT_COLUMN 2
  3653. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3654. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3655. #define SQLITE_LIMIT_VDBE_OP 5
  3656. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3657. #define SQLITE_LIMIT_ATTACHED 7
  3658. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3659. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3660. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3661. #define SQLITE_LIMIT_WORKER_THREADS 11
  3662. /*
  3663. ** CAPI3REF: Compiling An SQL Statement
  3664. ** KEYWORDS: {SQL statement compiler}
  3665. ** METHOD: sqlite3
  3666. ** CONSTRUCTOR: sqlite3_stmt
  3667. **
  3668. ** To execute an SQL query, it must first be compiled into a byte-code
  3669. ** program using one of these routines.
  3670. **
  3671. ** The first argument, "db", is a [database connection] obtained from a
  3672. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3673. ** [sqlite3_open16()]. The database connection must not have been closed.
  3674. **
  3675. ** The second argument, "zSql", is the statement to be compiled, encoded
  3676. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3677. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3678. ** use UTF-16.
  3679. **
  3680. ** ^If the nByte argument is negative, then zSql is read up to the
  3681. ** first zero terminator. ^If nByte is positive, then it is the
  3682. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  3683. ** statement is generated.
  3684. ** If the caller knows that the supplied string is nul-terminated, then
  3685. ** there is a small performance advantage to passing an nByte parameter that
  3686. ** is the number of bytes in the input string <i>including</i>
  3687. ** the nul-terminator.
  3688. **
  3689. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3690. ** past the end of the first SQL statement in zSql. These routines only
  3691. ** compile the first statement in zSql, so *pzTail is left pointing to
  3692. ** what remains uncompiled.
  3693. **
  3694. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3695. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3696. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3697. ** string or a comment) then *ppStmt is set to NULL.
  3698. ** The calling procedure is responsible for deleting the compiled
  3699. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3700. ** ppStmt may not be NULL.
  3701. **
  3702. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3703. ** otherwise an [error code] is returned.
  3704. **
  3705. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3706. ** recommended for all new programs. The two older interfaces are retained
  3707. ** for backwards compatibility, but their use is discouraged.
  3708. ** ^In the "v2" interfaces, the prepared statement
  3709. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3710. ** original SQL text. This causes the [sqlite3_step()] interface to
  3711. ** behave differently in three ways:
  3712. **
  3713. ** <ol>
  3714. ** <li>
  3715. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3716. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3717. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3718. ** retries will occur before sqlite3_step() gives up and returns an error.
  3719. ** </li>
  3720. **
  3721. ** <li>
  3722. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3723. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3724. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3725. ** and the application would have to make a second call to [sqlite3_reset()]
  3726. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3727. ** interfaces, the underlying reason for the error is returned immediately.
  3728. ** </li>
  3729. **
  3730. ** <li>
  3731. ** ^If the specific value bound to [parameter | host parameter] in the
  3732. ** WHERE clause might influence the choice of query plan for a statement,
  3733. ** then the statement will be automatically recompiled, as if there had been
  3734. ** a schema change, on the first [sqlite3_step()] call following any change
  3735. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3736. ** ^The specific value of WHERE-clause [parameter] might influence the
  3737. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3738. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3739. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3740. ** </li>
  3741. ** </ol>
  3742. */
  3743. SQLITE_API int sqlite3_prepare(
  3744. sqlite3 *db, /* Database handle */
  3745. const char *zSql, /* SQL statement, UTF-8 encoded */
  3746. int nByte, /* Maximum length of zSql in bytes. */
  3747. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3748. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3749. );
  3750. SQLITE_API int sqlite3_prepare_v2(
  3751. sqlite3 *db, /* Database handle */
  3752. const char *zSql, /* SQL statement, UTF-8 encoded */
  3753. int nByte, /* Maximum length of zSql in bytes. */
  3754. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3755. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3756. );
  3757. SQLITE_API int sqlite3_prepare16(
  3758. sqlite3 *db, /* Database handle */
  3759. const void *zSql, /* SQL statement, UTF-16 encoded */
  3760. int nByte, /* Maximum length of zSql in bytes. */
  3761. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3762. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3763. );
  3764. SQLITE_API int sqlite3_prepare16_v2(
  3765. sqlite3 *db, /* Database handle */
  3766. const void *zSql, /* SQL statement, UTF-16 encoded */
  3767. int nByte, /* Maximum length of zSql in bytes. */
  3768. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3769. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3770. );
  3771. /*
  3772. ** CAPI3REF: Retrieving Statement SQL
  3773. ** METHOD: sqlite3_stmt
  3774. **
  3775. ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  3776. ** SQL text used to create [prepared statement] P if P was
  3777. ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3778. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  3779. ** string containing the SQL text of prepared statement P with
  3780. ** [bound parameters] expanded.
  3781. **
  3782. ** ^(For example, if a prepared statement is created using the SQL
  3783. ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  3784. ** and parameter :xyz is unbound, then sqlite3_sql() will return
  3785. ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  3786. ** will return "SELECT 2345,NULL".)^
  3787. **
  3788. ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  3789. ** is available to hold the result, or if the result would exceed the
  3790. ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  3791. **
  3792. ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  3793. ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
  3794. ** option causes sqlite3_expanded_sql() to always return NULL.
  3795. **
  3796. ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
  3797. ** automatically freed when the prepared statement is finalized.
  3798. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  3799. ** is obtained from [sqlite3_malloc()] and must be free by the application
  3800. ** by passing it to [sqlite3_free()].
  3801. */
  3802. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3803. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  3804. /*
  3805. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3806. ** METHOD: sqlite3_stmt
  3807. **
  3808. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3809. ** and only if the [prepared statement] X makes no direct changes to
  3810. ** the content of the database file.
  3811. **
  3812. ** Note that [application-defined SQL functions] or
  3813. ** [virtual tables] might change the database indirectly as a side effect.
  3814. ** ^(For example, if an application defines a function "eval()" that
  3815. ** calls [sqlite3_exec()], then the following SQL statement would
  3816. ** change the database file through side-effects:
  3817. **
  3818. ** <blockquote><pre>
  3819. ** SELECT eval('DELETE FROM t1') FROM t2;
  3820. ** </pre></blockquote>
  3821. **
  3822. ** But because the [SELECT] statement does not change the database file
  3823. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3824. **
  3825. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3826. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3827. ** since the statements themselves do not actually modify the database but
  3828. ** rather they control the timing of when other statements modify the
  3829. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3830. ** sqlite3_stmt_readonly() to return true since, while those statements
  3831. ** change the configuration of a database connection, they do not make
  3832. ** changes to the content of the database files on disk.
  3833. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  3834. ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  3835. ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  3836. ** sqlite3_stmt_readonly() returns false for those commands.
  3837. */
  3838. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3839. /*
  3840. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3841. ** METHOD: sqlite3_stmt
  3842. **
  3843. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3844. ** [prepared statement] S has been stepped at least once using
  3845. ** [sqlite3_step(S)] but has neither run to completion (returned
  3846. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  3847. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3848. ** interface returns false if S is a NULL pointer. If S is not a
  3849. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3850. ** object, then the behavior is undefined and probably undesirable.
  3851. **
  3852. ** This interface can be used in combination [sqlite3_next_stmt()]
  3853. ** to locate all prepared statements associated with a database
  3854. ** connection that are in need of being reset. This can be used,
  3855. ** for example, in diagnostic routines to search for prepared
  3856. ** statements that are holding a transaction open.
  3857. */
  3858. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3859. /*
  3860. ** CAPI3REF: Dynamically Typed Value Object
  3861. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3862. **
  3863. ** SQLite uses the sqlite3_value object to represent all values
  3864. ** that can be stored in a database table. SQLite uses dynamic typing
  3865. ** for the values it stores. ^Values stored in sqlite3_value objects
  3866. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3867. **
  3868. ** An sqlite3_value object may be either "protected" or "unprotected".
  3869. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3870. ** will accept either a protected or an unprotected sqlite3_value.
  3871. ** Every interface that accepts sqlite3_value arguments specifies
  3872. ** whether or not it requires a protected sqlite3_value. The
  3873. ** [sqlite3_value_dup()] interface can be used to construct a new
  3874. ** protected sqlite3_value from an unprotected sqlite3_value.
  3875. **
  3876. ** The terms "protected" and "unprotected" refer to whether or not
  3877. ** a mutex is held. An internal mutex is held for a protected
  3878. ** sqlite3_value object but no mutex is held for an unprotected
  3879. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3880. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3881. ** or if SQLite is run in one of reduced mutex modes
  3882. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3883. ** then there is no distinction between protected and unprotected
  3884. ** sqlite3_value objects and they can be used interchangeably. However,
  3885. ** for maximum code portability it is recommended that applications
  3886. ** still make the distinction between protected and unprotected
  3887. ** sqlite3_value objects even when not strictly required.
  3888. **
  3889. ** ^The sqlite3_value objects that are passed as parameters into the
  3890. ** implementation of [application-defined SQL functions] are protected.
  3891. ** ^The sqlite3_value object returned by
  3892. ** [sqlite3_column_value()] is unprotected.
  3893. ** Unprotected sqlite3_value objects may only be used with
  3894. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3895. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3896. ** interfaces require protected sqlite3_value objects.
  3897. */
  3898. typedef struct sqlite3_value sqlite3_value;
  3899. /*
  3900. ** CAPI3REF: SQL Function Context Object
  3901. **
  3902. ** The context in which an SQL function executes is stored in an
  3903. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3904. ** is always first parameter to [application-defined SQL functions].
  3905. ** The application-defined SQL function implementation will pass this
  3906. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3907. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3908. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3909. ** and/or [sqlite3_set_auxdata()].
  3910. */
  3911. typedef struct sqlite3_context sqlite3_context;
  3912. /*
  3913. ** CAPI3REF: Binding Values To Prepared Statements
  3914. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3915. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3916. ** METHOD: sqlite3_stmt
  3917. **
  3918. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3919. ** literals may be replaced by a [parameter] that matches one of following
  3920. ** templates:
  3921. **
  3922. ** <ul>
  3923. ** <li> ?
  3924. ** <li> ?NNN
  3925. ** <li> :VVV
  3926. ** <li> @VVV
  3927. ** <li> $VVV
  3928. ** </ul>
  3929. **
  3930. ** In the templates above, NNN represents an integer literal,
  3931. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3932. ** parameters (also called "host parameter names" or "SQL parameters")
  3933. ** can be set using the sqlite3_bind_*() routines defined here.
  3934. **
  3935. ** ^The first argument to the sqlite3_bind_*() routines is always
  3936. ** a pointer to the [sqlite3_stmt] object returned from
  3937. ** [sqlite3_prepare_v2()] or its variants.
  3938. **
  3939. ** ^The second argument is the index of the SQL parameter to be set.
  3940. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3941. ** SQL parameter is used more than once, second and subsequent
  3942. ** occurrences have the same index as the first occurrence.
  3943. ** ^The index for named parameters can be looked up using the
  3944. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3945. ** for "?NNN" parameters is the value of NNN.
  3946. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3947. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3948. **
  3949. ** ^The third argument is the value to bind to the parameter.
  3950. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3951. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3952. ** is ignored and the end result is the same as sqlite3_bind_null().
  3953. **
  3954. ** ^(In those routines that have a fourth argument, its value is the
  3955. ** number of bytes in the parameter. To be clear: the value is the
  3956. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3957. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3958. ** is negative, then the length of the string is
  3959. ** the number of bytes up to the first zero terminator.
  3960. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3961. ** the behavior is undefined.
  3962. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3963. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  3964. ** that parameter must be the byte offset
  3965. ** where the NUL terminator would occur assuming the string were NUL
  3966. ** terminated. If any NUL characters occur at byte offsets less than
  3967. ** the value of the fourth parameter then the resulting string value will
  3968. ** contain embedded NULs. The result of expressions involving strings
  3969. ** with embedded NULs is undefined.
  3970. **
  3971. ** ^The fifth argument to the BLOB and string binding interfaces
  3972. ** is a destructor used to dispose of the BLOB or
  3973. ** string after SQLite has finished with it. ^The destructor is called
  3974. ** to dispose of the BLOB or string even if the call to bind API fails.
  3975. ** ^If the fifth argument is
  3976. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3977. ** information is in static, unmanaged space and does not need to be freed.
  3978. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3979. ** SQLite makes its own private copy of the data immediately, before
  3980. ** the sqlite3_bind_*() routine returns.
  3981. **
  3982. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  3983. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  3984. ** to specify the encoding of the text in the third parameter. If
  3985. ** the sixth argument to sqlite3_bind_text64() is not one of the
  3986. ** allowed values shown above, or if the text encoding is different
  3987. ** from the encoding specified by the sixth parameter, then the behavior
  3988. ** is undefined.
  3989. **
  3990. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3991. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3992. ** (just an integer to hold its size) while it is being processed.
  3993. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3994. ** content is later written using
  3995. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3996. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3997. **
  3998. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3999. ** for the [prepared statement] or with a prepared statement for which
  4000. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  4001. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  4002. ** routine is passed a [prepared statement] that has been finalized, the
  4003. ** result is undefined and probably harmful.
  4004. **
  4005. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  4006. ** ^Unbound parameters are interpreted as NULL.
  4007. **
  4008. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  4009. ** [error code] if anything goes wrong.
  4010. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  4011. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  4012. ** [SQLITE_MAX_LENGTH].
  4013. ** ^[SQLITE_RANGE] is returned if the parameter
  4014. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  4015. **
  4016. ** See also: [sqlite3_bind_parameter_count()],
  4017. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  4018. */
  4019. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  4020. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  4021. void(*)(void*));
  4022. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  4023. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  4024. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  4025. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  4026. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  4027. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  4028. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  4029. void(*)(void*), unsigned char encoding);
  4030. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  4031. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  4032. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  4033. /*
  4034. ** CAPI3REF: Number Of SQL Parameters
  4035. ** METHOD: sqlite3_stmt
  4036. **
  4037. ** ^This routine can be used to find the number of [SQL parameters]
  4038. ** in a [prepared statement]. SQL parameters are tokens of the
  4039. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  4040. ** placeholders for values that are [sqlite3_bind_blob | bound]
  4041. ** to the parameters at a later time.
  4042. **
  4043. ** ^(This routine actually returns the index of the largest (rightmost)
  4044. ** parameter. For all forms except ?NNN, this will correspond to the
  4045. ** number of unique parameters. If parameters of the ?NNN form are used,
  4046. ** there may be gaps in the list.)^
  4047. **
  4048. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4049. ** [sqlite3_bind_parameter_name()], and
  4050. ** [sqlite3_bind_parameter_index()].
  4051. */
  4052. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  4053. /*
  4054. ** CAPI3REF: Name Of A Host Parameter
  4055. ** METHOD: sqlite3_stmt
  4056. **
  4057. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  4058. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  4059. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4060. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4061. ** respectively.
  4062. ** In other words, the initial ":" or "$" or "@" or "?"
  4063. ** is included as part of the name.)^
  4064. ** ^Parameters of the form "?" without a following integer have no name
  4065. ** and are referred to as "nameless" or "anonymous parameters".
  4066. **
  4067. ** ^The first host parameter has an index of 1, not 0.
  4068. **
  4069. ** ^If the value N is out of range or if the N-th parameter is
  4070. ** nameless, then NULL is returned. ^The returned string is
  4071. ** always in UTF-8 encoding even if the named parameter was
  4072. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  4073. ** [sqlite3_prepare16_v2()].
  4074. **
  4075. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4076. ** [sqlite3_bind_parameter_count()], and
  4077. ** [sqlite3_bind_parameter_index()].
  4078. */
  4079. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  4080. /*
  4081. ** CAPI3REF: Index Of A Parameter With A Given Name
  4082. ** METHOD: sqlite3_stmt
  4083. **
  4084. ** ^Return the index of an SQL parameter given its name. ^The
  4085. ** index value returned is suitable for use as the second
  4086. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  4087. ** is returned if no matching parameter is found. ^The parameter
  4088. ** name must be given in UTF-8 even if the original statement
  4089. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  4090. **
  4091. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4092. ** [sqlite3_bind_parameter_count()], and
  4093. ** [sqlite3_bind_parameter_name()].
  4094. */
  4095. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  4096. /*
  4097. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  4098. ** METHOD: sqlite3_stmt
  4099. **
  4100. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  4101. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  4102. ** ^Use this routine to reset all host parameters to NULL.
  4103. */
  4104. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  4105. /*
  4106. ** CAPI3REF: Number Of Columns In A Result Set
  4107. ** METHOD: sqlite3_stmt
  4108. **
  4109. ** ^Return the number of columns in the result set returned by the
  4110. ** [prepared statement]. ^If this routine returns 0, that means the
  4111. ** [prepared statement] returns no data (for example an [UPDATE]).
  4112. ** ^However, just because this routine returns a positive number does not
  4113. ** mean that one or more rows of data will be returned. ^A SELECT statement
  4114. ** will always have a positive sqlite3_column_count() but depending on the
  4115. ** WHERE clause constraints and the table content, it might return no rows.
  4116. **
  4117. ** See also: [sqlite3_data_count()]
  4118. */
  4119. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  4120. /*
  4121. ** CAPI3REF: Column Names In A Result Set
  4122. ** METHOD: sqlite3_stmt
  4123. **
  4124. ** ^These routines return the name assigned to a particular column
  4125. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  4126. ** interface returns a pointer to a zero-terminated UTF-8 string
  4127. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  4128. ** UTF-16 string. ^The first parameter is the [prepared statement]
  4129. ** that implements the [SELECT] statement. ^The second parameter is the
  4130. ** column number. ^The leftmost column is number 0.
  4131. **
  4132. ** ^The returned string pointer is valid until either the [prepared statement]
  4133. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  4134. ** reprepared by the first call to [sqlite3_step()] for a particular run
  4135. ** or until the next call to
  4136. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  4137. **
  4138. ** ^If sqlite3_malloc() fails during the processing of either routine
  4139. ** (for example during a conversion from UTF-8 to UTF-16) then a
  4140. ** NULL pointer is returned.
  4141. **
  4142. ** ^The name of a result column is the value of the "AS" clause for
  4143. ** that column, if there is an AS clause. If there is no AS clause
  4144. ** then the name of the column is unspecified and may change from
  4145. ** one release of SQLite to the next.
  4146. */
  4147. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  4148. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  4149. /*
  4150. ** CAPI3REF: Source Of Data In A Query Result
  4151. ** METHOD: sqlite3_stmt
  4152. **
  4153. ** ^These routines provide a means to determine the database, table, and
  4154. ** table column that is the origin of a particular result column in
  4155. ** [SELECT] statement.
  4156. ** ^The name of the database or table or column can be returned as
  4157. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  4158. ** the database name, the _table_ routines return the table name, and
  4159. ** the origin_ routines return the column name.
  4160. ** ^The returned string is valid until the [prepared statement] is destroyed
  4161. ** using [sqlite3_finalize()] or until the statement is automatically
  4162. ** reprepared by the first call to [sqlite3_step()] for a particular run
  4163. ** or until the same information is requested
  4164. ** again in a different encoding.
  4165. **
  4166. ** ^The names returned are the original un-aliased names of the
  4167. ** database, table, and column.
  4168. **
  4169. ** ^The first argument to these interfaces is a [prepared statement].
  4170. ** ^These functions return information about the Nth result column returned by
  4171. ** the statement, where N is the second function argument.
  4172. ** ^The left-most column is column 0 for these routines.
  4173. **
  4174. ** ^If the Nth column returned by the statement is an expression or
  4175. ** subquery and is not a column value, then all of these functions return
  4176. ** NULL. ^These routine might also return NULL if a memory allocation error
  4177. ** occurs. ^Otherwise, they return the name of the attached database, table,
  4178. ** or column that query result column was extracted from.
  4179. **
  4180. ** ^As with all other SQLite APIs, those whose names end with "16" return
  4181. ** UTF-16 encoded strings and the other functions return UTF-8.
  4182. **
  4183. ** ^These APIs are only available if the library was compiled with the
  4184. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  4185. **
  4186. ** If two or more threads call one or more of these routines against the same
  4187. ** prepared statement and column at the same time then the results are
  4188. ** undefined.
  4189. **
  4190. ** If two or more threads call one or more
  4191. ** [sqlite3_column_database_name | column metadata interfaces]
  4192. ** for the same [prepared statement] and result column
  4193. ** at the same time then the results are undefined.
  4194. */
  4195. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  4196. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  4197. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  4198. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  4199. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  4200. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  4201. /*
  4202. ** CAPI3REF: Declared Datatype Of A Query Result
  4203. ** METHOD: sqlite3_stmt
  4204. **
  4205. ** ^(The first parameter is a [prepared statement].
  4206. ** If this statement is a [SELECT] statement and the Nth column of the
  4207. ** returned result set of that [SELECT] is a table column (not an
  4208. ** expression or subquery) then the declared type of the table
  4209. ** column is returned.)^ ^If the Nth column of the result set is an
  4210. ** expression or subquery, then a NULL pointer is returned.
  4211. ** ^The returned string is always UTF-8 encoded.
  4212. **
  4213. ** ^(For example, given the database schema:
  4214. **
  4215. ** CREATE TABLE t1(c1 VARIANT);
  4216. **
  4217. ** and the following statement to be compiled:
  4218. **
  4219. ** SELECT c1 + 1, c1 FROM t1;
  4220. **
  4221. ** this routine would return the string "VARIANT" for the second result
  4222. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  4223. **
  4224. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  4225. ** is declared to contain a particular type does not mean that the
  4226. ** data stored in that column is of the declared type. SQLite is
  4227. ** strongly typed, but the typing is dynamic not static. ^Type
  4228. ** is associated with individual values, not with the containers
  4229. ** used to hold those values.
  4230. */
  4231. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  4232. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  4233. /*
  4234. ** CAPI3REF: Evaluate An SQL Statement
  4235. ** METHOD: sqlite3_stmt
  4236. **
  4237. ** After a [prepared statement] has been prepared using either
  4238. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  4239. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  4240. ** must be called one or more times to evaluate the statement.
  4241. **
  4242. ** The details of the behavior of the sqlite3_step() interface depend
  4243. ** on whether the statement was prepared using the newer "v2" interface
  4244. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  4245. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  4246. ** new "v2" interface is recommended for new applications but the legacy
  4247. ** interface will continue to be supported.
  4248. **
  4249. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  4250. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  4251. ** ^With the "v2" interface, any of the other [result codes] or
  4252. ** [extended result codes] might be returned as well.
  4253. **
  4254. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  4255. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  4256. ** or occurs outside of an explicit transaction, then you can retry the
  4257. ** statement. If the statement is not a [COMMIT] and occurs within an
  4258. ** explicit transaction then you should rollback the transaction before
  4259. ** continuing.
  4260. **
  4261. ** ^[SQLITE_DONE] means that the statement has finished executing
  4262. ** successfully. sqlite3_step() should not be called again on this virtual
  4263. ** machine without first calling [sqlite3_reset()] to reset the virtual
  4264. ** machine back to its initial state.
  4265. **
  4266. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  4267. ** is returned each time a new row of data is ready for processing by the
  4268. ** caller. The values may be accessed using the [column access functions].
  4269. ** sqlite3_step() is called again to retrieve the next row of data.
  4270. **
  4271. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  4272. ** violation) has occurred. sqlite3_step() should not be called again on
  4273. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  4274. ** ^With the legacy interface, a more specific error code (for example,
  4275. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  4276. ** can be obtained by calling [sqlite3_reset()] on the
  4277. ** [prepared statement]. ^In the "v2" interface,
  4278. ** the more specific error code is returned directly by sqlite3_step().
  4279. **
  4280. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  4281. ** Perhaps it was called on a [prepared statement] that has
  4282. ** already been [sqlite3_finalize | finalized] or on one that had
  4283. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  4284. ** be the case that the same database connection is being used by two or
  4285. ** more threads at the same moment in time.
  4286. **
  4287. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  4288. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  4289. ** other than [SQLITE_ROW] before any subsequent invocation of
  4290. ** sqlite3_step(). Failure to reset the prepared statement using
  4291. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  4292. ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
  4293. ** sqlite3_step() began
  4294. ** calling [sqlite3_reset()] automatically in this circumstance rather
  4295. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  4296. ** break because any application that ever receives an SQLITE_MISUSE error
  4297. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  4298. ** can be used to restore the legacy behavior.
  4299. **
  4300. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  4301. ** API always returns a generic error code, [SQLITE_ERROR], following any
  4302. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  4303. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  4304. ** specific [error codes] that better describes the error.
  4305. ** We admit that this is a goofy design. The problem has been fixed
  4306. ** with the "v2" interface. If you prepare all of your SQL statements
  4307. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  4308. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  4309. ** then the more specific [error codes] are returned directly
  4310. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  4311. */
  4312. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  4313. /*
  4314. ** CAPI3REF: Number of columns in a result set
  4315. ** METHOD: sqlite3_stmt
  4316. **
  4317. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  4318. ** current row of the result set of [prepared statement] P.
  4319. ** ^If prepared statement P does not have results ready to return
  4320. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  4321. ** interfaces) then sqlite3_data_count(P) returns 0.
  4322. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  4323. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  4324. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  4325. ** will return non-zero if previous call to [sqlite3_step](P) returned
  4326. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  4327. ** where it always returns zero since each step of that multi-step
  4328. ** pragma returns 0 columns of data.
  4329. **
  4330. ** See also: [sqlite3_column_count()]
  4331. */
  4332. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  4333. /*
  4334. ** CAPI3REF: Fundamental Datatypes
  4335. ** KEYWORDS: SQLITE_TEXT
  4336. **
  4337. ** ^(Every value in SQLite has one of five fundamental datatypes:
  4338. **
  4339. ** <ul>
  4340. ** <li> 64-bit signed integer
  4341. ** <li> 64-bit IEEE floating point number
  4342. ** <li> string
  4343. ** <li> BLOB
  4344. ** <li> NULL
  4345. ** </ul>)^
  4346. **
  4347. ** These constants are codes for each of those types.
  4348. **
  4349. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  4350. ** for a completely different meaning. Software that links against both
  4351. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  4352. ** SQLITE_TEXT.
  4353. */
  4354. #define SQLITE_INTEGER 1
  4355. #define SQLITE_FLOAT 2
  4356. #define SQLITE_BLOB 4
  4357. #define SQLITE_NULL 5
  4358. #ifdef SQLITE_TEXT
  4359. # undef SQLITE_TEXT
  4360. #else
  4361. # define SQLITE_TEXT 3
  4362. #endif
  4363. #define SQLITE3_TEXT 3
  4364. /*
  4365. ** CAPI3REF: Result Values From A Query
  4366. ** KEYWORDS: {column access functions}
  4367. ** METHOD: sqlite3_stmt
  4368. **
  4369. ** ^These routines return information about a single column of the current
  4370. ** result row of a query. ^In every case the first argument is a pointer
  4371. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4372. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4373. ** and the second argument is the index of the column for which information
  4374. ** should be returned. ^The leftmost column of the result set has the index 0.
  4375. ** ^The number of columns in the result can be determined using
  4376. ** [sqlite3_column_count()].
  4377. **
  4378. ** If the SQL statement does not currently point to a valid row, or if the
  4379. ** column index is out of range, the result is undefined.
  4380. ** These routines may only be called when the most recent call to
  4381. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4382. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4383. ** If any of these routines are called after [sqlite3_reset()] or
  4384. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4385. ** something other than [SQLITE_ROW], the results are undefined.
  4386. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4387. ** are called from a different thread while any of these routines
  4388. ** are pending, then the results are undefined.
  4389. **
  4390. ** ^The sqlite3_column_type() routine returns the
  4391. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4392. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  4393. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4394. ** returned by sqlite3_column_type() is only meaningful if no type
  4395. ** conversions have occurred as described below. After a type conversion,
  4396. ** the value returned by sqlite3_column_type() is undefined. Future
  4397. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4398. ** following a type conversion.
  4399. **
  4400. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4401. ** routine returns the number of bytes in that BLOB or string.
  4402. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4403. ** the string to UTF-8 and then returns the number of bytes.
  4404. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  4405. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4406. ** the number of bytes in that string.
  4407. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  4408. **
  4409. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  4410. ** routine returns the number of bytes in that BLOB or string.
  4411. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  4412. ** the string to UTF-16 and then returns the number of bytes.
  4413. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  4414. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  4415. ** the number of bytes in that string.
  4416. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  4417. **
  4418. ** ^The values returned by [sqlite3_column_bytes()] and
  4419. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  4420. ** of the string. ^For clarity: the values returned by
  4421. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  4422. ** bytes in the string, not the number of characters.
  4423. **
  4424. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4425. ** even empty strings, are always zero-terminated. ^The return
  4426. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  4427. **
  4428. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  4429. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  4430. ** an unprotected sqlite3_value object may only be used safely with
  4431. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  4432. ** If the [unprotected sqlite3_value] object returned by
  4433. ** [sqlite3_column_value()] is used in any other way, including calls
  4434. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4435. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  4436. **
  4437. ** These routines attempt to convert the value where appropriate. ^For
  4438. ** example, if the internal representation is FLOAT and a text result
  4439. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4440. ** conversion automatically. ^(The following table details the conversions
  4441. ** that are applied:
  4442. **
  4443. ** <blockquote>
  4444. ** <table border="1">
  4445. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4446. **
  4447. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4448. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4449. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  4450. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  4451. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4452. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4453. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4454. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  4455. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4456. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  4457. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  4458. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  4459. ** <tr><td> TEXT <td> BLOB <td> No change
  4460. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  4461. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  4462. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4463. ** </table>
  4464. ** </blockquote>)^
  4465. **
  4466. ** Note that when type conversions occur, pointers returned by prior
  4467. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4468. ** sqlite3_column_text16() may be invalidated.
  4469. ** Type conversions and pointer invalidations might occur
  4470. ** in the following cases:
  4471. **
  4472. ** <ul>
  4473. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4474. ** sqlite3_column_text16() is called. A zero-terminator might
  4475. ** need to be added to the string.</li>
  4476. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4477. ** sqlite3_column_text16() is called. The content must be converted
  4478. ** to UTF-16.</li>
  4479. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4480. ** sqlite3_column_text() is called. The content must be converted
  4481. ** to UTF-8.</li>
  4482. ** </ul>
  4483. **
  4484. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4485. ** not invalidate a prior pointer, though of course the content of the buffer
  4486. ** that the prior pointer references will have been modified. Other kinds
  4487. ** of conversion are done in place when it is possible, but sometimes they
  4488. ** are not possible and in those cases prior pointers are invalidated.
  4489. **
  4490. ** The safest policy is to invoke these routines
  4491. ** in one of the following ways:
  4492. **
  4493. ** <ul>
  4494. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4495. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4496. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4497. ** </ul>
  4498. **
  4499. ** In other words, you should call sqlite3_column_text(),
  4500. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4501. ** into the desired format, then invoke sqlite3_column_bytes() or
  4502. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4503. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4504. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4505. ** with calls to sqlite3_column_bytes().
  4506. **
  4507. ** ^The pointers returned are valid until a type conversion occurs as
  4508. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4509. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4510. ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
  4511. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4512. ** [sqlite3_free()].
  4513. **
  4514. ** ^(If a memory allocation error occurs during the evaluation of any
  4515. ** of these routines, a default value is returned. The default value
  4516. ** is either the integer 0, the floating point number 0.0, or a NULL
  4517. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4518. ** [SQLITE_NOMEM].)^
  4519. */
  4520. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4521. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4522. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4523. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  4524. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  4525. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4526. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  4527. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4528. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  4529. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  4530. /*
  4531. ** CAPI3REF: Destroy A Prepared Statement Object
  4532. ** DESTRUCTOR: sqlite3_stmt
  4533. **
  4534. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4535. ** ^If the most recent evaluation of the statement encountered no errors
  4536. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4537. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4538. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4539. ** [extended error code].
  4540. **
  4541. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4542. ** the life cycle of [prepared statement] S:
  4543. ** before statement S is ever evaluated, after
  4544. ** one or more calls to [sqlite3_reset()], or after any call
  4545. ** to [sqlite3_step()] regardless of whether or not the statement has
  4546. ** completed execution.
  4547. **
  4548. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4549. **
  4550. ** The application must finalize every [prepared statement] in order to avoid
  4551. ** resource leaks. It is a grievous error for the application to try to use
  4552. ** a prepared statement after it has been finalized. Any use of a prepared
  4553. ** statement after it has been finalized can result in undefined and
  4554. ** undesirable behavior such as segfaults and heap corruption.
  4555. */
  4556. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  4557. /*
  4558. ** CAPI3REF: Reset A Prepared Statement Object
  4559. ** METHOD: sqlite3_stmt
  4560. **
  4561. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4562. ** object back to its initial state, ready to be re-executed.
  4563. ** ^Any SQL statement variables that had values bound to them using
  4564. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4565. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4566. **
  4567. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4568. ** back to the beginning of its program.
  4569. **
  4570. ** ^If the most recent call to [sqlite3_step(S)] for the
  4571. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4572. ** or if [sqlite3_step(S)] has never before been called on S,
  4573. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4574. **
  4575. ** ^If the most recent call to [sqlite3_step(S)] for the
  4576. ** [prepared statement] S indicated an error, then
  4577. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4578. **
  4579. ** ^The [sqlite3_reset(S)] interface does not change the values
  4580. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4581. */
  4582. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  4583. /*
  4584. ** CAPI3REF: Create Or Redefine SQL Functions
  4585. ** KEYWORDS: {function creation routines}
  4586. ** KEYWORDS: {application-defined SQL function}
  4587. ** KEYWORDS: {application-defined SQL functions}
  4588. ** METHOD: sqlite3
  4589. **
  4590. ** ^These functions (collectively known as "function creation routines")
  4591. ** are used to add SQL functions or aggregates or to redefine the behavior
  4592. ** of existing SQL functions or aggregates. The only differences between
  4593. ** these routines are the text encoding expected for
  4594. ** the second parameter (the name of the function being created)
  4595. ** and the presence or absence of a destructor callback for
  4596. ** the application data pointer.
  4597. **
  4598. ** ^The first parameter is the [database connection] to which the SQL
  4599. ** function is to be added. ^If an application uses more than one database
  4600. ** connection then application-defined SQL functions must be added
  4601. ** to each database connection separately.
  4602. **
  4603. ** ^The second parameter is the name of the SQL function to be created or
  4604. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4605. ** representation, exclusive of the zero-terminator. ^Note that the name
  4606. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4607. ** ^Any attempt to create a function with a longer name
  4608. ** will result in [SQLITE_MISUSE] being returned.
  4609. **
  4610. ** ^The third parameter (nArg)
  4611. ** is the number of arguments that the SQL function or
  4612. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4613. ** aggregate may take any number of arguments between 0 and the limit
  4614. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4615. ** parameter is less than -1 or greater than 127 then the behavior is
  4616. ** undefined.
  4617. **
  4618. ** ^The fourth parameter, eTextRep, specifies what
  4619. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4620. ** its parameters. The application should set this parameter to
  4621. ** [SQLITE_UTF16LE] if the function implementation invokes
  4622. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  4623. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  4624. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  4625. ** otherwise. ^The same SQL function may be registered multiple times using
  4626. ** different preferred text encodings, with different implementations for
  4627. ** each encoding.
  4628. ** ^When multiple implementations of the same function are available, SQLite
  4629. ** will pick the one that involves the least amount of data conversion.
  4630. **
  4631. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  4632. ** to signal that the function will always return the same result given
  4633. ** the same inputs within a single SQL statement. Most SQL functions are
  4634. ** deterministic. The built-in [random()] SQL function is an example of a
  4635. ** function that is not deterministic. The SQLite query planner is able to
  4636. ** perform additional optimizations on deterministic functions, so use
  4637. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  4638. **
  4639. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4640. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4641. **
  4642. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4643. ** pointers to C-language functions that implement the SQL function or
  4644. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4645. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4646. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4647. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4648. ** SQL function or aggregate, pass NULL pointers for all three function
  4649. ** callbacks.
  4650. **
  4651. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4652. ** then it is destructor for the application data pointer.
  4653. ** The destructor is invoked when the function is deleted, either by being
  4654. ** overloaded or when the database connection closes.)^
  4655. ** ^The destructor is also invoked if the call to
  4656. ** sqlite3_create_function_v2() fails.
  4657. ** ^When the destructor callback of the tenth parameter is invoked, it
  4658. ** is passed a single argument which is a copy of the application data
  4659. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4660. **
  4661. ** ^It is permitted to register multiple implementations of the same
  4662. ** functions with the same name but with either differing numbers of
  4663. ** arguments or differing preferred text encodings. ^SQLite will use
  4664. ** the implementation that most closely matches the way in which the
  4665. ** SQL function is used. ^A function implementation with a non-negative
  4666. ** nArg parameter is a better match than a function implementation with
  4667. ** a negative nArg. ^A function where the preferred text encoding
  4668. ** matches the database encoding is a better
  4669. ** match than a function where the encoding is different.
  4670. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4671. ** is a closer match than a function where the encoding difference is
  4672. ** between UTF8 and UTF16.
  4673. **
  4674. ** ^Built-in functions may be overloaded by new application-defined functions.
  4675. **
  4676. ** ^An application-defined function is permitted to call other
  4677. ** SQLite interfaces. However, such calls must not
  4678. ** close the database connection nor finalize or reset the prepared
  4679. ** statement in which the function is running.
  4680. */
  4681. SQLITE_API int sqlite3_create_function(
  4682. sqlite3 *db,
  4683. const char *zFunctionName,
  4684. int nArg,
  4685. int eTextRep,
  4686. void *pApp,
  4687. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4688. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4689. void (*xFinal)(sqlite3_context*)
  4690. );
  4691. SQLITE_API int sqlite3_create_function16(
  4692. sqlite3 *db,
  4693. const void *zFunctionName,
  4694. int nArg,
  4695. int eTextRep,
  4696. void *pApp,
  4697. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4698. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4699. void (*xFinal)(sqlite3_context*)
  4700. );
  4701. SQLITE_API int sqlite3_create_function_v2(
  4702. sqlite3 *db,
  4703. const char *zFunctionName,
  4704. int nArg,
  4705. int eTextRep,
  4706. void *pApp,
  4707. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4708. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4709. void (*xFinal)(sqlite3_context*),
  4710. void(*xDestroy)(void*)
  4711. );
  4712. /*
  4713. ** CAPI3REF: Text Encodings
  4714. **
  4715. ** These constant define integer codes that represent the various
  4716. ** text encodings supported by SQLite.
  4717. */
  4718. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  4719. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  4720. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  4721. #define SQLITE_UTF16 4 /* Use native byte order */
  4722. #define SQLITE_ANY 5 /* Deprecated */
  4723. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4724. /*
  4725. ** CAPI3REF: Function Flags
  4726. **
  4727. ** These constants may be ORed together with the
  4728. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  4729. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  4730. ** [sqlite3_create_function_v2()].
  4731. */
  4732. #define SQLITE_DETERMINISTIC 0x800
  4733. /*
  4734. ** CAPI3REF: Deprecated Functions
  4735. ** DEPRECATED
  4736. **
  4737. ** These functions are [deprecated]. In order to maintain
  4738. ** backwards compatibility with older code, these functions continue
  4739. ** to be supported. However, new applications should avoid
  4740. ** the use of these functions. To encourage programmers to avoid
  4741. ** these functions, we will not explain what they do.
  4742. */
  4743. #ifndef SQLITE_OMIT_DEPRECATED
  4744. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  4745. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  4746. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4747. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  4748. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  4749. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4750. void*,sqlite3_int64);
  4751. #endif
  4752. /*
  4753. ** CAPI3REF: Obtaining SQL Values
  4754. ** METHOD: sqlite3_value
  4755. **
  4756. ** The C-language implementation of SQL functions and aggregates uses
  4757. ** this set of interface routines to access the parameter values on
  4758. ** the function or aggregate.
  4759. **
  4760. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4761. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4762. ** define callbacks that implement the SQL functions and aggregates.
  4763. ** The 3rd parameter to these callbacks is an array of pointers to
  4764. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4765. ** each parameter to the SQL function. These routines are used to
  4766. ** extract values from the [sqlite3_value] objects.
  4767. **
  4768. ** These routines work only with [protected sqlite3_value] objects.
  4769. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4770. ** object results in undefined behavior.
  4771. **
  4772. ** ^These routines work just like the corresponding [column access functions]
  4773. ** except that these routines take a single [protected sqlite3_value] object
  4774. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4775. **
  4776. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4777. ** in the native byte-order of the host machine. ^The
  4778. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4779. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4780. **
  4781. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4782. ** numeric affinity to the value. This means that an attempt is
  4783. ** made to convert the value to an integer or floating point. If
  4784. ** such a conversion is possible without loss of information (in other
  4785. ** words, if the value is a string that looks like a number)
  4786. ** then the conversion is performed. Otherwise no conversion occurs.
  4787. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4788. **
  4789. ** Please pay particular attention to the fact that the pointer returned
  4790. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4791. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4792. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4793. ** or [sqlite3_value_text16()].
  4794. **
  4795. ** These routines must be called from the same thread as
  4796. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4797. */
  4798. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4799. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4800. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4801. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4802. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4803. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4804. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4805. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4806. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4807. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4808. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4809. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4810. /*
  4811. ** CAPI3REF: Finding The Subtype Of SQL Values
  4812. ** METHOD: sqlite3_value
  4813. **
  4814. ** The sqlite3_value_subtype(V) function returns the subtype for
  4815. ** an [application-defined SQL function] argument V. The subtype
  4816. ** information can be used to pass a limited amount of context from
  4817. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  4818. ** routine to set the subtype for the return value of an SQL function.
  4819. **
  4820. ** SQLite makes no use of subtype itself. It merely passes the subtype
  4821. ** from the result of one [application-defined SQL function] into the
  4822. ** input of another.
  4823. */
  4824. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  4825. /*
  4826. ** CAPI3REF: Copy And Free SQL Values
  4827. ** METHOD: sqlite3_value
  4828. **
  4829. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  4830. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  4831. ** is a [protected sqlite3_value] object even if the input is not.
  4832. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  4833. ** memory allocation fails.
  4834. **
  4835. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  4836. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  4837. ** then sqlite3_value_free(V) is a harmless no-op.
  4838. */
  4839. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  4840. SQLITE_API void sqlite3_value_free(sqlite3_value*);
  4841. /*
  4842. ** CAPI3REF: Obtain Aggregate Function Context
  4843. ** METHOD: sqlite3_context
  4844. **
  4845. ** Implementations of aggregate SQL functions use this
  4846. ** routine to allocate memory for storing their state.
  4847. **
  4848. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4849. ** for a particular aggregate function, SQLite
  4850. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4851. ** to the new memory. ^On second and subsequent calls to
  4852. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4853. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4854. ** called once for each invocation of the xStep callback and then one
  4855. ** last time when the xFinal callback is invoked. ^(When no rows match
  4856. ** an aggregate query, the xStep() callback of the aggregate function
  4857. ** implementation is never called and xFinal() is called exactly once.
  4858. ** In those cases, sqlite3_aggregate_context() might be called for the
  4859. ** first time from within xFinal().)^
  4860. **
  4861. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4862. ** when first called if N is less than or equal to zero or if a memory
  4863. ** allocate error occurs.
  4864. **
  4865. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4866. ** determined by the N parameter on first successful call. Changing the
  4867. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4868. ** the same aggregate function instance will not resize the memory
  4869. ** allocation.)^ Within the xFinal callback, it is customary to set
  4870. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4871. ** pointless memory allocations occur.
  4872. **
  4873. ** ^SQLite automatically frees the memory allocated by
  4874. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4875. **
  4876. ** The first parameter must be a copy of the
  4877. ** [sqlite3_context | SQL function context] that is the first parameter
  4878. ** to the xStep or xFinal callback routine that implements the aggregate
  4879. ** function.
  4880. **
  4881. ** This routine must be called from the same thread in which
  4882. ** the aggregate SQL function is running.
  4883. */
  4884. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4885. /*
  4886. ** CAPI3REF: User Data For Functions
  4887. ** METHOD: sqlite3_context
  4888. **
  4889. ** ^The sqlite3_user_data() interface returns a copy of
  4890. ** the pointer that was the pUserData parameter (the 5th parameter)
  4891. ** of the [sqlite3_create_function()]
  4892. ** and [sqlite3_create_function16()] routines that originally
  4893. ** registered the application defined function.
  4894. **
  4895. ** This routine must be called from the same thread in which
  4896. ** the application-defined function is running.
  4897. */
  4898. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4899. /*
  4900. ** CAPI3REF: Database Connection For Functions
  4901. ** METHOD: sqlite3_context
  4902. **
  4903. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4904. ** the pointer to the [database connection] (the 1st parameter)
  4905. ** of the [sqlite3_create_function()]
  4906. ** and [sqlite3_create_function16()] routines that originally
  4907. ** registered the application defined function.
  4908. */
  4909. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4910. /*
  4911. ** CAPI3REF: Function Auxiliary Data
  4912. ** METHOD: sqlite3_context
  4913. **
  4914. ** These functions may be used by (non-aggregate) SQL functions to
  4915. ** associate metadata with argument values. If the same value is passed to
  4916. ** multiple invocations of the same SQL function during query execution, under
  4917. ** some circumstances the associated metadata may be preserved. An example
  4918. ** of where this might be useful is in a regular-expression matching
  4919. ** function. The compiled version of the regular expression can be stored as
  4920. ** metadata associated with the pattern string.
  4921. ** Then as long as the pattern string remains the same,
  4922. ** the compiled regular expression can be reused on multiple
  4923. ** invocations of the same function.
  4924. **
  4925. ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  4926. ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  4927. ** value to the application-defined function. ^N is zero for the left-most
  4928. ** function argument. ^If there is no metadata
  4929. ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  4930. ** returns a NULL pointer.
  4931. **
  4932. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4933. ** argument of the application-defined function. ^Subsequent
  4934. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4935. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4936. ** NULL if the metadata has been discarded.
  4937. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4938. ** SQLite will invoke the destructor function X with parameter P exactly
  4939. ** once, when the metadata is discarded.
  4940. ** SQLite is free to discard the metadata at any time, including: <ul>
  4941. ** <li> ^(when the corresponding function parameter changes)^, or
  4942. ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4943. ** SQL statement)^, or
  4944. ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  4945. ** parameter)^, or
  4946. ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
  4947. ** allocation error occurs.)^ </ul>
  4948. **
  4949. ** Note the last bullet in particular. The destructor X in
  4950. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4951. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4952. ** should be called near the end of the function implementation and the
  4953. ** function implementation should not make any use of P after
  4954. ** sqlite3_set_auxdata() has been called.
  4955. **
  4956. ** ^(In practice, metadata is preserved between function calls for
  4957. ** function parameters that are compile-time constants, including literal
  4958. ** values and [parameters] and expressions composed from the same.)^
  4959. **
  4960. ** The value of the N parameter to these interfaces should be non-negative.
  4961. ** Future enhancements may make use of negative N values to define new
  4962. ** kinds of function caching behavior.
  4963. **
  4964. ** These routines must be called from the same thread in which
  4965. ** the SQL function is running.
  4966. */
  4967. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4968. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4969. /*
  4970. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4971. **
  4972. ** These are special values for the destructor that is passed in as the
  4973. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4974. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4975. ** and will never change. It does not need to be destroyed. ^The
  4976. ** SQLITE_TRANSIENT value means that the content will likely change in
  4977. ** the near future and that SQLite should make its own private copy of
  4978. ** the content before returning.
  4979. **
  4980. ** The typedef is necessary to work around problems in certain
  4981. ** C++ compilers.
  4982. */
  4983. typedef void (*sqlite3_destructor_type)(void*);
  4984. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4985. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4986. /*
  4987. ** CAPI3REF: Setting The Result Of An SQL Function
  4988. ** METHOD: sqlite3_context
  4989. **
  4990. ** These routines are used by the xFunc or xFinal callbacks that
  4991. ** implement SQL functions and aggregates. See
  4992. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4993. ** for additional information.
  4994. **
  4995. ** These functions work very much like the [parameter binding] family of
  4996. ** functions used to bind values to host parameters in prepared statements.
  4997. ** Refer to the [SQL parameter] documentation for additional information.
  4998. **
  4999. ** ^The sqlite3_result_blob() interface sets the result from
  5000. ** an application-defined function to be the BLOB whose content is pointed
  5001. ** to by the second parameter and which is N bytes long where N is the
  5002. ** third parameter.
  5003. **
  5004. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  5005. ** interfaces set the result of the application-defined function to be
  5006. ** a BLOB containing all zero bytes and N bytes in size.
  5007. **
  5008. ** ^The sqlite3_result_double() interface sets the result from
  5009. ** an application-defined function to be a floating point value specified
  5010. ** by its 2nd argument.
  5011. **
  5012. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  5013. ** cause the implemented SQL function to throw an exception.
  5014. ** ^SQLite uses the string pointed to by the
  5015. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  5016. ** as the text of an error message. ^SQLite interprets the error
  5017. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  5018. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  5019. ** byte order. ^If the third parameter to sqlite3_result_error()
  5020. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  5021. ** message all text up through the first zero character.
  5022. ** ^If the third parameter to sqlite3_result_error() or
  5023. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  5024. ** bytes (not characters) from the 2nd parameter as the error message.
  5025. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  5026. ** routines make a private copy of the error message text before
  5027. ** they return. Hence, the calling function can deallocate or
  5028. ** modify the text after they return without harm.
  5029. ** ^The sqlite3_result_error_code() function changes the error code
  5030. ** returned by SQLite as a result of an error in a function. ^By default,
  5031. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  5032. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  5033. **
  5034. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  5035. ** error indicating that a string or BLOB is too long to represent.
  5036. **
  5037. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  5038. ** error indicating that a memory allocation failed.
  5039. **
  5040. ** ^The sqlite3_result_int() interface sets the return value
  5041. ** of the application-defined function to be the 32-bit signed integer
  5042. ** value given in the 2nd argument.
  5043. ** ^The sqlite3_result_int64() interface sets the return value
  5044. ** of the application-defined function to be the 64-bit signed integer
  5045. ** value given in the 2nd argument.
  5046. **
  5047. ** ^The sqlite3_result_null() interface sets the return value
  5048. ** of the application-defined function to be NULL.
  5049. **
  5050. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  5051. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  5052. ** set the return value of the application-defined function to be
  5053. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  5054. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  5055. ** ^The sqlite3_result_text64() interface sets the return value of an
  5056. ** application-defined function to be a text string in an encoding
  5057. ** specified by the fifth (and last) parameter, which must be one
  5058. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  5059. ** ^SQLite takes the text result from the application from
  5060. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  5061. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  5062. ** is negative, then SQLite takes result text from the 2nd parameter
  5063. ** through the first zero character.
  5064. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  5065. ** is non-negative, then as many bytes (not characters) of the text
  5066. ** pointed to by the 2nd parameter are taken as the application-defined
  5067. ** function result. If the 3rd parameter is non-negative, then it
  5068. ** must be the byte offset into the string where the NUL terminator would
  5069. ** appear if the string where NUL terminated. If any NUL characters occur
  5070. ** in the string at a byte offset that is less than the value of the 3rd
  5071. ** parameter, then the resulting string will contain embedded NULs and the
  5072. ** result of expressions operating on strings with embedded NULs is undefined.
  5073. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  5074. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  5075. ** function as the destructor on the text or BLOB result when it has
  5076. ** finished using that result.
  5077. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  5078. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  5079. ** assumes that the text or BLOB result is in constant space and does not
  5080. ** copy the content of the parameter nor call a destructor on the content
  5081. ** when it has finished using that result.
  5082. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  5083. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  5084. ** then SQLite makes a copy of the result into space obtained from
  5085. ** from [sqlite3_malloc()] before it returns.
  5086. **
  5087. ** ^The sqlite3_result_value() interface sets the result of
  5088. ** the application-defined function to be a copy of the
  5089. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  5090. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  5091. ** so that the [sqlite3_value] specified in the parameter may change or
  5092. ** be deallocated after sqlite3_result_value() returns without harm.
  5093. ** ^A [protected sqlite3_value] object may always be used where an
  5094. ** [unprotected sqlite3_value] object is required, so either
  5095. ** kind of [sqlite3_value] object can be used with this interface.
  5096. **
  5097. ** If these routines are called from within the different thread
  5098. ** than the one containing the application-defined function that received
  5099. ** the [sqlite3_context] pointer, the results are undefined.
  5100. */
  5101. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  5102. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  5103. sqlite3_uint64,void(*)(void*));
  5104. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  5105. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  5106. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  5107. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  5108. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  5109. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  5110. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  5111. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  5112. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  5113. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  5114. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  5115. void(*)(void*), unsigned char encoding);
  5116. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  5117. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  5118. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  5119. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  5120. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  5121. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  5122. /*
  5123. ** CAPI3REF: Setting The Subtype Of An SQL Function
  5124. ** METHOD: sqlite3_context
  5125. **
  5126. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  5127. ** the result from the [application-defined SQL function] with
  5128. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  5129. ** of the subtype T are preserved in current versions of SQLite;
  5130. ** higher order bits are discarded.
  5131. ** The number of subtype bytes preserved by SQLite might increase
  5132. ** in future releases of SQLite.
  5133. */
  5134. SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  5135. /*
  5136. ** CAPI3REF: Define New Collating Sequences
  5137. ** METHOD: sqlite3
  5138. **
  5139. ** ^These functions add, remove, or modify a [collation] associated
  5140. ** with the [database connection] specified as the first argument.
  5141. **
  5142. ** ^The name of the collation is a UTF-8 string
  5143. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  5144. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  5145. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  5146. ** considered to be the same name.
  5147. **
  5148. ** ^(The third argument (eTextRep) must be one of the constants:
  5149. ** <ul>
  5150. ** <li> [SQLITE_UTF8],
  5151. ** <li> [SQLITE_UTF16LE],
  5152. ** <li> [SQLITE_UTF16BE],
  5153. ** <li> [SQLITE_UTF16], or
  5154. ** <li> [SQLITE_UTF16_ALIGNED].
  5155. ** </ul>)^
  5156. ** ^The eTextRep argument determines the encoding of strings passed
  5157. ** to the collating function callback, xCallback.
  5158. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  5159. ** force strings to be UTF16 with native byte order.
  5160. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  5161. ** on an even byte address.
  5162. **
  5163. ** ^The fourth argument, pArg, is an application data pointer that is passed
  5164. ** through as the first argument to the collating function callback.
  5165. **
  5166. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  5167. ** ^Multiple collating functions can be registered using the same name but
  5168. ** with different eTextRep parameters and SQLite will use whichever
  5169. ** function requires the least amount of data transformation.
  5170. ** ^If the xCallback argument is NULL then the collating function is
  5171. ** deleted. ^When all collating functions having the same name are deleted,
  5172. ** that collation is no longer usable.
  5173. **
  5174. ** ^The collating function callback is invoked with a copy of the pArg
  5175. ** application data pointer and with two strings in the encoding specified
  5176. ** by the eTextRep argument. The collating function must return an
  5177. ** integer that is negative, zero, or positive
  5178. ** if the first string is less than, equal to, or greater than the second,
  5179. ** respectively. A collating function must always return the same answer
  5180. ** given the same inputs. If two or more collating functions are registered
  5181. ** to the same collation name (using different eTextRep values) then all
  5182. ** must give an equivalent answer when invoked with equivalent strings.
  5183. ** The collating function must obey the following properties for all
  5184. ** strings A, B, and C:
  5185. **
  5186. ** <ol>
  5187. ** <li> If A==B then B==A.
  5188. ** <li> If A==B and B==C then A==C.
  5189. ** <li> If A&lt;B THEN B&gt;A.
  5190. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  5191. ** </ol>
  5192. **
  5193. ** If a collating function fails any of the above constraints and that
  5194. ** collating function is registered and used, then the behavior of SQLite
  5195. ** is undefined.
  5196. **
  5197. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  5198. ** with the addition that the xDestroy callback is invoked on pArg when
  5199. ** the collating function is deleted.
  5200. ** ^Collating functions are deleted when they are overridden by later
  5201. ** calls to the collation creation functions or when the
  5202. ** [database connection] is closed using [sqlite3_close()].
  5203. **
  5204. ** ^The xDestroy callback is <u>not</u> called if the
  5205. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  5206. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  5207. ** check the return code and dispose of the application data pointer
  5208. ** themselves rather than expecting SQLite to deal with it for them.
  5209. ** This is different from every other SQLite interface. The inconsistency
  5210. ** is unfortunate but cannot be changed without breaking backwards
  5211. ** compatibility.
  5212. **
  5213. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  5214. */
  5215. SQLITE_API int sqlite3_create_collation(
  5216. sqlite3*,
  5217. const char *zName,
  5218. int eTextRep,
  5219. void *pArg,
  5220. int(*xCompare)(void*,int,const void*,int,const void*)
  5221. );
  5222. SQLITE_API int sqlite3_create_collation_v2(
  5223. sqlite3*,
  5224. const char *zName,
  5225. int eTextRep,
  5226. void *pArg,
  5227. int(*xCompare)(void*,int,const void*,int,const void*),
  5228. void(*xDestroy)(void*)
  5229. );
  5230. SQLITE_API int sqlite3_create_collation16(
  5231. sqlite3*,
  5232. const void *zName,
  5233. int eTextRep,
  5234. void *pArg,
  5235. int(*xCompare)(void*,int,const void*,int,const void*)
  5236. );
  5237. /*
  5238. ** CAPI3REF: Collation Needed Callbacks
  5239. ** METHOD: sqlite3
  5240. **
  5241. ** ^To avoid having to register all collation sequences before a database
  5242. ** can be used, a single callback function may be registered with the
  5243. ** [database connection] to be invoked whenever an undefined collation
  5244. ** sequence is required.
  5245. **
  5246. ** ^If the function is registered using the sqlite3_collation_needed() API,
  5247. ** then it is passed the names of undefined collation sequences as strings
  5248. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  5249. ** the names are passed as UTF-16 in machine native byte order.
  5250. ** ^A call to either function replaces the existing collation-needed callback.
  5251. **
  5252. ** ^(When the callback is invoked, the first argument passed is a copy
  5253. ** of the second argument to sqlite3_collation_needed() or
  5254. ** sqlite3_collation_needed16(). The second argument is the database
  5255. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  5256. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  5257. ** sequence function required. The fourth parameter is the name of the
  5258. ** required collation sequence.)^
  5259. **
  5260. ** The callback function should register the desired collation using
  5261. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  5262. ** [sqlite3_create_collation_v2()].
  5263. */
  5264. SQLITE_API int sqlite3_collation_needed(
  5265. sqlite3*,
  5266. void*,
  5267. void(*)(void*,sqlite3*,int eTextRep,const char*)
  5268. );
  5269. SQLITE_API int sqlite3_collation_needed16(
  5270. sqlite3*,
  5271. void*,
  5272. void(*)(void*,sqlite3*,int eTextRep,const void*)
  5273. );
  5274. #ifdef SQLITE_HAS_CODEC
  5275. /*
  5276. ** Specify the key for an encrypted database. This routine should be
  5277. ** called right after sqlite3_open().
  5278. **
  5279. ** The code to implement this API is not available in the public release
  5280. ** of SQLite.
  5281. */
  5282. SQLITE_API int sqlite3_key(
  5283. sqlite3 *db, /* Database to be rekeyed */
  5284. const void *pKey, int nKey /* The key */
  5285. );
  5286. SQLITE_API int sqlite3_key_v2(
  5287. sqlite3 *db, /* Database to be rekeyed */
  5288. const char *zDbName, /* Name of the database */
  5289. const void *pKey, int nKey /* The key */
  5290. );
  5291. /*
  5292. ** Change the key on an open database. If the current database is not
  5293. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  5294. ** database is decrypted.
  5295. **
  5296. ** The code to implement this API is not available in the public release
  5297. ** of SQLite.
  5298. */
  5299. SQLITE_API int sqlite3_rekey(
  5300. sqlite3 *db, /* Database to be rekeyed */
  5301. const void *pKey, int nKey /* The new key */
  5302. );
  5303. SQLITE_API int sqlite3_rekey_v2(
  5304. sqlite3 *db, /* Database to be rekeyed */
  5305. const char *zDbName, /* Name of the database */
  5306. const void *pKey, int nKey /* The new key */
  5307. );
  5308. /*
  5309. ** Specify the activation key for a SEE database. Unless
  5310. ** activated, none of the SEE routines will work.
  5311. */
  5312. SQLITE_API void sqlite3_activate_see(
  5313. const char *zPassPhrase /* Activation phrase */
  5314. );
  5315. #endif
  5316. #ifdef SQLITE_ENABLE_CEROD
  5317. /*
  5318. ** Specify the activation key for a CEROD database. Unless
  5319. ** activated, none of the CEROD routines will work.
  5320. */
  5321. SQLITE_API void sqlite3_activate_cerod(
  5322. const char *zPassPhrase /* Activation phrase */
  5323. );
  5324. #endif
  5325. /*
  5326. ** CAPI3REF: Suspend Execution For A Short Time
  5327. **
  5328. ** The sqlite3_sleep() function causes the current thread to suspend execution
  5329. ** for at least a number of milliseconds specified in its parameter.
  5330. **
  5331. ** If the operating system does not support sleep requests with
  5332. ** millisecond time resolution, then the time will be rounded up to
  5333. ** the nearest second. The number of milliseconds of sleep actually
  5334. ** requested from the operating system is returned.
  5335. **
  5336. ** ^SQLite implements this interface by calling the xSleep()
  5337. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  5338. ** of the default VFS is not implemented correctly, or not implemented at
  5339. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  5340. ** in the previous paragraphs.
  5341. */
  5342. SQLITE_API int sqlite3_sleep(int);
  5343. /*
  5344. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  5345. **
  5346. ** ^(If this global variable is made to point to a string which is
  5347. ** the name of a folder (a.k.a. directory), then all temporary files
  5348. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  5349. ** will be placed in that directory.)^ ^If this variable
  5350. ** is a NULL pointer, then SQLite performs a search for an appropriate
  5351. ** temporary file directory.
  5352. **
  5353. ** Applications are strongly discouraged from using this global variable.
  5354. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  5355. ** But for all other platforms, it is highly recommended that applications
  5356. ** neither read nor write this variable. This global variable is a relic
  5357. ** that exists for backwards compatibility of legacy applications and should
  5358. ** be avoided in new projects.
  5359. **
  5360. ** It is not safe to read or modify this variable in more than one
  5361. ** thread at a time. It is not safe to read or modify this variable
  5362. ** if a [database connection] is being used at the same time in a separate
  5363. ** thread.
  5364. ** It is intended that this variable be set once
  5365. ** as part of process initialization and before any SQLite interface
  5366. ** routines have been called and that this variable remain unchanged
  5367. ** thereafter.
  5368. **
  5369. ** ^The [temp_store_directory pragma] may modify this variable and cause
  5370. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5371. ** the [temp_store_directory pragma] always assumes that any string
  5372. ** that this variable points to is held in memory obtained from
  5373. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5374. ** using [sqlite3_free].
  5375. ** Hence, if this variable is modified directly, either it should be
  5376. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5377. ** or else the use of the [temp_store_directory pragma] should be avoided.
  5378. ** Except when requested by the [temp_store_directory pragma], SQLite
  5379. ** does not free the memory that sqlite3_temp_directory points to. If
  5380. ** the application wants that memory to be freed, it must do
  5381. ** so itself, taking care to only do so after all [database connection]
  5382. ** objects have been destroyed.
  5383. **
  5384. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  5385. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  5386. ** features that require the use of temporary files may fail. Here is an
  5387. ** example of how to do this using C++ with the Windows Runtime:
  5388. **
  5389. ** <blockquote><pre>
  5390. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  5391. ** &nbsp; TemporaryFolder->Path->Data();
  5392. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  5393. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  5394. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  5395. ** &nbsp; NULL, NULL);
  5396. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  5397. ** </pre></blockquote>
  5398. */
  5399. SQLITE_API char *sqlite3_temp_directory;
  5400. /*
  5401. ** CAPI3REF: Name Of The Folder Holding Database Files
  5402. **
  5403. ** ^(If this global variable is made to point to a string which is
  5404. ** the name of a folder (a.k.a. directory), then all database files
  5405. ** specified with a relative pathname and created or accessed by
  5406. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  5407. ** to be relative to that directory.)^ ^If this variable is a NULL
  5408. ** pointer, then SQLite assumes that all database files specified
  5409. ** with a relative pathname are relative to the current directory
  5410. ** for the process. Only the windows VFS makes use of this global
  5411. ** variable; it is ignored by the unix VFS.
  5412. **
  5413. ** Changing the value of this variable while a database connection is
  5414. ** open can result in a corrupt database.
  5415. **
  5416. ** It is not safe to read or modify this variable in more than one
  5417. ** thread at a time. It is not safe to read or modify this variable
  5418. ** if a [database connection] is being used at the same time in a separate
  5419. ** thread.
  5420. ** It is intended that this variable be set once
  5421. ** as part of process initialization and before any SQLite interface
  5422. ** routines have been called and that this variable remain unchanged
  5423. ** thereafter.
  5424. **
  5425. ** ^The [data_store_directory pragma] may modify this variable and cause
  5426. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5427. ** the [data_store_directory pragma] always assumes that any string
  5428. ** that this variable points to is held in memory obtained from
  5429. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5430. ** using [sqlite3_free].
  5431. ** Hence, if this variable is modified directly, either it should be
  5432. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5433. ** or else the use of the [data_store_directory pragma] should be avoided.
  5434. */
  5435. SQLITE_API char *sqlite3_data_directory;
  5436. /*
  5437. ** CAPI3REF: Test For Auto-Commit Mode
  5438. ** KEYWORDS: {autocommit mode}
  5439. ** METHOD: sqlite3
  5440. **
  5441. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5442. ** zero if the given database connection is or is not in autocommit mode,
  5443. ** respectively. ^Autocommit mode is on by default.
  5444. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  5445. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5446. **
  5447. ** If certain kinds of errors occur on a statement within a multi-statement
  5448. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5449. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5450. ** transaction might be rolled back automatically. The only way to
  5451. ** find out whether SQLite automatically rolled back the transaction after
  5452. ** an error is to use this function.
  5453. **
  5454. ** If another thread changes the autocommit status of the database
  5455. ** connection while this routine is running, then the return value
  5456. ** is undefined.
  5457. */
  5458. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  5459. /*
  5460. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  5461. ** METHOD: sqlite3_stmt
  5462. **
  5463. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  5464. ** to which a [prepared statement] belongs. ^The [database connection]
  5465. ** returned by sqlite3_db_handle is the same [database connection]
  5466. ** that was the first argument
  5467. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5468. ** create the statement in the first place.
  5469. */
  5470. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  5471. /*
  5472. ** CAPI3REF: Return The Filename For A Database Connection
  5473. ** METHOD: sqlite3
  5474. **
  5475. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  5476. ** associated with database N of connection D. ^The main database file
  5477. ** has the name "main". If there is no attached database N on the database
  5478. ** connection D, or if database N is a temporary or in-memory database, then
  5479. ** a NULL pointer is returned.
  5480. **
  5481. ** ^The filename returned by this function is the output of the
  5482. ** xFullPathname method of the [VFS]. ^In other words, the filename
  5483. ** will be an absolute pathname, even if the filename used
  5484. ** to open the database originally was a URI or relative pathname.
  5485. */
  5486. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  5487. /*
  5488. ** CAPI3REF: Determine if a database is read-only
  5489. ** METHOD: sqlite3
  5490. **
  5491. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  5492. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  5493. ** the name of a database on connection D.
  5494. */
  5495. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  5496. /*
  5497. ** CAPI3REF: Find the next prepared statement
  5498. ** METHOD: sqlite3
  5499. **
  5500. ** ^This interface returns a pointer to the next [prepared statement] after
  5501. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  5502. ** then this interface returns a pointer to the first prepared statement
  5503. ** associated with the database connection pDb. ^If no prepared statement
  5504. ** satisfies the conditions of this routine, it returns NULL.
  5505. **
  5506. ** The [database connection] pointer D in a call to
  5507. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5508. ** connection and in particular must not be a NULL pointer.
  5509. */
  5510. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5511. /*
  5512. ** CAPI3REF: Commit And Rollback Notification Callbacks
  5513. ** METHOD: sqlite3
  5514. **
  5515. ** ^The sqlite3_commit_hook() interface registers a callback
  5516. ** function to be invoked whenever a transaction is [COMMIT | committed].
  5517. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  5518. ** for the same database connection is overridden.
  5519. ** ^The sqlite3_rollback_hook() interface registers a callback
  5520. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  5521. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  5522. ** for the same database connection is overridden.
  5523. ** ^The pArg argument is passed through to the callback.
  5524. ** ^If the callback on a commit hook function returns non-zero,
  5525. ** then the commit is converted into a rollback.
  5526. **
  5527. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  5528. ** return the P argument from the previous call of the same function
  5529. ** on the same [database connection] D, or NULL for
  5530. ** the first call for each function on D.
  5531. **
  5532. ** The commit and rollback hook callbacks are not reentrant.
  5533. ** The callback implementation must not do anything that will modify
  5534. ** the database connection that invoked the callback. Any actions
  5535. ** to modify the database connection must be deferred until after the
  5536. ** completion of the [sqlite3_step()] call that triggered the commit
  5537. ** or rollback hook in the first place.
  5538. ** Note that running any other SQL statements, including SELECT statements,
  5539. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  5540. ** the database connections for the meaning of "modify" in this paragraph.
  5541. **
  5542. ** ^Registering a NULL function disables the callback.
  5543. **
  5544. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  5545. ** operation is allowed to continue normally. ^If the commit hook
  5546. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  5547. ** ^The rollback hook is invoked on a rollback that results from a commit
  5548. ** hook returning non-zero, just as it would be with any other rollback.
  5549. **
  5550. ** ^For the purposes of this API, a transaction is said to have been
  5551. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5552. ** an error or constraint causes an implicit rollback to occur.
  5553. ** ^The rollback callback is not invoked if a transaction is
  5554. ** automatically rolled back because the database connection is closed.
  5555. **
  5556. ** See also the [sqlite3_update_hook()] interface.
  5557. */
  5558. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5559. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5560. /*
  5561. ** CAPI3REF: Data Change Notification Callbacks
  5562. ** METHOD: sqlite3
  5563. **
  5564. ** ^The sqlite3_update_hook() interface registers a callback function
  5565. ** with the [database connection] identified by the first argument
  5566. ** to be invoked whenever a row is updated, inserted or deleted in
  5567. ** a [rowid table].
  5568. ** ^Any callback set by a previous call to this function
  5569. ** for the same database connection is overridden.
  5570. **
  5571. ** ^The second argument is a pointer to the function to invoke when a
  5572. ** row is updated, inserted or deleted in a rowid table.
  5573. ** ^The first argument to the callback is a copy of the third argument
  5574. ** to sqlite3_update_hook().
  5575. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5576. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5577. ** to be invoked.
  5578. ** ^The third and fourth arguments to the callback contain pointers to the
  5579. ** database and table name containing the affected row.
  5580. ** ^The final callback parameter is the [rowid] of the row.
  5581. ** ^In the case of an update, this is the [rowid] after the update takes place.
  5582. **
  5583. ** ^(The update hook is not invoked when internal system tables are
  5584. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  5585. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  5586. **
  5587. ** ^In the current implementation, the update hook
  5588. ** is not invoked when conflicting rows are deleted because of an
  5589. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  5590. ** invoked when rows are deleted using the [truncate optimization].
  5591. ** The exceptions defined in this paragraph might change in a future
  5592. ** release of SQLite.
  5593. **
  5594. ** The update hook implementation must not do anything that will modify
  5595. ** the database connection that invoked the update hook. Any actions
  5596. ** to modify the database connection must be deferred until after the
  5597. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5598. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5599. ** database connections for the meaning of "modify" in this paragraph.
  5600. **
  5601. ** ^The sqlite3_update_hook(D,C,P) function
  5602. ** returns the P argument from the previous call
  5603. ** on the same [database connection] D, or NULL for
  5604. ** the first call on D.
  5605. **
  5606. ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  5607. ** and [sqlite3_preupdate_hook()] interfaces.
  5608. */
  5609. SQLITE_API void *sqlite3_update_hook(
  5610. sqlite3*,
  5611. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5612. void*
  5613. );
  5614. /*
  5615. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5616. **
  5617. ** ^(This routine enables or disables the sharing of the database cache
  5618. ** and schema data structures between [database connection | connections]
  5619. ** to the same database. Sharing is enabled if the argument is true
  5620. ** and disabled if the argument is false.)^
  5621. **
  5622. ** ^Cache sharing is enabled and disabled for an entire process.
  5623. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
  5624. ** In prior versions of SQLite,
  5625. ** sharing was enabled or disabled for each thread separately.
  5626. **
  5627. ** ^(The cache sharing mode set by this interface effects all subsequent
  5628. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5629. ** Existing database connections continue use the sharing mode
  5630. ** that was in effect at the time they were opened.)^
  5631. **
  5632. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5633. ** successfully. An [error code] is returned otherwise.)^
  5634. **
  5635. ** ^Shared cache is disabled by default. But this might change in
  5636. ** future releases of SQLite. Applications that care about shared
  5637. ** cache setting should set it explicitly.
  5638. **
  5639. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  5640. ** and will always return SQLITE_MISUSE. On those systems,
  5641. ** shared cache mode should be enabled per-database connection via
  5642. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  5643. **
  5644. ** This interface is threadsafe on processors where writing a
  5645. ** 32-bit integer is atomic.
  5646. **
  5647. ** See Also: [SQLite Shared-Cache Mode]
  5648. */
  5649. SQLITE_API int sqlite3_enable_shared_cache(int);
  5650. /*
  5651. ** CAPI3REF: Attempt To Free Heap Memory
  5652. **
  5653. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5654. ** of heap memory by deallocating non-essential memory allocations
  5655. ** held by the database library. Memory used to cache database
  5656. ** pages to improve performance is an example of non-essential memory.
  5657. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5658. ** which might be more or less than the amount requested.
  5659. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5660. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5661. **
  5662. ** See also: [sqlite3_db_release_memory()]
  5663. */
  5664. SQLITE_API int sqlite3_release_memory(int);
  5665. /*
  5666. ** CAPI3REF: Free Memory Used By A Database Connection
  5667. ** METHOD: sqlite3
  5668. **
  5669. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5670. ** memory as possible from database connection D. Unlike the
  5671. ** [sqlite3_release_memory()] interface, this interface is in effect even
  5672. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5673. ** omitted.
  5674. **
  5675. ** See also: [sqlite3_release_memory()]
  5676. */
  5677. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  5678. /*
  5679. ** CAPI3REF: Impose A Limit On Heap Size
  5680. **
  5681. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5682. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5683. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5684. ** limit by reducing the number of pages held in the page cache
  5685. ** as heap memory usages approaches the limit.
  5686. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5687. ** below the limit, it will exceed the limit rather than generate
  5688. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5689. ** is advisory only.
  5690. **
  5691. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5692. ** the soft heap limit prior to the call, or negative in the case of an
  5693. ** error. ^If the argument N is negative
  5694. ** then no change is made to the soft heap limit. Hence, the current
  5695. ** size of the soft heap limit can be determined by invoking
  5696. ** sqlite3_soft_heap_limit64() with a negative argument.
  5697. **
  5698. ** ^If the argument N is zero then the soft heap limit is disabled.
  5699. **
  5700. ** ^(The soft heap limit is not enforced in the current implementation
  5701. ** if one or more of following conditions are true:
  5702. **
  5703. ** <ul>
  5704. ** <li> The soft heap limit is set to zero.
  5705. ** <li> Memory accounting is disabled using a combination of the
  5706. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5707. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5708. ** <li> An alternative page cache implementation is specified using
  5709. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5710. ** <li> The page cache allocates from its own memory pool supplied
  5711. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5712. ** from the heap.
  5713. ** </ul>)^
  5714. **
  5715. ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
  5716. ** the soft heap limit is enforced
  5717. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5718. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5719. ** the soft heap limit is enforced on every memory allocation. Without
  5720. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5721. ** when memory is allocated by the page cache. Testing suggests that because
  5722. ** the page cache is the predominate memory user in SQLite, most
  5723. ** applications will achieve adequate soft heap limit enforcement without
  5724. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5725. **
  5726. ** The circumstances under which SQLite will enforce the soft heap limit may
  5727. ** changes in future releases of SQLite.
  5728. */
  5729. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5730. /*
  5731. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5732. ** DEPRECATED
  5733. **
  5734. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5735. ** interface. This routine is provided for historical compatibility
  5736. ** only. All new applications should use the
  5737. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5738. */
  5739. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  5740. /*
  5741. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5742. ** METHOD: sqlite3
  5743. **
  5744. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  5745. ** information about column C of table T in database D
  5746. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  5747. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  5748. ** the final five arguments with appropriate values if the specified
  5749. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  5750. ** SQLITE_ERROR and if the specified column does not exist.
  5751. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  5752. ** NULL pointer, then this routine simply checks for the existence of the
  5753. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  5754. ** does not.
  5755. **
  5756. ** ^The column is identified by the second, third and fourth parameters to
  5757. ** this function. ^(The second parameter is either the name of the database
  5758. ** (i.e. "main", "temp", or an attached database) containing the specified
  5759. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  5760. ** for the table using the same algorithm used by the database engine to
  5761. ** resolve unqualified table references.
  5762. **
  5763. ** ^The third and fourth parameters to this function are the table and column
  5764. ** name of the desired column, respectively.
  5765. **
  5766. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5767. ** and subsequent parameters to this function. ^Any of these arguments may be
  5768. ** NULL, in which case the corresponding element of metadata is omitted.
  5769. **
  5770. ** ^(<blockquote>
  5771. ** <table border="1">
  5772. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5773. **
  5774. ** <tr><td> 5th <td> const char* <td> Data type
  5775. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5776. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5777. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5778. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5779. ** </table>
  5780. ** </blockquote>)^
  5781. **
  5782. ** ^The memory pointed to by the character pointers returned for the
  5783. ** declaration type and collation sequence is valid until the next
  5784. ** call to any SQLite API function.
  5785. **
  5786. ** ^If the specified table is actually a view, an [error code] is returned.
  5787. **
  5788. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  5789. ** is not a [WITHOUT ROWID] table and an
  5790. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5791. ** parameters are set for the explicitly declared column. ^(If there is no
  5792. ** [INTEGER PRIMARY KEY] column, then the outputs
  5793. ** for the [rowid] are set as follows:
  5794. **
  5795. ** <pre>
  5796. ** data type: "INTEGER"
  5797. ** collation sequence: "BINARY"
  5798. ** not null: 0
  5799. ** primary key: 1
  5800. ** auto increment: 0
  5801. ** </pre>)^
  5802. **
  5803. ** ^This function causes all database schemas to be read from disk and
  5804. ** parsed, if that has not already been done, and returns an error if
  5805. ** any errors are encountered while loading the schema.
  5806. */
  5807. SQLITE_API int sqlite3_table_column_metadata(
  5808. sqlite3 *db, /* Connection handle */
  5809. const char *zDbName, /* Database name or NULL */
  5810. const char *zTableName, /* Table name */
  5811. const char *zColumnName, /* Column name */
  5812. char const **pzDataType, /* OUTPUT: Declared data type */
  5813. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5814. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5815. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5816. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5817. );
  5818. /*
  5819. ** CAPI3REF: Load An Extension
  5820. ** METHOD: sqlite3
  5821. **
  5822. ** ^This interface loads an SQLite extension library from the named file.
  5823. **
  5824. ** ^The sqlite3_load_extension() interface attempts to load an
  5825. ** [SQLite extension] library contained in the file zFile. If
  5826. ** the file cannot be loaded directly, attempts are made to load
  5827. ** with various operating-system specific extensions added.
  5828. ** So for example, if "samplelib" cannot be loaded, then names like
  5829. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5830. ** be tried also.
  5831. **
  5832. ** ^The entry point is zProc.
  5833. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5834. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5835. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5836. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5837. ** characters in the filename from the last "/" to the first following
  5838. ** "." and omitting any initial "lib".)^
  5839. ** ^The sqlite3_load_extension() interface returns
  5840. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5841. ** ^If an error occurs and pzErrMsg is not 0, then the
  5842. ** [sqlite3_load_extension()] interface shall attempt to
  5843. ** fill *pzErrMsg with error message text stored in memory
  5844. ** obtained from [sqlite3_malloc()]. The calling function
  5845. ** should free this memory by calling [sqlite3_free()].
  5846. **
  5847. ** ^Extension loading must be enabled using
  5848. ** [sqlite3_enable_load_extension()] or
  5849. ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  5850. ** prior to calling this API,
  5851. ** otherwise an error will be returned.
  5852. **
  5853. ** <b>Security warning:</b> It is recommended that the
  5854. ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  5855. ** interface. The use of the [sqlite3_enable_load_extension()] interface
  5856. ** should be avoided. This will keep the SQL function [load_extension()]
  5857. ** disabled and prevent SQL injections from giving attackers
  5858. ** access to extension loading capabilities.
  5859. **
  5860. ** See also the [load_extension() SQL function].
  5861. */
  5862. SQLITE_API int sqlite3_load_extension(
  5863. sqlite3 *db, /* Load the extension into this database connection */
  5864. const char *zFile, /* Name of the shared library containing extension */
  5865. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5866. char **pzErrMsg /* Put error message here if not 0 */
  5867. );
  5868. /*
  5869. ** CAPI3REF: Enable Or Disable Extension Loading
  5870. ** METHOD: sqlite3
  5871. **
  5872. ** ^So as not to open security holes in older applications that are
  5873. ** unprepared to deal with [extension loading], and as a means of disabling
  5874. ** [extension loading] while evaluating user-entered SQL, the following API
  5875. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5876. **
  5877. ** ^Extension loading is off by default.
  5878. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5879. ** to turn extension loading on and call it with onoff==0 to turn
  5880. ** it back off again.
  5881. **
  5882. ** ^This interface enables or disables both the C-API
  5883. ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  5884. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  5885. ** to enable or disable only the C-API.)^
  5886. **
  5887. ** <b>Security warning:</b> It is recommended that extension loading
  5888. ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  5889. ** rather than this interface, so the [load_extension()] SQL function
  5890. ** remains disabled. This will prevent SQL injections from giving attackers
  5891. ** access to extension loading capabilities.
  5892. */
  5893. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5894. /*
  5895. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5896. **
  5897. ** ^This interface causes the xEntryPoint() function to be invoked for
  5898. ** each new [database connection] that is created. The idea here is that
  5899. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5900. ** that is to be automatically loaded into all new database connections.
  5901. **
  5902. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5903. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5904. ** arguments and expects an integer result as if the signature of the
  5905. ** entry point where as follows:
  5906. **
  5907. ** <blockquote><pre>
  5908. ** &nbsp; int xEntryPoint(
  5909. ** &nbsp; sqlite3 *db,
  5910. ** &nbsp; const char **pzErrMsg,
  5911. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5912. ** &nbsp; );
  5913. ** </pre></blockquote>)^
  5914. **
  5915. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5916. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5917. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5918. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5919. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5920. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5921. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5922. **
  5923. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5924. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5925. ** will be called more than once for each database connection that is opened.
  5926. **
  5927. ** See also: [sqlite3_reset_auto_extension()]
  5928. ** and [sqlite3_cancel_auto_extension()]
  5929. */
  5930. SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  5931. /*
  5932. ** CAPI3REF: Cancel Automatic Extension Loading
  5933. **
  5934. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5935. ** initialization routine X that was registered using a prior call to
  5936. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5937. ** routine returns 1 if initialization routine X was successfully
  5938. ** unregistered and it returns 0 if X was not on the list of initialization
  5939. ** routines.
  5940. */
  5941. SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  5942. /*
  5943. ** CAPI3REF: Reset Automatic Extension Loading
  5944. **
  5945. ** ^This interface disables all automatic extensions previously
  5946. ** registered using [sqlite3_auto_extension()].
  5947. */
  5948. SQLITE_API void sqlite3_reset_auto_extension(void);
  5949. /*
  5950. ** The interface to the virtual-table mechanism is currently considered
  5951. ** to be experimental. The interface might change in incompatible ways.
  5952. ** If this is a problem for you, do not use the interface at this time.
  5953. **
  5954. ** When the virtual-table mechanism stabilizes, we will declare the
  5955. ** interface fixed, support it indefinitely, and remove this comment.
  5956. */
  5957. /*
  5958. ** Structures used by the virtual table interface
  5959. */
  5960. typedef struct sqlite3_vtab sqlite3_vtab;
  5961. typedef struct sqlite3_index_info sqlite3_index_info;
  5962. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5963. typedef struct sqlite3_module sqlite3_module;
  5964. /*
  5965. ** CAPI3REF: Virtual Table Object
  5966. ** KEYWORDS: sqlite3_module {virtual table module}
  5967. **
  5968. ** This structure, sometimes called a "virtual table module",
  5969. ** defines the implementation of a [virtual tables].
  5970. ** This structure consists mostly of methods for the module.
  5971. **
  5972. ** ^A virtual table module is created by filling in a persistent
  5973. ** instance of this structure and passing a pointer to that instance
  5974. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5975. ** ^The registration remains valid until it is replaced by a different
  5976. ** module or until the [database connection] closes. The content
  5977. ** of this structure must not change while it is registered with
  5978. ** any database connection.
  5979. */
  5980. struct sqlite3_module {
  5981. int iVersion;
  5982. int (*xCreate)(sqlite3*, void *pAux,
  5983. int argc, const char *const*argv,
  5984. sqlite3_vtab **ppVTab, char**);
  5985. int (*xConnect)(sqlite3*, void *pAux,
  5986. int argc, const char *const*argv,
  5987. sqlite3_vtab **ppVTab, char**);
  5988. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5989. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5990. int (*xDestroy)(sqlite3_vtab *pVTab);
  5991. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5992. int (*xClose)(sqlite3_vtab_cursor*);
  5993. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5994. int argc, sqlite3_value **argv);
  5995. int (*xNext)(sqlite3_vtab_cursor*);
  5996. int (*xEof)(sqlite3_vtab_cursor*);
  5997. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5998. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5999. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  6000. int (*xBegin)(sqlite3_vtab *pVTab);
  6001. int (*xSync)(sqlite3_vtab *pVTab);
  6002. int (*xCommit)(sqlite3_vtab *pVTab);
  6003. int (*xRollback)(sqlite3_vtab *pVTab);
  6004. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  6005. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  6006. void **ppArg);
  6007. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  6008. /* The methods above are in version 1 of the sqlite_module object. Those
  6009. ** below are for version 2 and greater. */
  6010. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  6011. int (*xRelease)(sqlite3_vtab *pVTab, int);
  6012. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  6013. };
  6014. /*
  6015. ** CAPI3REF: Virtual Table Indexing Information
  6016. ** KEYWORDS: sqlite3_index_info
  6017. **
  6018. ** The sqlite3_index_info structure and its substructures is used as part
  6019. ** of the [virtual table] interface to
  6020. ** pass information into and receive the reply from the [xBestIndex]
  6021. ** method of a [virtual table module]. The fields under **Inputs** are the
  6022. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  6023. ** results into the **Outputs** fields.
  6024. **
  6025. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  6026. **
  6027. ** <blockquote>column OP expr</blockquote>
  6028. **
  6029. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  6030. ** stored in aConstraint[].op using one of the
  6031. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  6032. ** ^(The index of the column is stored in
  6033. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  6034. ** expr on the right-hand side can be evaluated (and thus the constraint
  6035. ** is usable) and false if it cannot.)^
  6036. **
  6037. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  6038. ** and makes other simplifications to the WHERE clause in an attempt to
  6039. ** get as many WHERE clause terms into the form shown above as possible.
  6040. ** ^The aConstraint[] array only reports WHERE clause terms that are
  6041. ** relevant to the particular virtual table being queried.
  6042. **
  6043. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  6044. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  6045. **
  6046. ** The colUsed field indicates which columns of the virtual table may be
  6047. ** required by the current scan. Virtual table columns are numbered from
  6048. ** zero in the order in which they appear within the CREATE TABLE statement
  6049. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  6050. ** the corresponding bit is set within the colUsed mask if the column may be
  6051. ** required by SQLite. If the table has at least 64 columns and any column
  6052. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  6053. ** set. In other words, column iCol may be required if the expression
  6054. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  6055. ** non-zero.
  6056. **
  6057. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  6058. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  6059. ** the right-hand side of the corresponding aConstraint[] is evaluated
  6060. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  6061. ** is true, then the constraint is assumed to be fully handled by the
  6062. ** virtual table and is not checked again by SQLite.)^
  6063. **
  6064. ** ^The idxNum and idxPtr values are recorded and passed into the
  6065. ** [xFilter] method.
  6066. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  6067. ** needToFreeIdxPtr is true.
  6068. **
  6069. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  6070. ** the correct order to satisfy the ORDER BY clause so that no separate
  6071. ** sorting step is required.
  6072. **
  6073. ** ^The estimatedCost value is an estimate of the cost of a particular
  6074. ** strategy. A cost of N indicates that the cost of the strategy is similar
  6075. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  6076. ** indicates that the expense of the operation is similar to that of a
  6077. ** binary search on a unique indexed field of an SQLite table with N rows.
  6078. **
  6079. ** ^The estimatedRows value is an estimate of the number of rows that
  6080. ** will be returned by the strategy.
  6081. **
  6082. ** The xBestIndex method may optionally populate the idxFlags field with a
  6083. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  6084. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  6085. ** assumes that the strategy may visit at most one row.
  6086. **
  6087. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  6088. ** SQLite also assumes that if a call to the xUpdate() method is made as
  6089. ** part of the same statement to delete or update a virtual table row and the
  6090. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  6091. ** any database changes. In other words, if the xUpdate() returns
  6092. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  6093. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  6094. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  6095. ** the xUpdate method are automatically rolled back by SQLite.
  6096. **
  6097. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  6098. ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
  6099. ** If a virtual table extension is
  6100. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  6101. ** to read or write the estimatedRows field are undefined (but are likely
  6102. ** to included crashing the application). The estimatedRows field should
  6103. ** therefore only be used if [sqlite3_libversion_number()] returns a
  6104. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  6105. ** was added for [version 3.9.0] ([dateof:3.9.0]).
  6106. ** It may therefore only be used if
  6107. ** sqlite3_libversion_number() returns a value greater than or equal to
  6108. ** 3009000.
  6109. */
  6110. struct sqlite3_index_info {
  6111. /* Inputs */
  6112. int nConstraint; /* Number of entries in aConstraint */
  6113. struct sqlite3_index_constraint {
  6114. int iColumn; /* Column constrained. -1 for ROWID */
  6115. unsigned char op; /* Constraint operator */
  6116. unsigned char usable; /* True if this constraint is usable */
  6117. int iTermOffset; /* Used internally - xBestIndex should ignore */
  6118. } *aConstraint; /* Table of WHERE clause constraints */
  6119. int nOrderBy; /* Number of terms in the ORDER BY clause */
  6120. struct sqlite3_index_orderby {
  6121. int iColumn; /* Column number */
  6122. unsigned char desc; /* True for DESC. False for ASC. */
  6123. } *aOrderBy; /* The ORDER BY clause */
  6124. /* Outputs */
  6125. struct sqlite3_index_constraint_usage {
  6126. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  6127. unsigned char omit; /* Do not code a test for this constraint */
  6128. } *aConstraintUsage;
  6129. int idxNum; /* Number used to identify the index */
  6130. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  6131. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  6132. int orderByConsumed; /* True if output is already ordered */
  6133. double estimatedCost; /* Estimated cost of using this index */
  6134. /* Fields below are only available in SQLite 3.8.2 and later */
  6135. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  6136. /* Fields below are only available in SQLite 3.9.0 and later */
  6137. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  6138. /* Fields below are only available in SQLite 3.10.0 and later */
  6139. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  6140. };
  6141. /*
  6142. ** CAPI3REF: Virtual Table Scan Flags
  6143. */
  6144. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  6145. /*
  6146. ** CAPI3REF: Virtual Table Constraint Operator Codes
  6147. **
  6148. ** These macros defined the allowed values for the
  6149. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  6150. ** an operator that is part of a constraint term in the wHERE clause of
  6151. ** a query that uses a [virtual table].
  6152. */
  6153. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  6154. #define SQLITE_INDEX_CONSTRAINT_GT 4
  6155. #define SQLITE_INDEX_CONSTRAINT_LE 8
  6156. #define SQLITE_INDEX_CONSTRAINT_LT 16
  6157. #define SQLITE_INDEX_CONSTRAINT_GE 32
  6158. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  6159. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  6160. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  6161. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  6162. /*
  6163. ** CAPI3REF: Register A Virtual Table Implementation
  6164. ** METHOD: sqlite3
  6165. **
  6166. ** ^These routines are used to register a new [virtual table module] name.
  6167. ** ^Module names must be registered before
  6168. ** creating a new [virtual table] using the module and before using a
  6169. ** preexisting [virtual table] for the module.
  6170. **
  6171. ** ^The module name is registered on the [database connection] specified
  6172. ** by the first parameter. ^The name of the module is given by the
  6173. ** second parameter. ^The third parameter is a pointer to
  6174. ** the implementation of the [virtual table module]. ^The fourth
  6175. ** parameter is an arbitrary client data pointer that is passed through
  6176. ** into the [xCreate] and [xConnect] methods of the virtual table module
  6177. ** when a new virtual table is be being created or reinitialized.
  6178. **
  6179. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  6180. ** is a pointer to a destructor for the pClientData. ^SQLite will
  6181. ** invoke the destructor function (if it is not NULL) when SQLite
  6182. ** no longer needs the pClientData pointer. ^The destructor will also
  6183. ** be invoked if the call to sqlite3_create_module_v2() fails.
  6184. ** ^The sqlite3_create_module()
  6185. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  6186. ** destructor.
  6187. */
  6188. SQLITE_API int sqlite3_create_module(
  6189. sqlite3 *db, /* SQLite connection to register module with */
  6190. const char *zName, /* Name of the module */
  6191. const sqlite3_module *p, /* Methods for the module */
  6192. void *pClientData /* Client data for xCreate/xConnect */
  6193. );
  6194. SQLITE_API int sqlite3_create_module_v2(
  6195. sqlite3 *db, /* SQLite connection to register module with */
  6196. const char *zName, /* Name of the module */
  6197. const sqlite3_module *p, /* Methods for the module */
  6198. void *pClientData, /* Client data for xCreate/xConnect */
  6199. void(*xDestroy)(void*) /* Module destructor function */
  6200. );
  6201. /*
  6202. ** CAPI3REF: Virtual Table Instance Object
  6203. ** KEYWORDS: sqlite3_vtab
  6204. **
  6205. ** Every [virtual table module] implementation uses a subclass
  6206. ** of this object to describe a particular instance
  6207. ** of the [virtual table]. Each subclass will
  6208. ** be tailored to the specific needs of the module implementation.
  6209. ** The purpose of this superclass is to define certain fields that are
  6210. ** common to all module implementations.
  6211. **
  6212. ** ^Virtual tables methods can set an error message by assigning a
  6213. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  6214. ** take care that any prior string is freed by a call to [sqlite3_free()]
  6215. ** prior to assigning a new string to zErrMsg. ^After the error message
  6216. ** is delivered up to the client application, the string will be automatically
  6217. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  6218. */
  6219. struct sqlite3_vtab {
  6220. const sqlite3_module *pModule; /* The module for this virtual table */
  6221. int nRef; /* Number of open cursors */
  6222. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  6223. /* Virtual table implementations will typically add additional fields */
  6224. };
  6225. /*
  6226. ** CAPI3REF: Virtual Table Cursor Object
  6227. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  6228. **
  6229. ** Every [virtual table module] implementation uses a subclass of the
  6230. ** following structure to describe cursors that point into the
  6231. ** [virtual table] and are used
  6232. ** to loop through the virtual table. Cursors are created using the
  6233. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  6234. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  6235. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  6236. ** of the module. Each module implementation will define
  6237. ** the content of a cursor structure to suit its own needs.
  6238. **
  6239. ** This superclass exists in order to define fields of the cursor that
  6240. ** are common to all implementations.
  6241. */
  6242. struct sqlite3_vtab_cursor {
  6243. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  6244. /* Virtual table implementations will typically add additional fields */
  6245. };
  6246. /*
  6247. ** CAPI3REF: Declare The Schema Of A Virtual Table
  6248. **
  6249. ** ^The [xCreate] and [xConnect] methods of a
  6250. ** [virtual table module] call this interface
  6251. ** to declare the format (the names and datatypes of the columns) of
  6252. ** the virtual tables they implement.
  6253. */
  6254. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  6255. /*
  6256. ** CAPI3REF: Overload A Function For A Virtual Table
  6257. ** METHOD: sqlite3
  6258. **
  6259. ** ^(Virtual tables can provide alternative implementations of functions
  6260. ** using the [xFindFunction] method of the [virtual table module].
  6261. ** But global versions of those functions
  6262. ** must exist in order to be overloaded.)^
  6263. **
  6264. ** ^(This API makes sure a global version of a function with a particular
  6265. ** name and number of parameters exists. If no such function exists
  6266. ** before this API is called, a new function is created.)^ ^The implementation
  6267. ** of the new function always causes an exception to be thrown. So
  6268. ** the new function is not good for anything by itself. Its only
  6269. ** purpose is to be a placeholder function that can be overloaded
  6270. ** by a [virtual table].
  6271. */
  6272. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  6273. /*
  6274. ** The interface to the virtual-table mechanism defined above (back up
  6275. ** to a comment remarkably similar to this one) is currently considered
  6276. ** to be experimental. The interface might change in incompatible ways.
  6277. ** If this is a problem for you, do not use the interface at this time.
  6278. **
  6279. ** When the virtual-table mechanism stabilizes, we will declare the
  6280. ** interface fixed, support it indefinitely, and remove this comment.
  6281. */
  6282. /*
  6283. ** CAPI3REF: A Handle To An Open BLOB
  6284. ** KEYWORDS: {BLOB handle} {BLOB handles}
  6285. **
  6286. ** An instance of this object represents an open BLOB on which
  6287. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  6288. ** ^Objects of this type are created by [sqlite3_blob_open()]
  6289. ** and destroyed by [sqlite3_blob_close()].
  6290. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  6291. ** can be used to read or write small subsections of the BLOB.
  6292. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  6293. */
  6294. typedef struct sqlite3_blob sqlite3_blob;
  6295. /*
  6296. ** CAPI3REF: Open A BLOB For Incremental I/O
  6297. ** METHOD: sqlite3
  6298. ** CONSTRUCTOR: sqlite3_blob
  6299. **
  6300. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  6301. ** in row iRow, column zColumn, table zTable in database zDb;
  6302. ** in other words, the same BLOB that would be selected by:
  6303. **
  6304. ** <pre>
  6305. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  6306. ** </pre>)^
  6307. **
  6308. ** ^(Parameter zDb is not the filename that contains the database, but
  6309. ** rather the symbolic name of the database. For attached databases, this is
  6310. ** the name that appears after the AS keyword in the [ATTACH] statement.
  6311. ** For the main database file, the database name is "main". For TEMP
  6312. ** tables, the database name is "temp".)^
  6313. **
  6314. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  6315. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  6316. ** read-only access.
  6317. **
  6318. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  6319. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  6320. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  6321. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  6322. ** on *ppBlob after this function it returns.
  6323. **
  6324. ** This function fails with SQLITE_ERROR if any of the following are true:
  6325. ** <ul>
  6326. ** <li> ^(Database zDb does not exist)^,
  6327. ** <li> ^(Table zTable does not exist within database zDb)^,
  6328. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  6329. ** <li> ^(Column zColumn does not exist)^,
  6330. ** <li> ^(Row iRow is not present in the table)^,
  6331. ** <li> ^(The specified column of row iRow contains a value that is not
  6332. ** a TEXT or BLOB value)^,
  6333. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  6334. ** constraint and the blob is being opened for read/write access)^,
  6335. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  6336. ** column zColumn is part of a [child key] definition and the blob is
  6337. ** being opened for read/write access)^.
  6338. ** </ul>
  6339. **
  6340. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  6341. ** [database connection] error code and message accessible via
  6342. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6343. **
  6344. ** A BLOB referenced by sqlite3_blob_open() may be read using the
  6345. ** [sqlite3_blob_read()] interface and modified by using
  6346. ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
  6347. ** different row of the same table using the [sqlite3_blob_reopen()]
  6348. ** interface. However, the column, table, or database of a [BLOB handle]
  6349. ** cannot be changed after the [BLOB handle] is opened.
  6350. **
  6351. ** ^(If the row that a BLOB handle points to is modified by an
  6352. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  6353. ** then the BLOB handle is marked as "expired".
  6354. ** This is true if any column of the row is changed, even a column
  6355. ** other than the one the BLOB handle is open on.)^
  6356. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  6357. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  6358. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  6359. ** rolled back by the expiration of the BLOB. Such changes will eventually
  6360. ** commit if the transaction continues to completion.)^
  6361. **
  6362. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  6363. ** the opened blob. ^The size of a blob may not be changed by this
  6364. ** interface. Use the [UPDATE] SQL command to change the size of a
  6365. ** blob.
  6366. **
  6367. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  6368. ** and the built-in [zeroblob] SQL function may be used to create a
  6369. ** zero-filled blob to read or write using the incremental-blob interface.
  6370. **
  6371. ** To avoid a resource leak, every open [BLOB handle] should eventually
  6372. ** be released by a call to [sqlite3_blob_close()].
  6373. **
  6374. ** See also: [sqlite3_blob_close()],
  6375. ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  6376. ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  6377. */
  6378. SQLITE_API int sqlite3_blob_open(
  6379. sqlite3*,
  6380. const char *zDb,
  6381. const char *zTable,
  6382. const char *zColumn,
  6383. sqlite3_int64 iRow,
  6384. int flags,
  6385. sqlite3_blob **ppBlob
  6386. );
  6387. /*
  6388. ** CAPI3REF: Move a BLOB Handle to a New Row
  6389. ** METHOD: sqlite3_blob
  6390. **
  6391. ** ^This function is used to move an existing [BLOB handle] so that it points
  6392. ** to a different row of the same database table. ^The new row is identified
  6393. ** by the rowid value passed as the second argument. Only the row can be
  6394. ** changed. ^The database, table and column on which the blob handle is open
  6395. ** remain the same. Moving an existing [BLOB handle] to a new row is
  6396. ** faster than closing the existing handle and opening a new one.
  6397. **
  6398. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  6399. ** it must exist and there must be either a blob or text value stored in
  6400. ** the nominated column.)^ ^If the new row is not present in the table, or if
  6401. ** it does not contain a blob or text value, or if another error occurs, an
  6402. ** SQLite error code is returned and the blob handle is considered aborted.
  6403. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  6404. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  6405. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  6406. ** always returns zero.
  6407. **
  6408. ** ^This function sets the database handle error code and message.
  6409. */
  6410. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  6411. /*
  6412. ** CAPI3REF: Close A BLOB Handle
  6413. ** DESTRUCTOR: sqlite3_blob
  6414. **
  6415. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  6416. ** unconditionally. Even if this routine returns an error code, the
  6417. ** handle is still closed.)^
  6418. **
  6419. ** ^If the blob handle being closed was opened for read-write access, and if
  6420. ** the database is in auto-commit mode and there are no other open read-write
  6421. ** blob handles or active write statements, the current transaction is
  6422. ** committed. ^If an error occurs while committing the transaction, an error
  6423. ** code is returned and the transaction rolled back.
  6424. **
  6425. ** Calling this function with an argument that is not a NULL pointer or an
  6426. ** open blob handle results in undefined behaviour. ^Calling this routine
  6427. ** with a null pointer (such as would be returned by a failed call to
  6428. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  6429. ** is passed a valid open blob handle, the values returned by the
  6430. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  6431. */
  6432. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  6433. /*
  6434. ** CAPI3REF: Return The Size Of An Open BLOB
  6435. ** METHOD: sqlite3_blob
  6436. **
  6437. ** ^Returns the size in bytes of the BLOB accessible via the
  6438. ** successfully opened [BLOB handle] in its only argument. ^The
  6439. ** incremental blob I/O routines can only read or overwriting existing
  6440. ** blob content; they cannot change the size of a blob.
  6441. **
  6442. ** This routine only works on a [BLOB handle] which has been created
  6443. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6444. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6445. ** to this routine results in undefined and probably undesirable behavior.
  6446. */
  6447. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  6448. /*
  6449. ** CAPI3REF: Read Data From A BLOB Incrementally
  6450. ** METHOD: sqlite3_blob
  6451. **
  6452. ** ^(This function is used to read data from an open [BLOB handle] into a
  6453. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  6454. ** from the open BLOB, starting at offset iOffset.)^
  6455. **
  6456. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6457. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  6458. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  6459. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  6460. ** can be determined using the [sqlite3_blob_bytes()] interface.
  6461. **
  6462. ** ^An attempt to read from an expired [BLOB handle] fails with an
  6463. ** error code of [SQLITE_ABORT].
  6464. **
  6465. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  6466. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6467. **
  6468. ** This routine only works on a [BLOB handle] which has been created
  6469. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6470. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6471. ** to this routine results in undefined and probably undesirable behavior.
  6472. **
  6473. ** See also: [sqlite3_blob_write()].
  6474. */
  6475. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  6476. /*
  6477. ** CAPI3REF: Write Data Into A BLOB Incrementally
  6478. ** METHOD: sqlite3_blob
  6479. **
  6480. ** ^(This function is used to write data into an open [BLOB handle] from a
  6481. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  6482. ** into the open BLOB, starting at offset iOffset.)^
  6483. **
  6484. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  6485. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6486. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  6487. ** [database connection] error code and message accessible via
  6488. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6489. **
  6490. ** ^If the [BLOB handle] passed as the first argument was not opened for
  6491. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  6492. ** this function returns [SQLITE_READONLY].
  6493. **
  6494. ** This function may only modify the contents of the BLOB; it is
  6495. ** not possible to increase the size of a BLOB using this API.
  6496. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6497. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  6498. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  6499. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  6500. ** than zero [SQLITE_ERROR] is returned and no data is written.
  6501. **
  6502. ** ^An attempt to write to an expired [BLOB handle] fails with an
  6503. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  6504. ** before the [BLOB handle] expired are not rolled back by the
  6505. ** expiration of the handle, though of course those changes might
  6506. ** have been overwritten by the statement that expired the BLOB handle
  6507. ** or by other independent statements.
  6508. **
  6509. ** This routine only works on a [BLOB handle] which has been created
  6510. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6511. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6512. ** to this routine results in undefined and probably undesirable behavior.
  6513. **
  6514. ** See also: [sqlite3_blob_read()].
  6515. */
  6516. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  6517. /*
  6518. ** CAPI3REF: Virtual File System Objects
  6519. **
  6520. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  6521. ** that SQLite uses to interact
  6522. ** with the underlying operating system. Most SQLite builds come with a
  6523. ** single default VFS that is appropriate for the host computer.
  6524. ** New VFSes can be registered and existing VFSes can be unregistered.
  6525. ** The following interfaces are provided.
  6526. **
  6527. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  6528. ** ^Names are case sensitive.
  6529. ** ^Names are zero-terminated UTF-8 strings.
  6530. ** ^If there is no match, a NULL pointer is returned.
  6531. ** ^If zVfsName is NULL then the default VFS is returned.
  6532. **
  6533. ** ^New VFSes are registered with sqlite3_vfs_register().
  6534. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  6535. ** ^The same VFS can be registered multiple times without injury.
  6536. ** ^To make an existing VFS into the default VFS, register it again
  6537. ** with the makeDflt flag set. If two different VFSes with the
  6538. ** same name are registered, the behavior is undefined. If a
  6539. ** VFS is registered with a name that is NULL or an empty string,
  6540. ** then the behavior is undefined.
  6541. **
  6542. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  6543. ** ^(If the default VFS is unregistered, another VFS is chosen as
  6544. ** the default. The choice for the new VFS is arbitrary.)^
  6545. */
  6546. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  6547. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  6548. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  6549. /*
  6550. ** CAPI3REF: Mutexes
  6551. **
  6552. ** The SQLite core uses these routines for thread
  6553. ** synchronization. Though they are intended for internal
  6554. ** use by SQLite, code that links against SQLite is
  6555. ** permitted to use any of these routines.
  6556. **
  6557. ** The SQLite source code contains multiple implementations
  6558. ** of these mutex routines. An appropriate implementation
  6559. ** is selected automatically at compile-time. The following
  6560. ** implementations are available in the SQLite core:
  6561. **
  6562. ** <ul>
  6563. ** <li> SQLITE_MUTEX_PTHREADS
  6564. ** <li> SQLITE_MUTEX_W32
  6565. ** <li> SQLITE_MUTEX_NOOP
  6566. ** </ul>
  6567. **
  6568. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  6569. ** that does no real locking and is appropriate for use in
  6570. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  6571. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  6572. ** and Windows.
  6573. **
  6574. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  6575. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  6576. ** implementation is included with the library. In this case the
  6577. ** application must supply a custom mutex implementation using the
  6578. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  6579. ** before calling sqlite3_initialize() or any other public sqlite3_
  6580. ** function that calls sqlite3_initialize().
  6581. **
  6582. ** ^The sqlite3_mutex_alloc() routine allocates a new
  6583. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  6584. ** routine returns NULL if it is unable to allocate the requested
  6585. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  6586. ** integer constants:
  6587. **
  6588. ** <ul>
  6589. ** <li> SQLITE_MUTEX_FAST
  6590. ** <li> SQLITE_MUTEX_RECURSIVE
  6591. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6592. ** <li> SQLITE_MUTEX_STATIC_MEM
  6593. ** <li> SQLITE_MUTEX_STATIC_OPEN
  6594. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6595. ** <li> SQLITE_MUTEX_STATIC_LRU
  6596. ** <li> SQLITE_MUTEX_STATIC_PMEM
  6597. ** <li> SQLITE_MUTEX_STATIC_APP1
  6598. ** <li> SQLITE_MUTEX_STATIC_APP2
  6599. ** <li> SQLITE_MUTEX_STATIC_APP3
  6600. ** <li> SQLITE_MUTEX_STATIC_VFS1
  6601. ** <li> SQLITE_MUTEX_STATIC_VFS2
  6602. ** <li> SQLITE_MUTEX_STATIC_VFS3
  6603. ** </ul>
  6604. **
  6605. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  6606. ** cause sqlite3_mutex_alloc() to create
  6607. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6608. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  6609. ** The mutex implementation does not need to make a distinction
  6610. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6611. ** not want to. SQLite will only request a recursive mutex in
  6612. ** cases where it really needs one. If a faster non-recursive mutex
  6613. ** implementation is available on the host platform, the mutex subsystem
  6614. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6615. **
  6616. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  6617. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  6618. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  6619. ** used by the current version of SQLite. Future versions of SQLite
  6620. ** may add additional static mutexes. Static mutexes are for internal
  6621. ** use by SQLite only. Applications that use SQLite mutexes should
  6622. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6623. ** SQLITE_MUTEX_RECURSIVE.
  6624. **
  6625. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6626. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6627. ** returns a different mutex on every call. ^For the static
  6628. ** mutex types, the same mutex is returned on every call that has
  6629. ** the same type number.
  6630. **
  6631. ** ^The sqlite3_mutex_free() routine deallocates a previously
  6632. ** allocated dynamic mutex. Attempting to deallocate a static
  6633. ** mutex results in undefined behavior.
  6634. **
  6635. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6636. ** to enter a mutex. ^If another thread is already within the mutex,
  6637. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6638. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6639. ** upon successful entry. ^(Mutexes created using
  6640. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6641. ** In such cases, the
  6642. ** mutex must be exited an equal number of times before another thread
  6643. ** can enter.)^ If the same thread tries to enter any mutex other
  6644. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  6645. **
  6646. ** ^(Some systems (for example, Windows 95) do not support the operation
  6647. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6648. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  6649. ** sqlite3_mutex_try() as an optimization so this is acceptable
  6650. ** behavior.)^
  6651. **
  6652. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  6653. ** previously entered by the same thread. The behavior
  6654. ** is undefined if the mutex is not currently entered by the
  6655. ** calling thread or is not currently allocated.
  6656. **
  6657. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6658. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6659. ** behave as no-ops.
  6660. **
  6661. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6662. */
  6663. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  6664. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  6665. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  6666. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  6667. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  6668. /*
  6669. ** CAPI3REF: Mutex Methods Object
  6670. **
  6671. ** An instance of this structure defines the low-level routines
  6672. ** used to allocate and use mutexes.
  6673. **
  6674. ** Usually, the default mutex implementations provided by SQLite are
  6675. ** sufficient, however the application has the option of substituting a custom
  6676. ** implementation for specialized deployments or systems for which SQLite
  6677. ** does not provide a suitable implementation. In this case, the application
  6678. ** creates and populates an instance of this structure to pass
  6679. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6680. ** Additionally, an instance of this structure can be used as an
  6681. ** output variable when querying the system for the current mutex
  6682. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6683. **
  6684. ** ^The xMutexInit method defined by this structure is invoked as
  6685. ** part of system initialization by the sqlite3_initialize() function.
  6686. ** ^The xMutexInit routine is called by SQLite exactly once for each
  6687. ** effective call to [sqlite3_initialize()].
  6688. **
  6689. ** ^The xMutexEnd method defined by this structure is invoked as
  6690. ** part of system shutdown by the sqlite3_shutdown() function. The
  6691. ** implementation of this method is expected to release all outstanding
  6692. ** resources obtained by the mutex methods implementation, especially
  6693. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  6694. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  6695. **
  6696. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  6697. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6698. ** xMutexNotheld) implement the following interfaces (respectively):
  6699. **
  6700. ** <ul>
  6701. ** <li> [sqlite3_mutex_alloc()] </li>
  6702. ** <li> [sqlite3_mutex_free()] </li>
  6703. ** <li> [sqlite3_mutex_enter()] </li>
  6704. ** <li> [sqlite3_mutex_try()] </li>
  6705. ** <li> [sqlite3_mutex_leave()] </li>
  6706. ** <li> [sqlite3_mutex_held()] </li>
  6707. ** <li> [sqlite3_mutex_notheld()] </li>
  6708. ** </ul>)^
  6709. **
  6710. ** The only difference is that the public sqlite3_XXX functions enumerated
  6711. ** above silently ignore any invocations that pass a NULL pointer instead
  6712. ** of a valid mutex handle. The implementations of the methods defined
  6713. ** by this structure are not required to handle this case, the results
  6714. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6715. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6716. ** it is passed a NULL pointer).
  6717. **
  6718. ** The xMutexInit() method must be threadsafe. It must be harmless to
  6719. ** invoke xMutexInit() multiple times within the same process and without
  6720. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6721. ** xMutexInit() must be no-ops.
  6722. **
  6723. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6724. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  6725. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6726. ** memory allocation for a fast or recursive mutex.
  6727. **
  6728. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6729. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6730. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6731. ** prior to returning.
  6732. */
  6733. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6734. struct sqlite3_mutex_methods {
  6735. int (*xMutexInit)(void);
  6736. int (*xMutexEnd)(void);
  6737. sqlite3_mutex *(*xMutexAlloc)(int);
  6738. void (*xMutexFree)(sqlite3_mutex *);
  6739. void (*xMutexEnter)(sqlite3_mutex *);
  6740. int (*xMutexTry)(sqlite3_mutex *);
  6741. void (*xMutexLeave)(sqlite3_mutex *);
  6742. int (*xMutexHeld)(sqlite3_mutex *);
  6743. int (*xMutexNotheld)(sqlite3_mutex *);
  6744. };
  6745. /*
  6746. ** CAPI3REF: Mutex Verification Routines
  6747. **
  6748. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6749. ** are intended for use inside assert() statements. The SQLite core
  6750. ** never uses these routines except inside an assert() and applications
  6751. ** are advised to follow the lead of the core. The SQLite core only
  6752. ** provides implementations for these routines when it is compiled
  6753. ** with the SQLITE_DEBUG flag. External mutex implementations
  6754. ** are only required to provide these routines if SQLITE_DEBUG is
  6755. ** defined and if NDEBUG is not defined.
  6756. **
  6757. ** These routines should return true if the mutex in their argument
  6758. ** is held or not held, respectively, by the calling thread.
  6759. **
  6760. ** The implementation is not required to provide versions of these
  6761. ** routines that actually work. If the implementation does not provide working
  6762. ** versions of these routines, it should at least provide stubs that always
  6763. ** return true so that one does not get spurious assertion failures.
  6764. **
  6765. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  6766. ** the routine should return 1. This seems counter-intuitive since
  6767. ** clearly the mutex cannot be held if it does not exist. But
  6768. ** the reason the mutex does not exist is because the build is not
  6769. ** using mutexes. And we do not want the assert() containing the
  6770. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6771. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  6772. ** interface should also return 1 when given a NULL pointer.
  6773. */
  6774. #ifndef NDEBUG
  6775. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  6776. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  6777. #endif
  6778. /*
  6779. ** CAPI3REF: Mutex Types
  6780. **
  6781. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6782. ** which is one of these integer constants.
  6783. **
  6784. ** The set of static mutexes may change from one SQLite release to the
  6785. ** next. Applications that override the built-in mutex logic must be
  6786. ** prepared to accommodate additional static mutexes.
  6787. */
  6788. #define SQLITE_MUTEX_FAST 0
  6789. #define SQLITE_MUTEX_RECURSIVE 1
  6790. #define SQLITE_MUTEX_STATIC_MASTER 2
  6791. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6792. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6793. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6794. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
  6795. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6796. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6797. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6798. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  6799. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  6800. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  6801. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  6802. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  6803. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  6804. /*
  6805. ** CAPI3REF: Retrieve the mutex for a database connection
  6806. ** METHOD: sqlite3
  6807. **
  6808. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6809. ** serializes access to the [database connection] given in the argument
  6810. ** when the [threading mode] is Serialized.
  6811. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6812. ** routine returns a NULL pointer.
  6813. */
  6814. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  6815. /*
  6816. ** CAPI3REF: Low-Level Control Of Database Files
  6817. ** METHOD: sqlite3
  6818. **
  6819. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6820. ** xFileControl method for the [sqlite3_io_methods] object associated
  6821. ** with a particular database identified by the second argument. ^The
  6822. ** name of the database is "main" for the main database or "temp" for the
  6823. ** TEMP database, or the name that appears after the AS keyword for
  6824. ** databases that are added using the [ATTACH] SQL command.
  6825. ** ^A NULL pointer can be used in place of "main" to refer to the
  6826. ** main database file.
  6827. ** ^The third and fourth parameters to this routine
  6828. ** are passed directly through to the second and third parameters of
  6829. ** the xFileControl method. ^The return value of the xFileControl
  6830. ** method becomes the return value of this routine.
  6831. **
  6832. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6833. ** a pointer to the underlying [sqlite3_file] object to be written into
  6834. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6835. ** case is a short-circuit path which does not actually invoke the
  6836. ** underlying sqlite3_io_methods.xFileControl method.
  6837. **
  6838. ** ^If the second parameter (zDbName) does not match the name of any
  6839. ** open database file, then SQLITE_ERROR is returned. ^This error
  6840. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6841. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6842. ** also return SQLITE_ERROR. There is no way to distinguish between
  6843. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6844. ** xFileControl method.
  6845. **
  6846. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6847. */
  6848. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6849. /*
  6850. ** CAPI3REF: Testing Interface
  6851. **
  6852. ** ^The sqlite3_test_control() interface is used to read out internal
  6853. ** state of SQLite and to inject faults into SQLite for testing
  6854. ** purposes. ^The first parameter is an operation code that determines
  6855. ** the number, meaning, and operation of all subsequent parameters.
  6856. **
  6857. ** This interface is not for use by applications. It exists solely
  6858. ** for verifying the correct operation of the SQLite library. Depending
  6859. ** on how the SQLite library is compiled, this interface might not exist.
  6860. **
  6861. ** The details of the operation codes, their meanings, the parameters
  6862. ** they take, and what they do are all subject to change without notice.
  6863. ** Unlike most of the SQLite API, this function is not guaranteed to
  6864. ** operate consistently from one release to the next.
  6865. */
  6866. SQLITE_API int sqlite3_test_control(int op, ...);
  6867. /*
  6868. ** CAPI3REF: Testing Interface Operation Codes
  6869. **
  6870. ** These constants are the valid operation code parameters used
  6871. ** as the first argument to [sqlite3_test_control()].
  6872. **
  6873. ** These parameters and their meanings are subject to change
  6874. ** without notice. These values are for testing purposes only.
  6875. ** Applications should not use any of these parameters or the
  6876. ** [sqlite3_test_control()] interface.
  6877. */
  6878. #define SQLITE_TESTCTRL_FIRST 5
  6879. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6880. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6881. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6882. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6883. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6884. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6885. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6886. #define SQLITE_TESTCTRL_ASSERT 12
  6887. #define SQLITE_TESTCTRL_ALWAYS 13
  6888. #define SQLITE_TESTCTRL_RESERVE 14
  6889. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6890. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6891. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6892. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6893. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  6894. #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
  6895. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  6896. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  6897. #define SQLITE_TESTCTRL_BYTEORDER 22
  6898. #define SQLITE_TESTCTRL_ISINIT 23
  6899. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  6900. #define SQLITE_TESTCTRL_IMPOSTER 25
  6901. #define SQLITE_TESTCTRL_LAST 25
  6902. /*
  6903. ** CAPI3REF: SQLite Runtime Status
  6904. **
  6905. ** ^These interfaces are used to retrieve runtime status information
  6906. ** about the performance of SQLite, and optionally to reset various
  6907. ** highwater marks. ^The first argument is an integer code for
  6908. ** the specific parameter to measure. ^(Recognized integer codes
  6909. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6910. ** ^The current value of the parameter is returned into *pCurrent.
  6911. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6912. ** resetFlag is true, then the highest record value is reset after
  6913. ** *pHighwater is written. ^(Some parameters do not record the highest
  6914. ** value. For those parameters
  6915. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6916. ** ^(Other parameters record only the highwater mark and not the current
  6917. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6918. **
  6919. ** ^The sqlite3_status() and sqlite3_status64() routines return
  6920. ** SQLITE_OK on success and a non-zero [error code] on failure.
  6921. **
  6922. ** If either the current value or the highwater mark is too large to
  6923. ** be represented by a 32-bit integer, then the values returned by
  6924. ** sqlite3_status() are undefined.
  6925. **
  6926. ** See also: [sqlite3_db_status()]
  6927. */
  6928. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6929. SQLITE_API int sqlite3_status64(
  6930. int op,
  6931. sqlite3_int64 *pCurrent,
  6932. sqlite3_int64 *pHighwater,
  6933. int resetFlag
  6934. );
  6935. /*
  6936. ** CAPI3REF: Status Parameters
  6937. ** KEYWORDS: {status parameters}
  6938. **
  6939. ** These integer constants designate various run-time status parameters
  6940. ** that can be returned by [sqlite3_status()].
  6941. **
  6942. ** <dl>
  6943. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6944. ** <dd>This parameter is the current amount of memory checked out
  6945. ** using [sqlite3_malloc()], either directly or indirectly. The
  6946. ** figure includes calls made to [sqlite3_malloc()] by the application
  6947. ** and internal memory usage by the SQLite library. Scratch memory
  6948. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6949. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6950. ** this parameter. The amount returned is the sum of the allocation
  6951. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6952. **
  6953. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6954. ** <dd>This parameter records the largest memory allocation request
  6955. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6956. ** internal equivalents). Only the value returned in the
  6957. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6958. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6959. **
  6960. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6961. ** <dd>This parameter records the number of separate memory allocations
  6962. ** currently checked out.</dd>)^
  6963. **
  6964. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6965. ** <dd>This parameter returns the number of pages used out of the
  6966. ** [pagecache memory allocator] that was configured using
  6967. ** [SQLITE_CONFIG_PAGECACHE]. The
  6968. ** value returned is in pages, not in bytes.</dd>)^
  6969. **
  6970. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6971. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6972. ** <dd>This parameter returns the number of bytes of page cache
  6973. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6974. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6975. ** returned value includes allocations that overflowed because they
  6976. ** where too large (they were larger than the "sz" parameter to
  6977. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6978. ** no space was left in the page cache.</dd>)^
  6979. **
  6980. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6981. ** <dd>This parameter records the largest memory allocation request
  6982. ** handed to [pagecache memory allocator]. Only the value returned in the
  6983. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6984. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6985. **
  6986. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6987. ** <dd>This parameter returns the number of allocations used out of the
  6988. ** [scratch memory allocator] configured using
  6989. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6990. ** in bytes. Since a single thread may only have one scratch allocation
  6991. ** outstanding at time, this parameter also reports the number of threads
  6992. ** using scratch memory at the same time.</dd>)^
  6993. **
  6994. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6995. ** <dd>This parameter returns the number of bytes of scratch memory
  6996. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6997. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6998. ** returned include overflows because the requested allocation was too
  6999. ** larger (that is, because the requested allocation was larger than the
  7000. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  7001. ** slots were available.
  7002. ** </dd>)^
  7003. **
  7004. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  7005. ** <dd>This parameter records the largest memory allocation request
  7006. ** handed to [scratch memory allocator]. Only the value returned in the
  7007. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  7008. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  7009. **
  7010. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  7011. ** <dd>The *pHighwater parameter records the deepest parser stack.
  7012. ** The *pCurrent value is undefined. The *pHighwater value is only
  7013. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  7014. ** </dl>
  7015. **
  7016. ** New status parameters may be added from time to time.
  7017. */
  7018. #define SQLITE_STATUS_MEMORY_USED 0
  7019. #define SQLITE_STATUS_PAGECACHE_USED 1
  7020. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  7021. #define SQLITE_STATUS_SCRATCH_USED 3
  7022. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  7023. #define SQLITE_STATUS_MALLOC_SIZE 5
  7024. #define SQLITE_STATUS_PARSER_STACK 6
  7025. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  7026. #define SQLITE_STATUS_SCRATCH_SIZE 8
  7027. #define SQLITE_STATUS_MALLOC_COUNT 9
  7028. /*
  7029. ** CAPI3REF: Database Connection Status
  7030. ** METHOD: sqlite3
  7031. **
  7032. ** ^This interface is used to retrieve runtime status information
  7033. ** about a single [database connection]. ^The first argument is the
  7034. ** database connection object to be interrogated. ^The second argument
  7035. ** is an integer constant, taken from the set of
  7036. ** [SQLITE_DBSTATUS options], that
  7037. ** determines the parameter to interrogate. The set of
  7038. ** [SQLITE_DBSTATUS options] is likely
  7039. ** to grow in future releases of SQLite.
  7040. **
  7041. ** ^The current value of the requested parameter is written into *pCur
  7042. ** and the highest instantaneous value is written into *pHiwtr. ^If
  7043. ** the resetFlg is true, then the highest instantaneous value is
  7044. ** reset back down to the current value.
  7045. **
  7046. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  7047. ** non-zero [error code] on failure.
  7048. **
  7049. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  7050. */
  7051. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  7052. /*
  7053. ** CAPI3REF: Status Parameters for database connections
  7054. ** KEYWORDS: {SQLITE_DBSTATUS options}
  7055. **
  7056. ** These constants are the available integer "verbs" that can be passed as
  7057. ** the second argument to the [sqlite3_db_status()] interface.
  7058. **
  7059. ** New verbs may be added in future releases of SQLite. Existing verbs
  7060. ** might be discontinued. Applications should check the return code from
  7061. ** [sqlite3_db_status()] to make sure that the call worked.
  7062. ** The [sqlite3_db_status()] interface will return a non-zero error code
  7063. ** if a discontinued or unsupported verb is invoked.
  7064. **
  7065. ** <dl>
  7066. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  7067. ** <dd>This parameter returns the number of lookaside memory slots currently
  7068. ** checked out.</dd>)^
  7069. **
  7070. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  7071. ** <dd>This parameter returns the number malloc attempts that were
  7072. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  7073. ** the current value is always zero.)^
  7074. **
  7075. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  7076. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  7077. ** <dd>This parameter returns the number malloc attempts that might have
  7078. ** been satisfied using lookaside memory but failed due to the amount of
  7079. ** memory requested being larger than the lookaside slot size.
  7080. ** Only the high-water value is meaningful;
  7081. ** the current value is always zero.)^
  7082. **
  7083. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  7084. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  7085. ** <dd>This parameter returns the number malloc attempts that might have
  7086. ** been satisfied using lookaside memory but failed due to all lookaside
  7087. ** memory already being in use.
  7088. ** Only the high-water value is meaningful;
  7089. ** the current value is always zero.)^
  7090. **
  7091. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  7092. ** <dd>This parameter returns the approximate number of bytes of heap
  7093. ** memory used by all pager caches associated with the database connection.)^
  7094. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  7095. **
  7096. ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
  7097. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  7098. ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  7099. ** pager cache is shared between two or more connections the bytes of heap
  7100. ** memory used by that pager cache is divided evenly between the attached
  7101. ** connections.)^ In other words, if none of the pager caches associated
  7102. ** with the database connection are shared, this request returns the same
  7103. ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  7104. ** shared, the value returned by this call will be smaller than that returned
  7105. ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  7106. ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  7107. **
  7108. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  7109. ** <dd>This parameter returns the approximate number of bytes of heap
  7110. ** memory used to store the schema for all databases associated
  7111. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  7112. ** ^The full amount of memory used by the schemas is reported, even if the
  7113. ** schema memory is shared with other database connections due to
  7114. ** [shared cache mode] being enabled.
  7115. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  7116. **
  7117. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  7118. ** <dd>This parameter returns the approximate number of bytes of heap
  7119. ** and lookaside memory used by all prepared statements associated with
  7120. ** the database connection.)^
  7121. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  7122. ** </dd>
  7123. **
  7124. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  7125. ** <dd>This parameter returns the number of pager cache hits that have
  7126. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  7127. ** is always 0.
  7128. ** </dd>
  7129. **
  7130. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  7131. ** <dd>This parameter returns the number of pager cache misses that have
  7132. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  7133. ** is always 0.
  7134. ** </dd>
  7135. **
  7136. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  7137. ** <dd>This parameter returns the number of dirty cache entries that have
  7138. ** been written to disk. Specifically, the number of pages written to the
  7139. ** wal file in wal mode databases, or the number of pages written to the
  7140. ** database file in rollback mode databases. Any pages written as part of
  7141. ** transaction rollback or database recovery operations are not included.
  7142. ** If an IO or other error occurs while writing a page to disk, the effect
  7143. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  7144. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  7145. ** </dd>
  7146. **
  7147. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  7148. ** <dd>This parameter returns zero for the current value if and only if
  7149. ** all foreign key constraints (deferred or immediate) have been
  7150. ** resolved.)^ ^The highwater mark is always 0.
  7151. ** </dd>
  7152. ** </dl>
  7153. */
  7154. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  7155. #define SQLITE_DBSTATUS_CACHE_USED 1
  7156. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  7157. #define SQLITE_DBSTATUS_STMT_USED 3
  7158. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  7159. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  7160. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  7161. #define SQLITE_DBSTATUS_CACHE_HIT 7
  7162. #define SQLITE_DBSTATUS_CACHE_MISS 8
  7163. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  7164. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  7165. #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
  7166. #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */
  7167. /*
  7168. ** CAPI3REF: Prepared Statement Status
  7169. ** METHOD: sqlite3_stmt
  7170. **
  7171. ** ^(Each prepared statement maintains various
  7172. ** [SQLITE_STMTSTATUS counters] that measure the number
  7173. ** of times it has performed specific operations.)^ These counters can
  7174. ** be used to monitor the performance characteristics of the prepared
  7175. ** statements. For example, if the number of table steps greatly exceeds
  7176. ** the number of table searches or result rows, that would tend to indicate
  7177. ** that the prepared statement is using a full table scan rather than
  7178. ** an index.
  7179. **
  7180. ** ^(This interface is used to retrieve and reset counter values from
  7181. ** a [prepared statement]. The first argument is the prepared statement
  7182. ** object to be interrogated. The second argument
  7183. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  7184. ** to be interrogated.)^
  7185. ** ^The current value of the requested counter is returned.
  7186. ** ^If the resetFlg is true, then the counter is reset to zero after this
  7187. ** interface call returns.
  7188. **
  7189. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  7190. */
  7191. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  7192. /*
  7193. ** CAPI3REF: Status Parameters for prepared statements
  7194. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  7195. **
  7196. ** These preprocessor macros define integer codes that name counter
  7197. ** values associated with the [sqlite3_stmt_status()] interface.
  7198. ** The meanings of the various counters are as follows:
  7199. **
  7200. ** <dl>
  7201. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  7202. ** <dd>^This is the number of times that SQLite has stepped forward in
  7203. ** a table as part of a full table scan. Large numbers for this counter
  7204. ** may indicate opportunities for performance improvement through
  7205. ** careful use of indices.</dd>
  7206. **
  7207. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  7208. ** <dd>^This is the number of sort operations that have occurred.
  7209. ** A non-zero value in this counter may indicate an opportunity to
  7210. ** improvement performance through careful use of indices.</dd>
  7211. **
  7212. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  7213. ** <dd>^This is the number of rows inserted into transient indices that
  7214. ** were created automatically in order to help joins run faster.
  7215. ** A non-zero value in this counter may indicate an opportunity to
  7216. ** improvement performance by adding permanent indices that do not
  7217. ** need to be reinitialized each time the statement is run.</dd>
  7218. **
  7219. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  7220. ** <dd>^This is the number of virtual machine operations executed
  7221. ** by the prepared statement if that number is less than or equal
  7222. ** to 2147483647. The number of virtual machine operations can be
  7223. ** used as a proxy for the total work done by the prepared statement.
  7224. ** If the number of virtual machine operations exceeds 2147483647
  7225. ** then the value returned by this statement status code is undefined.
  7226. ** </dd>
  7227. ** </dl>
  7228. */
  7229. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  7230. #define SQLITE_STMTSTATUS_SORT 2
  7231. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  7232. #define SQLITE_STMTSTATUS_VM_STEP 4
  7233. /*
  7234. ** CAPI3REF: Custom Page Cache Object
  7235. **
  7236. ** The sqlite3_pcache type is opaque. It is implemented by
  7237. ** the pluggable module. The SQLite core has no knowledge of
  7238. ** its size or internal structure and never deals with the
  7239. ** sqlite3_pcache object except by holding and passing pointers
  7240. ** to the object.
  7241. **
  7242. ** See [sqlite3_pcache_methods2] for additional information.
  7243. */
  7244. typedef struct sqlite3_pcache sqlite3_pcache;
  7245. /*
  7246. ** CAPI3REF: Custom Page Cache Object
  7247. **
  7248. ** The sqlite3_pcache_page object represents a single page in the
  7249. ** page cache. The page cache will allocate instances of this
  7250. ** object. Various methods of the page cache use pointers to instances
  7251. ** of this object as parameters or as their return value.
  7252. **
  7253. ** See [sqlite3_pcache_methods2] for additional information.
  7254. */
  7255. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  7256. struct sqlite3_pcache_page {
  7257. void *pBuf; /* The content of the page */
  7258. void *pExtra; /* Extra information associated with the page */
  7259. };
  7260. /*
  7261. ** CAPI3REF: Application Defined Page Cache.
  7262. ** KEYWORDS: {page cache}
  7263. **
  7264. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  7265. ** register an alternative page cache implementation by passing in an
  7266. ** instance of the sqlite3_pcache_methods2 structure.)^
  7267. ** In many applications, most of the heap memory allocated by
  7268. ** SQLite is used for the page cache.
  7269. ** By implementing a
  7270. ** custom page cache using this API, an application can better control
  7271. ** the amount of memory consumed by SQLite, the way in which
  7272. ** that memory is allocated and released, and the policies used to
  7273. ** determine exactly which parts of a database file are cached and for
  7274. ** how long.
  7275. **
  7276. ** The alternative page cache mechanism is an
  7277. ** extreme measure that is only needed by the most demanding applications.
  7278. ** The built-in page cache is recommended for most uses.
  7279. **
  7280. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  7281. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  7282. ** the application may discard the parameter after the call to
  7283. ** [sqlite3_config()] returns.)^
  7284. **
  7285. ** [[the xInit() page cache method]]
  7286. ** ^(The xInit() method is called once for each effective
  7287. ** call to [sqlite3_initialize()])^
  7288. ** (usually only once during the lifetime of the process). ^(The xInit()
  7289. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  7290. ** The intent of the xInit() method is to set up global data structures
  7291. ** required by the custom page cache implementation.
  7292. ** ^(If the xInit() method is NULL, then the
  7293. ** built-in default page cache is used instead of the application defined
  7294. ** page cache.)^
  7295. **
  7296. ** [[the xShutdown() page cache method]]
  7297. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  7298. ** It can be used to clean up
  7299. ** any outstanding resources before process shutdown, if required.
  7300. ** ^The xShutdown() method may be NULL.
  7301. **
  7302. ** ^SQLite automatically serializes calls to the xInit method,
  7303. ** so the xInit method need not be threadsafe. ^The
  7304. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  7305. ** not need to be threadsafe either. All other methods must be threadsafe
  7306. ** in multithreaded applications.
  7307. **
  7308. ** ^SQLite will never invoke xInit() more than once without an intervening
  7309. ** call to xShutdown().
  7310. **
  7311. ** [[the xCreate() page cache methods]]
  7312. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  7313. ** SQLite will typically create one cache instance for each open database file,
  7314. ** though this is not guaranteed. ^The
  7315. ** first parameter, szPage, is the size in bytes of the pages that must
  7316. ** be allocated by the cache. ^szPage will always a power of two. ^The
  7317. ** second parameter szExtra is a number of bytes of extra storage
  7318. ** associated with each page cache entry. ^The szExtra parameter will
  7319. ** a number less than 250. SQLite will use the
  7320. ** extra szExtra bytes on each page to store metadata about the underlying
  7321. ** database page on disk. The value passed into szExtra depends
  7322. ** on the SQLite version, the target platform, and how SQLite was compiled.
  7323. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  7324. ** created will be used to cache database pages of a file stored on disk, or
  7325. ** false if it is used for an in-memory database. The cache implementation
  7326. ** does not have to do anything special based with the value of bPurgeable;
  7327. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  7328. ** never invoke xUnpin() except to deliberately delete a page.
  7329. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  7330. ** false will always have the "discard" flag set to true.
  7331. ** ^Hence, a cache created with bPurgeable false will
  7332. ** never contain any unpinned pages.
  7333. **
  7334. ** [[the xCachesize() page cache method]]
  7335. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  7336. ** suggested maximum cache-size (number of pages stored by) the cache
  7337. ** instance passed as the first argument. This is the value configured using
  7338. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  7339. ** parameter, the implementation is not required to do anything with this
  7340. ** value; it is advisory only.
  7341. **
  7342. ** [[the xPagecount() page cache methods]]
  7343. ** The xPagecount() method must return the number of pages currently
  7344. ** stored in the cache, both pinned and unpinned.
  7345. **
  7346. ** [[the xFetch() page cache methods]]
  7347. ** The xFetch() method locates a page in the cache and returns a pointer to
  7348. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  7349. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  7350. ** pointer to a buffer of szPage bytes used to store the content of a
  7351. ** single database page. The pExtra element of sqlite3_pcache_page will be
  7352. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  7353. ** for each entry in the page cache.
  7354. **
  7355. ** The page to be fetched is determined by the key. ^The minimum key value
  7356. ** is 1. After it has been retrieved using xFetch, the page is considered
  7357. ** to be "pinned".
  7358. **
  7359. ** If the requested page is already in the page cache, then the page cache
  7360. ** implementation must return a pointer to the page buffer with its content
  7361. ** intact. If the requested page is not already in the cache, then the
  7362. ** cache implementation should use the value of the createFlag
  7363. ** parameter to help it determined what action to take:
  7364. **
  7365. ** <table border=1 width=85% align=center>
  7366. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  7367. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  7368. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  7369. ** Otherwise return NULL.
  7370. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  7371. ** NULL if allocating a new page is effectively impossible.
  7372. ** </table>
  7373. **
  7374. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  7375. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  7376. ** failed.)^ In between the to xFetch() calls, SQLite may
  7377. ** attempt to unpin one or more cache pages by spilling the content of
  7378. ** pinned pages to disk and synching the operating system disk cache.
  7379. **
  7380. ** [[the xUnpin() page cache method]]
  7381. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  7382. ** as its second argument. If the third parameter, discard, is non-zero,
  7383. ** then the page must be evicted from the cache.
  7384. ** ^If the discard parameter is
  7385. ** zero, then the page may be discarded or retained at the discretion of
  7386. ** page cache implementation. ^The page cache implementation
  7387. ** may choose to evict unpinned pages at any time.
  7388. **
  7389. ** The cache must not perform any reference counting. A single
  7390. ** call to xUnpin() unpins the page regardless of the number of prior calls
  7391. ** to xFetch().
  7392. **
  7393. ** [[the xRekey() page cache methods]]
  7394. ** The xRekey() method is used to change the key value associated with the
  7395. ** page passed as the second argument. If the cache
  7396. ** previously contains an entry associated with newKey, it must be
  7397. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  7398. ** to be pinned.
  7399. **
  7400. ** When SQLite calls the xTruncate() method, the cache must discard all
  7401. ** existing cache entries with page numbers (keys) greater than or equal
  7402. ** to the value of the iLimit parameter passed to xTruncate(). If any
  7403. ** of these pages are pinned, they are implicitly unpinned, meaning that
  7404. ** they can be safely discarded.
  7405. **
  7406. ** [[the xDestroy() page cache method]]
  7407. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  7408. ** All resources associated with the specified cache should be freed. ^After
  7409. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  7410. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  7411. ** functions.
  7412. **
  7413. ** [[the xShrink() page cache method]]
  7414. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  7415. ** free up as much of heap memory as possible. The page cache implementation
  7416. ** is not obligated to free any memory, but well-behaved implementations should
  7417. ** do their best.
  7418. */
  7419. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  7420. struct sqlite3_pcache_methods2 {
  7421. int iVersion;
  7422. void *pArg;
  7423. int (*xInit)(void*);
  7424. void (*xShutdown)(void*);
  7425. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  7426. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7427. int (*xPagecount)(sqlite3_pcache*);
  7428. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7429. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  7430. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  7431. unsigned oldKey, unsigned newKey);
  7432. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7433. void (*xDestroy)(sqlite3_pcache*);
  7434. void (*xShrink)(sqlite3_pcache*);
  7435. };
  7436. /*
  7437. ** This is the obsolete pcache_methods object that has now been replaced
  7438. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  7439. ** retained in the header file for backwards compatibility only.
  7440. */
  7441. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  7442. struct sqlite3_pcache_methods {
  7443. void *pArg;
  7444. int (*xInit)(void*);
  7445. void (*xShutdown)(void*);
  7446. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  7447. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7448. int (*xPagecount)(sqlite3_pcache*);
  7449. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7450. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  7451. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  7452. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7453. void (*xDestroy)(sqlite3_pcache*);
  7454. };
  7455. /*
  7456. ** CAPI3REF: Online Backup Object
  7457. **
  7458. ** The sqlite3_backup object records state information about an ongoing
  7459. ** online backup operation. ^The sqlite3_backup object is created by
  7460. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  7461. ** [sqlite3_backup_finish()].
  7462. **
  7463. ** See Also: [Using the SQLite Online Backup API]
  7464. */
  7465. typedef struct sqlite3_backup sqlite3_backup;
  7466. /*
  7467. ** CAPI3REF: Online Backup API.
  7468. **
  7469. ** The backup API copies the content of one database into another.
  7470. ** It is useful either for creating backups of databases or
  7471. ** for copying in-memory databases to or from persistent files.
  7472. **
  7473. ** See Also: [Using the SQLite Online Backup API]
  7474. **
  7475. ** ^SQLite holds a write transaction open on the destination database file
  7476. ** for the duration of the backup operation.
  7477. ** ^The source database is read-locked only while it is being read;
  7478. ** it is not locked continuously for the entire backup operation.
  7479. ** ^Thus, the backup may be performed on a live source database without
  7480. ** preventing other database connections from
  7481. ** reading or writing to the source database while the backup is underway.
  7482. **
  7483. ** ^(To perform a backup operation:
  7484. ** <ol>
  7485. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  7486. ** backup,
  7487. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  7488. ** the data between the two databases, and finally
  7489. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  7490. ** associated with the backup operation.
  7491. ** </ol>)^
  7492. ** There should be exactly one call to sqlite3_backup_finish() for each
  7493. ** successful call to sqlite3_backup_init().
  7494. **
  7495. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  7496. **
  7497. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  7498. ** [database connection] associated with the destination database
  7499. ** and the database name, respectively.
  7500. ** ^The database name is "main" for the main database, "temp" for the
  7501. ** temporary database, or the name specified after the AS keyword in
  7502. ** an [ATTACH] statement for an attached database.
  7503. ** ^The S and M arguments passed to
  7504. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  7505. ** and database name of the source database, respectively.
  7506. ** ^The source and destination [database connections] (parameters S and D)
  7507. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  7508. ** an error.
  7509. **
  7510. ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
  7511. ** there is already a read or read-write transaction open on the
  7512. ** destination database.
  7513. **
  7514. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  7515. ** returned and an error code and error message are stored in the
  7516. ** destination [database connection] D.
  7517. ** ^The error code and message for the failed call to sqlite3_backup_init()
  7518. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  7519. ** [sqlite3_errmsg16()] functions.
  7520. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  7521. ** [sqlite3_backup] object.
  7522. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  7523. ** sqlite3_backup_finish() functions to perform the specified backup
  7524. ** operation.
  7525. **
  7526. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  7527. **
  7528. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  7529. ** the source and destination databases specified by [sqlite3_backup] object B.
  7530. ** ^If N is negative, all remaining source pages are copied.
  7531. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  7532. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  7533. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  7534. ** from source to destination, then it returns [SQLITE_DONE].
  7535. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  7536. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  7537. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  7538. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  7539. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  7540. **
  7541. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  7542. ** <ol>
  7543. ** <li> the destination database was opened read-only, or
  7544. ** <li> the destination database is using write-ahead-log journaling
  7545. ** and the destination and source page sizes differ, or
  7546. ** <li> the destination database is an in-memory database and the
  7547. ** destination and source page sizes differ.
  7548. ** </ol>)^
  7549. **
  7550. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  7551. ** the [sqlite3_busy_handler | busy-handler function]
  7552. ** is invoked (if one is specified). ^If the
  7553. ** busy-handler returns non-zero before the lock is available, then
  7554. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  7555. ** sqlite3_backup_step() can be retried later. ^If the source
  7556. ** [database connection]
  7557. ** is being used to write to the source database when sqlite3_backup_step()
  7558. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  7559. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  7560. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  7561. ** [SQLITE_READONLY] is returned, then
  7562. ** there is no point in retrying the call to sqlite3_backup_step(). These
  7563. ** errors are considered fatal.)^ The application must accept
  7564. ** that the backup operation has failed and pass the backup operation handle
  7565. ** to the sqlite3_backup_finish() to release associated resources.
  7566. **
  7567. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  7568. ** on the destination file. ^The exclusive lock is not released until either
  7569. ** sqlite3_backup_finish() is called or the backup operation is complete
  7570. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  7571. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  7572. ** lasts for the duration of the sqlite3_backup_step() call.
  7573. ** ^Because the source database is not locked between calls to
  7574. ** sqlite3_backup_step(), the source database may be modified mid-way
  7575. ** through the backup process. ^If the source database is modified by an
  7576. ** external process or via a database connection other than the one being
  7577. ** used by the backup operation, then the backup will be automatically
  7578. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  7579. ** database is modified by the using the same database connection as is used
  7580. ** by the backup operation, then the backup database is automatically
  7581. ** updated at the same time.
  7582. **
  7583. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  7584. **
  7585. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  7586. ** application wishes to abandon the backup operation, the application
  7587. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  7588. ** ^The sqlite3_backup_finish() interfaces releases all
  7589. ** resources associated with the [sqlite3_backup] object.
  7590. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  7591. ** active write-transaction on the destination database is rolled back.
  7592. ** The [sqlite3_backup] object is invalid
  7593. ** and may not be used following a call to sqlite3_backup_finish().
  7594. **
  7595. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  7596. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  7597. ** sqlite3_backup_step() completed.
  7598. ** ^If an out-of-memory condition or IO error occurred during any prior
  7599. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  7600. ** sqlite3_backup_finish() returns the corresponding [error code].
  7601. **
  7602. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  7603. ** is not a permanent error and does not affect the return value of
  7604. ** sqlite3_backup_finish().
  7605. **
  7606. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  7607. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  7608. **
  7609. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  7610. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  7611. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  7612. ** in the source database at the conclusion of the most recent
  7613. ** sqlite3_backup_step().
  7614. ** ^(The values returned by these functions are only updated by
  7615. ** sqlite3_backup_step(). If the source database is modified in a way that
  7616. ** changes the size of the source database or the number of pages remaining,
  7617. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  7618. ** and sqlite3_backup_remaining() until after the next
  7619. ** sqlite3_backup_step().)^
  7620. **
  7621. ** <b>Concurrent Usage of Database Handles</b>
  7622. **
  7623. ** ^The source [database connection] may be used by the application for other
  7624. ** purposes while a backup operation is underway or being initialized.
  7625. ** ^If SQLite is compiled and configured to support threadsafe database
  7626. ** connections, then the source database connection may be used concurrently
  7627. ** from within other threads.
  7628. **
  7629. ** However, the application must guarantee that the destination
  7630. ** [database connection] is not passed to any other API (by any thread) after
  7631. ** sqlite3_backup_init() is called and before the corresponding call to
  7632. ** sqlite3_backup_finish(). SQLite does not currently check to see
  7633. ** if the application incorrectly accesses the destination [database connection]
  7634. ** and so no error code is reported, but the operations may malfunction
  7635. ** nevertheless. Use of the destination database connection while a
  7636. ** backup is in progress might also also cause a mutex deadlock.
  7637. **
  7638. ** If running in [shared cache mode], the application must
  7639. ** guarantee that the shared cache used by the destination database
  7640. ** is not accessed while the backup is running. In practice this means
  7641. ** that the application must guarantee that the disk file being
  7642. ** backed up to is not accessed by any connection within the process,
  7643. ** not just the specific connection that was passed to sqlite3_backup_init().
  7644. **
  7645. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  7646. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  7647. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  7648. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  7649. ** same time as another thread is invoking sqlite3_backup_step() it is
  7650. ** possible that they return invalid values.
  7651. */
  7652. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  7653. sqlite3 *pDest, /* Destination database handle */
  7654. const char *zDestName, /* Destination database name */
  7655. sqlite3 *pSource, /* Source database handle */
  7656. const char *zSourceName /* Source database name */
  7657. );
  7658. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  7659. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  7660. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  7661. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  7662. /*
  7663. ** CAPI3REF: Unlock Notification
  7664. ** METHOD: sqlite3
  7665. **
  7666. ** ^When running in shared-cache mode, a database operation may fail with
  7667. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  7668. ** individual tables within the shared-cache cannot be obtained. See
  7669. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  7670. ** ^This API may be used to register a callback that SQLite will invoke
  7671. ** when the connection currently holding the required lock relinquishes it.
  7672. ** ^This API is only available if the library was compiled with the
  7673. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  7674. **
  7675. ** See Also: [Using the SQLite Unlock Notification Feature].
  7676. **
  7677. ** ^Shared-cache locks are released when a database connection concludes
  7678. ** its current transaction, either by committing it or rolling it back.
  7679. **
  7680. ** ^When a connection (known as the blocked connection) fails to obtain a
  7681. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  7682. ** identity of the database connection (the blocking connection) that
  7683. ** has locked the required resource is stored internally. ^After an
  7684. ** application receives an SQLITE_LOCKED error, it may call the
  7685. ** sqlite3_unlock_notify() method with the blocked connection handle as
  7686. ** the first argument to register for a callback that will be invoked
  7687. ** when the blocking connections current transaction is concluded. ^The
  7688. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  7689. ** call that concludes the blocking connections transaction.
  7690. **
  7691. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  7692. ** there is a chance that the blocking connection will have already
  7693. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  7694. ** If this happens, then the specified callback is invoked immediately,
  7695. ** from within the call to sqlite3_unlock_notify().)^
  7696. **
  7697. ** ^If the blocked connection is attempting to obtain a write-lock on a
  7698. ** shared-cache table, and more than one other connection currently holds
  7699. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  7700. ** the other connections to use as the blocking connection.
  7701. **
  7702. ** ^(There may be at most one unlock-notify callback registered by a
  7703. ** blocked connection. If sqlite3_unlock_notify() is called when the
  7704. ** blocked connection already has a registered unlock-notify callback,
  7705. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  7706. ** called with a NULL pointer as its second argument, then any existing
  7707. ** unlock-notify callback is canceled. ^The blocked connections
  7708. ** unlock-notify callback may also be canceled by closing the blocked
  7709. ** connection using [sqlite3_close()].
  7710. **
  7711. ** The unlock-notify callback is not reentrant. If an application invokes
  7712. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  7713. ** crash or deadlock may be the result.
  7714. **
  7715. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  7716. ** returns SQLITE_OK.
  7717. **
  7718. ** <b>Callback Invocation Details</b>
  7719. **
  7720. ** When an unlock-notify callback is registered, the application provides a
  7721. ** single void* pointer that is passed to the callback when it is invoked.
  7722. ** However, the signature of the callback function allows SQLite to pass
  7723. ** it an array of void* context pointers. The first argument passed to
  7724. ** an unlock-notify callback is a pointer to an array of void* pointers,
  7725. ** and the second is the number of entries in the array.
  7726. **
  7727. ** When a blocking connections transaction is concluded, there may be
  7728. ** more than one blocked connection that has registered for an unlock-notify
  7729. ** callback. ^If two or more such blocked connections have specified the
  7730. ** same callback function, then instead of invoking the callback function
  7731. ** multiple times, it is invoked once with the set of void* context pointers
  7732. ** specified by the blocked connections bundled together into an array.
  7733. ** This gives the application an opportunity to prioritize any actions
  7734. ** related to the set of unblocked database connections.
  7735. **
  7736. ** <b>Deadlock Detection</b>
  7737. **
  7738. ** Assuming that after registering for an unlock-notify callback a
  7739. ** database waits for the callback to be issued before taking any further
  7740. ** action (a reasonable assumption), then using this API may cause the
  7741. ** application to deadlock. For example, if connection X is waiting for
  7742. ** connection Y's transaction to be concluded, and similarly connection
  7743. ** Y is waiting on connection X's transaction, then neither connection
  7744. ** will proceed and the system may remain deadlocked indefinitely.
  7745. **
  7746. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7747. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7748. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7749. ** unlock-notify callback is registered. The system is said to be in
  7750. ** a deadlocked state if connection A has registered for an unlock-notify
  7751. ** callback on the conclusion of connection B's transaction, and connection
  7752. ** B has itself registered for an unlock-notify callback when connection
  7753. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7754. ** the system is also considered to be deadlocked if connection B has
  7755. ** registered for an unlock-notify callback on the conclusion of connection
  7756. ** C's transaction, where connection C is waiting on connection A. ^Any
  7757. ** number of levels of indirection are allowed.
  7758. **
  7759. ** <b>The "DROP TABLE" Exception</b>
  7760. **
  7761. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7762. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7763. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7764. ** SQLite checks if there are any currently executing SELECT statements
  7765. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7766. ** returned. In this case there is no "blocking connection", so invoking
  7767. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7768. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7769. ** or "DROP INDEX" query, an infinite loop might be the result.
  7770. **
  7771. ** One way around this problem is to check the extended error code returned
  7772. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7773. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7774. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7775. ** SQLITE_LOCKED.)^
  7776. */
  7777. SQLITE_API int sqlite3_unlock_notify(
  7778. sqlite3 *pBlocked, /* Waiting connection */
  7779. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7780. void *pNotifyArg /* Argument to pass to xNotify */
  7781. );
  7782. /*
  7783. ** CAPI3REF: String Comparison
  7784. **
  7785. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7786. ** and extensions to compare the contents of two buffers containing UTF-8
  7787. ** strings in a case-independent fashion, using the same definition of "case
  7788. ** independence" that SQLite uses internally when comparing identifiers.
  7789. */
  7790. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  7791. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  7792. /*
  7793. ** CAPI3REF: String Globbing
  7794. *
  7795. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  7796. ** string X matches the [GLOB] pattern P.
  7797. ** ^The definition of [GLOB] pattern matching used in
  7798. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7799. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  7800. ** is case sensitive.
  7801. **
  7802. ** Note that this routine returns zero on a match and non-zero if the strings
  7803. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7804. **
  7805. ** See also: [sqlite3_strlike()].
  7806. */
  7807. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  7808. /*
  7809. ** CAPI3REF: String LIKE Matching
  7810. *
  7811. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  7812. ** string X matches the [LIKE] pattern P with escape character E.
  7813. ** ^The definition of [LIKE] pattern matching used in
  7814. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  7815. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  7816. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  7817. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  7818. ** insensitive - equivalent upper and lower case ASCII characters match
  7819. ** one another.
  7820. **
  7821. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  7822. ** only ASCII characters are case folded.
  7823. **
  7824. ** Note that this routine returns zero on a match and non-zero if the strings
  7825. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7826. **
  7827. ** See also: [sqlite3_strglob()].
  7828. */
  7829. SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  7830. /*
  7831. ** CAPI3REF: Error Logging Interface
  7832. **
  7833. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7834. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7835. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7836. ** used with [sqlite3_snprintf()] to generate the final output string.
  7837. **
  7838. ** The sqlite3_log() interface is intended for use by extensions such as
  7839. ** virtual tables, collating functions, and SQL functions. While there is
  7840. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7841. ** is considered bad form.
  7842. **
  7843. ** The zFormat string must not be NULL.
  7844. **
  7845. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7846. ** will not use dynamically allocated memory. The log message is stored in
  7847. ** a fixed-length buffer on the stack. If the log message is longer than
  7848. ** a few hundred characters, it will be truncated to the length of the
  7849. ** buffer.
  7850. */
  7851. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  7852. /*
  7853. ** CAPI3REF: Write-Ahead Log Commit Hook
  7854. ** METHOD: sqlite3
  7855. **
  7856. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7857. ** is invoked each time data is committed to a database in wal mode.
  7858. **
  7859. ** ^(The callback is invoked by SQLite after the commit has taken place and
  7860. ** the associated write-lock on the database released)^, so the implementation
  7861. ** may read, write or [checkpoint] the database as required.
  7862. **
  7863. ** ^The first parameter passed to the callback function when it is invoked
  7864. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7865. ** registering the callback. ^The second is a copy of the database handle.
  7866. ** ^The third parameter is the name of the database that was written to -
  7867. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7868. ** is the number of pages currently in the write-ahead log file,
  7869. ** including those that were just committed.
  7870. **
  7871. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7872. ** code is returned, that error will propagate back up through the
  7873. ** SQLite code base to cause the statement that provoked the callback
  7874. ** to report an error, though the commit will have still occurred. If the
  7875. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7876. ** that does not correspond to any valid SQLite error code, the results
  7877. ** are undefined.
  7878. **
  7879. ** A single database handle may have at most a single write-ahead log callback
  7880. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7881. ** previously registered write-ahead log callback. ^Note that the
  7882. ** [sqlite3_wal_autocheckpoint()] interface and the
  7883. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7884. ** overwrite any prior [sqlite3_wal_hook()] settings.
  7885. */
  7886. SQLITE_API void *sqlite3_wal_hook(
  7887. sqlite3*,
  7888. int(*)(void *,sqlite3*,const char*,int),
  7889. void*
  7890. );
  7891. /*
  7892. ** CAPI3REF: Configure an auto-checkpoint
  7893. ** METHOD: sqlite3
  7894. **
  7895. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7896. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7897. ** to automatically [checkpoint]
  7898. ** after committing a transaction if there are N or
  7899. ** more frames in the [write-ahead log] file. ^Passing zero or
  7900. ** a negative value as the nFrame parameter disables automatic
  7901. ** checkpoints entirely.
  7902. **
  7903. ** ^The callback registered by this function replaces any existing callback
  7904. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7905. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7906. ** configured by this function.
  7907. **
  7908. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7909. ** from SQL.
  7910. **
  7911. ** ^Checkpoints initiated by this mechanism are
  7912. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  7913. **
  7914. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7915. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7916. ** pages. The use of this interface
  7917. ** is only necessary if the default setting is found to be suboptimal
  7918. ** for a particular application.
  7919. */
  7920. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7921. /*
  7922. ** CAPI3REF: Checkpoint a database
  7923. ** METHOD: sqlite3
  7924. **
  7925. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  7926. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  7927. **
  7928. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  7929. ** [write-ahead log] for database X on [database connection] D to be
  7930. ** transferred into the database file and for the write-ahead log to
  7931. ** be reset. See the [checkpointing] documentation for addition
  7932. ** information.
  7933. **
  7934. ** This interface used to be the only way to cause a checkpoint to
  7935. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  7936. ** interface was added. This interface is retained for backwards
  7937. ** compatibility and as a convenience for applications that need to manually
  7938. ** start a callback but which do not need the full power (and corresponding
  7939. ** complication) of [sqlite3_wal_checkpoint_v2()].
  7940. */
  7941. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7942. /*
  7943. ** CAPI3REF: Checkpoint a database
  7944. ** METHOD: sqlite3
  7945. **
  7946. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  7947. ** operation on database X of [database connection] D in mode M. Status
  7948. ** information is written back into integers pointed to by L and C.)^
  7949. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  7950. **
  7951. ** <dl>
  7952. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7953. ** ^Checkpoint as many frames as possible without waiting for any database
  7954. ** readers or writers to finish, then sync the database file if all frames
  7955. ** in the log were checkpointed. ^The [busy-handler callback]
  7956. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  7957. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  7958. ** if there are concurrent readers or writers.
  7959. **
  7960. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7961. ** ^This mode blocks (it invokes the
  7962. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  7963. ** database writer and all readers are reading from the most recent database
  7964. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  7965. ** database file. ^This mode blocks new database writers while it is pending,
  7966. ** but new database readers are allowed to continue unimpeded.
  7967. **
  7968. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7969. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  7970. ** that after checkpointing the log file it blocks (calls the
  7971. ** [busy-handler callback])
  7972. ** until all readers are reading from the database file only. ^This ensures
  7973. ** that the next writer will restart the log file from the beginning.
  7974. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  7975. ** database writer attempts while it is pending, but does not impede readers.
  7976. **
  7977. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  7978. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  7979. ** addition that it also truncates the log file to zero bytes just prior
  7980. ** to a successful return.
  7981. ** </dl>
  7982. **
  7983. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7984. ** the log file or to -1 if the checkpoint could not run because
  7985. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  7986. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  7987. ** log file (including any that were already checkpointed before the function
  7988. ** was called) or to -1 if the checkpoint could not run due to an error or
  7989. ** because the database is not in WAL mode. ^Note that upon successful
  7990. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  7991. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  7992. **
  7993. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  7994. ** any other process is running a checkpoint operation at the same time, the
  7995. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  7996. ** busy-handler configured, it will not be invoked in this case.
  7997. **
  7998. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  7999. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  8000. ** obtained immediately, and a busy-handler is configured, it is invoked and
  8001. ** the writer lock retried until either the busy-handler returns 0 or the lock
  8002. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  8003. ** database readers as described above. ^If the busy-handler returns 0 before
  8004. ** the writer lock is obtained or while waiting for database readers, the
  8005. ** checkpoint operation proceeds from that point in the same way as
  8006. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  8007. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  8008. **
  8009. ** ^If parameter zDb is NULL or points to a zero length string, then the
  8010. ** specified operation is attempted on all WAL databases [attached] to
  8011. ** [database connection] db. In this case the
  8012. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  8013. ** an SQLITE_BUSY error is encountered when processing one or more of the
  8014. ** attached WAL databases, the operation is still attempted on any remaining
  8015. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  8016. ** error occurs while processing an attached database, processing is abandoned
  8017. ** and the error code is returned to the caller immediately. ^If no error
  8018. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  8019. ** databases, SQLITE_OK is returned.
  8020. **
  8021. ** ^If database zDb is the name of an attached database that is not in WAL
  8022. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  8023. ** zDb is not NULL (or a zero length string) and is not the name of any
  8024. ** attached database, SQLITE_ERROR is returned to the caller.
  8025. **
  8026. ** ^Unless it returns SQLITE_MISUSE,
  8027. ** the sqlite3_wal_checkpoint_v2() interface
  8028. ** sets the error information that is queried by
  8029. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  8030. **
  8031. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  8032. ** from SQL.
  8033. */
  8034. SQLITE_API int sqlite3_wal_checkpoint_v2(
  8035. sqlite3 *db, /* Database handle */
  8036. const char *zDb, /* Name of attached database (or NULL) */
  8037. int eMode, /* SQLITE_CHECKPOINT_* value */
  8038. int *pnLog, /* OUT: Size of WAL log in frames */
  8039. int *pnCkpt /* OUT: Total number of frames checkpointed */
  8040. );
  8041. /*
  8042. ** CAPI3REF: Checkpoint Mode Values
  8043. ** KEYWORDS: {checkpoint mode}
  8044. **
  8045. ** These constants define all valid values for the "checkpoint mode" passed
  8046. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  8047. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  8048. ** meaning of each of these checkpoint modes.
  8049. */
  8050. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  8051. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  8052. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  8053. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  8054. /*
  8055. ** CAPI3REF: Virtual Table Interface Configuration
  8056. **
  8057. ** This function may be called by either the [xConnect] or [xCreate] method
  8058. ** of a [virtual table] implementation to configure
  8059. ** various facets of the virtual table interface.
  8060. **
  8061. ** If this interface is invoked outside the context of an xConnect or
  8062. ** xCreate virtual table method then the behavior is undefined.
  8063. **
  8064. ** At present, there is only one option that may be configured using
  8065. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  8066. ** may be added in the future.
  8067. */
  8068. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  8069. /*
  8070. ** CAPI3REF: Virtual Table Configuration Options
  8071. **
  8072. ** These macros define the various options to the
  8073. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  8074. ** can use to customize and optimize their behavior.
  8075. **
  8076. ** <dl>
  8077. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  8078. ** <dd>Calls of the form
  8079. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  8080. ** where X is an integer. If X is zero, then the [virtual table] whose
  8081. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  8082. ** support constraints. In this configuration (which is the default) if
  8083. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  8084. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  8085. ** specified as part of the users SQL statement, regardless of the actual
  8086. ** ON CONFLICT mode specified.
  8087. **
  8088. ** If X is non-zero, then the virtual table implementation guarantees
  8089. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  8090. ** any modifications to internal or persistent data structures have been made.
  8091. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  8092. ** is able to roll back a statement or database transaction, and abandon
  8093. ** or continue processing the current SQL statement as appropriate.
  8094. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  8095. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  8096. ** had been ABORT.
  8097. **
  8098. ** Virtual table implementations that are required to handle OR REPLACE
  8099. ** must do so within the [xUpdate] method. If a call to the
  8100. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  8101. ** CONFLICT policy is REPLACE, the virtual table implementation should
  8102. ** silently replace the appropriate rows within the xUpdate callback and
  8103. ** return SQLITE_OK. Or, if this is not possible, it may return
  8104. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  8105. ** constraint handling.
  8106. ** </dl>
  8107. */
  8108. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  8109. /*
  8110. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  8111. **
  8112. ** This function may only be called from within a call to the [xUpdate] method
  8113. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  8114. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  8115. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  8116. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  8117. ** [virtual table].
  8118. */
  8119. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  8120. /*
  8121. ** CAPI3REF: Conflict resolution modes
  8122. ** KEYWORDS: {conflict resolution mode}
  8123. **
  8124. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  8125. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  8126. ** is for the SQL statement being evaluated.
  8127. **
  8128. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  8129. ** return value from the [sqlite3_set_authorizer()] callback and that
  8130. ** [SQLITE_ABORT] is also a [result code].
  8131. */
  8132. #define SQLITE_ROLLBACK 1
  8133. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  8134. #define SQLITE_FAIL 3
  8135. /* #define SQLITE_ABORT 4 // Also an error code */
  8136. #define SQLITE_REPLACE 5
  8137. /*
  8138. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  8139. ** KEYWORDS: {scanstatus options}
  8140. **
  8141. ** The following constants can be used for the T parameter to the
  8142. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  8143. ** different metric for sqlite3_stmt_scanstatus() to return.
  8144. **
  8145. ** When the value returned to V is a string, space to hold that string is
  8146. ** managed by the prepared statement S and will be automatically freed when
  8147. ** S is finalized.
  8148. **
  8149. ** <dl>
  8150. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  8151. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  8152. ** set to the total number of times that the X-th loop has run.</dd>
  8153. **
  8154. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  8155. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  8156. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  8157. **
  8158. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  8159. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  8160. ** query planner's estimate for the average number of rows output from each
  8161. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  8162. ** then this value will approximate the quotient NVISIT/NLOOP and the
  8163. ** product of this value for all prior loops with the same SELECTID will
  8164. ** be the NLOOP value for the current loop.
  8165. **
  8166. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  8167. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  8168. ** to a zero-terminated UTF-8 string containing the name of the index or table
  8169. ** used for the X-th loop.
  8170. **
  8171. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  8172. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  8173. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  8174. ** description for the X-th loop.
  8175. **
  8176. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  8177. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  8178. ** "select-id" for the X-th loop. The select-id identifies which query or
  8179. ** subquery the loop is part of. The main query has a select-id of zero.
  8180. ** The select-id is the same value as is output in the first column
  8181. ** of an [EXPLAIN QUERY PLAN] query.
  8182. ** </dl>
  8183. */
  8184. #define SQLITE_SCANSTAT_NLOOP 0
  8185. #define SQLITE_SCANSTAT_NVISIT 1
  8186. #define SQLITE_SCANSTAT_EST 2
  8187. #define SQLITE_SCANSTAT_NAME 3
  8188. #define SQLITE_SCANSTAT_EXPLAIN 4
  8189. #define SQLITE_SCANSTAT_SELECTID 5
  8190. /*
  8191. ** CAPI3REF: Prepared Statement Scan Status
  8192. ** METHOD: sqlite3_stmt
  8193. **
  8194. ** This interface returns information about the predicted and measured
  8195. ** performance for pStmt. Advanced applications can use this
  8196. ** interface to compare the predicted and the measured performance and
  8197. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  8198. **
  8199. ** Since this interface is expected to be rarely used, it is only
  8200. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  8201. ** compile-time option.
  8202. **
  8203. ** The "iScanStatusOp" parameter determines which status information to return.
  8204. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  8205. ** of this interface is undefined.
  8206. ** ^The requested measurement is written into a variable pointed to by
  8207. ** the "pOut" parameter.
  8208. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  8209. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  8210. ** zero or greater than or equal to the total number of loops used to implement
  8211. ** the statement - a non-zero value is returned and the variable that pOut
  8212. ** points to is unchanged.
  8213. **
  8214. ** ^Statistics might not be available for all loops in all statements. ^In cases
  8215. ** where there exist loops with no available statistics, this function behaves
  8216. ** as if the loop did not exist - it returns non-zero and leave the variable
  8217. ** that pOut points to unchanged.
  8218. **
  8219. ** See also: [sqlite3_stmt_scanstatus_reset()]
  8220. */
  8221. SQLITE_API int sqlite3_stmt_scanstatus(
  8222. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  8223. int idx, /* Index of loop to report on */
  8224. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  8225. void *pOut /* Result written here */
  8226. );
  8227. /*
  8228. ** CAPI3REF: Zero Scan-Status Counters
  8229. ** METHOD: sqlite3_stmt
  8230. **
  8231. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  8232. **
  8233. ** This API is only available if the library is built with pre-processor
  8234. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  8235. */
  8236. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  8237. /*
  8238. ** CAPI3REF: Flush caches to disk mid-transaction
  8239. **
  8240. ** ^If a write-transaction is open on [database connection] D when the
  8241. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  8242. ** pages in the pager-cache that are not currently in use are written out
  8243. ** to disk. A dirty page may be in use if a database cursor created by an
  8244. ** active SQL statement is reading from it, or if it is page 1 of a database
  8245. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  8246. ** interface flushes caches for all schemas - "main", "temp", and
  8247. ** any [attached] databases.
  8248. **
  8249. ** ^If this function needs to obtain extra database locks before dirty pages
  8250. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  8251. ** immediately and there is a busy-handler callback configured, it is invoked
  8252. ** in the usual manner. ^If the required lock still cannot be obtained, then
  8253. ** the database is skipped and an attempt made to flush any dirty pages
  8254. ** belonging to the next (if any) database. ^If any databases are skipped
  8255. ** because locks cannot be obtained, but no other error occurs, this
  8256. ** function returns SQLITE_BUSY.
  8257. **
  8258. ** ^If any other error occurs while flushing dirty pages to disk (for
  8259. ** example an IO error or out-of-memory condition), then processing is
  8260. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  8261. **
  8262. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  8263. **
  8264. ** ^This function does not set the database handle error code or message
  8265. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  8266. */
  8267. SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  8268. /*
  8269. ** CAPI3REF: The pre-update hook.
  8270. **
  8271. ** ^These interfaces are only available if SQLite is compiled using the
  8272. ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  8273. **
  8274. ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  8275. ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  8276. ** on a database table.
  8277. ** ^At most one preupdate hook may be registered at a time on a single
  8278. ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  8279. ** the previous setting.
  8280. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  8281. ** with a NULL pointer as the second parameter.
  8282. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  8283. ** the first parameter to callbacks.
  8284. **
  8285. ** ^The preupdate hook only fires for changes to real database tables; the
  8286. ** preupdate hook is not invoked for changes to [virtual tables] or to
  8287. ** system tables like sqlite_master or sqlite_stat1.
  8288. **
  8289. ** ^The second parameter to the preupdate callback is a pointer to
  8290. ** the [database connection] that registered the preupdate hook.
  8291. ** ^The third parameter to the preupdate callback is one of the constants
  8292. ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  8293. ** kind of update operation that is about to occur.
  8294. ** ^(The fourth parameter to the preupdate callback is the name of the
  8295. ** database within the database connection that is being modified. This
  8296. ** will be "main" for the main database or "temp" for TEMP tables or
  8297. ** the name given after the AS keyword in the [ATTACH] statement for attached
  8298. ** databases.)^
  8299. ** ^The fifth parameter to the preupdate callback is the name of the
  8300. ** table that is being modified.
  8301. **
  8302. ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  8303. ** parameter passed to the preupdate callback is the initial [rowid] of the
  8304. ** row being modified or deleted. For an INSERT operation on a rowid table,
  8305. ** or any operation on a WITHOUT ROWID table, the value of the sixth
  8306. ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  8307. ** seventh parameter is the final rowid value of the row being inserted
  8308. ** or updated. The value of the seventh parameter passed to the callback
  8309. ** function is not defined for operations on WITHOUT ROWID tables, or for
  8310. ** INSERT operations on rowid tables.
  8311. **
  8312. ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  8313. ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  8314. ** provide additional information about a preupdate event. These routines
  8315. ** may only be called from within a preupdate callback. Invoking any of
  8316. ** these routines from outside of a preupdate callback or with a
  8317. ** [database connection] pointer that is different from the one supplied
  8318. ** to the preupdate callback results in undefined and probably undesirable
  8319. ** behavior.
  8320. **
  8321. ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  8322. ** in the row that is being inserted, updated, or deleted.
  8323. **
  8324. ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  8325. ** a [protected sqlite3_value] that contains the value of the Nth column of
  8326. ** the table row before it is updated. The N parameter must be between 0
  8327. ** and one less than the number of columns or the behavior will be
  8328. ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  8329. ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  8330. ** behavior is undefined. The [sqlite3_value] that P points to
  8331. ** will be destroyed when the preupdate callback returns.
  8332. **
  8333. ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  8334. ** a [protected sqlite3_value] that contains the value of the Nth column of
  8335. ** the table row after it is updated. The N parameter must be between 0
  8336. ** and one less than the number of columns or the behavior will be
  8337. ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  8338. ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  8339. ** behavior is undefined. The [sqlite3_value] that P points to
  8340. ** will be destroyed when the preupdate callback returns.
  8341. **
  8342. ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  8343. ** callback was invoked as a result of a direct insert, update, or delete
  8344. ** operation; or 1 for inserts, updates, or deletes invoked by top-level
  8345. ** triggers; or 2 for changes resulting from triggers called by top-level
  8346. ** triggers; and so forth.
  8347. **
  8348. ** See also: [sqlite3_update_hook()]
  8349. */
  8350. #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  8351. SQLITE_API void *sqlite3_preupdate_hook(
  8352. sqlite3 *db,
  8353. void(*xPreUpdate)(
  8354. void *pCtx, /* Copy of third arg to preupdate_hook() */
  8355. sqlite3 *db, /* Database handle */
  8356. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  8357. char const *zDb, /* Database name */
  8358. char const *zName, /* Table name */
  8359. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  8360. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  8361. ),
  8362. void*
  8363. );
  8364. SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  8365. SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  8366. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  8367. SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  8368. #endif
  8369. /*
  8370. ** CAPI3REF: Low-level system error code
  8371. **
  8372. ** ^Attempt to return the underlying operating system error code or error
  8373. ** number that caused the most recent I/O error or failure to open a file.
  8374. ** The return value is OS-dependent. For example, on unix systems, after
  8375. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  8376. ** called to get back the underlying "errno" that caused the problem, such
  8377. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  8378. */
  8379. SQLITE_API int sqlite3_system_errno(sqlite3*);
  8380. /*
  8381. ** CAPI3REF: Database Snapshot
  8382. ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  8383. ** EXPERIMENTAL
  8384. **
  8385. ** An instance of the snapshot object records the state of a [WAL mode]
  8386. ** database for some specific point in history.
  8387. **
  8388. ** In [WAL mode], multiple [database connections] that are open on the
  8389. ** same database file can each be reading a different historical version
  8390. ** of the database file. When a [database connection] begins a read
  8391. ** transaction, that connection sees an unchanging copy of the database
  8392. ** as it existed for the point in time when the transaction first started.
  8393. ** Subsequent changes to the database from other connections are not seen
  8394. ** by the reader until a new read transaction is started.
  8395. **
  8396. ** The sqlite3_snapshot object records state information about an historical
  8397. ** version of the database file so that it is possible to later open a new read
  8398. ** transaction that sees that historical version of the database rather than
  8399. ** the most recent version.
  8400. **
  8401. ** The constructor for this object is [sqlite3_snapshot_get()]. The
  8402. ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
  8403. ** to an historical snapshot (if possible). The destructor for
  8404. ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
  8405. */
  8406. typedef struct sqlite3_snapshot {
  8407. unsigned char hidden[48];
  8408. } sqlite3_snapshot;
  8409. /*
  8410. ** CAPI3REF: Record A Database Snapshot
  8411. ** EXPERIMENTAL
  8412. **
  8413. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  8414. ** new [sqlite3_snapshot] object that records the current state of
  8415. ** schema S in database connection D. ^On success, the
  8416. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  8417. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  8418. ** If there is not already a read-transaction open on schema S when
  8419. ** this function is called, one is opened automatically.
  8420. **
  8421. ** The following must be true for this function to succeed. If any of
  8422. ** the following statements are false when sqlite3_snapshot_get() is
  8423. ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  8424. ** in this case.
  8425. **
  8426. ** <ul>
  8427. ** <li> The database handle must be in [autocommit mode].
  8428. **
  8429. ** <li> Schema S of [database connection] D must be a [WAL mode] database.
  8430. **
  8431. ** <li> There must not be a write transaction open on schema S of database
  8432. ** connection D.
  8433. **
  8434. ** <li> One or more transactions must have been written to the current wal
  8435. ** file since it was created on disk (by any connection). This means
  8436. ** that a snapshot cannot be taken on a wal mode database with no wal
  8437. ** file immediately after it is first opened. At least one transaction
  8438. ** must be written to it first.
  8439. ** </ul>
  8440. **
  8441. ** This function may also return SQLITE_NOMEM. If it is called with the
  8442. ** database handle in autocommit mode but fails for some other reason,
  8443. ** whether or not a read transaction is opened on schema S is undefined.
  8444. **
  8445. ** The [sqlite3_snapshot] object returned from a successful call to
  8446. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  8447. ** to avoid a memory leak.
  8448. **
  8449. ** The [sqlite3_snapshot_get()] interface is only available when the
  8450. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  8451. */
  8452. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  8453. sqlite3 *db,
  8454. const char *zSchema,
  8455. sqlite3_snapshot **ppSnapshot
  8456. );
  8457. /*
  8458. ** CAPI3REF: Start a read transaction on an historical snapshot
  8459. ** EXPERIMENTAL
  8460. **
  8461. ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
  8462. ** read transaction for schema S of
  8463. ** [database connection] D such that the read transaction
  8464. ** refers to historical [snapshot] P, rather than the most
  8465. ** recent change to the database.
  8466. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
  8467. ** or an appropriate [error code] if it fails.
  8468. **
  8469. ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
  8470. ** the first operation following the [BEGIN] that takes the schema S
  8471. ** out of [autocommit mode].
  8472. ** ^In other words, schema S must not currently be in
  8473. ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
  8474. ** database connection D must be out of [autocommit mode].
  8475. ** ^A [snapshot] will fail to open if it has been overwritten by a
  8476. ** [checkpoint].
  8477. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  8478. ** database connection D does not know that the database file for
  8479. ** schema S is in [WAL mode]. A database connection might not know
  8480. ** that the database file is in [WAL mode] if there has been no prior
  8481. ** I/O on that database connection, or if the database entered [WAL mode]
  8482. ** after the most recent I/O on the database connection.)^
  8483. ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  8484. ** database connection in order to make it ready to use snapshots.)
  8485. **
  8486. ** The [sqlite3_snapshot_open()] interface is only available when the
  8487. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  8488. */
  8489. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  8490. sqlite3 *db,
  8491. const char *zSchema,
  8492. sqlite3_snapshot *pSnapshot
  8493. );
  8494. /*
  8495. ** CAPI3REF: Destroy a snapshot
  8496. ** EXPERIMENTAL
  8497. **
  8498. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  8499. ** The application must eventually free every [sqlite3_snapshot] object
  8500. ** using this routine to avoid a memory leak.
  8501. **
  8502. ** The [sqlite3_snapshot_free()] interface is only available when the
  8503. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  8504. */
  8505. SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  8506. /*
  8507. ** CAPI3REF: Compare the ages of two snapshot handles.
  8508. ** EXPERIMENTAL
  8509. **
  8510. ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  8511. ** of two valid snapshot handles.
  8512. **
  8513. ** If the two snapshot handles are not associated with the same database
  8514. ** file, the result of the comparison is undefined.
  8515. **
  8516. ** Additionally, the result of the comparison is only valid if both of the
  8517. ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  8518. ** last time the wal file was deleted. The wal file is deleted when the
  8519. ** database is changed back to rollback mode or when the number of database
  8520. ** clients drops to zero. If either snapshot handle was obtained before the
  8521. ** wal file was last deleted, the value returned by this function
  8522. ** is undefined.
  8523. **
  8524. ** Otherwise, this API returns a negative value if P1 refers to an older
  8525. ** snapshot than P2, zero if the two handles refer to the same database
  8526. ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  8527. */
  8528. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  8529. sqlite3_snapshot *p1,
  8530. sqlite3_snapshot *p2
  8531. );
  8532. /*
  8533. ** CAPI3REF: Recover snapshots from a wal file
  8534. ** EXPERIMENTAL
  8535. **
  8536. ** If all connections disconnect from a database file but do not perform
  8537. ** a checkpoint, the existing wal file is opened along with the database
  8538. ** file the next time the database is opened. At this point it is only
  8539. ** possible to successfully call sqlite3_snapshot_open() to open the most
  8540. ** recent snapshot of the database (the one at the head of the wal file),
  8541. ** even though the wal file may contain other valid snapshots for which
  8542. ** clients have sqlite3_snapshot handles.
  8543. **
  8544. ** This function attempts to scan the wal file associated with database zDb
  8545. ** of database handle db and make all valid snapshots available to
  8546. ** sqlite3_snapshot_open(). It is an error if there is already a read
  8547. ** transaction open on the database, or if the database is not a wal mode
  8548. ** database.
  8549. **
  8550. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  8551. */
  8552. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  8553. /*
  8554. ** Undo the hack that converts floating point types to integer for
  8555. ** builds on processors without floating point support.
  8556. */
  8557. #ifdef SQLITE_OMIT_FLOATING_POINT
  8558. # undef double
  8559. #endif
  8560. #if 0
  8561. } /* End of the 'extern "C"' block */
  8562. #endif
  8563. #endif /* SQLITE3_H */
  8564. /******** Begin file sqlite3rtree.h *********/
  8565. /*
  8566. ** 2010 August 30
  8567. **
  8568. ** The author disclaims copyright to this source code. In place of
  8569. ** a legal notice, here is a blessing:
  8570. **
  8571. ** May you do good and not evil.
  8572. ** May you find forgiveness for yourself and forgive others.
  8573. ** May you share freely, never taking more than you give.
  8574. **
  8575. *************************************************************************
  8576. */
  8577. #ifndef _SQLITE3RTREE_H_
  8578. #define _SQLITE3RTREE_H_
  8579. #if 0
  8580. extern "C" {
  8581. #endif
  8582. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  8583. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  8584. /* The double-precision datatype used by RTree depends on the
  8585. ** SQLITE_RTREE_INT_ONLY compile-time option.
  8586. */
  8587. #ifdef SQLITE_RTREE_INT_ONLY
  8588. typedef sqlite3_int64 sqlite3_rtree_dbl;
  8589. #else
  8590. typedef double sqlite3_rtree_dbl;
  8591. #endif
  8592. /*
  8593. ** Register a geometry callback named zGeom that can be used as part of an
  8594. ** R-Tree geometry query as follows:
  8595. **
  8596. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  8597. */
  8598. SQLITE_API int sqlite3_rtree_geometry_callback(
  8599. sqlite3 *db,
  8600. const char *zGeom,
  8601. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  8602. void *pContext
  8603. );
  8604. /*
  8605. ** A pointer to a structure of the following type is passed as the first
  8606. ** argument to callbacks registered using rtree_geometry_callback().
  8607. */
  8608. struct sqlite3_rtree_geometry {
  8609. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  8610. int nParam; /* Size of array aParam[] */
  8611. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  8612. void *pUser; /* Callback implementation user data */
  8613. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  8614. };
  8615. /*
  8616. ** Register a 2nd-generation geometry callback named zScore that can be
  8617. ** used as part of an R-Tree geometry query as follows:
  8618. **
  8619. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  8620. */
  8621. SQLITE_API int sqlite3_rtree_query_callback(
  8622. sqlite3 *db,
  8623. const char *zQueryFunc,
  8624. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  8625. void *pContext,
  8626. void (*xDestructor)(void*)
  8627. );
  8628. /*
  8629. ** A pointer to a structure of the following type is passed as the
  8630. ** argument to scored geometry callback registered using
  8631. ** sqlite3_rtree_query_callback().
  8632. **
  8633. ** Note that the first 5 fields of this structure are identical to
  8634. ** sqlite3_rtree_geometry. This structure is a subclass of
  8635. ** sqlite3_rtree_geometry.
  8636. */
  8637. struct sqlite3_rtree_query_info {
  8638. void *pContext; /* pContext from when function registered */
  8639. int nParam; /* Number of function parameters */
  8640. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  8641. void *pUser; /* callback can use this, if desired */
  8642. void (*xDelUser)(void*); /* function to free pUser */
  8643. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  8644. unsigned int *anQueue; /* Number of pending entries in the queue */
  8645. int nCoord; /* Number of coordinates */
  8646. int iLevel; /* Level of current node or entry */
  8647. int mxLevel; /* The largest iLevel value in the tree */
  8648. sqlite3_int64 iRowid; /* Rowid for current entry */
  8649. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  8650. int eParentWithin; /* Visibility of parent node */
  8651. int eWithin; /* OUT: Visiblity */
  8652. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  8653. /* The following fields are only available in 3.8.11 and later */
  8654. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  8655. };
  8656. /*
  8657. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  8658. */
  8659. #define NOT_WITHIN 0 /* Object completely outside of query region */
  8660. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  8661. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  8662. #if 0
  8663. } /* end of the 'extern "C"' block */
  8664. #endif
  8665. #endif /* ifndef _SQLITE3RTREE_H_ */
  8666. /******** End of sqlite3rtree.h *********/
  8667. /******** Begin file sqlite3session.h *********/
  8668. #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  8669. #define __SQLITESESSION_H_ 1
  8670. /*
  8671. ** Make sure we can call this stuff from C++.
  8672. */
  8673. #if 0
  8674. extern "C" {
  8675. #endif
  8676. /*
  8677. ** CAPI3REF: Session Object Handle
  8678. */
  8679. typedef struct sqlite3_session sqlite3_session;
  8680. /*
  8681. ** CAPI3REF: Changeset Iterator Handle
  8682. */
  8683. typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  8684. /*
  8685. ** CAPI3REF: Create A New Session Object
  8686. **
  8687. ** Create a new session object attached to database handle db. If successful,
  8688. ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  8689. ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  8690. ** error code (e.g. SQLITE_NOMEM) is returned.
  8691. **
  8692. ** It is possible to create multiple session objects attached to a single
  8693. ** database handle.
  8694. **
  8695. ** Session objects created using this function should be deleted using the
  8696. ** [sqlite3session_delete()] function before the database handle that they
  8697. ** are attached to is itself closed. If the database handle is closed before
  8698. ** the session object is deleted, then the results of calling any session
  8699. ** module function, including [sqlite3session_delete()] on the session object
  8700. ** are undefined.
  8701. **
  8702. ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  8703. ** is not possible for an application to register a pre-update hook on a
  8704. ** database handle that has one or more session objects attached. Nor is
  8705. ** it possible to create a session object attached to a database handle for
  8706. ** which a pre-update hook is already defined. The results of attempting
  8707. ** either of these things are undefined.
  8708. **
  8709. ** The session object will be used to create changesets for tables in
  8710. ** database zDb, where zDb is either "main", or "temp", or the name of an
  8711. ** attached database. It is not an error if database zDb is not attached
  8712. ** to the database when the session object is created.
  8713. */
  8714. SQLITE_API int sqlite3session_create(
  8715. sqlite3 *db, /* Database handle */
  8716. const char *zDb, /* Name of db (e.g. "main") */
  8717. sqlite3_session **ppSession /* OUT: New session object */
  8718. );
  8719. /*
  8720. ** CAPI3REF: Delete A Session Object
  8721. **
  8722. ** Delete a session object previously allocated using
  8723. ** [sqlite3session_create()]. Once a session object has been deleted, the
  8724. ** results of attempting to use pSession with any other session module
  8725. ** function are undefined.
  8726. **
  8727. ** Session objects must be deleted before the database handle to which they
  8728. ** are attached is closed. Refer to the documentation for
  8729. ** [sqlite3session_create()] for details.
  8730. */
  8731. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  8732. /*
  8733. ** CAPI3REF: Enable Or Disable A Session Object
  8734. **
  8735. ** Enable or disable the recording of changes by a session object. When
  8736. ** enabled, a session object records changes made to the database. When
  8737. ** disabled - it does not. A newly created session object is enabled.
  8738. ** Refer to the documentation for [sqlite3session_changeset()] for further
  8739. ** details regarding how enabling and disabling a session object affects
  8740. ** the eventual changesets.
  8741. **
  8742. ** Passing zero to this function disables the session. Passing a value
  8743. ** greater than zero enables it. Passing a value less than zero is a
  8744. ** no-op, and may be used to query the current state of the session.
  8745. **
  8746. ** The return value indicates the final state of the session object: 0 if
  8747. ** the session is disabled, or 1 if it is enabled.
  8748. */
  8749. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  8750. /*
  8751. ** CAPI3REF: Set Or Clear the Indirect Change Flag
  8752. **
  8753. ** Each change recorded by a session object is marked as either direct or
  8754. ** indirect. A change is marked as indirect if either:
  8755. **
  8756. ** <ul>
  8757. ** <li> The session object "indirect" flag is set when the change is
  8758. ** made, or
  8759. ** <li> The change is made by an SQL trigger or foreign key action
  8760. ** instead of directly as a result of a users SQL statement.
  8761. ** </ul>
  8762. **
  8763. ** If a single row is affected by more than one operation within a session,
  8764. ** then the change is considered indirect if all operations meet the criteria
  8765. ** for an indirect change above, or direct otherwise.
  8766. **
  8767. ** This function is used to set, clear or query the session object indirect
  8768. ** flag. If the second argument passed to this function is zero, then the
  8769. ** indirect flag is cleared. If it is greater than zero, the indirect flag
  8770. ** is set. Passing a value less than zero does not modify the current value
  8771. ** of the indirect flag, and may be used to query the current state of the
  8772. ** indirect flag for the specified session object.
  8773. **
  8774. ** The return value indicates the final state of the indirect flag: 0 if
  8775. ** it is clear, or 1 if it is set.
  8776. */
  8777. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
  8778. /*
  8779. ** CAPI3REF: Attach A Table To A Session Object
  8780. **
  8781. ** If argument zTab is not NULL, then it is the name of a table to attach
  8782. ** to the session object passed as the first argument. All subsequent changes
  8783. ** made to the table while the session object is enabled will be recorded. See
  8784. ** documentation for [sqlite3session_changeset()] for further details.
  8785. **
  8786. ** Or, if argument zTab is NULL, then changes are recorded for all tables
  8787. ** in the database. If additional tables are added to the database (by
  8788. ** executing "CREATE TABLE" statements) after this call is made, changes for
  8789. ** the new tables are also recorded.
  8790. **
  8791. ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
  8792. ** defined as part of their CREATE TABLE statement. It does not matter if the
  8793. ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
  8794. ** KEY may consist of a single column, or may be a composite key.
  8795. **
  8796. ** It is not an error if the named table does not exist in the database. Nor
  8797. ** is it an error if the named table does not have a PRIMARY KEY. However,
  8798. ** no changes will be recorded in either of these scenarios.
  8799. **
  8800. ** Changes are not recorded for individual rows that have NULL values stored
  8801. ** in one or more of their PRIMARY KEY columns.
  8802. **
  8803. ** SQLITE_OK is returned if the call completes without error. Or, if an error
  8804. ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  8805. */
  8806. SQLITE_API int sqlite3session_attach(
  8807. sqlite3_session *pSession, /* Session object */
  8808. const char *zTab /* Table name */
  8809. );
  8810. /*
  8811. ** CAPI3REF: Set a table filter on a Session Object.
  8812. **
  8813. ** The second argument (xFilter) is the "filter callback". For changes to rows
  8814. ** in tables that are not attached to the Session object, the filter is called
  8815. ** to determine whether changes to the table's rows should be tracked or not.
  8816. ** If xFilter returns 0, changes is not tracked. Note that once a table is
  8817. ** attached, xFilter will not be called again.
  8818. */
  8819. SQLITE_API void sqlite3session_table_filter(
  8820. sqlite3_session *pSession, /* Session object */
  8821. int(*xFilter)(
  8822. void *pCtx, /* Copy of third arg to _filter_table() */
  8823. const char *zTab /* Table name */
  8824. ),
  8825. void *pCtx /* First argument passed to xFilter */
  8826. );
  8827. /*
  8828. ** CAPI3REF: Generate A Changeset From A Session Object
  8829. **
  8830. ** Obtain a changeset containing changes to the tables attached to the
  8831. ** session object passed as the first argument. If successful,
  8832. ** set *ppChangeset to point to a buffer containing the changeset
  8833. ** and *pnChangeset to the size of the changeset in bytes before returning
  8834. ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
  8835. ** zero and return an SQLite error code.
  8836. **
  8837. ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
  8838. ** each representing a change to a single row of an attached table. An INSERT
  8839. ** change contains the values of each field of a new database row. A DELETE
  8840. ** contains the original values of each field of a deleted database row. An
  8841. ** UPDATE change contains the original values of each field of an updated
  8842. ** database row along with the updated values for each updated non-primary-key
  8843. ** column. It is not possible for an UPDATE change to represent a change that
  8844. ** modifies the values of primary key columns. If such a change is made, it
  8845. ** is represented in a changeset as a DELETE followed by an INSERT.
  8846. **
  8847. ** Changes are not recorded for rows that have NULL values stored in one or
  8848. ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
  8849. ** no corresponding change is present in the changesets returned by this
  8850. ** function. If an existing row with one or more NULL values stored in
  8851. ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
  8852. ** only an INSERT is appears in the changeset. Similarly, if an existing row
  8853. ** with non-NULL PRIMARY KEY values is updated so that one or more of its
  8854. ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
  8855. ** DELETE change only.
  8856. **
  8857. ** The contents of a changeset may be traversed using an iterator created
  8858. ** using the [sqlite3changeset_start()] API. A changeset may be applied to
  8859. ** a database with a compatible schema using the [sqlite3changeset_apply()]
  8860. ** API.
  8861. **
  8862. ** Within a changeset generated by this function, all changes related to a
  8863. ** single table are grouped together. In other words, when iterating through
  8864. ** a changeset or when applying a changeset to a database, all changes related
  8865. ** to a single table are processed before moving on to the next table. Tables
  8866. ** are sorted in the same order in which they were attached (or auto-attached)
  8867. ** to the sqlite3_session object. The order in which the changes related to
  8868. ** a single table are stored is undefined.
  8869. **
  8870. ** Following a successful call to this function, it is the responsibility of
  8871. ** the caller to eventually free the buffer that *ppChangeset points to using
  8872. ** [sqlite3_free()].
  8873. **
  8874. ** <h3>Changeset Generation</h3>
  8875. **
  8876. ** Once a table has been attached to a session object, the session object
  8877. ** records the primary key values of all new rows inserted into the table.
  8878. ** It also records the original primary key and other column values of any
  8879. ** deleted or updated rows. For each unique primary key value, data is only
  8880. ** recorded once - the first time a row with said primary key is inserted,
  8881. ** updated or deleted in the lifetime of the session.
  8882. **
  8883. ** There is one exception to the previous paragraph: when a row is inserted,
  8884. ** updated or deleted, if one or more of its primary key columns contain a
  8885. ** NULL value, no record of the change is made.
  8886. **
  8887. ** The session object therefore accumulates two types of records - those
  8888. ** that consist of primary key values only (created when the user inserts
  8889. ** a new record) and those that consist of the primary key values and the
  8890. ** original values of other table columns (created when the users deletes
  8891. ** or updates a record).
  8892. **
  8893. ** When this function is called, the requested changeset is created using
  8894. ** both the accumulated records and the current contents of the database
  8895. ** file. Specifically:
  8896. **
  8897. ** <ul>
  8898. ** <li> For each record generated by an insert, the database is queried
  8899. ** for a row with a matching primary key. If one is found, an INSERT
  8900. ** change is added to the changeset. If no such row is found, no change
  8901. ** is added to the changeset.
  8902. **
  8903. ** <li> For each record generated by an update or delete, the database is
  8904. ** queried for a row with a matching primary key. If such a row is
  8905. ** found and one or more of the non-primary key fields have been
  8906. ** modified from their original values, an UPDATE change is added to
  8907. ** the changeset. Or, if no such row is found in the table, a DELETE
  8908. ** change is added to the changeset. If there is a row with a matching
  8909. ** primary key in the database, but all fields contain their original
  8910. ** values, no change is added to the changeset.
  8911. ** </ul>
  8912. **
  8913. ** This means, amongst other things, that if a row is inserted and then later
  8914. ** deleted while a session object is active, neither the insert nor the delete
  8915. ** will be present in the changeset. Or if a row is deleted and then later a
  8916. ** row with the same primary key values inserted while a session object is
  8917. ** active, the resulting changeset will contain an UPDATE change instead of
  8918. ** a DELETE and an INSERT.
  8919. **
  8920. ** When a session object is disabled (see the [sqlite3session_enable()] API),
  8921. ** it does not accumulate records when rows are inserted, updated or deleted.
  8922. ** This may appear to have some counter-intuitive effects if a single row
  8923. ** is written to more than once during a session. For example, if a row
  8924. ** is inserted while a session object is enabled, then later deleted while
  8925. ** the same session object is disabled, no INSERT record will appear in the
  8926. ** changeset, even though the delete took place while the session was disabled.
  8927. ** Or, if one field of a row is updated while a session is disabled, and
  8928. ** another field of the same row is updated while the session is enabled, the
  8929. ** resulting changeset will contain an UPDATE change that updates both fields.
  8930. */
  8931. SQLITE_API int sqlite3session_changeset(
  8932. sqlite3_session *pSession, /* Session object */
  8933. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  8934. void **ppChangeset /* OUT: Buffer containing changeset */
  8935. );
  8936. /*
  8937. ** CAPI3REF: Load The Difference Between Tables Into A Session
  8938. **
  8939. ** If it is not already attached to the session object passed as the first
  8940. ** argument, this function attaches table zTbl in the same manner as the
  8941. ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
  8942. ** does not have a primary key, this function is a no-op (but does not return
  8943. ** an error).
  8944. **
  8945. ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
  8946. ** attached to the same database handle as the session object that contains
  8947. ** a table compatible with the table attached to the session by this function.
  8948. ** A table is considered compatible if it:
  8949. **
  8950. ** <ul>
  8951. ** <li> Has the same name,
  8952. ** <li> Has the same set of columns declared in the same order, and
  8953. ** <li> Has the same PRIMARY KEY definition.
  8954. ** </ul>
  8955. **
  8956. ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
  8957. ** are compatible but do not have any PRIMARY KEY columns, it is not an error
  8958. ** but no changes are added to the session object. As with other session
  8959. ** APIs, tables without PRIMARY KEYs are simply ignored.
  8960. **
  8961. ** This function adds a set of changes to the session object that could be
  8962. ** used to update the table in database zFrom (call this the "from-table")
  8963. ** so that its content is the same as the table attached to the session
  8964. ** object (call this the "to-table"). Specifically:
  8965. **
  8966. ** <ul>
  8967. ** <li> For each row (primary key) that exists in the to-table but not in
  8968. ** the from-table, an INSERT record is added to the session object.
  8969. **
  8970. ** <li> For each row (primary key) that exists in the to-table but not in
  8971. ** the from-table, a DELETE record is added to the session object.
  8972. **
  8973. ** <li> For each row (primary key) that exists in both tables, but features
  8974. ** different non-PK values in each, an UPDATE record is added to the
  8975. ** session.
  8976. ** </ul>
  8977. **
  8978. ** To clarify, if this function is called and then a changeset constructed
  8979. ** using [sqlite3session_changeset()], then after applying that changeset to
  8980. ** database zFrom the contents of the two compatible tables would be
  8981. ** identical.
  8982. **
  8983. ** It an error if database zFrom does not exist or does not contain the
  8984. ** required compatible table.
  8985. **
  8986. ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
  8987. ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
  8988. ** may be set to point to a buffer containing an English language error
  8989. ** message. It is the responsibility of the caller to free this buffer using
  8990. ** sqlite3_free().
  8991. */
  8992. SQLITE_API int sqlite3session_diff(
  8993. sqlite3_session *pSession,
  8994. const char *zFromDb,
  8995. const char *zTbl,
  8996. char **pzErrMsg
  8997. );
  8998. /*
  8999. ** CAPI3REF: Generate A Patchset From A Session Object
  9000. **
  9001. ** The differences between a patchset and a changeset are that:
  9002. **
  9003. ** <ul>
  9004. ** <li> DELETE records consist of the primary key fields only. The
  9005. ** original values of other fields are omitted.
  9006. ** <li> The original values of any modified fields are omitted from
  9007. ** UPDATE records.
  9008. ** </ul>
  9009. **
  9010. ** A patchset blob may be used with up to date versions of all
  9011. ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
  9012. ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
  9013. ** attempting to use a patchset blob with old versions of the
  9014. ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
  9015. **
  9016. ** Because the non-primary key "old.*" fields are omitted, no
  9017. ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
  9018. ** is passed to the sqlite3changeset_apply() API. Other conflict types work
  9019. ** in the same way as for changesets.
  9020. **
  9021. ** Changes within a patchset are ordered in the same way as for changesets
  9022. ** generated by the sqlite3session_changeset() function (i.e. all changes for
  9023. ** a single table are grouped together, tables appear in the order in which
  9024. ** they were attached to the session object).
  9025. */
  9026. SQLITE_API int sqlite3session_patchset(
  9027. sqlite3_session *pSession, /* Session object */
  9028. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  9029. void **ppPatchset /* OUT: Buffer containing changeset */
  9030. );
  9031. /*
  9032. ** CAPI3REF: Test if a changeset has recorded any changes.
  9033. **
  9034. ** Return non-zero if no changes to attached tables have been recorded by
  9035. ** the session object passed as the first argument. Otherwise, if one or
  9036. ** more changes have been recorded, return zero.
  9037. **
  9038. ** Even if this function returns zero, it is possible that calling
  9039. ** [sqlite3session_changeset()] on the session handle may still return a
  9040. ** changeset that contains no changes. This can happen when a row in
  9041. ** an attached table is modified and then later on the original values
  9042. ** are restored. However, if this function returns non-zero, then it is
  9043. ** guaranteed that a call to sqlite3session_changeset() will return a
  9044. ** changeset containing zero changes.
  9045. */
  9046. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
  9047. /*
  9048. ** CAPI3REF: Create An Iterator To Traverse A Changeset
  9049. **
  9050. ** Create an iterator used to iterate through the contents of a changeset.
  9051. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
  9052. ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
  9053. ** SQLite error code is returned.
  9054. **
  9055. ** The following functions can be used to advance and query a changeset
  9056. ** iterator created by this function:
  9057. **
  9058. ** <ul>
  9059. ** <li> [sqlite3changeset_next()]
  9060. ** <li> [sqlite3changeset_op()]
  9061. ** <li> [sqlite3changeset_new()]
  9062. ** <li> [sqlite3changeset_old()]
  9063. ** </ul>
  9064. **
  9065. ** It is the responsibility of the caller to eventually destroy the iterator
  9066. ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
  9067. ** changeset (pChangeset) must remain valid until after the iterator is
  9068. ** destroyed.
  9069. **
  9070. ** Assuming the changeset blob was created by one of the
  9071. ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
  9072. ** [sqlite3changeset_invert()] functions, all changes within the changeset
  9073. ** that apply to a single table are grouped together. This means that when
  9074. ** an application iterates through a changeset using an iterator created by
  9075. ** this function, all changes that relate to a single table are visited
  9076. ** consecutively. There is no chance that the iterator will visit a change
  9077. ** the applies to table X, then one for table Y, and then later on visit
  9078. ** another change for table X.
  9079. */
  9080. SQLITE_API int sqlite3changeset_start(
  9081. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  9082. int nChangeset, /* Size of changeset blob in bytes */
  9083. void *pChangeset /* Pointer to blob containing changeset */
  9084. );
  9085. /*
  9086. ** CAPI3REF: Advance A Changeset Iterator
  9087. **
  9088. ** This function may only be used with iterators created by function
  9089. ** [sqlite3changeset_start()]. If it is called on an iterator passed to
  9090. ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
  9091. ** is returned and the call has no effect.
  9092. **
  9093. ** Immediately after an iterator is created by sqlite3changeset_start(), it
  9094. ** does not point to any change in the changeset. Assuming the changeset
  9095. ** is not empty, the first call to this function advances the iterator to
  9096. ** point to the first change in the changeset. Each subsequent call advances
  9097. ** the iterator to point to the next change in the changeset (if any). If
  9098. ** no error occurs and the iterator points to a valid change after a call
  9099. ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
  9100. ** Otherwise, if all changes in the changeset have already been visited,
  9101. ** SQLITE_DONE is returned.
  9102. **
  9103. ** If an error occurs, an SQLite error code is returned. Possible error
  9104. ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
  9105. ** SQLITE_NOMEM.
  9106. */
  9107. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
  9108. /*
  9109. ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
  9110. **
  9111. ** The pIter argument passed to this function may either be an iterator
  9112. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  9113. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  9114. ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
  9115. ** is not the case, this function returns [SQLITE_MISUSE].
  9116. **
  9117. ** If argument pzTab is not NULL, then *pzTab is set to point to a
  9118. ** nul-terminated utf-8 encoded string containing the name of the table
  9119. ** affected by the current change. The buffer remains valid until either
  9120. ** sqlite3changeset_next() is called on the iterator or until the
  9121. ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
  9122. ** set to the number of columns in the table affected by the change. If
  9123. ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
  9124. ** is an indirect change, or false (0) otherwise. See the documentation for
  9125. ** [sqlite3session_indirect()] for a description of direct and indirect
  9126. ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
  9127. ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
  9128. ** type of change that the iterator currently points to.
  9129. **
  9130. ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
  9131. ** SQLite error code is returned. The values of the output variables may not
  9132. ** be trusted in this case.
  9133. */
  9134. SQLITE_API int sqlite3changeset_op(
  9135. sqlite3_changeset_iter *pIter, /* Iterator object */
  9136. const char **pzTab, /* OUT: Pointer to table name */
  9137. int *pnCol, /* OUT: Number of columns in table */
  9138. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  9139. int *pbIndirect /* OUT: True for an 'indirect' change */
  9140. );
  9141. /*
  9142. ** CAPI3REF: Obtain The Primary Key Definition Of A Table
  9143. **
  9144. ** For each modified table, a changeset includes the following:
  9145. **
  9146. ** <ul>
  9147. ** <li> The number of columns in the table, and
  9148. ** <li> Which of those columns make up the tables PRIMARY KEY.
  9149. ** </ul>
  9150. **
  9151. ** This function is used to find which columns comprise the PRIMARY KEY of
  9152. ** the table modified by the change that iterator pIter currently points to.
  9153. ** If successful, *pabPK is set to point to an array of nCol entries, where
  9154. ** nCol is the number of columns in the table. Elements of *pabPK are set to
  9155. ** 0x01 if the corresponding column is part of the tables primary key, or
  9156. ** 0x00 if it is not.
  9157. **
  9158. ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
  9159. ** in the table.
  9160. **
  9161. ** If this function is called when the iterator does not point to a valid
  9162. ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
  9163. ** SQLITE_OK is returned and the output variables populated as described
  9164. ** above.
  9165. */
  9166. SQLITE_API int sqlite3changeset_pk(
  9167. sqlite3_changeset_iter *pIter, /* Iterator object */
  9168. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  9169. int *pnCol /* OUT: Number of entries in output array */
  9170. );
  9171. /*
  9172. ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
  9173. **
  9174. ** The pIter argument passed to this function may either be an iterator
  9175. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  9176. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  9177. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  9178. ** Furthermore, it may only be called if the type of change that the iterator
  9179. ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
  9180. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  9181. **
  9182. ** Argument iVal must be greater than or equal to 0, and less than the number
  9183. ** of columns in the table affected by the current change. Otherwise,
  9184. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  9185. **
  9186. ** If successful, this function sets *ppValue to point to a protected
  9187. ** sqlite3_value object containing the iVal'th value from the vector of
  9188. ** original row values stored as part of the UPDATE or DELETE change and
  9189. ** returns SQLITE_OK. The name of the function comes from the fact that this
  9190. ** is similar to the "old.*" columns available to update or delete triggers.
  9191. **
  9192. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  9193. ** is returned and *ppValue is set to NULL.
  9194. */
  9195. SQLITE_API int sqlite3changeset_old(
  9196. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  9197. int iVal, /* Column number */
  9198. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  9199. );
  9200. /*
  9201. ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
  9202. **
  9203. ** The pIter argument passed to this function may either be an iterator
  9204. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  9205. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  9206. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  9207. ** Furthermore, it may only be called if the type of change that the iterator
  9208. ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
  9209. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  9210. **
  9211. ** Argument iVal must be greater than or equal to 0, and less than the number
  9212. ** of columns in the table affected by the current change. Otherwise,
  9213. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  9214. **
  9215. ** If successful, this function sets *ppValue to point to a protected
  9216. ** sqlite3_value object containing the iVal'th value from the vector of
  9217. ** new row values stored as part of the UPDATE or INSERT change and
  9218. ** returns SQLITE_OK. If the change is an UPDATE and does not include
  9219. ** a new value for the requested column, *ppValue is set to NULL and
  9220. ** SQLITE_OK returned. The name of the function comes from the fact that
  9221. ** this is similar to the "new.*" columns available to update or delete
  9222. ** triggers.
  9223. **
  9224. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  9225. ** is returned and *ppValue is set to NULL.
  9226. */
  9227. SQLITE_API int sqlite3changeset_new(
  9228. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  9229. int iVal, /* Column number */
  9230. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  9231. );
  9232. /*
  9233. ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
  9234. **
  9235. ** This function should only be used with iterator objects passed to a
  9236. ** conflict-handler callback by [sqlite3changeset_apply()] with either
  9237. ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
  9238. ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
  9239. ** is set to NULL.
  9240. **
  9241. ** Argument iVal must be greater than or equal to 0, and less than the number
  9242. ** of columns in the table affected by the current change. Otherwise,
  9243. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  9244. **
  9245. ** If successful, this function sets *ppValue to point to a protected
  9246. ** sqlite3_value object containing the iVal'th value from the
  9247. ** "conflicting row" associated with the current conflict-handler callback
  9248. ** and returns SQLITE_OK.
  9249. **
  9250. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  9251. ** is returned and *ppValue is set to NULL.
  9252. */
  9253. SQLITE_API int sqlite3changeset_conflict(
  9254. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  9255. int iVal, /* Column number */
  9256. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  9257. );
  9258. /*
  9259. ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
  9260. **
  9261. ** This function may only be called with an iterator passed to an
  9262. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  9263. ** it sets the output variable to the total number of known foreign key
  9264. ** violations in the destination database and returns SQLITE_OK.
  9265. **
  9266. ** In all other cases this function returns SQLITE_MISUSE.
  9267. */
  9268. SQLITE_API int sqlite3changeset_fk_conflicts(
  9269. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  9270. int *pnOut /* OUT: Number of FK violations */
  9271. );
  9272. /*
  9273. ** CAPI3REF: Finalize A Changeset Iterator
  9274. **
  9275. ** This function is used to finalize an iterator allocated with
  9276. ** [sqlite3changeset_start()].
  9277. **
  9278. ** This function should only be called on iterators created using the
  9279. ** [sqlite3changeset_start()] function. If an application calls this
  9280. ** function with an iterator passed to a conflict-handler by
  9281. ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
  9282. ** call has no effect.
  9283. **
  9284. ** If an error was encountered within a call to an sqlite3changeset_xxx()
  9285. ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
  9286. ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
  9287. ** to that error is returned by this function. Otherwise, SQLITE_OK is
  9288. ** returned. This is to allow the following pattern (pseudo-code):
  9289. **
  9290. ** sqlite3changeset_start();
  9291. ** while( SQLITE_ROW==sqlite3changeset_next() ){
  9292. ** // Do something with change.
  9293. ** }
  9294. ** rc = sqlite3changeset_finalize();
  9295. ** if( rc!=SQLITE_OK ){
  9296. ** // An error has occurred
  9297. ** }
  9298. */
  9299. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
  9300. /*
  9301. ** CAPI3REF: Invert A Changeset
  9302. **
  9303. ** This function is used to "invert" a changeset object. Applying an inverted
  9304. ** changeset to a database reverses the effects of applying the uninverted
  9305. ** changeset. Specifically:
  9306. **
  9307. ** <ul>
  9308. ** <li> Each DELETE change is changed to an INSERT, and
  9309. ** <li> Each INSERT change is changed to a DELETE, and
  9310. ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
  9311. ** </ul>
  9312. **
  9313. ** This function does not change the order in which changes appear within
  9314. ** the changeset. It merely reverses the sense of each individual change.
  9315. **
  9316. ** If successful, a pointer to a buffer containing the inverted changeset
  9317. ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
  9318. ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
  9319. ** zeroed and an SQLite error code returned.
  9320. **
  9321. ** It is the responsibility of the caller to eventually call sqlite3_free()
  9322. ** on the *ppOut pointer to free the buffer allocation following a successful
  9323. ** call to this function.
  9324. **
  9325. ** WARNING/TODO: This function currently assumes that the input is a valid
  9326. ** changeset. If it is not, the results are undefined.
  9327. */
  9328. SQLITE_API int sqlite3changeset_invert(
  9329. int nIn, const void *pIn, /* Input changeset */
  9330. int *pnOut, void **ppOut /* OUT: Inverse of input */
  9331. );
  9332. /*
  9333. ** CAPI3REF: Concatenate Two Changeset Objects
  9334. **
  9335. ** This function is used to concatenate two changesets, A and B, into a
  9336. ** single changeset. The result is a changeset equivalent to applying
  9337. ** changeset A followed by changeset B.
  9338. **
  9339. ** This function combines the two input changesets using an
  9340. ** sqlite3_changegroup object. Calling it produces similar results as the
  9341. ** following code fragment:
  9342. **
  9343. ** sqlite3_changegroup *pGrp;
  9344. ** rc = sqlite3_changegroup_new(&pGrp);
  9345. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
  9346. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
  9347. ** if( rc==SQLITE_OK ){
  9348. ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  9349. ** }else{
  9350. ** *ppOut = 0;
  9351. ** *pnOut = 0;
  9352. ** }
  9353. **
  9354. ** Refer to the sqlite3_changegroup documentation below for details.
  9355. */
  9356. SQLITE_API int sqlite3changeset_concat(
  9357. int nA, /* Number of bytes in buffer pA */
  9358. void *pA, /* Pointer to buffer containing changeset A */
  9359. int nB, /* Number of bytes in buffer pB */
  9360. void *pB, /* Pointer to buffer containing changeset B */
  9361. int *pnOut, /* OUT: Number of bytes in output changeset */
  9362. void **ppOut /* OUT: Buffer containing output changeset */
  9363. );
  9364. /*
  9365. ** CAPI3REF: Changegroup Handle
  9366. */
  9367. typedef struct sqlite3_changegroup sqlite3_changegroup;
  9368. /*
  9369. ** CAPI3REF: Create A New Changegroup Object
  9370. **
  9371. ** An sqlite3_changegroup object is used to combine two or more changesets
  9372. ** (or patchsets) into a single changeset (or patchset). A single changegroup
  9373. ** object may combine changesets or patchsets, but not both. The output is
  9374. ** always in the same format as the input.
  9375. **
  9376. ** If successful, this function returns SQLITE_OK and populates (*pp) with
  9377. ** a pointer to a new sqlite3_changegroup object before returning. The caller
  9378. ** should eventually free the returned object using a call to
  9379. ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
  9380. ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
  9381. **
  9382. ** The usual usage pattern for an sqlite3_changegroup object is as follows:
  9383. **
  9384. ** <ul>
  9385. ** <li> It is created using a call to sqlite3changegroup_new().
  9386. **
  9387. ** <li> Zero or more changesets (or patchsets) are added to the object
  9388. ** by calling sqlite3changegroup_add().
  9389. **
  9390. ** <li> The result of combining all input changesets together is obtained
  9391. ** by the application via a call to sqlite3changegroup_output().
  9392. **
  9393. ** <li> The object is deleted using a call to sqlite3changegroup_delete().
  9394. ** </ul>
  9395. **
  9396. ** Any number of calls to add() and output() may be made between the calls to
  9397. ** new() and delete(), and in any order.
  9398. **
  9399. ** As well as the regular sqlite3changegroup_add() and
  9400. ** sqlite3changegroup_output() functions, also available are the streaming
  9401. ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
  9402. */
  9403. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
  9404. /*
  9405. ** CAPI3REF: Add A Changeset To A Changegroup
  9406. **
  9407. ** Add all changes within the changeset (or patchset) in buffer pData (size
  9408. ** nData bytes) to the changegroup.
  9409. **
  9410. ** If the buffer contains a patchset, then all prior calls to this function
  9411. ** on the same changegroup object must also have specified patchsets. Or, if
  9412. ** the buffer contains a changeset, so must have the earlier calls to this
  9413. ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
  9414. ** to the changegroup.
  9415. **
  9416. ** Rows within the changeset and changegroup are identified by the values in
  9417. ** their PRIMARY KEY columns. A change in the changeset is considered to
  9418. ** apply to the same row as a change already present in the changegroup if
  9419. ** the two rows have the same primary key.
  9420. **
  9421. ** Changes to rows that do not already appear in the changegroup are
  9422. ** simply copied into it. Or, if both the new changeset and the changegroup
  9423. ** contain changes that apply to a single row, the final contents of the
  9424. ** changegroup depends on the type of each change, as follows:
  9425. **
  9426. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  9427. ** <tr><th style="white-space:pre">Existing Change </th>
  9428. ** <th style="white-space:pre">New Change </th>
  9429. ** <th>Output Change
  9430. ** <tr><td>INSERT <td>INSERT <td>
  9431. ** The new change is ignored. This case does not occur if the new
  9432. ** changeset was recorded immediately after the changesets already
  9433. ** added to the changegroup.
  9434. ** <tr><td>INSERT <td>UPDATE <td>
  9435. ** The INSERT change remains in the changegroup. The values in the
  9436. ** INSERT change are modified as if the row was inserted by the
  9437. ** existing change and then updated according to the new change.
  9438. ** <tr><td>INSERT <td>DELETE <td>
  9439. ** The existing INSERT is removed from the changegroup. The DELETE is
  9440. ** not added.
  9441. ** <tr><td>UPDATE <td>INSERT <td>
  9442. ** The new change is ignored. This case does not occur if the new
  9443. ** changeset was recorded immediately after the changesets already
  9444. ** added to the changegroup.
  9445. ** <tr><td>UPDATE <td>UPDATE <td>
  9446. ** The existing UPDATE remains within the changegroup. It is amended
  9447. ** so that the accompanying values are as if the row was updated once
  9448. ** by the existing change and then again by the new change.
  9449. ** <tr><td>UPDATE <td>DELETE <td>
  9450. ** The existing UPDATE is replaced by the new DELETE within the
  9451. ** changegroup.
  9452. ** <tr><td>DELETE <td>INSERT <td>
  9453. ** If one or more of the column values in the row inserted by the
  9454. ** new change differ from those in the row deleted by the existing
  9455. ** change, the existing DELETE is replaced by an UPDATE within the
  9456. ** changegroup. Otherwise, if the inserted row is exactly the same
  9457. ** as the deleted row, the existing DELETE is simply discarded.
  9458. ** <tr><td>DELETE <td>UPDATE <td>
  9459. ** The new change is ignored. This case does not occur if the new
  9460. ** changeset was recorded immediately after the changesets already
  9461. ** added to the changegroup.
  9462. ** <tr><td>DELETE <td>DELETE <td>
  9463. ** The new change is ignored. This case does not occur if the new
  9464. ** changeset was recorded immediately after the changesets already
  9465. ** added to the changegroup.
  9466. ** </table>
  9467. **
  9468. ** If the new changeset contains changes to a table that is already present
  9469. ** in the changegroup, then the number of columns and the position of the
  9470. ** primary key columns for the table must be consistent. If this is not the
  9471. ** case, this function fails with SQLITE_SCHEMA. If the input changeset
  9472. ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
  9473. ** returned. Or, if an out-of-memory condition occurs during processing, this
  9474. ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
  9475. ** final contents of the changegroup is undefined.
  9476. **
  9477. ** If no error occurs, SQLITE_OK is returned.
  9478. */
  9479. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
  9480. /*
  9481. ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
  9482. **
  9483. ** Obtain a buffer containing a changeset (or patchset) representing the
  9484. ** current contents of the changegroup. If the inputs to the changegroup
  9485. ** were themselves changesets, the output is a changeset. Or, if the
  9486. ** inputs were patchsets, the output is also a patchset.
  9487. **
  9488. ** As with the output of the sqlite3session_changeset() and
  9489. ** sqlite3session_patchset() functions, all changes related to a single
  9490. ** table are grouped together in the output of this function. Tables appear
  9491. ** in the same order as for the very first changeset added to the changegroup.
  9492. ** If the second or subsequent changesets added to the changegroup contain
  9493. ** changes for tables that do not appear in the first changeset, they are
  9494. ** appended onto the end of the output changeset, again in the order in
  9495. ** which they are first encountered.
  9496. **
  9497. ** If an error occurs, an SQLite error code is returned and the output
  9498. ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
  9499. ** is returned and the output variables are set to the size of and a
  9500. ** pointer to the output buffer, respectively. In this case it is the
  9501. ** responsibility of the caller to eventually free the buffer using a
  9502. ** call to sqlite3_free().
  9503. */
  9504. SQLITE_API int sqlite3changegroup_output(
  9505. sqlite3_changegroup*,
  9506. int *pnData, /* OUT: Size of output buffer in bytes */
  9507. void **ppData /* OUT: Pointer to output buffer */
  9508. );
  9509. /*
  9510. ** CAPI3REF: Delete A Changegroup Object
  9511. */
  9512. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
  9513. /*
  9514. ** CAPI3REF: Apply A Changeset To A Database
  9515. **
  9516. ** Apply a changeset to a database. This function attempts to update the
  9517. ** "main" database attached to handle db with the changes found in the
  9518. ** changeset passed via the second and third arguments.
  9519. **
  9520. ** The fourth argument (xFilter) passed to this function is the "filter
  9521. ** callback". If it is not NULL, then for each table affected by at least one
  9522. ** change in the changeset, the filter callback is invoked with
  9523. ** the table name as the second argument, and a copy of the context pointer
  9524. ** passed as the sixth argument to this function as the first. If the "filter
  9525. ** callback" returns zero, then no attempt is made to apply any changes to
  9526. ** the table. Otherwise, if the return value is non-zero or the xFilter
  9527. ** argument to this function is NULL, all changes related to the table are
  9528. ** attempted.
  9529. **
  9530. ** For each table that is not excluded by the filter callback, this function
  9531. ** tests that the target database contains a compatible table. A table is
  9532. ** considered compatible if all of the following are true:
  9533. **
  9534. ** <ul>
  9535. ** <li> The table has the same name as the name recorded in the
  9536. ** changeset, and
  9537. ** <li> The table has at least as many columns as recorded in the
  9538. ** changeset, and
  9539. ** <li> The table has primary key columns in the same position as
  9540. ** recorded in the changeset.
  9541. ** </ul>
  9542. **
  9543. ** If there is no compatible table, it is not an error, but none of the
  9544. ** changes associated with the table are applied. A warning message is issued
  9545. ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
  9546. ** one such warning is issued for each table in the changeset.
  9547. **
  9548. ** For each change for which there is a compatible table, an attempt is made
  9549. ** to modify the table contents according to the UPDATE, INSERT or DELETE
  9550. ** change. If a change cannot be applied cleanly, the conflict handler
  9551. ** function passed as the fifth argument to sqlite3changeset_apply() may be
  9552. ** invoked. A description of exactly when the conflict handler is invoked for
  9553. ** each type of change is below.
  9554. **
  9555. ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
  9556. ** of passing anything other than a valid function pointer as the xConflict
  9557. ** argument are undefined.
  9558. **
  9559. ** Each time the conflict handler function is invoked, it must return one
  9560. ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
  9561. ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
  9562. ** if the second argument passed to the conflict handler is either
  9563. ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
  9564. ** returns an illegal value, any changes already made are rolled back and
  9565. ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
  9566. ** actions are taken by sqlite3changeset_apply() depending on the value
  9567. ** returned by each invocation of the conflict-handler function. Refer to
  9568. ** the documentation for the three
  9569. ** [SQLITE_CHANGESET_OMIT|available return values] for details.
  9570. **
  9571. ** <dl>
  9572. ** <dt>DELETE Changes<dd>
  9573. ** For each DELETE change, this function checks if the target database
  9574. ** contains a row with the same primary key value (or values) as the
  9575. ** original row values stored in the changeset. If it does, and the values
  9576. ** stored in all non-primary key columns also match the values stored in
  9577. ** the changeset the row is deleted from the target database.
  9578. **
  9579. ** If a row with matching primary key values is found, but one or more of
  9580. ** the non-primary key fields contains a value different from the original
  9581. ** row value stored in the changeset, the conflict-handler function is
  9582. ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
  9583. ** database table has more columns than are recorded in the changeset,
  9584. ** only the values of those non-primary key fields are compared against
  9585. ** the current database contents - any trailing database table columns
  9586. ** are ignored.
  9587. **
  9588. ** If no row with matching primary key values is found in the database,
  9589. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  9590. ** passed as the second argument.
  9591. **
  9592. ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
  9593. ** (which can only happen if a foreign key constraint is violated), the
  9594. ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
  9595. ** passed as the second argument. This includes the case where the DELETE
  9596. ** operation is attempted because an earlier call to the conflict handler
  9597. ** function returned [SQLITE_CHANGESET_REPLACE].
  9598. **
  9599. ** <dt>INSERT Changes<dd>
  9600. ** For each INSERT change, an attempt is made to insert the new row into
  9601. ** the database. If the changeset row contains fewer fields than the
  9602. ** database table, the trailing fields are populated with their default
  9603. ** values.
  9604. **
  9605. ** If the attempt to insert the row fails because the database already
  9606. ** contains a row with the same primary key values, the conflict handler
  9607. ** function is invoked with the second argument set to
  9608. ** [SQLITE_CHANGESET_CONFLICT].
  9609. **
  9610. ** If the attempt to insert the row fails because of some other constraint
  9611. ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
  9612. ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
  9613. ** This includes the case where the INSERT operation is re-attempted because
  9614. ** an earlier call to the conflict handler function returned
  9615. ** [SQLITE_CHANGESET_REPLACE].
  9616. **
  9617. ** <dt>UPDATE Changes<dd>
  9618. ** For each UPDATE change, this function checks if the target database
  9619. ** contains a row with the same primary key value (or values) as the
  9620. ** original row values stored in the changeset. If it does, and the values
  9621. ** stored in all modified non-primary key columns also match the values
  9622. ** stored in the changeset the row is updated within the target database.
  9623. **
  9624. ** If a row with matching primary key values is found, but one or more of
  9625. ** the modified non-primary key fields contains a value different from an
  9626. ** original row value stored in the changeset, the conflict-handler function
  9627. ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
  9628. ** UPDATE changes only contain values for non-primary key fields that are
  9629. ** to be modified, only those fields need to match the original values to
  9630. ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
  9631. **
  9632. ** If no row with matching primary key values is found in the database,
  9633. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  9634. ** passed as the second argument.
  9635. **
  9636. ** If the UPDATE operation is attempted, but SQLite returns
  9637. ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
  9638. ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
  9639. ** This includes the case where the UPDATE operation is attempted after
  9640. ** an earlier call to the conflict handler function returned
  9641. ** [SQLITE_CHANGESET_REPLACE].
  9642. ** </dl>
  9643. **
  9644. ** It is safe to execute SQL statements, including those that write to the
  9645. ** table that the callback related to, from within the xConflict callback.
  9646. ** This can be used to further customize the applications conflict
  9647. ** resolution strategy.
  9648. **
  9649. ** All changes made by this function are enclosed in a savepoint transaction.
  9650. ** If any other error (aside from a constraint failure when attempting to
  9651. ** write to the target database) occurs, then the savepoint transaction is
  9652. ** rolled back, restoring the target database to its original state, and an
  9653. ** SQLite error code returned.
  9654. */
  9655. SQLITE_API int sqlite3changeset_apply(
  9656. sqlite3 *db, /* Apply change to "main" db of this handle */
  9657. int nChangeset, /* Size of changeset in bytes */
  9658. void *pChangeset, /* Changeset blob */
  9659. int(*xFilter)(
  9660. void *pCtx, /* Copy of sixth arg to _apply() */
  9661. const char *zTab /* Table name */
  9662. ),
  9663. int(*xConflict)(
  9664. void *pCtx, /* Copy of sixth arg to _apply() */
  9665. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  9666. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  9667. ),
  9668. void *pCtx /* First argument passed to xConflict */
  9669. );
  9670. /*
  9671. ** CAPI3REF: Constants Passed To The Conflict Handler
  9672. **
  9673. ** Values that may be passed as the second argument to a conflict-handler.
  9674. **
  9675. ** <dl>
  9676. ** <dt>SQLITE_CHANGESET_DATA<dd>
  9677. ** The conflict handler is invoked with CHANGESET_DATA as the second argument
  9678. ** when processing a DELETE or UPDATE change if a row with the required
  9679. ** PRIMARY KEY fields is present in the database, but one or more other
  9680. ** (non primary-key) fields modified by the update do not contain the
  9681. ** expected "before" values.
  9682. **
  9683. ** The conflicting row, in this case, is the database row with the matching
  9684. ** primary key.
  9685. **
  9686. ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
  9687. ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
  9688. ** argument when processing a DELETE or UPDATE change if a row with the
  9689. ** required PRIMARY KEY fields is not present in the database.
  9690. **
  9691. ** There is no conflicting row in this case. The results of invoking the
  9692. ** sqlite3changeset_conflict() API are undefined.
  9693. **
  9694. ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
  9695. ** CHANGESET_CONFLICT is passed as the second argument to the conflict
  9696. ** handler while processing an INSERT change if the operation would result
  9697. ** in duplicate primary key values.
  9698. **
  9699. ** The conflicting row in this case is the database row with the matching
  9700. ** primary key.
  9701. **
  9702. ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
  9703. ** If foreign key handling is enabled, and applying a changeset leaves the
  9704. ** database in a state containing foreign key violations, the conflict
  9705. ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
  9706. ** exactly once before the changeset is committed. If the conflict handler
  9707. ** returns CHANGESET_OMIT, the changes, including those that caused the
  9708. ** foreign key constraint violation, are committed. Or, if it returns
  9709. ** CHANGESET_ABORT, the changeset is rolled back.
  9710. **
  9711. ** No current or conflicting row information is provided. The only function
  9712. ** it is possible to call on the supplied sqlite3_changeset_iter handle
  9713. ** is sqlite3changeset_fk_conflicts().
  9714. **
  9715. ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
  9716. ** If any other constraint violation occurs while applying a change (i.e.
  9717. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
  9718. ** invoked with CHANGESET_CONSTRAINT as the second argument.
  9719. **
  9720. ** There is no conflicting row in this case. The results of invoking the
  9721. ** sqlite3changeset_conflict() API are undefined.
  9722. **
  9723. ** </dl>
  9724. */
  9725. #define SQLITE_CHANGESET_DATA 1
  9726. #define SQLITE_CHANGESET_NOTFOUND 2
  9727. #define SQLITE_CHANGESET_CONFLICT 3
  9728. #define SQLITE_CHANGESET_CONSTRAINT 4
  9729. #define SQLITE_CHANGESET_FOREIGN_KEY 5
  9730. /*
  9731. ** CAPI3REF: Constants Returned By The Conflict Handler
  9732. **
  9733. ** A conflict handler callback must return one of the following three values.
  9734. **
  9735. ** <dl>
  9736. ** <dt>SQLITE_CHANGESET_OMIT<dd>
  9737. ** If a conflict handler returns this value no special action is taken. The
  9738. ** change that caused the conflict is not applied. The session module
  9739. ** continues to the next change in the changeset.
  9740. **
  9741. ** <dt>SQLITE_CHANGESET_REPLACE<dd>
  9742. ** This value may only be returned if the second argument to the conflict
  9743. ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
  9744. ** is not the case, any changes applied so far are rolled back and the
  9745. ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
  9746. **
  9747. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
  9748. ** handler, then the conflicting row is either updated or deleted, depending
  9749. ** on the type of change.
  9750. **
  9751. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
  9752. ** handler, then the conflicting row is removed from the database and a
  9753. ** second attempt to apply the change is made. If this second attempt fails,
  9754. ** the original row is restored to the database before continuing.
  9755. **
  9756. ** <dt>SQLITE_CHANGESET_ABORT<dd>
  9757. ** If this value is returned, any changes applied so far are rolled back
  9758. ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
  9759. ** </dl>
  9760. */
  9761. #define SQLITE_CHANGESET_OMIT 0
  9762. #define SQLITE_CHANGESET_REPLACE 1
  9763. #define SQLITE_CHANGESET_ABORT 2
  9764. /*
  9765. ** CAPI3REF: Streaming Versions of API functions.
  9766. **
  9767. ** The six streaming API xxx_strm() functions serve similar purposes to the
  9768. ** corresponding non-streaming API functions:
  9769. **
  9770. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  9771. ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
  9772. ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
  9773. ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
  9774. ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
  9775. ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
  9776. ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
  9777. ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
  9778. ** </table>
  9779. **
  9780. ** Non-streaming functions that accept changesets (or patchsets) as input
  9781. ** require that the entire changeset be stored in a single buffer in memory.
  9782. ** Similarly, those that return a changeset or patchset do so by returning
  9783. ** a pointer to a single large buffer allocated using sqlite3_malloc().
  9784. ** Normally this is convenient. However, if an application running in a
  9785. ** low-memory environment is required to handle very large changesets, the
  9786. ** large contiguous memory allocations required can become onerous.
  9787. **
  9788. ** In order to avoid this problem, instead of a single large buffer, input
  9789. ** is passed to a streaming API functions by way of a callback function that
  9790. ** the sessions module invokes to incrementally request input data as it is
  9791. ** required. In all cases, a pair of API function parameters such as
  9792. **
  9793. ** <pre>
  9794. ** &nbsp; int nChangeset,
  9795. ** &nbsp; void *pChangeset,
  9796. ** </pre>
  9797. **
  9798. ** Is replaced by:
  9799. **
  9800. ** <pre>
  9801. ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
  9802. ** &nbsp; void *pIn,
  9803. ** </pre>
  9804. **
  9805. ** Each time the xInput callback is invoked by the sessions module, the first
  9806. ** argument passed is a copy of the supplied pIn context pointer. The second
  9807. ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
  9808. ** error occurs the xInput method should copy up to (*pnData) bytes of data
  9809. ** into the buffer and set (*pnData) to the actual number of bytes copied
  9810. ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
  9811. ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
  9812. ** error code should be returned. In all cases, if an xInput callback returns
  9813. ** an error, all processing is abandoned and the streaming API function
  9814. ** returns a copy of the error code to the caller.
  9815. **
  9816. ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
  9817. ** invoked by the sessions module at any point during the lifetime of the
  9818. ** iterator. If such an xInput callback returns an error, the iterator enters
  9819. ** an error state, whereby all subsequent calls to iterator functions
  9820. ** immediately fail with the same error code as returned by xInput.
  9821. **
  9822. ** Similarly, streaming API functions that return changesets (or patchsets)
  9823. ** return them in chunks by way of a callback function instead of via a
  9824. ** pointer to a single large buffer. In this case, a pair of parameters such
  9825. ** as:
  9826. **
  9827. ** <pre>
  9828. ** &nbsp; int *pnChangeset,
  9829. ** &nbsp; void **ppChangeset,
  9830. ** </pre>
  9831. **
  9832. ** Is replaced by:
  9833. **
  9834. ** <pre>
  9835. ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
  9836. ** &nbsp; void *pOut
  9837. ** </pre>
  9838. **
  9839. ** The xOutput callback is invoked zero or more times to return data to
  9840. ** the application. The first parameter passed to each call is a copy of the
  9841. ** pOut pointer supplied by the application. The second parameter, pData,
  9842. ** points to a buffer nData bytes in size containing the chunk of output
  9843. ** data being returned. If the xOutput callback successfully processes the
  9844. ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
  9845. ** it should return some other SQLite error code. In this case processing
  9846. ** is immediately abandoned and the streaming API function returns a copy
  9847. ** of the xOutput error code to the application.
  9848. **
  9849. ** The sessions module never invokes an xOutput callback with the third
  9850. ** parameter set to a value less than or equal to zero. Other than this,
  9851. ** no guarantees are made as to the size of the chunks of data returned.
  9852. */
  9853. SQLITE_API int sqlite3changeset_apply_strm(
  9854. sqlite3 *db, /* Apply change to "main" db of this handle */
  9855. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  9856. void *pIn, /* First arg for xInput */
  9857. int(*xFilter)(
  9858. void *pCtx, /* Copy of sixth arg to _apply() */
  9859. const char *zTab /* Table name */
  9860. ),
  9861. int(*xConflict)(
  9862. void *pCtx, /* Copy of sixth arg to _apply() */
  9863. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  9864. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  9865. ),
  9866. void *pCtx /* First argument passed to xConflict */
  9867. );
  9868. SQLITE_API int sqlite3changeset_concat_strm(
  9869. int (*xInputA)(void *pIn, void *pData, int *pnData),
  9870. void *pInA,
  9871. int (*xInputB)(void *pIn, void *pData, int *pnData),
  9872. void *pInB,
  9873. int (*xOutput)(void *pOut, const void *pData, int nData),
  9874. void *pOut
  9875. );
  9876. SQLITE_API int sqlite3changeset_invert_strm(
  9877. int (*xInput)(void *pIn, void *pData, int *pnData),
  9878. void *pIn,
  9879. int (*xOutput)(void *pOut, const void *pData, int nData),
  9880. void *pOut
  9881. );
  9882. SQLITE_API int sqlite3changeset_start_strm(
  9883. sqlite3_changeset_iter **pp,
  9884. int (*xInput)(void *pIn, void *pData, int *pnData),
  9885. void *pIn
  9886. );
  9887. SQLITE_API int sqlite3session_changeset_strm(
  9888. sqlite3_session *pSession,
  9889. int (*xOutput)(void *pOut, const void *pData, int nData),
  9890. void *pOut
  9891. );
  9892. SQLITE_API int sqlite3session_patchset_strm(
  9893. sqlite3_session *pSession,
  9894. int (*xOutput)(void *pOut, const void *pData, int nData),
  9895. void *pOut
  9896. );
  9897. SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
  9898. int (*xInput)(void *pIn, void *pData, int *pnData),
  9899. void *pIn
  9900. );
  9901. SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
  9902. int (*xOutput)(void *pOut, const void *pData, int nData),
  9903. void *pOut
  9904. );
  9905. /*
  9906. ** Make sure we can call this stuff from C++.
  9907. */
  9908. #if 0
  9909. }
  9910. #endif
  9911. #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
  9912. /******** End of sqlite3session.h *********/
  9913. /******** Begin file fts5.h *********/
  9914. /*
  9915. ** 2014 May 31
  9916. **
  9917. ** The author disclaims copyright to this source code. In place of
  9918. ** a legal notice, here is a blessing:
  9919. **
  9920. ** May you do good and not evil.
  9921. ** May you find forgiveness for yourself and forgive others.
  9922. ** May you share freely, never taking more than you give.
  9923. **
  9924. ******************************************************************************
  9925. **
  9926. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  9927. ** FTS5 may be extended with:
  9928. **
  9929. ** * custom tokenizers, and
  9930. ** * custom auxiliary functions.
  9931. */
  9932. #ifndef _FTS5_H
  9933. #define _FTS5_H
  9934. #if 0
  9935. extern "C" {
  9936. #endif
  9937. /*************************************************************************
  9938. ** CUSTOM AUXILIARY FUNCTIONS
  9939. **
  9940. ** Virtual table implementations may overload SQL functions by implementing
  9941. ** the sqlite3_module.xFindFunction() method.
  9942. */
  9943. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  9944. typedef struct Fts5Context Fts5Context;
  9945. typedef struct Fts5PhraseIter Fts5PhraseIter;
  9946. typedef void (*fts5_extension_function)(
  9947. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  9948. Fts5Context *pFts, /* First arg to pass to pApi functions */
  9949. sqlite3_context *pCtx, /* Context for returning result/error */
  9950. int nVal, /* Number of values in apVal[] array */
  9951. sqlite3_value **apVal /* Array of trailing arguments */
  9952. );
  9953. struct Fts5PhraseIter {
  9954. const unsigned char *a;
  9955. const unsigned char *b;
  9956. };
  9957. /*
  9958. ** EXTENSION API FUNCTIONS
  9959. **
  9960. ** xUserData(pFts):
  9961. ** Return a copy of the context pointer the extension function was
  9962. ** registered with.
  9963. **
  9964. ** xColumnTotalSize(pFts, iCol, pnToken):
  9965. ** If parameter iCol is less than zero, set output variable *pnToken
  9966. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  9967. ** non-negative but less than the number of columns in the table, return
  9968. ** the total number of tokens in column iCol, considering all rows in
  9969. ** the FTS5 table.
  9970. **
  9971. ** If parameter iCol is greater than or equal to the number of columns
  9972. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  9973. ** an OOM condition or IO error), an appropriate SQLite error code is
  9974. ** returned.
  9975. **
  9976. ** xColumnCount(pFts):
  9977. ** Return the number of columns in the table.
  9978. **
  9979. ** xColumnSize(pFts, iCol, pnToken):
  9980. ** If parameter iCol is less than zero, set output variable *pnToken
  9981. ** to the total number of tokens in the current row. Or, if iCol is
  9982. ** non-negative but less than the number of columns in the table, set
  9983. ** *pnToken to the number of tokens in column iCol of the current row.
  9984. **
  9985. ** If parameter iCol is greater than or equal to the number of columns
  9986. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  9987. ** an OOM condition or IO error), an appropriate SQLite error code is
  9988. ** returned.
  9989. **
  9990. ** This function may be quite inefficient if used with an FTS5 table
  9991. ** created with the "columnsize=0" option.
  9992. **
  9993. ** xColumnText:
  9994. ** This function attempts to retrieve the text of column iCol of the
  9995. ** current document. If successful, (*pz) is set to point to a buffer
  9996. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  9997. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  9998. ** if an error occurs, an SQLite error code is returned and the final values
  9999. ** of (*pz) and (*pn) are undefined.
  10000. **
  10001. ** xPhraseCount:
  10002. ** Returns the number of phrases in the current query expression.
  10003. **
  10004. ** xPhraseSize:
  10005. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  10006. ** are numbered starting from zero.
  10007. **
  10008. ** xInstCount:
  10009. ** Set *pnInst to the total number of occurrences of all phrases within
  10010. ** the query within the current row. Return SQLITE_OK if successful, or
  10011. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  10012. **
  10013. ** This API can be quite slow if used with an FTS5 table created with the
  10014. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  10015. ** with either "detail=none" or "detail=column" and "content=" option
  10016. ** (i.e. if it is a contentless table), then this API always returns 0.
  10017. **
  10018. ** xInst:
  10019. ** Query for the details of phrase match iIdx within the current row.
  10020. ** Phrase matches are numbered starting from zero, so the iIdx argument
  10021. ** should be greater than or equal to zero and smaller than the value
  10022. ** output by xInstCount().
  10023. **
  10024. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  10025. ** to the column in which it occurs and *piOff the token offset of the
  10026. ** first token of the phrase. The exception is if the table was created
  10027. ** with the offsets=0 option specified. In this case *piOff is always
  10028. ** set to -1.
  10029. **
  10030. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  10031. ** if an error occurs.
  10032. **
  10033. ** This API can be quite slow if used with an FTS5 table created with the
  10034. ** "detail=none" or "detail=column" option.
  10035. **
  10036. ** xRowid:
  10037. ** Returns the rowid of the current row.
  10038. **
  10039. ** xTokenize:
  10040. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  10041. **
  10042. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  10043. ** This API function is used to query the FTS table for phrase iPhrase
  10044. ** of the current query. Specifically, a query equivalent to:
  10045. **
  10046. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  10047. **
  10048. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  10049. ** current query is executed. Any column filter that applies to
  10050. ** phrase iPhrase of the current query is included in $p. For each
  10051. ** row visited, the callback function passed as the fourth argument
  10052. ** is invoked. The context and API objects passed to the callback
  10053. ** function may be used to access the properties of each matched row.
  10054. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  10055. ** the third argument to pUserData.
  10056. **
  10057. ** If the callback function returns any value other than SQLITE_OK, the
  10058. ** query is abandoned and the xQueryPhrase function returns immediately.
  10059. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  10060. ** Otherwise, the error code is propagated upwards.
  10061. **
  10062. ** If the query runs to completion without incident, SQLITE_OK is returned.
  10063. ** Or, if some error occurs before the query completes or is aborted by
  10064. ** the callback, an SQLite error code is returned.
  10065. **
  10066. **
  10067. ** xSetAuxdata(pFts5, pAux, xDelete)
  10068. **
  10069. ** Save the pointer passed as the second argument as the extension functions
  10070. ** "auxiliary data". The pointer may then be retrieved by the current or any
  10071. ** future invocation of the same fts5 extension function made as part of
  10072. ** of the same MATCH query using the xGetAuxdata() API.
  10073. **
  10074. ** Each extension function is allocated a single auxiliary data slot for
  10075. ** each FTS query (MATCH expression). If the extension function is invoked
  10076. ** more than once for a single FTS query, then all invocations share a
  10077. ** single auxiliary data context.
  10078. **
  10079. ** If there is already an auxiliary data pointer when this function is
  10080. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  10081. ** was specified along with the original pointer, it is invoked at this
  10082. ** point.
  10083. **
  10084. ** The xDelete callback, if one is specified, is also invoked on the
  10085. ** auxiliary data pointer after the FTS5 query has finished.
  10086. **
  10087. ** If an error (e.g. an OOM condition) occurs within this function, an
  10088. ** the auxiliary data is set to NULL and an error code returned. If the
  10089. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  10090. ** pointer before returning.
  10091. **
  10092. **
  10093. ** xGetAuxdata(pFts5, bClear)
  10094. **
  10095. ** Returns the current auxiliary data pointer for the fts5 extension
  10096. ** function. See the xSetAuxdata() method for details.
  10097. **
  10098. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  10099. ** (set to NULL) before this function returns. In this case the xDelete,
  10100. ** if any, is not invoked.
  10101. **
  10102. **
  10103. ** xRowCount(pFts5, pnRow)
  10104. **
  10105. ** This function is used to retrieve the total number of rows in the table.
  10106. ** In other words, the same value that would be returned by:
  10107. **
  10108. ** SELECT count(*) FROM ftstable;
  10109. **
  10110. ** xPhraseFirst()
  10111. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  10112. ** method, to iterate through all instances of a single query phrase within
  10113. ** the current row. This is the same information as is accessible via the
  10114. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  10115. ** to use, this API may be faster under some circumstances. To iterate
  10116. ** through instances of phrase iPhrase, use the following code:
  10117. **
  10118. ** Fts5PhraseIter iter;
  10119. ** int iCol, iOff;
  10120. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  10121. ** iCol>=0;
  10122. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  10123. ** ){
  10124. ** // An instance of phrase iPhrase at offset iOff of column iCol
  10125. ** }
  10126. **
  10127. ** The Fts5PhraseIter structure is defined above. Applications should not
  10128. ** modify this structure directly - it should only be used as shown above
  10129. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  10130. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  10131. **
  10132. ** This API can be quite slow if used with an FTS5 table created with the
  10133. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  10134. ** with either "detail=none" or "detail=column" and "content=" option
  10135. ** (i.e. if it is a contentless table), then this API always iterates
  10136. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  10137. **
  10138. ** xPhraseNext()
  10139. ** See xPhraseFirst above.
  10140. **
  10141. ** xPhraseFirstColumn()
  10142. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  10143. ** and xPhraseNext() APIs described above. The difference is that instead
  10144. ** of iterating through all instances of a phrase in the current row, these
  10145. ** APIs are used to iterate through the set of columns in the current row
  10146. ** that contain one or more instances of a specified phrase. For example:
  10147. **
  10148. ** Fts5PhraseIter iter;
  10149. ** int iCol;
  10150. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  10151. ** iCol>=0;
  10152. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  10153. ** ){
  10154. ** // Column iCol contains at least one instance of phrase iPhrase
  10155. ** }
  10156. **
  10157. ** This API can be quite slow if used with an FTS5 table created with the
  10158. ** "detail=none" option. If the FTS5 table is created with either
  10159. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  10160. ** then this API always iterates through an empty set (all calls to
  10161. ** xPhraseFirstColumn() set iCol to -1).
  10162. **
  10163. ** The information accessed using this API and its companion
  10164. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  10165. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  10166. ** significantly more efficient than those alternatives when used with
  10167. ** "detail=column" tables.
  10168. **
  10169. ** xPhraseNextColumn()
  10170. ** See xPhraseFirstColumn above.
  10171. */
  10172. struct Fts5ExtensionApi {
  10173. int iVersion; /* Currently always set to 3 */
  10174. void *(*xUserData)(Fts5Context*);
  10175. int (*xColumnCount)(Fts5Context*);
  10176. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  10177. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  10178. int (*xTokenize)(Fts5Context*,
  10179. const char *pText, int nText, /* Text to tokenize */
  10180. void *pCtx, /* Context passed to xToken() */
  10181. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  10182. );
  10183. int (*xPhraseCount)(Fts5Context*);
  10184. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  10185. int (*xInstCount)(Fts5Context*, int *pnInst);
  10186. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  10187. sqlite3_int64 (*xRowid)(Fts5Context*);
  10188. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  10189. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  10190. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  10191. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  10192. );
  10193. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  10194. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  10195. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  10196. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  10197. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  10198. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  10199. };
  10200. /*
  10201. ** CUSTOM AUXILIARY FUNCTIONS
  10202. *************************************************************************/
  10203. /*************************************************************************
  10204. ** CUSTOM TOKENIZERS
  10205. **
  10206. ** Applications may also register custom tokenizer types. A tokenizer
  10207. ** is registered by providing fts5 with a populated instance of the
  10208. ** following structure. All structure methods must be defined, setting
  10209. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  10210. ** behaviour. The structure methods are expected to function as follows:
  10211. **
  10212. ** xCreate:
  10213. ** This function is used to allocate and initialize a tokenizer instance.
  10214. ** A tokenizer instance is required to actually tokenize text.
  10215. **
  10216. ** The first argument passed to this function is a copy of the (void*)
  10217. ** pointer provided by the application when the fts5_tokenizer object
  10218. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  10219. ** The second and third arguments are an array of nul-terminated strings
  10220. ** containing the tokenizer arguments, if any, specified following the
  10221. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  10222. ** to create the FTS5 table.
  10223. **
  10224. ** The final argument is an output variable. If successful, (*ppOut)
  10225. ** should be set to point to the new tokenizer handle and SQLITE_OK
  10226. ** returned. If an error occurs, some value other than SQLITE_OK should
  10227. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  10228. ** is undefined.
  10229. **
  10230. ** xDelete:
  10231. ** This function is invoked to delete a tokenizer handle previously
  10232. ** allocated using xCreate(). Fts5 guarantees that this function will
  10233. ** be invoked exactly once for each successful call to xCreate().
  10234. **
  10235. ** xTokenize:
  10236. ** This function is expected to tokenize the nText byte string indicated
  10237. ** by argument pText. pText may or may not be nul-terminated. The first
  10238. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  10239. ** returned by an earlier call to xCreate().
  10240. **
  10241. ** The second argument indicates the reason that FTS5 is requesting
  10242. ** tokenization of the supplied text. This is always one of the following
  10243. ** four values:
  10244. **
  10245. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  10246. ** or removed from the FTS table. The tokenizer is being invoked to
  10247. ** determine the set of tokens to add to (or delete from) the
  10248. ** FTS index.
  10249. **
  10250. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  10251. ** against the FTS index. The tokenizer is being called to tokenize
  10252. ** a bareword or quoted string specified as part of the query.
  10253. **
  10254. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  10255. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  10256. ** followed by a "*" character, indicating that the last token
  10257. ** returned by the tokenizer will be treated as a token prefix.
  10258. **
  10259. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  10260. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  10261. ** function. Or an fts5_api.xColumnSize() request made by the same
  10262. ** on a columnsize=0 database.
  10263. ** </ul>
  10264. **
  10265. ** For each token in the input string, the supplied callback xToken() must
  10266. ** be invoked. The first argument to it should be a copy of the pointer
  10267. ** passed as the second argument to xTokenize(). The third and fourth
  10268. ** arguments are a pointer to a buffer containing the token text, and the
  10269. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  10270. ** of the first byte of and first byte immediately following the text from
  10271. ** which the token is derived within the input.
  10272. **
  10273. ** The second argument passed to the xToken() callback ("tflags") should
  10274. ** normally be set to 0. The exception is if the tokenizer supports
  10275. ** synonyms. In this case see the discussion below for details.
  10276. **
  10277. ** FTS5 assumes the xToken() callback is invoked for each token in the
  10278. ** order that they occur within the input text.
  10279. **
  10280. ** If an xToken() callback returns any value other than SQLITE_OK, then
  10281. ** the tokenization should be abandoned and the xTokenize() method should
  10282. ** immediately return a copy of the xToken() return value. Or, if the
  10283. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  10284. ** if an error occurs with the xTokenize() implementation itself, it
  10285. ** may abandon the tokenization and return any error code other than
  10286. ** SQLITE_OK or SQLITE_DONE.
  10287. **
  10288. ** SYNONYM SUPPORT
  10289. **
  10290. ** Custom tokenizers may also support synonyms. Consider a case in which a
  10291. ** user wishes to query for a phrase such as "first place". Using the
  10292. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  10293. ** of "first place" within the document set, but not alternative forms
  10294. ** such as "1st place". In some applications, it would be better to match
  10295. ** all instances of "first place" or "1st place" regardless of which form
  10296. ** the user specified in the MATCH query text.
  10297. **
  10298. ** There are several ways to approach this in FTS5:
  10299. **
  10300. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  10301. ** In the above example, this means that the tokenizer returns the
  10302. ** same token for inputs "first" and "1st". Say that token is in
  10303. ** fact "first", so that when the user inserts the document "I won
  10304. ** 1st place" entries are added to the index for tokens "i", "won",
  10305. ** "first" and "place". If the user then queries for '1st + place',
  10306. ** the tokenizer substitutes "first" for "1st" and the query works
  10307. ** as expected.
  10308. **
  10309. ** <li> By adding multiple synonyms for a single term to the FTS index.
  10310. ** In this case, when tokenizing query text, the tokenizer may
  10311. ** provide multiple synonyms for a single term within the document.
  10312. ** FTS5 then queries the index for each synonym individually. For
  10313. ** example, faced with the query:
  10314. **
  10315. ** <codeblock>
  10316. ** ... MATCH 'first place'</codeblock>
  10317. **
  10318. ** the tokenizer offers both "1st" and "first" as synonyms for the
  10319. ** first token in the MATCH query and FTS5 effectively runs a query
  10320. ** similar to:
  10321. **
  10322. ** <codeblock>
  10323. ** ... MATCH '(first OR 1st) place'</codeblock>
  10324. **
  10325. ** except that, for the purposes of auxiliary functions, the query
  10326. ** still appears to contain just two phrases - "(first OR 1st)"
  10327. ** being treated as a single phrase.
  10328. **
  10329. ** <li> By adding multiple synonyms for a single term to the FTS index.
  10330. ** Using this method, when tokenizing document text, the tokenizer
  10331. ** provides multiple synonyms for each token. So that when a
  10332. ** document such as "I won first place" is tokenized, entries are
  10333. ** added to the FTS index for "i", "won", "first", "1st" and
  10334. ** "place".
  10335. **
  10336. ** This way, even if the tokenizer does not provide synonyms
  10337. ** when tokenizing query text (it should not - to do would be
  10338. ** inefficient), it doesn't matter if the user queries for
  10339. ** 'first + place' or '1st + place', as there are entires in the
  10340. ** FTS index corresponding to both forms of the first token.
  10341. ** </ol>
  10342. **
  10343. ** Whether it is parsing document or query text, any call to xToken that
  10344. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  10345. ** is considered to supply a synonym for the previous token. For example,
  10346. ** when parsing the document "I won first place", a tokenizer that supports
  10347. ** synonyms would call xToken() 5 times, as follows:
  10348. **
  10349. ** <codeblock>
  10350. ** xToken(pCtx, 0, "i", 1, 0, 1);
  10351. ** xToken(pCtx, 0, "won", 3, 2, 5);
  10352. ** xToken(pCtx, 0, "first", 5, 6, 11);
  10353. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  10354. ** xToken(pCtx, 0, "place", 5, 12, 17);
  10355. **</codeblock>
  10356. **
  10357. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  10358. ** xToken() is called. Multiple synonyms may be specified for a single token
  10359. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  10360. ** There is no limit to the number of synonyms that may be provided for a
  10361. ** single token.
  10362. **
  10363. ** In many cases, method (1) above is the best approach. It does not add
  10364. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  10365. ** so it is efficient in terms of disk space and query speed. However, it
  10366. ** does not support prefix queries very well. If, as suggested above, the
  10367. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  10368. **
  10369. ** <codeblock>
  10370. ** ... MATCH '1s*'</codeblock>
  10371. **
  10372. ** will not match documents that contain the token "1st" (as the tokenizer
  10373. ** will probably not map "1s" to any prefix of "first").
  10374. **
  10375. ** For full prefix support, method (3) may be preferred. In this case,
  10376. ** because the index contains entries for both "first" and "1st", prefix
  10377. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  10378. ** extra entries are added to the FTS index, this method uses more space
  10379. ** within the database.
  10380. **
  10381. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  10382. ** a query such as '1s*' will match documents that contain the literal
  10383. ** token "1st", but not "first" (assuming the tokenizer is not able to
  10384. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  10385. ** will match against "1st" and "first". This method does not require
  10386. ** extra disk space, as no extra entries are added to the FTS index.
  10387. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  10388. ** as separate queries of the FTS index are required for each synonym.
  10389. **
  10390. ** When using methods (2) or (3), it is important that the tokenizer only
  10391. ** provide synonyms when tokenizing document text (method (2)) or query
  10392. ** text (method (3)), not both. Doing so will not cause any errors, but is
  10393. ** inefficient.
  10394. */
  10395. typedef struct Fts5Tokenizer Fts5Tokenizer;
  10396. typedef struct fts5_tokenizer fts5_tokenizer;
  10397. struct fts5_tokenizer {
  10398. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  10399. void (*xDelete)(Fts5Tokenizer*);
  10400. int (*xTokenize)(Fts5Tokenizer*,
  10401. void *pCtx,
  10402. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  10403. const char *pText, int nText,
  10404. int (*xToken)(
  10405. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  10406. int tflags, /* Mask of FTS5_TOKEN_* flags */
  10407. const char *pToken, /* Pointer to buffer containing token */
  10408. int nToken, /* Size of token in bytes */
  10409. int iStart, /* Byte offset of token within input text */
  10410. int iEnd /* Byte offset of end of token within input text */
  10411. )
  10412. );
  10413. };
  10414. /* Flags that may be passed as the third argument to xTokenize() */
  10415. #define FTS5_TOKENIZE_QUERY 0x0001
  10416. #define FTS5_TOKENIZE_PREFIX 0x0002
  10417. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  10418. #define FTS5_TOKENIZE_AUX 0x0008
  10419. /* Flags that may be passed by the tokenizer implementation back to FTS5
  10420. ** as the third argument to the supplied xToken callback. */
  10421. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  10422. /*
  10423. ** END OF CUSTOM TOKENIZERS
  10424. *************************************************************************/
  10425. /*************************************************************************
  10426. ** FTS5 EXTENSION REGISTRATION API
  10427. */
  10428. typedef struct fts5_api fts5_api;
  10429. struct fts5_api {
  10430. int iVersion; /* Currently always set to 2 */
  10431. /* Create a new tokenizer */
  10432. int (*xCreateTokenizer)(
  10433. fts5_api *pApi,
  10434. const char *zName,
  10435. void *pContext,
  10436. fts5_tokenizer *pTokenizer,
  10437. void (*xDestroy)(void*)
  10438. );
  10439. /* Find an existing tokenizer */
  10440. int (*xFindTokenizer)(
  10441. fts5_api *pApi,
  10442. const char *zName,
  10443. void **ppContext,
  10444. fts5_tokenizer *pTokenizer
  10445. );
  10446. /* Create a new auxiliary function */
  10447. int (*xCreateFunction)(
  10448. fts5_api *pApi,
  10449. const char *zName,
  10450. void *pContext,
  10451. fts5_extension_function xFunction,
  10452. void (*xDestroy)(void*)
  10453. );
  10454. };
  10455. /*
  10456. ** END OF REGISTRATION API
  10457. *************************************************************************/
  10458. #if 0
  10459. } /* end of the 'extern "C"' block */
  10460. #endif
  10461. #endif /* _FTS5_H */
  10462. /******** End of fts5.h *********/
  10463. /************** End of sqlite3.h *********************************************/
  10464. /************** Continuing where we left off in sqliteInt.h ******************/
  10465. /*
  10466. ** Include the configuration header output by 'configure' if we're using the
  10467. ** autoconf-based build
  10468. */
  10469. #ifdef _HAVE_SQLITE_CONFIG_H
  10470. #include "config.h"
  10471. #endif
  10472. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  10473. /************** Begin file sqliteLimit.h *************************************/
  10474. /*
  10475. ** 2007 May 7
  10476. **
  10477. ** The author disclaims copyright to this source code. In place of
  10478. ** a legal notice, here is a blessing:
  10479. **
  10480. ** May you do good and not evil.
  10481. ** May you find forgiveness for yourself and forgive others.
  10482. ** May you share freely, never taking more than you give.
  10483. **
  10484. *************************************************************************
  10485. **
  10486. ** This file defines various limits of what SQLite can process.
  10487. */
  10488. /*
  10489. ** The maximum length of a TEXT or BLOB in bytes. This also
  10490. ** limits the size of a row in a table or index.
  10491. **
  10492. ** The hard limit is the ability of a 32-bit signed integer
  10493. ** to count the size: 2^31-1 or 2147483647.
  10494. */
  10495. #ifndef SQLITE_MAX_LENGTH
  10496. # define SQLITE_MAX_LENGTH 1000000000
  10497. #endif
  10498. /*
  10499. ** This is the maximum number of
  10500. **
  10501. ** * Columns in a table
  10502. ** * Columns in an index
  10503. ** * Columns in a view
  10504. ** * Terms in the SET clause of an UPDATE statement
  10505. ** * Terms in the result set of a SELECT statement
  10506. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  10507. ** * Terms in the VALUES clause of an INSERT statement
  10508. **
  10509. ** The hard upper limit here is 32676. Most database people will
  10510. ** tell you that in a well-normalized database, you usually should
  10511. ** not have more than a dozen or so columns in any table. And if
  10512. ** that is the case, there is no point in having more than a few
  10513. ** dozen values in any of the other situations described above.
  10514. */
  10515. #ifndef SQLITE_MAX_COLUMN
  10516. # define SQLITE_MAX_COLUMN 2000
  10517. #endif
  10518. /*
  10519. ** The maximum length of a single SQL statement in bytes.
  10520. **
  10521. ** It used to be the case that setting this value to zero would
  10522. ** turn the limit off. That is no longer true. It is not possible
  10523. ** to turn this limit off.
  10524. */
  10525. #ifndef SQLITE_MAX_SQL_LENGTH
  10526. # define SQLITE_MAX_SQL_LENGTH 1000000000
  10527. #endif
  10528. /*
  10529. ** The maximum depth of an expression tree. This is limited to
  10530. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  10531. ** want to place more severe limits on the complexity of an
  10532. ** expression.
  10533. **
  10534. ** A value of 0 used to mean that the limit was not enforced.
  10535. ** But that is no longer true. The limit is now strictly enforced
  10536. ** at all times.
  10537. */
  10538. #ifndef SQLITE_MAX_EXPR_DEPTH
  10539. # define SQLITE_MAX_EXPR_DEPTH 1000
  10540. #endif
  10541. /*
  10542. ** The maximum number of terms in a compound SELECT statement.
  10543. ** The code generator for compound SELECT statements does one
  10544. ** level of recursion for each term. A stack overflow can result
  10545. ** if the number of terms is too large. In practice, most SQL
  10546. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  10547. ** any limit on the number of terms in a compount SELECT.
  10548. */
  10549. #ifndef SQLITE_MAX_COMPOUND_SELECT
  10550. # define SQLITE_MAX_COMPOUND_SELECT 500
  10551. #endif
  10552. /*
  10553. ** The maximum number of opcodes in a VDBE program.
  10554. ** Not currently enforced.
  10555. */
  10556. #ifndef SQLITE_MAX_VDBE_OP
  10557. # define SQLITE_MAX_VDBE_OP 250000000
  10558. #endif
  10559. /*
  10560. ** The maximum number of arguments to an SQL function.
  10561. */
  10562. #ifndef SQLITE_MAX_FUNCTION_ARG
  10563. # define SQLITE_MAX_FUNCTION_ARG 127
  10564. #endif
  10565. /*
  10566. ** The suggested maximum number of in-memory pages to use for
  10567. ** the main database table and for temporary tables.
  10568. **
  10569. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  10570. ** which means the cache size is limited to 2048000 bytes of memory.
  10571. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  10572. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  10573. */
  10574. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  10575. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  10576. #endif
  10577. /*
  10578. ** The default number of frames to accumulate in the log file before
  10579. ** checkpointing the database in WAL mode.
  10580. */
  10581. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  10582. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  10583. #endif
  10584. /*
  10585. ** The maximum number of attached databases. This must be between 0
  10586. ** and 125. The upper bound of 125 is because the attached databases are
  10587. ** counted using a signed 8-bit integer which has a maximum value of 127
  10588. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  10589. */
  10590. #ifndef SQLITE_MAX_ATTACHED
  10591. # define SQLITE_MAX_ATTACHED 10
  10592. #endif
  10593. /*
  10594. ** The maximum value of a ?nnn wildcard that the parser will accept.
  10595. */
  10596. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  10597. # define SQLITE_MAX_VARIABLE_NUMBER 999
  10598. #endif
  10599. /* Maximum page size. The upper bound on this value is 65536. This a limit
  10600. ** imposed by the use of 16-bit offsets within each page.
  10601. **
  10602. ** Earlier versions of SQLite allowed the user to change this value at
  10603. ** compile time. This is no longer permitted, on the grounds that it creates
  10604. ** a library that is technically incompatible with an SQLite library
  10605. ** compiled with a different limit. If a process operating on a database
  10606. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  10607. ** compiled with the default page-size limit will not be able to rollback
  10608. ** the aborted transaction. This could lead to database corruption.
  10609. */
  10610. #ifdef SQLITE_MAX_PAGE_SIZE
  10611. # undef SQLITE_MAX_PAGE_SIZE
  10612. #endif
  10613. #define SQLITE_MAX_PAGE_SIZE 65536
  10614. /*
  10615. ** The default size of a database page.
  10616. */
  10617. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  10618. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  10619. #endif
  10620. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  10621. # undef SQLITE_DEFAULT_PAGE_SIZE
  10622. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  10623. #endif
  10624. /*
  10625. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  10626. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  10627. ** device characteristics (sector-size and atomic write() support),
  10628. ** SQLite may choose a larger value. This constant is the maximum value
  10629. ** SQLite will choose on its own.
  10630. */
  10631. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  10632. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  10633. #endif
  10634. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  10635. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  10636. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  10637. #endif
  10638. /*
  10639. ** Maximum number of pages in one database file.
  10640. **
  10641. ** This is really just the default value for the max_page_count pragma.
  10642. ** This value can be lowered (or raised) at run-time using that the
  10643. ** max_page_count macro.
  10644. */
  10645. #ifndef SQLITE_MAX_PAGE_COUNT
  10646. # define SQLITE_MAX_PAGE_COUNT 1073741823
  10647. #endif
  10648. /*
  10649. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  10650. ** operator.
  10651. */
  10652. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  10653. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  10654. #endif
  10655. /*
  10656. ** Maximum depth of recursion for triggers.
  10657. **
  10658. ** A value of 1 means that a trigger program will not be able to itself
  10659. ** fire any triggers. A value of 0 means that no trigger programs at all
  10660. ** may be executed.
  10661. */
  10662. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  10663. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  10664. #endif
  10665. /************** End of sqliteLimit.h *****************************************/
  10666. /************** Continuing where we left off in sqliteInt.h ******************/
  10667. /* Disable nuisance warnings on Borland compilers */
  10668. #if defined(__BORLANDC__)
  10669. #pragma warn -rch /* unreachable code */
  10670. #pragma warn -ccc /* Condition is always true or false */
  10671. #pragma warn -aus /* Assigned value is never used */
  10672. #pragma warn -csu /* Comparing signed and unsigned */
  10673. #pragma warn -spa /* Suspicious pointer arithmetic */
  10674. #endif
  10675. /*
  10676. ** Include standard header files as necessary
  10677. */
  10678. #ifdef HAVE_STDINT_H
  10679. #include <stdint.h>
  10680. #endif
  10681. #ifdef HAVE_INTTYPES_H
  10682. #include <inttypes.h>
  10683. #endif
  10684. /*
  10685. ** The following macros are used to cast pointers to integers and
  10686. ** integers to pointers. The way you do this varies from one compiler
  10687. ** to the next, so we have developed the following set of #if statements
  10688. ** to generate appropriate macros for a wide range of compilers.
  10689. **
  10690. ** The correct "ANSI" way to do this is to use the intptr_t type.
  10691. ** Unfortunately, that typedef is not available on all compilers, or
  10692. ** if it is available, it requires an #include of specific headers
  10693. ** that vary from one machine to the next.
  10694. **
  10695. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  10696. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  10697. ** So we have to define the macros in different ways depending on the
  10698. ** compiler.
  10699. */
  10700. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  10701. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  10702. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  10703. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  10704. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  10705. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  10706. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  10707. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  10708. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  10709. #else /* Generates a warning - but it always works */
  10710. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  10711. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  10712. #endif
  10713. /*
  10714. ** A macro to hint to the compiler that a function should not be
  10715. ** inlined.
  10716. */
  10717. #if defined(__GNUC__)
  10718. # define SQLITE_NOINLINE __attribute__((noinline))
  10719. #elif defined(_MSC_VER) && _MSC_VER>=1310
  10720. # define SQLITE_NOINLINE __declspec(noinline)
  10721. #else
  10722. # define SQLITE_NOINLINE
  10723. #endif
  10724. /*
  10725. ** Make sure that the compiler intrinsics we desire are enabled when
  10726. ** compiling with an appropriate version of MSVC unless prevented by
  10727. ** the SQLITE_DISABLE_INTRINSIC define.
  10728. */
  10729. #if !defined(SQLITE_DISABLE_INTRINSIC)
  10730. # if defined(_MSC_VER) && _MSC_VER>=1400
  10731. # if !defined(_WIN32_WCE)
  10732. # include <intrin.h>
  10733. # pragma intrinsic(_byteswap_ushort)
  10734. # pragma intrinsic(_byteswap_ulong)
  10735. # pragma intrinsic(_byteswap_uint64)
  10736. # pragma intrinsic(_ReadWriteBarrier)
  10737. # else
  10738. # include <cmnintrin.h>
  10739. # endif
  10740. # endif
  10741. #endif
  10742. /*
  10743. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  10744. ** 0 means mutexes are permanently disable and the library is never
  10745. ** threadsafe. 1 means the library is serialized which is the highest
  10746. ** level of threadsafety. 2 means the library is multithreaded - multiple
  10747. ** threads can use SQLite as long as no two threads try to use the same
  10748. ** database connection at the same time.
  10749. **
  10750. ** Older versions of SQLite used an optional THREADSAFE macro.
  10751. ** We support that for legacy.
  10752. */
  10753. #if !defined(SQLITE_THREADSAFE)
  10754. # if defined(THREADSAFE)
  10755. # define SQLITE_THREADSAFE THREADSAFE
  10756. # else
  10757. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  10758. # endif
  10759. #endif
  10760. /*
  10761. ** Powersafe overwrite is on by default. But can be turned off using
  10762. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  10763. */
  10764. #ifndef SQLITE_POWERSAFE_OVERWRITE
  10765. # define SQLITE_POWERSAFE_OVERWRITE 1
  10766. #endif
  10767. /*
  10768. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  10769. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  10770. ** which case memory allocation statistics are disabled by default.
  10771. */
  10772. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  10773. # define SQLITE_DEFAULT_MEMSTATUS 1
  10774. #endif
  10775. /*
  10776. ** Exactly one of the following macros must be defined in order to
  10777. ** specify which memory allocation subsystem to use.
  10778. **
  10779. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  10780. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  10781. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  10782. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  10783. **
  10784. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  10785. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  10786. ** will cause HeapValidate to be called. If heap validation should fail, an
  10787. ** assertion will be triggered.
  10788. **
  10789. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  10790. ** the default.
  10791. */
  10792. #if defined(SQLITE_SYSTEM_MALLOC) \
  10793. + defined(SQLITE_WIN32_MALLOC) \
  10794. + defined(SQLITE_ZERO_MALLOC) \
  10795. + defined(SQLITE_MEMDEBUG)>1
  10796. # error "Two or more of the following compile-time configuration options\
  10797. are defined but at most one is allowed:\
  10798. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  10799. SQLITE_ZERO_MALLOC"
  10800. #endif
  10801. #if defined(SQLITE_SYSTEM_MALLOC) \
  10802. + defined(SQLITE_WIN32_MALLOC) \
  10803. + defined(SQLITE_ZERO_MALLOC) \
  10804. + defined(SQLITE_MEMDEBUG)==0
  10805. # define SQLITE_SYSTEM_MALLOC 1
  10806. #endif
  10807. /*
  10808. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  10809. ** sizes of memory allocations below this value where possible.
  10810. */
  10811. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  10812. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  10813. #endif
  10814. /*
  10815. ** We need to define _XOPEN_SOURCE as follows in order to enable
  10816. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  10817. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  10818. ** it.
  10819. */
  10820. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  10821. # define _XOPEN_SOURCE 600
  10822. #endif
  10823. /*
  10824. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  10825. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  10826. ** make it true by defining or undefining NDEBUG.
  10827. **
  10828. ** Setting NDEBUG makes the code smaller and faster by disabling the
  10829. ** assert() statements in the code. So we want the default action
  10830. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  10831. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  10832. ** feature.
  10833. */
  10834. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  10835. # define NDEBUG 1
  10836. #endif
  10837. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  10838. # undef NDEBUG
  10839. #endif
  10840. /*
  10841. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  10842. */
  10843. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  10844. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  10845. #endif
  10846. /*
  10847. ** The testcase() macro is used to aid in coverage testing. When
  10848. ** doing coverage testing, the condition inside the argument to
  10849. ** testcase() must be evaluated both true and false in order to
  10850. ** get full branch coverage. The testcase() macro is inserted
  10851. ** to help ensure adequate test coverage in places where simple
  10852. ** condition/decision coverage is inadequate. For example, testcase()
  10853. ** can be used to make sure boundary values are tested. For
  10854. ** bitmask tests, testcase() can be used to make sure each bit
  10855. ** is significant and used at least once. On switch statements
  10856. ** where multiple cases go to the same block of code, testcase()
  10857. ** can insure that all cases are evaluated.
  10858. **
  10859. */
  10860. #ifdef SQLITE_COVERAGE_TEST
  10861. SQLITE_PRIVATE void sqlite3Coverage(int);
  10862. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  10863. #else
  10864. # define testcase(X)
  10865. #endif
  10866. /*
  10867. ** The TESTONLY macro is used to enclose variable declarations or
  10868. ** other bits of code that are needed to support the arguments
  10869. ** within testcase() and assert() macros.
  10870. */
  10871. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  10872. # define TESTONLY(X) X
  10873. #else
  10874. # define TESTONLY(X)
  10875. #endif
  10876. /*
  10877. ** Sometimes we need a small amount of code such as a variable initialization
  10878. ** to setup for a later assert() statement. We do not want this code to
  10879. ** appear when assert() is disabled. The following macro is therefore
  10880. ** used to contain that setup code. The "VVA" acronym stands for
  10881. ** "Verification, Validation, and Accreditation". In other words, the
  10882. ** code within VVA_ONLY() will only run during verification processes.
  10883. */
  10884. #ifndef NDEBUG
  10885. # define VVA_ONLY(X) X
  10886. #else
  10887. # define VVA_ONLY(X)
  10888. #endif
  10889. /*
  10890. ** The ALWAYS and NEVER macros surround boolean expressions which
  10891. ** are intended to always be true or false, respectively. Such
  10892. ** expressions could be omitted from the code completely. But they
  10893. ** are included in a few cases in order to enhance the resilience
  10894. ** of SQLite to unexpected behavior - to make the code "self-healing"
  10895. ** or "ductile" rather than being "brittle" and crashing at the first
  10896. ** hint of unplanned behavior.
  10897. **
  10898. ** In other words, ALWAYS and NEVER are added for defensive code.
  10899. **
  10900. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  10901. ** be true and false so that the unreachable code they specify will
  10902. ** not be counted as untested code.
  10903. */
  10904. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  10905. # define ALWAYS(X) (1)
  10906. # define NEVER(X) (0)
  10907. #elif !defined(NDEBUG)
  10908. # define ALWAYS(X) ((X)?1:(assert(0),0))
  10909. # define NEVER(X) ((X)?(assert(0),1):0)
  10910. #else
  10911. # define ALWAYS(X) (X)
  10912. # define NEVER(X) (X)
  10913. #endif
  10914. /*
  10915. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  10916. ** defined. We need to defend against those failures when testing with
  10917. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  10918. ** during a normal build. The following macro can be used to disable tests
  10919. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  10920. */
  10921. #if defined(SQLITE_TEST_REALLOC_STRESS)
  10922. # define ONLY_IF_REALLOC_STRESS(X) (X)
  10923. #elif !defined(NDEBUG)
  10924. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  10925. #else
  10926. # define ONLY_IF_REALLOC_STRESS(X) (0)
  10927. #endif
  10928. /*
  10929. ** Declarations used for tracing the operating system interfaces.
  10930. */
  10931. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  10932. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  10933. extern int sqlite3OSTrace;
  10934. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  10935. # define SQLITE_HAVE_OS_TRACE
  10936. #else
  10937. # define OSTRACE(X)
  10938. # undef SQLITE_HAVE_OS_TRACE
  10939. #endif
  10940. /*
  10941. ** Is the sqlite3ErrName() function needed in the build? Currently,
  10942. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  10943. ** OSTRACE is enabled), and by several "test*.c" files (which are
  10944. ** compiled using SQLITE_TEST).
  10945. */
  10946. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  10947. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  10948. # define SQLITE_NEED_ERR_NAME
  10949. #else
  10950. # undef SQLITE_NEED_ERR_NAME
  10951. #endif
  10952. /*
  10953. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  10954. */
  10955. #ifdef SQLITE_OMIT_EXPLAIN
  10956. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  10957. #endif
  10958. /*
  10959. ** Return true (non-zero) if the input is an integer that is too large
  10960. ** to fit in 32-bits. This macro is used inside of various testcase()
  10961. ** macros to verify that we have tested SQLite for large-file support.
  10962. */
  10963. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  10964. /*
  10965. ** The macro unlikely() is a hint that surrounds a boolean
  10966. ** expression that is usually false. Macro likely() surrounds
  10967. ** a boolean expression that is usually true. These hints could,
  10968. ** in theory, be used by the compiler to generate better code, but
  10969. ** currently they are just comments for human readers.
  10970. */
  10971. #define likely(X) (X)
  10972. #define unlikely(X) (X)
  10973. /************** Include hash.h in the middle of sqliteInt.h ******************/
  10974. /************** Begin file hash.h ********************************************/
  10975. /*
  10976. ** 2001 September 22
  10977. **
  10978. ** The author disclaims copyright to this source code. In place of
  10979. ** a legal notice, here is a blessing:
  10980. **
  10981. ** May you do good and not evil.
  10982. ** May you find forgiveness for yourself and forgive others.
  10983. ** May you share freely, never taking more than you give.
  10984. **
  10985. *************************************************************************
  10986. ** This is the header file for the generic hash-table implementation
  10987. ** used in SQLite.
  10988. */
  10989. #ifndef SQLITE_HASH_H
  10990. #define SQLITE_HASH_H
  10991. /* Forward declarations of structures. */
  10992. typedef struct Hash Hash;
  10993. typedef struct HashElem HashElem;
  10994. /* A complete hash table is an instance of the following structure.
  10995. ** The internals of this structure are intended to be opaque -- client
  10996. ** code should not attempt to access or modify the fields of this structure
  10997. ** directly. Change this structure only by using the routines below.
  10998. ** However, some of the "procedures" and "functions" for modifying and
  10999. ** accessing this structure are really macros, so we can't really make
  11000. ** this structure opaque.
  11001. **
  11002. ** All elements of the hash table are on a single doubly-linked list.
  11003. ** Hash.first points to the head of this list.
  11004. **
  11005. ** There are Hash.htsize buckets. Each bucket points to a spot in
  11006. ** the global doubly-linked list. The contents of the bucket are the
  11007. ** element pointed to plus the next _ht.count-1 elements in the list.
  11008. **
  11009. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  11010. ** by a linear search of the global list. For small tables, the
  11011. ** Hash.ht table is never allocated because if there are few elements
  11012. ** in the table, it is faster to do a linear search than to manage
  11013. ** the hash table.
  11014. */
  11015. struct Hash {
  11016. unsigned int htsize; /* Number of buckets in the hash table */
  11017. unsigned int count; /* Number of entries in this table */
  11018. HashElem *first; /* The first element of the array */
  11019. struct _ht { /* the hash table */
  11020. int count; /* Number of entries with this hash */
  11021. HashElem *chain; /* Pointer to first entry with this hash */
  11022. } *ht;
  11023. };
  11024. /* Each element in the hash table is an instance of the following
  11025. ** structure. All elements are stored on a single doubly-linked list.
  11026. **
  11027. ** Again, this structure is intended to be opaque, but it can't really
  11028. ** be opaque because it is used by macros.
  11029. */
  11030. struct HashElem {
  11031. HashElem *next, *prev; /* Next and previous elements in the table */
  11032. void *data; /* Data associated with this element */
  11033. const char *pKey; /* Key associated with this element */
  11034. };
  11035. /*
  11036. ** Access routines. To delete, insert a NULL pointer.
  11037. */
  11038. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  11039. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  11040. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  11041. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  11042. /*
  11043. ** Macros for looping over all elements of a hash table. The idiom is
  11044. ** like this:
  11045. **
  11046. ** Hash h;
  11047. ** HashElem *p;
  11048. ** ...
  11049. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  11050. ** SomeStructure *pData = sqliteHashData(p);
  11051. ** // do something with pData
  11052. ** }
  11053. */
  11054. #define sqliteHashFirst(H) ((H)->first)
  11055. #define sqliteHashNext(E) ((E)->next)
  11056. #define sqliteHashData(E) ((E)->data)
  11057. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  11058. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  11059. /*
  11060. ** Number of entries in a hash table
  11061. */
  11062. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  11063. #endif /* SQLITE_HASH_H */
  11064. /************** End of hash.h ************************************************/
  11065. /************** Continuing where we left off in sqliteInt.h ******************/
  11066. /************** Include parse.h in the middle of sqliteInt.h *****************/
  11067. /************** Begin file parse.h *******************************************/
  11068. #define TK_SEMI 1
  11069. #define TK_EXPLAIN 2
  11070. #define TK_QUERY 3
  11071. #define TK_PLAN 4
  11072. #define TK_BEGIN 5
  11073. #define TK_TRANSACTION 6
  11074. #define TK_DEFERRED 7
  11075. #define TK_IMMEDIATE 8
  11076. #define TK_EXCLUSIVE 9
  11077. #define TK_COMMIT 10
  11078. #define TK_END 11
  11079. #define TK_ROLLBACK 12
  11080. #define TK_SAVEPOINT 13
  11081. #define TK_RELEASE 14
  11082. #define TK_TO 15
  11083. #define TK_TABLE 16
  11084. #define TK_CREATE 17
  11085. #define TK_IF 18
  11086. #define TK_NOT 19
  11087. #define TK_EXISTS 20
  11088. #define TK_TEMP 21
  11089. #define TK_LP 22
  11090. #define TK_RP 23
  11091. #define TK_AS 24
  11092. #define TK_WITHOUT 25
  11093. #define TK_COMMA 26
  11094. #define TK_ID 27
  11095. #define TK_ABORT 28
  11096. #define TK_ACTION 29
  11097. #define TK_AFTER 30
  11098. #define TK_ANALYZE 31
  11099. #define TK_ASC 32
  11100. #define TK_ATTACH 33
  11101. #define TK_BEFORE 34
  11102. #define TK_BY 35
  11103. #define TK_CASCADE 36
  11104. #define TK_CAST 37
  11105. #define TK_COLUMNKW 38
  11106. #define TK_CONFLICT 39
  11107. #define TK_DATABASE 40
  11108. #define TK_DESC 41
  11109. #define TK_DETACH 42
  11110. #define TK_EACH 43
  11111. #define TK_FAIL 44
  11112. #define TK_FOR 45
  11113. #define TK_IGNORE 46
  11114. #define TK_INITIALLY 47
  11115. #define TK_INSTEAD 48
  11116. #define TK_LIKE_KW 49
  11117. #define TK_MATCH 50
  11118. #define TK_NO 51
  11119. #define TK_KEY 52
  11120. #define TK_OF 53
  11121. #define TK_OFFSET 54
  11122. #define TK_PRAGMA 55
  11123. #define TK_RAISE 56
  11124. #define TK_RECURSIVE 57
  11125. #define TK_REPLACE 58
  11126. #define TK_RESTRICT 59
  11127. #define TK_ROW 60
  11128. #define TK_TRIGGER 61
  11129. #define TK_VACUUM 62
  11130. #define TK_VIEW 63
  11131. #define TK_VIRTUAL 64
  11132. #define TK_WITH 65
  11133. #define TK_REINDEX 66
  11134. #define TK_RENAME 67
  11135. #define TK_CTIME_KW 68
  11136. #define TK_ANY 69
  11137. #define TK_OR 70
  11138. #define TK_AND 71
  11139. #define TK_IS 72
  11140. #define TK_BETWEEN 73
  11141. #define TK_IN 74
  11142. #define TK_ISNULL 75
  11143. #define TK_NOTNULL 76
  11144. #define TK_NE 77
  11145. #define TK_EQ 78
  11146. #define TK_GT 79
  11147. #define TK_LE 80
  11148. #define TK_LT 81
  11149. #define TK_GE 82
  11150. #define TK_ESCAPE 83
  11151. #define TK_BITAND 84
  11152. #define TK_BITOR 85
  11153. #define TK_LSHIFT 86
  11154. #define TK_RSHIFT 87
  11155. #define TK_PLUS 88
  11156. #define TK_MINUS 89
  11157. #define TK_STAR 90
  11158. #define TK_SLASH 91
  11159. #define TK_REM 92
  11160. #define TK_CONCAT 93
  11161. #define TK_COLLATE 94
  11162. #define TK_BITNOT 95
  11163. #define TK_INDEXED 96
  11164. #define TK_STRING 97
  11165. #define TK_JOIN_KW 98
  11166. #define TK_CONSTRAINT 99
  11167. #define TK_DEFAULT 100
  11168. #define TK_NULL 101
  11169. #define TK_PRIMARY 102
  11170. #define TK_UNIQUE 103
  11171. #define TK_CHECK 104
  11172. #define TK_REFERENCES 105
  11173. #define TK_AUTOINCR 106
  11174. #define TK_ON 107
  11175. #define TK_INSERT 108
  11176. #define TK_DELETE 109
  11177. #define TK_UPDATE 110
  11178. #define TK_SET 111
  11179. #define TK_DEFERRABLE 112
  11180. #define TK_FOREIGN 113
  11181. #define TK_DROP 114
  11182. #define TK_UNION 115
  11183. #define TK_ALL 116
  11184. #define TK_EXCEPT 117
  11185. #define TK_INTERSECT 118
  11186. #define TK_SELECT 119
  11187. #define TK_VALUES 120
  11188. #define TK_DISTINCT 121
  11189. #define TK_DOT 122
  11190. #define TK_FROM 123
  11191. #define TK_JOIN 124
  11192. #define TK_USING 125
  11193. #define TK_ORDER 126
  11194. #define TK_GROUP 127
  11195. #define TK_HAVING 128
  11196. #define TK_LIMIT 129
  11197. #define TK_WHERE 130
  11198. #define TK_INTO 131
  11199. #define TK_FLOAT 132
  11200. #define TK_BLOB 133
  11201. #define TK_INTEGER 134
  11202. #define TK_VARIABLE 135
  11203. #define TK_CASE 136
  11204. #define TK_WHEN 137
  11205. #define TK_THEN 138
  11206. #define TK_ELSE 139
  11207. #define TK_INDEX 140
  11208. #define TK_ALTER 141
  11209. #define TK_ADD 142
  11210. #define TK_TO_TEXT 143
  11211. #define TK_TO_BLOB 144
  11212. #define TK_TO_NUMERIC 145
  11213. #define TK_TO_INT 146
  11214. #define TK_TO_REAL 147
  11215. #define TK_ISNOT 148
  11216. #define TK_END_OF_FILE 149
  11217. #define TK_UNCLOSED_STRING 150
  11218. #define TK_FUNCTION 151
  11219. #define TK_COLUMN 152
  11220. #define TK_AGG_FUNCTION 153
  11221. #define TK_AGG_COLUMN 154
  11222. #define TK_UMINUS 155
  11223. #define TK_UPLUS 156
  11224. #define TK_REGISTER 157
  11225. #define TK_VECTOR 158
  11226. #define TK_SELECT_COLUMN 159
  11227. #define TK_IF_NULL_ROW 160
  11228. #define TK_ASTERISK 161
  11229. #define TK_SPAN 162
  11230. #define TK_SPACE 163
  11231. #define TK_ILLEGAL 164
  11232. /* The token codes above must all fit in 8 bits */
  11233. #define TKFLG_MASK 0xff
  11234. /* Flags that can be added to a token code when it is not
  11235. ** being stored in a u8: */
  11236. #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
  11237. /************** End of parse.h ***********************************************/
  11238. /************** Continuing where we left off in sqliteInt.h ******************/
  11239. #include <stdio.h>
  11240. #include <stdlib.h>
  11241. #include <string.h>
  11242. #include <assert.h>
  11243. #include <stddef.h>
  11244. /*
  11245. ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
  11246. ** This allows better measurements of where memcpy() is used when running
  11247. ** cachegrind. But this macro version of memcpy() is very slow so it
  11248. ** should not be used in production. This is a performance measurement
  11249. ** hack only.
  11250. */
  11251. #ifdef SQLITE_INLINE_MEMCPY
  11252. # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
  11253. int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
  11254. #endif
  11255. /*
  11256. ** If compiling for a processor that lacks floating point support,
  11257. ** substitute integer for floating-point
  11258. */
  11259. #ifdef SQLITE_OMIT_FLOATING_POINT
  11260. # define double sqlite_int64
  11261. # define float sqlite_int64
  11262. # define LONGDOUBLE_TYPE sqlite_int64
  11263. # ifndef SQLITE_BIG_DBL
  11264. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  11265. # endif
  11266. # define SQLITE_OMIT_DATETIME_FUNCS 1
  11267. # define SQLITE_OMIT_TRACE 1
  11268. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  11269. # undef SQLITE_HAVE_ISNAN
  11270. #endif
  11271. #ifndef SQLITE_BIG_DBL
  11272. # define SQLITE_BIG_DBL (1e99)
  11273. #endif
  11274. /*
  11275. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  11276. ** afterward. Having this macro allows us to cause the C compiler
  11277. ** to omit code used by TEMP tables without messy #ifndef statements.
  11278. */
  11279. #ifdef SQLITE_OMIT_TEMPDB
  11280. #define OMIT_TEMPDB 1
  11281. #else
  11282. #define OMIT_TEMPDB 0
  11283. #endif
  11284. /*
  11285. ** The "file format" number is an integer that is incremented whenever
  11286. ** the VDBE-level file format changes. The following macros define the
  11287. ** the default file format for new databases and the maximum file format
  11288. ** that the library can read.
  11289. */
  11290. #define SQLITE_MAX_FILE_FORMAT 4
  11291. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  11292. # define SQLITE_DEFAULT_FILE_FORMAT 4
  11293. #endif
  11294. /*
  11295. ** Determine whether triggers are recursive by default. This can be
  11296. ** changed at run-time using a pragma.
  11297. */
  11298. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  11299. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  11300. #endif
  11301. /*
  11302. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  11303. ** on the command-line
  11304. */
  11305. #ifndef SQLITE_TEMP_STORE
  11306. # define SQLITE_TEMP_STORE 1
  11307. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  11308. #endif
  11309. /*
  11310. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  11311. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  11312. ** to zero.
  11313. */
  11314. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  11315. # undef SQLITE_MAX_WORKER_THREADS
  11316. # define SQLITE_MAX_WORKER_THREADS 0
  11317. #endif
  11318. #ifndef SQLITE_MAX_WORKER_THREADS
  11319. # define SQLITE_MAX_WORKER_THREADS 8
  11320. #endif
  11321. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  11322. # define SQLITE_DEFAULT_WORKER_THREADS 0
  11323. #endif
  11324. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  11325. # undef SQLITE_MAX_WORKER_THREADS
  11326. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  11327. #endif
  11328. /*
  11329. ** The default initial allocation for the pagecache when using separate
  11330. ** pagecaches for each database connection. A positive number is the
  11331. ** number of pages. A negative number N translations means that a buffer
  11332. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  11333. **
  11334. ** The default value of "20" was choosen to minimize the run-time of the
  11335. ** speedtest1 test program with options: --shrink-memory --reprepare
  11336. */
  11337. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  11338. # define SQLITE_DEFAULT_PCACHE_INITSZ 20
  11339. #endif
  11340. /*
  11341. ** GCC does not define the offsetof() macro so we'll have to do it
  11342. ** ourselves.
  11343. */
  11344. #ifndef offsetof
  11345. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  11346. #endif
  11347. /*
  11348. ** Macros to compute minimum and maximum of two numbers.
  11349. */
  11350. #ifndef MIN
  11351. # define MIN(A,B) ((A)<(B)?(A):(B))
  11352. #endif
  11353. #ifndef MAX
  11354. # define MAX(A,B) ((A)>(B)?(A):(B))
  11355. #endif
  11356. /*
  11357. ** Swap two objects of type TYPE.
  11358. */
  11359. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  11360. /*
  11361. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  11362. ** not, there are still machines out there that use EBCDIC.)
  11363. */
  11364. #if 'A' == '\301'
  11365. # define SQLITE_EBCDIC 1
  11366. #else
  11367. # define SQLITE_ASCII 1
  11368. #endif
  11369. /*
  11370. ** Integers of known sizes. These typedefs might change for architectures
  11371. ** where the sizes very. Preprocessor macros are available so that the
  11372. ** types can be conveniently redefined at compile-type. Like this:
  11373. **
  11374. ** cc '-DUINTPTR_TYPE=long long int' ...
  11375. */
  11376. #ifndef UINT32_TYPE
  11377. # ifdef HAVE_UINT32_T
  11378. # define UINT32_TYPE uint32_t
  11379. # else
  11380. # define UINT32_TYPE unsigned int
  11381. # endif
  11382. #endif
  11383. #ifndef UINT16_TYPE
  11384. # ifdef HAVE_UINT16_T
  11385. # define UINT16_TYPE uint16_t
  11386. # else
  11387. # define UINT16_TYPE unsigned short int
  11388. # endif
  11389. #endif
  11390. #ifndef INT16_TYPE
  11391. # ifdef HAVE_INT16_T
  11392. # define INT16_TYPE int16_t
  11393. # else
  11394. # define INT16_TYPE short int
  11395. # endif
  11396. #endif
  11397. #ifndef UINT8_TYPE
  11398. # ifdef HAVE_UINT8_T
  11399. # define UINT8_TYPE uint8_t
  11400. # else
  11401. # define UINT8_TYPE unsigned char
  11402. # endif
  11403. #endif
  11404. #ifndef INT8_TYPE
  11405. # ifdef HAVE_INT8_T
  11406. # define INT8_TYPE int8_t
  11407. # else
  11408. # define INT8_TYPE signed char
  11409. # endif
  11410. #endif
  11411. #ifndef LONGDOUBLE_TYPE
  11412. # define LONGDOUBLE_TYPE long double
  11413. #endif
  11414. typedef sqlite_int64 i64; /* 8-byte signed integer */
  11415. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  11416. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  11417. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  11418. typedef INT16_TYPE i16; /* 2-byte signed integer */
  11419. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  11420. typedef INT8_TYPE i8; /* 1-byte signed integer */
  11421. /*
  11422. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  11423. ** that can be stored in a u32 without loss of data. The value
  11424. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  11425. ** have to specify the value in the less intuitive manner shown:
  11426. */
  11427. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  11428. /*
  11429. ** The datatype used to store estimates of the number of rows in a
  11430. ** table or index. This is an unsigned integer type. For 99.9% of
  11431. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  11432. ** can be used at compile-time if desired.
  11433. */
  11434. #ifdef SQLITE_64BIT_STATS
  11435. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  11436. #else
  11437. typedef u32 tRowcnt; /* 32-bit is the default */
  11438. #endif
  11439. /*
  11440. ** Estimated quantities used for query planning are stored as 16-bit
  11441. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  11442. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  11443. ** But the allowed values are "grainy". Not every value is representable.
  11444. ** For example, quantities 16 and 17 are both represented by a LogEst
  11445. ** of 40. However, since LogEst quantities are suppose to be estimates,
  11446. ** not exact values, this imprecision is not a problem.
  11447. **
  11448. ** "LogEst" is short for "Logarithmic Estimate".
  11449. **
  11450. ** Examples:
  11451. ** 1 -> 0 20 -> 43 10000 -> 132
  11452. ** 2 -> 10 25 -> 46 25000 -> 146
  11453. ** 3 -> 16 100 -> 66 1000000 -> 199
  11454. ** 4 -> 20 1000 -> 99 1048576 -> 200
  11455. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  11456. **
  11457. ** The LogEst can be negative to indicate fractional values.
  11458. ** Examples:
  11459. **
  11460. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  11461. */
  11462. typedef INT16_TYPE LogEst;
  11463. /*
  11464. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  11465. */
  11466. #ifndef SQLITE_PTRSIZE
  11467. # if defined(__SIZEOF_POINTER__)
  11468. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  11469. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  11470. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  11471. # define SQLITE_PTRSIZE 4
  11472. # else
  11473. # define SQLITE_PTRSIZE 8
  11474. # endif
  11475. #endif
  11476. /* The uptr type is an unsigned integer large enough to hold a pointer
  11477. */
  11478. #if defined(HAVE_STDINT_H)
  11479. typedef uintptr_t uptr;
  11480. #elif SQLITE_PTRSIZE==4
  11481. typedef u32 uptr;
  11482. #else
  11483. typedef u64 uptr;
  11484. #endif
  11485. /*
  11486. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  11487. ** something between S (inclusive) and E (exclusive).
  11488. **
  11489. ** In other words, S is a buffer and E is a pointer to the first byte after
  11490. ** the end of buffer S. This macro returns true if P points to something
  11491. ** contained within the buffer S.
  11492. */
  11493. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  11494. /*
  11495. ** Macros to determine whether the machine is big or little endian,
  11496. ** and whether or not that determination is run-time or compile-time.
  11497. **
  11498. ** For best performance, an attempt is made to guess at the byte-order
  11499. ** using C-preprocessor macros. If that is unsuccessful, or if
  11500. ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
  11501. ** at run-time.
  11502. */
  11503. #ifndef SQLITE_BYTEORDER
  11504. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  11505. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  11506. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  11507. defined(__arm__)
  11508. # define SQLITE_BYTEORDER 1234
  11509. # elif defined(sparc) || defined(__ppc__)
  11510. # define SQLITE_BYTEORDER 4321
  11511. # else
  11512. # define SQLITE_BYTEORDER 0
  11513. # endif
  11514. #endif
  11515. #if SQLITE_BYTEORDER==4321
  11516. # define SQLITE_BIGENDIAN 1
  11517. # define SQLITE_LITTLEENDIAN 0
  11518. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  11519. #elif SQLITE_BYTEORDER==1234
  11520. # define SQLITE_BIGENDIAN 0
  11521. # define SQLITE_LITTLEENDIAN 1
  11522. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  11523. #else
  11524. # ifdef SQLITE_AMALGAMATION
  11525. const int sqlite3one = 1;
  11526. # else
  11527. extern const int sqlite3one;
  11528. # endif
  11529. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  11530. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  11531. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  11532. #endif
  11533. /*
  11534. ** Constants for the largest and smallest possible 64-bit signed integers.
  11535. ** These macros are designed to work correctly on both 32-bit and 64-bit
  11536. ** compilers.
  11537. */
  11538. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  11539. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  11540. /*
  11541. ** Round up a number to the next larger multiple of 8. This is used
  11542. ** to force 8-byte alignment on 64-bit architectures.
  11543. */
  11544. #define ROUND8(x) (((x)+7)&~7)
  11545. /*
  11546. ** Round down to the nearest multiple of 8
  11547. */
  11548. #define ROUNDDOWN8(x) ((x)&~7)
  11549. /*
  11550. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  11551. ** macro is used only within assert() to verify that the code gets
  11552. ** all alignment restrictions correct.
  11553. **
  11554. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  11555. ** underlying malloc() implementation might return us 4-byte aligned
  11556. ** pointers. In that case, only verify 4-byte alignment.
  11557. */
  11558. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  11559. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  11560. #else
  11561. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  11562. #endif
  11563. /*
  11564. ** Disable MMAP on platforms where it is known to not work
  11565. */
  11566. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  11567. # undef SQLITE_MAX_MMAP_SIZE
  11568. # define SQLITE_MAX_MMAP_SIZE 0
  11569. #endif
  11570. /*
  11571. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  11572. */
  11573. #ifdef __APPLE__
  11574. # include <TargetConditionals.h>
  11575. #endif
  11576. #ifndef SQLITE_MAX_MMAP_SIZE
  11577. # if defined(__linux__) \
  11578. || defined(_WIN32) \
  11579. || (defined(__APPLE__) && defined(__MACH__)) \
  11580. || defined(__sun) \
  11581. || defined(__FreeBSD__) \
  11582. || defined(__DragonFly__)
  11583. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  11584. # else
  11585. # define SQLITE_MAX_MMAP_SIZE 0
  11586. # endif
  11587. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  11588. #endif
  11589. /*
  11590. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  11591. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  11592. ** not exceed the maximum mmap size.
  11593. */
  11594. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  11595. # define SQLITE_DEFAULT_MMAP_SIZE 0
  11596. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  11597. #endif
  11598. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  11599. # undef SQLITE_DEFAULT_MMAP_SIZE
  11600. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  11601. #endif
  11602. /*
  11603. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  11604. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  11605. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  11606. */
  11607. #ifdef SQLITE_ENABLE_STAT4
  11608. # undef SQLITE_ENABLE_STAT3
  11609. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  11610. #elif SQLITE_ENABLE_STAT3
  11611. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  11612. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  11613. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  11614. #endif
  11615. /*
  11616. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  11617. ** the Select query generator tracing logic is turned on.
  11618. */
  11619. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
  11620. # define SELECTTRACE_ENABLED 1
  11621. #else
  11622. # define SELECTTRACE_ENABLED 0
  11623. #endif
  11624. /*
  11625. ** An instance of the following structure is used to store the busy-handler
  11626. ** callback for a given sqlite handle.
  11627. **
  11628. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  11629. ** callback for the database handle. Each pager opened via the sqlite
  11630. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  11631. ** callback is currently invoked only from within pager.c.
  11632. */
  11633. typedef struct BusyHandler BusyHandler;
  11634. struct BusyHandler {
  11635. int (*xFunc)(void *,int); /* The busy callback */
  11636. void *pArg; /* First arg to busy callback */
  11637. int nBusy; /* Incremented with each busy call */
  11638. };
  11639. /*
  11640. ** Name of the master database table. The master database table
  11641. ** is a special table that holds the names and attributes of all
  11642. ** user tables and indices.
  11643. */
  11644. #define MASTER_NAME "sqlite_master"
  11645. #define TEMP_MASTER_NAME "sqlite_temp_master"
  11646. /*
  11647. ** The root-page of the master database table.
  11648. */
  11649. #define MASTER_ROOT 1
  11650. /*
  11651. ** The name of the schema table.
  11652. */
  11653. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  11654. /*
  11655. ** A convenience macro that returns the number of elements in
  11656. ** an array.
  11657. */
  11658. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  11659. /*
  11660. ** Determine if the argument is a power of two
  11661. */
  11662. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  11663. /*
  11664. ** The following value as a destructor means to use sqlite3DbFree().
  11665. ** The sqlite3DbFree() routine requires two parameters instead of the
  11666. ** one parameter that destructors normally want. So we have to introduce
  11667. ** this magic value that the code knows to handle differently. Any
  11668. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  11669. ** and SQLITE_TRANSIENT.
  11670. */
  11671. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  11672. /*
  11673. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  11674. ** not support Writable Static Data (WSD) such as global and static variables.
  11675. ** All variables must either be on the stack or dynamically allocated from
  11676. ** the heap. When WSD is unsupported, the variable declarations scattered
  11677. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  11678. ** macro is used for this purpose. And instead of referencing the variable
  11679. ** directly, we use its constant as a key to lookup the run-time allocated
  11680. ** buffer that holds real variable. The constant is also the initializer
  11681. ** for the run-time allocated buffer.
  11682. **
  11683. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  11684. ** macros become no-ops and have zero performance impact.
  11685. */
  11686. #ifdef SQLITE_OMIT_WSD
  11687. #define SQLITE_WSD const
  11688. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  11689. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  11690. SQLITE_API int sqlite3_wsd_init(int N, int J);
  11691. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  11692. #else
  11693. #define SQLITE_WSD
  11694. #define GLOBAL(t,v) v
  11695. #define sqlite3GlobalConfig sqlite3Config
  11696. #endif
  11697. /*
  11698. ** The following macros are used to suppress compiler warnings and to
  11699. ** make it clear to human readers when a function parameter is deliberately
  11700. ** left unused within the body of a function. This usually happens when
  11701. ** a function is called via a function pointer. For example the
  11702. ** implementation of an SQL aggregate step callback may not use the
  11703. ** parameter indicating the number of arguments passed to the aggregate,
  11704. ** if it knows that this is enforced elsewhere.
  11705. **
  11706. ** When a function parameter is not used at all within the body of a function,
  11707. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  11708. ** However, these macros may also be used to suppress warnings related to
  11709. ** parameters that may or may not be used depending on compilation options.
  11710. ** For example those parameters only used in assert() statements. In these
  11711. ** cases the parameters are named as per the usual conventions.
  11712. */
  11713. #define UNUSED_PARAMETER(x) (void)(x)
  11714. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  11715. /*
  11716. ** Forward references to structures
  11717. */
  11718. typedef struct AggInfo AggInfo;
  11719. typedef struct AuthContext AuthContext;
  11720. typedef struct AutoincInfo AutoincInfo;
  11721. typedef struct Bitvec Bitvec;
  11722. typedef struct CollSeq CollSeq;
  11723. typedef struct Column Column;
  11724. typedef struct Db Db;
  11725. typedef struct Schema Schema;
  11726. typedef struct Expr Expr;
  11727. typedef struct ExprList ExprList;
  11728. typedef struct ExprSpan ExprSpan;
  11729. typedef struct FKey FKey;
  11730. typedef struct FuncDestructor FuncDestructor;
  11731. typedef struct FuncDef FuncDef;
  11732. typedef struct FuncDefHash FuncDefHash;
  11733. typedef struct IdList IdList;
  11734. typedef struct Index Index;
  11735. typedef struct IndexSample IndexSample;
  11736. typedef struct KeyClass KeyClass;
  11737. typedef struct KeyInfo KeyInfo;
  11738. typedef struct Lookaside Lookaside;
  11739. typedef struct LookasideSlot LookasideSlot;
  11740. typedef struct Module Module;
  11741. typedef struct NameContext NameContext;
  11742. typedef struct Parse Parse;
  11743. typedef struct PreUpdate PreUpdate;
  11744. typedef struct PrintfArguments PrintfArguments;
  11745. typedef struct RowSet RowSet;
  11746. typedef struct Savepoint Savepoint;
  11747. typedef struct Select Select;
  11748. typedef struct SQLiteThread SQLiteThread;
  11749. typedef struct SelectDest SelectDest;
  11750. typedef struct SrcList SrcList;
  11751. typedef struct StrAccum StrAccum;
  11752. typedef struct Table Table;
  11753. typedef struct TableLock TableLock;
  11754. typedef struct Token Token;
  11755. typedef struct TreeView TreeView;
  11756. typedef struct Trigger Trigger;
  11757. typedef struct TriggerPrg TriggerPrg;
  11758. typedef struct TriggerStep TriggerStep;
  11759. typedef struct UnpackedRecord UnpackedRecord;
  11760. typedef struct VTable VTable;
  11761. typedef struct VtabCtx VtabCtx;
  11762. typedef struct Walker Walker;
  11763. typedef struct WhereInfo WhereInfo;
  11764. typedef struct With With;
  11765. /* A VList object records a mapping between parameters/variables/wildcards
  11766. ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
  11767. ** variable number associated with that parameter. See the format description
  11768. ** on the sqlite3VListAdd() routine for more information. A VList is really
  11769. ** just an array of integers.
  11770. */
  11771. typedef int VList;
  11772. /*
  11773. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  11774. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  11775. ** pointer types (i.e. FuncDef) defined above.
  11776. */
  11777. /************** Include btree.h in the middle of sqliteInt.h *****************/
  11778. /************** Begin file btree.h *******************************************/
  11779. /*
  11780. ** 2001 September 15
  11781. **
  11782. ** The author disclaims copyright to this source code. In place of
  11783. ** a legal notice, here is a blessing:
  11784. **
  11785. ** May you do good and not evil.
  11786. ** May you find forgiveness for yourself and forgive others.
  11787. ** May you share freely, never taking more than you give.
  11788. **
  11789. *************************************************************************
  11790. ** This header file defines the interface that the sqlite B-Tree file
  11791. ** subsystem. See comments in the source code for a detailed description
  11792. ** of what each interface routine does.
  11793. */
  11794. #ifndef SQLITE_BTREE_H
  11795. #define SQLITE_BTREE_H
  11796. /* TODO: This definition is just included so other modules compile. It
  11797. ** needs to be revisited.
  11798. */
  11799. #define SQLITE_N_BTREE_META 16
  11800. /*
  11801. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  11802. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  11803. */
  11804. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  11805. #define SQLITE_DEFAULT_AUTOVACUUM 0
  11806. #endif
  11807. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  11808. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  11809. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  11810. /*
  11811. ** Forward declarations of structure
  11812. */
  11813. typedef struct Btree Btree;
  11814. typedef struct BtCursor BtCursor;
  11815. typedef struct BtShared BtShared;
  11816. typedef struct BtreePayload BtreePayload;
  11817. SQLITE_PRIVATE int sqlite3BtreeOpen(
  11818. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  11819. const char *zFilename, /* Name of database file to open */
  11820. sqlite3 *db, /* Associated database connection */
  11821. Btree **ppBtree, /* Return open Btree* here */
  11822. int flags, /* Flags */
  11823. int vfsFlags /* Flags passed through to VFS open */
  11824. );
  11825. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  11826. ** following values.
  11827. **
  11828. ** NOTE: These values must match the corresponding PAGER_ values in
  11829. ** pager.h.
  11830. */
  11831. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  11832. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  11833. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  11834. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  11835. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  11836. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  11837. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  11838. #if SQLITE_MAX_MMAP_SIZE>0
  11839. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  11840. #endif
  11841. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  11842. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  11843. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  11844. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  11845. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  11846. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  11847. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  11848. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  11849. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  11850. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  11851. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  11852. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  11853. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  11854. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  11855. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  11856. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  11857. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  11858. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  11859. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  11860. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  11861. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  11862. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  11863. #ifndef SQLITE_OMIT_SHARED_CACHE
  11864. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  11865. #endif
  11866. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  11867. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  11868. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  11869. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  11870. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  11871. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  11872. ** of the flags shown below.
  11873. **
  11874. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  11875. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  11876. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  11877. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  11878. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  11879. ** indices.)
  11880. */
  11881. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  11882. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  11883. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  11884. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  11885. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  11886. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  11887. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  11888. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  11889. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  11890. /*
  11891. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  11892. ** should be one of the following values. The integer values are assigned
  11893. ** to constants so that the offset of the corresponding field in an
  11894. ** SQLite database header may be found using the following formula:
  11895. **
  11896. ** offset = 36 + (idx * 4)
  11897. **
  11898. ** For example, the free-page-count field is located at byte offset 36 of
  11899. ** the database file header. The incr-vacuum-flag field is located at
  11900. ** byte offset 64 (== 36+4*7).
  11901. **
  11902. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  11903. ** It is a read-only number computed by the pager. But we merge it with
  11904. ** the header value access routines since its access pattern is the same.
  11905. ** Call it a "virtual meta value".
  11906. */
  11907. #define BTREE_FREE_PAGE_COUNT 0
  11908. #define BTREE_SCHEMA_VERSION 1
  11909. #define BTREE_FILE_FORMAT 2
  11910. #define BTREE_DEFAULT_CACHE_SIZE 3
  11911. #define BTREE_LARGEST_ROOT_PAGE 4
  11912. #define BTREE_TEXT_ENCODING 5
  11913. #define BTREE_USER_VERSION 6
  11914. #define BTREE_INCR_VACUUM 7
  11915. #define BTREE_APPLICATION_ID 8
  11916. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  11917. /*
  11918. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  11919. ** interface.
  11920. **
  11921. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  11922. **
  11923. ** The first argument is an Expr* (which is guaranteed to be constant for
  11924. ** the lifetime of the cursor) that defines constraints on which rows
  11925. ** might be fetched with this cursor. The Expr* tree may contain
  11926. ** TK_REGISTER nodes that refer to values stored in the array of registers
  11927. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  11928. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  11929. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  11930. ** column of the b-tree of the cursor. The Expr tree will not contain
  11931. ** any function calls nor subqueries nor references to b-trees other than
  11932. ** the cursor being hinted.
  11933. **
  11934. ** The design of the _RANGE hint is aid b-tree implementations that try
  11935. ** to prefetch content from remote machines - to provide those
  11936. ** implementations with limits on what needs to be prefetched and thereby
  11937. ** reduce network bandwidth.
  11938. **
  11939. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  11940. ** standard SQLite. The other hints are provided for extentions that use
  11941. ** the SQLite parser and code generator but substitute their own storage
  11942. ** engine.
  11943. */
  11944. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  11945. /*
  11946. ** Values that may be OR'd together to form the argument to the
  11947. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  11948. **
  11949. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  11950. ** to be filled with content that is already in sorted order.
  11951. **
  11952. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  11953. ** OP_SeekLE opcodes for a range search, but where the range of entries
  11954. ** selected will all have the same key. In other words, the cursor will
  11955. ** be used only for equality key searches.
  11956. **
  11957. */
  11958. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  11959. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  11960. /*
  11961. ** Flags passed as the third argument to sqlite3BtreeCursor().
  11962. **
  11963. ** For read-only cursors the wrFlag argument is always zero. For read-write
  11964. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  11965. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  11966. ** only be used by SQLite for the following:
  11967. **
  11968. ** * to seek to and then delete specific entries, and/or
  11969. **
  11970. ** * to read values that will be used to create keys that other
  11971. ** BTREE_FORDELETE cursors will seek to and delete.
  11972. **
  11973. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  11974. ** by this, the native b-tree engine of SQLite, but it is available to
  11975. ** alternative storage engines that might be substituted in place of this
  11976. ** b-tree system. For alternative storage engines in which a delete of
  11977. ** the main table row automatically deletes corresponding index rows,
  11978. ** the FORDELETE flag hint allows those alternative storage engines to
  11979. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  11980. ** and DELETE operations as no-ops, and any READ operation against a
  11981. ** FORDELETE cursor may return a null row: 0x01 0x00.
  11982. */
  11983. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  11984. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  11985. SQLITE_PRIVATE int sqlite3BtreeCursor(
  11986. Btree*, /* BTree containing table to open */
  11987. int iTable, /* Index of root page */
  11988. int wrFlag, /* 1 for writing. 0 for read-only */
  11989. struct KeyInfo*, /* First argument to compare function */
  11990. BtCursor *pCursor /* Space to write cursor structure */
  11991. );
  11992. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  11993. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  11994. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  11995. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  11996. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  11997. #endif
  11998. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  11999. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  12000. BtCursor*,
  12001. UnpackedRecord *pUnKey,
  12002. i64 intKey,
  12003. int bias,
  12004. int *pRes
  12005. );
  12006. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  12007. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  12008. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  12009. /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
  12010. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  12011. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  12012. #define BTREE_APPEND 0x08 /* Insert is likely an append */
  12013. /* An instance of the BtreePayload object describes the content of a single
  12014. ** entry in either an index or table btree.
  12015. **
  12016. ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
  12017. ** an arbitrary key and no data. These btrees have pKey,nKey set to their
  12018. ** key and pData,nData,nZero set to zero.
  12019. **
  12020. ** Table btrees (used for rowid tables) contain an integer rowid used as
  12021. ** the key and passed in the nKey field. The pKey field is zero.
  12022. ** pData,nData hold the content of the new entry. nZero extra zero bytes
  12023. ** are appended to the end of the content when constructing the entry.
  12024. **
  12025. ** This object is used to pass information into sqlite3BtreeInsert(). The
  12026. ** same information used to be passed as five separate parameters. But placing
  12027. ** the information into this object helps to keep the interface more
  12028. ** organized and understandable, and it also helps the resulting code to
  12029. ** run a little faster by using fewer registers for parameter passing.
  12030. */
  12031. struct BtreePayload {
  12032. const void *pKey; /* Key content for indexes. NULL for tables */
  12033. sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
  12034. const void *pData; /* Data for tables. NULL for indexes */
  12035. sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
  12036. u16 nMem; /* Number of aMem[] value. Might be zero */
  12037. int nData; /* Size of pData. 0 if none. */
  12038. int nZero; /* Extra zero data appended after pData,nData */
  12039. };
  12040. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
  12041. int flags, int seekResult);
  12042. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  12043. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  12044. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  12045. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  12046. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  12047. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
  12048. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
  12049. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
  12050. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
  12051. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  12052. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  12053. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
  12054. #ifndef SQLITE_OMIT_INCRBLOB
  12055. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
  12056. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  12057. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  12058. #endif
  12059. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  12060. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  12061. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  12062. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  12063. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  12064. #ifndef NDEBUG
  12065. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  12066. #endif
  12067. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
  12068. #ifndef SQLITE_OMIT_BTREECOUNT
  12069. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  12070. #endif
  12071. #ifdef SQLITE_TEST
  12072. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  12073. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  12074. #endif
  12075. #ifndef SQLITE_OMIT_WAL
  12076. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  12077. #endif
  12078. /*
  12079. ** If we are not using shared cache, then there is no need to
  12080. ** use mutexes to access the BtShared structures. So make the
  12081. ** Enter and Leave procedures no-ops.
  12082. */
  12083. #ifndef SQLITE_OMIT_SHARED_CACHE
  12084. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  12085. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  12086. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  12087. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  12088. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
  12089. #else
  12090. # define sqlite3BtreeEnter(X)
  12091. # define sqlite3BtreeEnterAll(X)
  12092. # define sqlite3BtreeSharable(X) 0
  12093. # define sqlite3BtreeEnterCursor(X)
  12094. # define sqlite3BtreeConnectionCount(X) 1
  12095. #endif
  12096. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  12097. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  12098. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  12099. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  12100. #ifndef NDEBUG
  12101. /* These routines are used inside assert() statements only. */
  12102. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  12103. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  12104. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  12105. #endif
  12106. #else
  12107. # define sqlite3BtreeLeave(X)
  12108. # define sqlite3BtreeLeaveCursor(X)
  12109. # define sqlite3BtreeLeaveAll(X)
  12110. # define sqlite3BtreeHoldsMutex(X) 1
  12111. # define sqlite3BtreeHoldsAllMutexes(X) 1
  12112. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  12113. #endif
  12114. #endif /* SQLITE_BTREE_H */
  12115. /************** End of btree.h ***********************************************/
  12116. /************** Continuing where we left off in sqliteInt.h ******************/
  12117. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  12118. /************** Begin file vdbe.h ********************************************/
  12119. /*
  12120. ** 2001 September 15
  12121. **
  12122. ** The author disclaims copyright to this source code. In place of
  12123. ** a legal notice, here is a blessing:
  12124. **
  12125. ** May you do good and not evil.
  12126. ** May you find forgiveness for yourself and forgive others.
  12127. ** May you share freely, never taking more than you give.
  12128. **
  12129. *************************************************************************
  12130. ** Header file for the Virtual DataBase Engine (VDBE)
  12131. **
  12132. ** This header defines the interface to the virtual database engine
  12133. ** or VDBE. The VDBE implements an abstract machine that runs a
  12134. ** simple program to access and modify the underlying database.
  12135. */
  12136. #ifndef SQLITE_VDBE_H
  12137. #define SQLITE_VDBE_H
  12138. /* #include <stdio.h> */
  12139. /*
  12140. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  12141. ** in the source file sqliteVdbe.c are allowed to see the insides
  12142. ** of this structure.
  12143. */
  12144. typedef struct Vdbe Vdbe;
  12145. /*
  12146. ** The names of the following types declared in vdbeInt.h are required
  12147. ** for the VdbeOp definition.
  12148. */
  12149. typedef struct sqlite3_value Mem;
  12150. typedef struct SubProgram SubProgram;
  12151. /*
  12152. ** A single instruction of the virtual machine has an opcode
  12153. ** and as many as three operands. The instruction is recorded
  12154. ** as an instance of the following structure:
  12155. */
  12156. struct VdbeOp {
  12157. u8 opcode; /* What operation to perform */
  12158. signed char p4type; /* One of the P4_xxx constants for p4 */
  12159. u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
  12160. int p1; /* First operand */
  12161. int p2; /* Second parameter (often the jump destination) */
  12162. int p3; /* The third parameter */
  12163. union p4union { /* fourth parameter */
  12164. int i; /* Integer value if p4type==P4_INT32 */
  12165. void *p; /* Generic pointer */
  12166. char *z; /* Pointer to data for string (char array) types */
  12167. i64 *pI64; /* Used when p4type is P4_INT64 */
  12168. double *pReal; /* Used when p4type is P4_REAL */
  12169. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  12170. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  12171. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  12172. Mem *pMem; /* Used when p4type is P4_MEM */
  12173. VTable *pVtab; /* Used when p4type is P4_VTAB */
  12174. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  12175. int *ai; /* Used when p4type is P4_INTARRAY */
  12176. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  12177. Table *pTab; /* Used when p4type is P4_TABLE */
  12178. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  12179. Expr *pExpr; /* Used when p4type is P4_EXPR */
  12180. #endif
  12181. int (*xAdvance)(BtCursor *, int *);
  12182. } p4;
  12183. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  12184. char *zComment; /* Comment to improve readability */
  12185. #endif
  12186. #ifdef VDBE_PROFILE
  12187. u32 cnt; /* Number of times this instruction was executed */
  12188. u64 cycles; /* Total time spent executing this instruction */
  12189. #endif
  12190. #ifdef SQLITE_VDBE_COVERAGE
  12191. int iSrcLine; /* Source-code line that generated this opcode */
  12192. #endif
  12193. };
  12194. typedef struct VdbeOp VdbeOp;
  12195. /*
  12196. ** A sub-routine used to implement a trigger program.
  12197. */
  12198. struct SubProgram {
  12199. VdbeOp *aOp; /* Array of opcodes for sub-program */
  12200. int nOp; /* Elements in aOp[] */
  12201. int nMem; /* Number of memory cells required */
  12202. int nCsr; /* Number of cursors required */
  12203. u8 *aOnce; /* Array of OP_Once flags */
  12204. void *token; /* id that may be used to recursive triggers */
  12205. SubProgram *pNext; /* Next sub-program already visited */
  12206. };
  12207. /*
  12208. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  12209. ** it takes up less space.
  12210. */
  12211. struct VdbeOpList {
  12212. u8 opcode; /* What operation to perform */
  12213. signed char p1; /* First operand */
  12214. signed char p2; /* Second parameter (often the jump destination) */
  12215. signed char p3; /* Third parameter */
  12216. };
  12217. typedef struct VdbeOpList VdbeOpList;
  12218. /*
  12219. ** Allowed values of VdbeOp.p4type
  12220. */
  12221. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  12222. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  12223. #define P4_STATIC (-2) /* Pointer to a static string */
  12224. #define P4_COLLSEQ (-3) /* P4 is a pointer to a CollSeq structure */
  12225. #define P4_FUNCDEF (-4) /* P4 is a pointer to a FuncDef structure */
  12226. #define P4_KEYINFO (-5) /* P4 is a pointer to a KeyInfo structure */
  12227. #define P4_EXPR (-6) /* P4 is a pointer to an Expr tree */
  12228. #define P4_MEM (-7) /* P4 is a pointer to a Mem* structure */
  12229. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  12230. #define P4_VTAB (-8) /* P4 is a pointer to an sqlite3_vtab structure */
  12231. #define P4_REAL (-9) /* P4 is a 64-bit floating point value */
  12232. #define P4_INT64 (-10) /* P4 is a 64-bit signed integer */
  12233. #define P4_INT32 (-11) /* P4 is a 32-bit signed integer */
  12234. #define P4_INTARRAY (-12) /* P4 is a vector of 32-bit integers */
  12235. #define P4_SUBPROGRAM (-13) /* P4 is a pointer to a SubProgram structure */
  12236. #define P4_ADVANCE (-14) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  12237. #define P4_TABLE (-15) /* P4 is a pointer to a Table structure */
  12238. #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
  12239. /* Error message codes for OP_Halt */
  12240. #define P5_ConstraintNotNull 1
  12241. #define P5_ConstraintUnique 2
  12242. #define P5_ConstraintCheck 3
  12243. #define P5_ConstraintFK 4
  12244. /*
  12245. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  12246. ** number of columns of data returned by the statement.
  12247. */
  12248. #define COLNAME_NAME 0
  12249. #define COLNAME_DECLTYPE 1
  12250. #define COLNAME_DATABASE 2
  12251. #define COLNAME_TABLE 3
  12252. #define COLNAME_COLUMN 4
  12253. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  12254. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  12255. #else
  12256. # ifdef SQLITE_OMIT_DECLTYPE
  12257. # define COLNAME_N 1 /* Store only the name */
  12258. # else
  12259. # define COLNAME_N 2 /* Store the name and decltype */
  12260. # endif
  12261. #endif
  12262. /*
  12263. ** The following macro converts a relative address in the p2 field
  12264. ** of a VdbeOp structure into a negative number so that
  12265. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  12266. ** the macro again restores the address.
  12267. */
  12268. #define ADDR(X) (-1-(X))
  12269. /*
  12270. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  12271. ** header file that defines a number for each opcode used by the VDBE.
  12272. */
  12273. /************** Include opcodes.h in the middle of vdbe.h ********************/
  12274. /************** Begin file opcodes.h *****************************************/
  12275. /* Automatically generated. Do not edit */
  12276. /* See the tool/mkopcodeh.tcl script for details */
  12277. #define OP_Savepoint 0
  12278. #define OP_AutoCommit 1
  12279. #define OP_Transaction 2
  12280. #define OP_SorterNext 3
  12281. #define OP_PrevIfOpen 4
  12282. #define OP_NextIfOpen 5
  12283. #define OP_Prev 6
  12284. #define OP_Next 7
  12285. #define OP_Checkpoint 8
  12286. #define OP_JournalMode 9
  12287. #define OP_Vacuum 10
  12288. #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
  12289. #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
  12290. #define OP_Goto 13
  12291. #define OP_Gosub 14
  12292. #define OP_InitCoroutine 15
  12293. #define OP_Yield 16
  12294. #define OP_MustBeInt 17
  12295. #define OP_Jump 18
  12296. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  12297. #define OP_Once 20
  12298. #define OP_If 21
  12299. #define OP_IfNot 22
  12300. #define OP_IfNullRow 23 /* synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
  12301. #define OP_SeekLT 24 /* synopsis: key=r[P3@P4] */
  12302. #define OP_SeekLE 25 /* synopsis: key=r[P3@P4] */
  12303. #define OP_SeekGE 26 /* synopsis: key=r[P3@P4] */
  12304. #define OP_SeekGT 27 /* synopsis: key=r[P3@P4] */
  12305. #define OP_NoConflict 28 /* synopsis: key=r[P3@P4] */
  12306. #define OP_NotFound 29 /* synopsis: key=r[P3@P4] */
  12307. #define OP_Found 30 /* synopsis: key=r[P3@P4] */
  12308. #define OP_SeekRowid 31 /* synopsis: intkey=r[P3] */
  12309. #define OP_NotExists 32 /* synopsis: intkey=r[P3] */
  12310. #define OP_Last 33
  12311. #define OP_IfSmaller 34
  12312. #define OP_SorterSort 35
  12313. #define OP_Sort 36
  12314. #define OP_Rewind 37
  12315. #define OP_IdxLE 38 /* synopsis: key=r[P3@P4] */
  12316. #define OP_IdxGT 39 /* synopsis: key=r[P3@P4] */
  12317. #define OP_IdxLT 40 /* synopsis: key=r[P3@P4] */
  12318. #define OP_IdxGE 41 /* synopsis: key=r[P3@P4] */
  12319. #define OP_RowSetRead 42 /* synopsis: r[P3]=rowset(P1) */
  12320. #define OP_RowSetTest 43 /* synopsis: if r[P3] in rowset(P1) goto P2 */
  12321. #define OP_Program 44
  12322. #define OP_FkIfZero 45 /* synopsis: if fkctr[P1]==0 goto P2 */
  12323. #define OP_IfPos 46 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  12324. #define OP_IfNotZero 47 /* synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
  12325. #define OP_DecrJumpZero 48 /* synopsis: if (--r[P1])==0 goto P2 */
  12326. #define OP_IncrVacuum 49
  12327. #define OP_VNext 50
  12328. #define OP_Init 51 /* synopsis: Start at P2 */
  12329. #define OP_Return 52
  12330. #define OP_EndCoroutine 53
  12331. #define OP_HaltIfNull 54 /* synopsis: if r[P3]=null halt */
  12332. #define OP_Halt 55
  12333. #define OP_Integer 56 /* synopsis: r[P2]=P1 */
  12334. #define OP_Int64 57 /* synopsis: r[P2]=P4 */
  12335. #define OP_String 58 /* synopsis: r[P2]='P4' (len=P1) */
  12336. #define OP_Null 59 /* synopsis: r[P2..P3]=NULL */
  12337. #define OP_SoftNull 60 /* synopsis: r[P1]=NULL */
  12338. #define OP_Blob 61 /* synopsis: r[P2]=P4 (len=P1) */
  12339. #define OP_Variable 62 /* synopsis: r[P2]=parameter(P1,P4) */
  12340. #define OP_Move 63 /* synopsis: r[P2@P3]=r[P1@P3] */
  12341. #define OP_Copy 64 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  12342. #define OP_SCopy 65 /* synopsis: r[P2]=r[P1] */
  12343. #define OP_IntCopy 66 /* synopsis: r[P2]=r[P1] */
  12344. #define OP_ResultRow 67 /* synopsis: output=r[P1@P2] */
  12345. #define OP_CollSeq 68
  12346. #define OP_Function0 69 /* synopsis: r[P3]=func(r[P2@P5]) */
  12347. #define OP_Or 70 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  12348. #define OP_And 71 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  12349. #define OP_Function 72 /* synopsis: r[P3]=func(r[P2@P5]) */
  12350. #define OP_AddImm 73 /* synopsis: r[P1]=r[P1]+P2 */
  12351. #define OP_RealAffinity 74
  12352. #define OP_IsNull 75 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  12353. #define OP_NotNull 76 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  12354. #define OP_Ne 77 /* same as TK_NE, synopsis: IF r[P3]!=r[P1] */
  12355. #define OP_Eq 78 /* same as TK_EQ, synopsis: IF r[P3]==r[P1] */
  12356. #define OP_Gt 79 /* same as TK_GT, synopsis: IF r[P3]>r[P1] */
  12357. #define OP_Le 80 /* same as TK_LE, synopsis: IF r[P3]<=r[P1] */
  12358. #define OP_Lt 81 /* same as TK_LT, synopsis: IF r[P3]<r[P1] */
  12359. #define OP_Ge 82 /* same as TK_GE, synopsis: IF r[P3]>=r[P1] */
  12360. #define OP_ElseNotEq 83 /* same as TK_ESCAPE */
  12361. #define OP_BitAnd 84 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  12362. #define OP_BitOr 85 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  12363. #define OP_ShiftLeft 86 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  12364. #define OP_ShiftRight 87 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  12365. #define OP_Add 88 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  12366. #define OP_Subtract 89 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  12367. #define OP_Multiply 90 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  12368. #define OP_Divide 91 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  12369. #define OP_Remainder 92 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  12370. #define OP_Concat 93 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  12371. #define OP_Cast 94 /* synopsis: affinity(r[P1]) */
  12372. #define OP_BitNot 95 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  12373. #define OP_Permutation 96
  12374. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  12375. #define OP_Compare 98 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  12376. #define OP_Column 99 /* synopsis: r[P3]=PX */
  12377. #define OP_Affinity 100 /* synopsis: affinity(r[P1@P2]) */
  12378. #define OP_MakeRecord 101 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  12379. #define OP_Count 102 /* synopsis: r[P2]=count() */
  12380. #define OP_ReadCookie 103
  12381. #define OP_SetCookie 104
  12382. #define OP_ReopenIdx 105 /* synopsis: root=P2 iDb=P3 */
  12383. #define OP_OpenRead 106 /* synopsis: root=P2 iDb=P3 */
  12384. #define OP_OpenWrite 107 /* synopsis: root=P2 iDb=P3 */
  12385. #define OP_OpenDup 108
  12386. #define OP_OpenAutoindex 109 /* synopsis: nColumn=P2 */
  12387. #define OP_OpenEphemeral 110 /* synopsis: nColumn=P2 */
  12388. #define OP_SorterOpen 111
  12389. #define OP_SequenceTest 112 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  12390. #define OP_OpenPseudo 113 /* synopsis: P3 columns in r[P2] */
  12391. #define OP_Close 114
  12392. #define OP_ColumnsUsed 115
  12393. #define OP_Sequence 116 /* synopsis: r[P2]=cursor[P1].ctr++ */
  12394. #define OP_NewRowid 117 /* synopsis: r[P2]=rowid */
  12395. #define OP_Insert 118 /* synopsis: intkey=r[P3] data=r[P2] */
  12396. #define OP_InsertInt 119 /* synopsis: intkey=P3 data=r[P2] */
  12397. #define OP_Delete 120
  12398. #define OP_ResetCount 121
  12399. #define OP_SorterCompare 122 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  12400. #define OP_SorterData 123 /* synopsis: r[P2]=data */
  12401. #define OP_RowData 124 /* synopsis: r[P2]=data */
  12402. #define OP_Rowid 125 /* synopsis: r[P2]=rowid */
  12403. #define OP_NullRow 126
  12404. #define OP_SorterInsert 127 /* synopsis: key=r[P2] */
  12405. #define OP_IdxInsert 128 /* synopsis: key=r[P2] */
  12406. #define OP_IdxDelete 129 /* synopsis: key=r[P2@P3] */
  12407. #define OP_Seek 130 /* synopsis: Move P3 to P1.rowid */
  12408. #define OP_IdxRowid 131 /* synopsis: r[P2]=rowid */
  12409. #define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  12410. #define OP_Destroy 133
  12411. #define OP_Clear 134
  12412. #define OP_ResetSorter 135
  12413. #define OP_CreateIndex 136 /* synopsis: r[P2]=root iDb=P1 */
  12414. #define OP_CreateTable 137 /* synopsis: r[P2]=root iDb=P1 */
  12415. #define OP_SqlExec 138
  12416. #define OP_ParseSchema 139
  12417. #define OP_LoadAnalysis 140
  12418. #define OP_DropTable 141
  12419. #define OP_DropIndex 142
  12420. #define OP_DropTrigger 143
  12421. #define OP_IntegrityCk 144
  12422. #define OP_RowSetAdd 145 /* synopsis: rowset(P1)=r[P2] */
  12423. #define OP_Param 146
  12424. #define OP_FkCounter 147 /* synopsis: fkctr[P1]+=P2 */
  12425. #define OP_MemMax 148 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  12426. #define OP_OffsetLimit 149 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  12427. #define OP_AggStep0 150 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  12428. #define OP_AggStep 151 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  12429. #define OP_AggFinal 152 /* synopsis: accum=r[P1] N=P2 */
  12430. #define OP_Expire 153
  12431. #define OP_TableLock 154 /* synopsis: iDb=P1 root=P2 write=P3 */
  12432. #define OP_VBegin 155
  12433. #define OP_VCreate 156
  12434. #define OP_VDestroy 157
  12435. #define OP_VOpen 158
  12436. #define OP_VColumn 159 /* synopsis: r[P3]=vcolumn(P2) */
  12437. #define OP_VRename 160
  12438. #define OP_Pagecount 161
  12439. #define OP_MaxPgcnt 162
  12440. #define OP_CursorHint 163
  12441. #define OP_Noop 164
  12442. #define OP_Explain 165
  12443. /* Properties such as "out2" or "jump" that are specified in
  12444. ** comments following the "case" for each opcode in the vdbe.c
  12445. ** are encoded into bitvectors as follows:
  12446. */
  12447. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  12448. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  12449. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  12450. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  12451. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  12452. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  12453. #define OPFLG_INITIALIZER {\
  12454. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
  12455. /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
  12456. /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\
  12457. /* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
  12458. /* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
  12459. /* 40 */ 0x01, 0x01, 0x23, 0x0b, 0x01, 0x01, 0x03, 0x03,\
  12460. /* 48 */ 0x03, 0x01, 0x01, 0x01, 0x02, 0x02, 0x08, 0x00,\
  12461. /* 56 */ 0x10, 0x10, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00,\
  12462. /* 64 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x26, 0x26,\
  12463. /* 72 */ 0x00, 0x02, 0x02, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\
  12464. /* 80 */ 0x0b, 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26,\
  12465. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x02, 0x12,\
  12466. /* 96 */ 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
  12467. /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  12468. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  12469. /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x04,\
  12470. /* 128 */ 0x04, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00,\
  12471. /* 136 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  12472. /* 144 */ 0x00, 0x06, 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00,\
  12473. /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  12474. /* 160 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,}
  12475. /* The sqlite3P2Values() routine is able to run faster if it knows
  12476. ** the value of the largest JUMP opcode. The smaller the maximum
  12477. ** JUMP opcode the better, so the mkopcodeh.tcl script that
  12478. ** generated this include file strives to group all JUMP opcodes
  12479. ** together near the beginning of the list.
  12480. */
  12481. #define SQLITE_MX_JUMP_OPCODE 83 /* Maximum JUMP opcode */
  12482. /************** End of opcodes.h *********************************************/
  12483. /************** Continuing where we left off in vdbe.h ***********************/
  12484. /*
  12485. ** Prototypes for the VDBE interface. See comments on the implementation
  12486. ** for a description of what each of these routines does.
  12487. */
  12488. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  12489. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  12490. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  12491. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  12492. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  12493. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  12494. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  12495. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  12496. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  12497. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  12498. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  12499. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  12500. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  12501. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  12502. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
  12503. #else
  12504. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  12505. # define sqlite3VdbeVerifyNoResultRow(A)
  12506. #endif
  12507. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  12508. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  12509. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  12510. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  12511. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  12512. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  12513. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
  12514. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  12515. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  12516. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  12517. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  12518. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
  12519. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  12520. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  12521. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  12522. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  12523. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  12524. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  12525. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  12526. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  12527. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  12528. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  12529. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  12530. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  12531. #ifdef SQLITE_DEBUG
  12532. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  12533. #endif
  12534. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  12535. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  12536. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  12537. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  12538. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  12539. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  12540. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  12541. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  12542. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  12543. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  12544. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  12545. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  12546. #ifndef SQLITE_OMIT_TRACE
  12547. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  12548. #endif
  12549. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  12550. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  12551. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  12552. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  12553. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
  12554. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  12555. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  12556. #ifndef SQLITE_OMIT_TRIGGER
  12557. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  12558. #endif
  12559. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  12560. ** each VDBE opcode.
  12561. **
  12562. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  12563. ** comments in VDBE programs that show key decision points in the code
  12564. ** generator.
  12565. */
  12566. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  12567. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  12568. # define VdbeComment(X) sqlite3VdbeComment X
  12569. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  12570. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  12571. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  12572. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  12573. # else
  12574. # define VdbeModuleComment(X)
  12575. # endif
  12576. #else
  12577. # define VdbeComment(X)
  12578. # define VdbeNoopComment(X)
  12579. # define VdbeModuleComment(X)
  12580. #endif
  12581. /*
  12582. ** The VdbeCoverage macros are used to set a coverage testing point
  12583. ** for VDBE branch instructions. The coverage testing points are line
  12584. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  12585. ** only works with an amalagmation build. That's ok since a VDBE branch
  12586. ** coverage build designed for testing the test suite only. No application
  12587. ** should ever ship with VDBE branch coverage measuring turned on.
  12588. **
  12589. ** VdbeCoverage(v) // Mark the previously coded instruction
  12590. ** // as a branch
  12591. **
  12592. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  12593. **
  12594. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  12595. **
  12596. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  12597. **
  12598. ** Every VDBE branch operation must be tagged with one of the macros above.
  12599. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  12600. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  12601. ** routine in vdbe.c, alerting the developer to the missed tag.
  12602. */
  12603. #ifdef SQLITE_VDBE_COVERAGE
  12604. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  12605. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  12606. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  12607. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  12608. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  12609. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  12610. #else
  12611. # define VdbeCoverage(v)
  12612. # define VdbeCoverageIf(v,x)
  12613. # define VdbeCoverageAlwaysTaken(v)
  12614. # define VdbeCoverageNeverTaken(v)
  12615. # define VDBE_OFFSET_LINENO(x) 0
  12616. #endif
  12617. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  12618. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  12619. #else
  12620. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  12621. #endif
  12622. #endif /* SQLITE_VDBE_H */
  12623. /************** End of vdbe.h ************************************************/
  12624. /************** Continuing where we left off in sqliteInt.h ******************/
  12625. /************** Include pager.h in the middle of sqliteInt.h *****************/
  12626. /************** Begin file pager.h *******************************************/
  12627. /*
  12628. ** 2001 September 15
  12629. **
  12630. ** The author disclaims copyright to this source code. In place of
  12631. ** a legal notice, here is a blessing:
  12632. **
  12633. ** May you do good and not evil.
  12634. ** May you find forgiveness for yourself and forgive others.
  12635. ** May you share freely, never taking more than you give.
  12636. **
  12637. *************************************************************************
  12638. ** This header file defines the interface that the sqlite page cache
  12639. ** subsystem. The page cache subsystem reads and writes a file a page
  12640. ** at a time and provides a journal for rollback.
  12641. */
  12642. #ifndef SQLITE_PAGER_H
  12643. #define SQLITE_PAGER_H
  12644. /*
  12645. ** Default maximum size for persistent journal files. A negative
  12646. ** value means no limit. This value may be overridden using the
  12647. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  12648. */
  12649. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  12650. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  12651. #endif
  12652. /*
  12653. ** The type used to represent a page number. The first page in a file
  12654. ** is called page 1. 0 is used to represent "not a page".
  12655. */
  12656. typedef u32 Pgno;
  12657. /*
  12658. ** Each open file is managed by a separate instance of the "Pager" structure.
  12659. */
  12660. typedef struct Pager Pager;
  12661. /*
  12662. ** Handle type for pages.
  12663. */
  12664. typedef struct PgHdr DbPage;
  12665. /*
  12666. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  12667. ** reserved for working around a windows/posix incompatibility). It is
  12668. ** used in the journal to signify that the remainder of the journal file
  12669. ** is devoted to storing a master journal name - there are no more pages to
  12670. ** roll back. See comments for function writeMasterJournal() in pager.c
  12671. ** for details.
  12672. */
  12673. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  12674. /*
  12675. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  12676. **
  12677. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  12678. */
  12679. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  12680. #define PAGER_MEMORY 0x0002 /* In-memory database */
  12681. /*
  12682. ** Valid values for the second argument to sqlite3PagerLockingMode().
  12683. */
  12684. #define PAGER_LOCKINGMODE_QUERY -1
  12685. #define PAGER_LOCKINGMODE_NORMAL 0
  12686. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  12687. /*
  12688. ** Numeric constants that encode the journalmode.
  12689. **
  12690. ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
  12691. ** are exposed in the API via the "PRAGMA journal_mode" command and
  12692. ** therefore cannot be changed without a compatibility break.
  12693. */
  12694. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  12695. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  12696. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  12697. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  12698. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  12699. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  12700. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  12701. /*
  12702. ** Flags that make up the mask passed to sqlite3PagerGet().
  12703. */
  12704. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  12705. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  12706. /*
  12707. ** Flags for sqlite3PagerSetFlags()
  12708. **
  12709. ** Value constraints (enforced via assert()):
  12710. ** PAGER_FULLFSYNC == SQLITE_FullFSync
  12711. ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
  12712. ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
  12713. */
  12714. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  12715. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  12716. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  12717. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  12718. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  12719. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  12720. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  12721. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  12722. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  12723. /*
  12724. ** The remainder of this file contains the declarations of the functions
  12725. ** that make up the Pager sub-system API. See source code comments for
  12726. ** a detailed description of each routine.
  12727. */
  12728. /* Open and close a Pager connection. */
  12729. SQLITE_PRIVATE int sqlite3PagerOpen(
  12730. sqlite3_vfs*,
  12731. Pager **ppPager,
  12732. const char*,
  12733. int,
  12734. int,
  12735. int,
  12736. void(*)(DbPage*)
  12737. );
  12738. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
  12739. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  12740. /* Functions used to configure a Pager object. */
  12741. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  12742. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  12743. #ifdef SQLITE_HAS_CODEC
  12744. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  12745. #endif
  12746. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  12747. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  12748. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  12749. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  12750. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  12751. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  12752. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  12753. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  12754. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  12755. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  12756. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  12757. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  12758. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  12759. /* Functions used to obtain and release page references. */
  12760. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  12761. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  12762. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  12763. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  12764. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  12765. /* Operations on page references. */
  12766. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  12767. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  12768. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  12769. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  12770. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  12771. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  12772. /* Functions used to manage pager transactions and savepoints. */
  12773. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  12774. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  12775. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  12776. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  12777. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  12778. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  12779. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  12780. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  12781. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  12782. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  12783. #ifndef SQLITE_OMIT_WAL
  12784. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  12785. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  12786. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  12787. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  12788. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
  12789. # ifdef SQLITE_DIRECT_OVERFLOW_READ
  12790. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno);
  12791. # endif
  12792. # ifdef SQLITE_ENABLE_SNAPSHOT
  12793. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  12794. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  12795. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
  12796. # endif
  12797. #else
  12798. # define sqlite3PagerUseWal(x,y) 0
  12799. #endif
  12800. #ifdef SQLITE_ENABLE_ZIPVFS
  12801. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  12802. #endif
  12803. /* Functions used to query pager state and configuration. */
  12804. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  12805. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  12806. #ifdef SQLITE_DEBUG
  12807. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  12808. #endif
  12809. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  12810. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  12811. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  12812. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  12813. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  12814. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  12815. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  12816. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  12817. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  12818. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
  12819. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  12820. /* Functions used to truncate the database file. */
  12821. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  12822. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  12823. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  12824. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  12825. #endif
  12826. /* Functions to support testing and debugging. */
  12827. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  12828. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  12829. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  12830. #endif
  12831. #ifdef SQLITE_TEST
  12832. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  12833. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  12834. void disable_simulated_io_errors(void);
  12835. void enable_simulated_io_errors(void);
  12836. #else
  12837. # define disable_simulated_io_errors()
  12838. # define enable_simulated_io_errors()
  12839. #endif
  12840. #endif /* SQLITE_PAGER_H */
  12841. /************** End of pager.h ***********************************************/
  12842. /************** Continuing where we left off in sqliteInt.h ******************/
  12843. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  12844. /************** Begin file pcache.h ******************************************/
  12845. /*
  12846. ** 2008 August 05
  12847. **
  12848. ** The author disclaims copyright to this source code. In place of
  12849. ** a legal notice, here is a blessing:
  12850. **
  12851. ** May you do good and not evil.
  12852. ** May you find forgiveness for yourself and forgive others.
  12853. ** May you share freely, never taking more than you give.
  12854. **
  12855. *************************************************************************
  12856. ** This header file defines the interface that the sqlite page cache
  12857. ** subsystem.
  12858. */
  12859. #ifndef _PCACHE_H_
  12860. typedef struct PgHdr PgHdr;
  12861. typedef struct PCache PCache;
  12862. /*
  12863. ** Every page in the cache is controlled by an instance of the following
  12864. ** structure.
  12865. */
  12866. struct PgHdr {
  12867. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  12868. void *pData; /* Page data */
  12869. void *pExtra; /* Extra content */
  12870. PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
  12871. Pager *pPager; /* The pager this page is part of */
  12872. Pgno pgno; /* Page number for this page */
  12873. #ifdef SQLITE_CHECK_PAGES
  12874. u32 pageHash; /* Hash of page content */
  12875. #endif
  12876. u16 flags; /* PGHDR flags defined below */
  12877. /**********************************************************************
  12878. ** Elements above are public. All that follows is private to pcache.c
  12879. ** and should not be accessed by other modules.
  12880. */
  12881. i16 nRef; /* Number of users of this page */
  12882. PCache *pCache; /* Cache that owns this page */
  12883. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  12884. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  12885. };
  12886. /* Bit values for PgHdr.flags */
  12887. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  12888. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  12889. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  12890. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  12891. ** writing this page to the database */
  12892. #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
  12893. #define PGHDR_MMAP 0x020 /* This is an mmap page object */
  12894. #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
  12895. /* Initialize and shutdown the page cache subsystem */
  12896. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  12897. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  12898. /* Page cache buffer management:
  12899. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  12900. */
  12901. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  12902. /* Create a new pager cache.
  12903. ** Under memory stress, invoke xStress to try to make pages clean.
  12904. ** Only clean and unpinned pages can be reclaimed.
  12905. */
  12906. SQLITE_PRIVATE int sqlite3PcacheOpen(
  12907. int szPage, /* Size of every page */
  12908. int szExtra, /* Extra space associated with each page */
  12909. int bPurgeable, /* True if pages are on backing store */
  12910. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  12911. void *pStress, /* Argument to xStress */
  12912. PCache *pToInit /* Preallocated space for the PCache */
  12913. );
  12914. /* Modify the page-size after the cache has been created. */
  12915. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  12916. /* Return the size in bytes of a PCache object. Used to preallocate
  12917. ** storage space.
  12918. */
  12919. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  12920. /* One release per successful fetch. Page is pinned until released.
  12921. ** Reference counted.
  12922. */
  12923. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  12924. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  12925. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  12926. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  12927. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  12928. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  12929. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  12930. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  12931. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
  12932. /* Change a page number. Used by incr-vacuum. */
  12933. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  12934. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  12935. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  12936. /* Get a list of all dirty pages in the cache, sorted by page number */
  12937. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  12938. /* Reset and close the cache object */
  12939. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  12940. /* Clear flags from pages of the page cache */
  12941. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  12942. /* Discard the contents of the cache */
  12943. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  12944. /* Return the total number of outstanding page references */
  12945. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  12946. /* Increment the reference count of an existing page */
  12947. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  12948. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  12949. /* Return the total number of pages stored in the cache */
  12950. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  12951. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  12952. /* Iterate through all dirty pages currently stored in the cache. This
  12953. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  12954. ** library is built.
  12955. */
  12956. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  12957. #endif
  12958. #if defined(SQLITE_DEBUG)
  12959. /* Check invariants on a PgHdr object */
  12960. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
  12961. #endif
  12962. /* Set and get the suggested cache-size for the specified pager-cache.
  12963. **
  12964. ** If no global maximum is configured, then the system attempts to limit
  12965. ** the total number of pages cached by purgeable pager-caches to the sum
  12966. ** of the suggested cache-sizes.
  12967. */
  12968. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  12969. #ifdef SQLITE_TEST
  12970. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  12971. #endif
  12972. /* Set or get the suggested spill-size for the specified pager-cache.
  12973. **
  12974. ** The spill-size is the minimum number of pages in cache before the cache
  12975. ** will attempt to spill dirty pages by calling xStress.
  12976. */
  12977. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  12978. /* Free up as much memory as possible from the page cache */
  12979. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  12980. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  12981. /* Try to return memory used by the pcache module to the main memory heap */
  12982. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  12983. #endif
  12984. #ifdef SQLITE_TEST
  12985. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  12986. #endif
  12987. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  12988. /* Return the header size */
  12989. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  12990. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  12991. /* Number of dirty pages as a percentage of the configured cache size */
  12992. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
  12993. #endif /* _PCACHE_H_ */
  12994. /************** End of pcache.h **********************************************/
  12995. /************** Continuing where we left off in sqliteInt.h ******************/
  12996. /************** Include os.h in the middle of sqliteInt.h ********************/
  12997. /************** Begin file os.h **********************************************/
  12998. /*
  12999. ** 2001 September 16
  13000. **
  13001. ** The author disclaims copyright to this source code. In place of
  13002. ** a legal notice, here is a blessing:
  13003. **
  13004. ** May you do good and not evil.
  13005. ** May you find forgiveness for yourself and forgive others.
  13006. ** May you share freely, never taking more than you give.
  13007. **
  13008. ******************************************************************************
  13009. **
  13010. ** This header file (together with is companion C source-code file
  13011. ** "os.c") attempt to abstract the underlying operating system so that
  13012. ** the SQLite library will work on both POSIX and windows systems.
  13013. **
  13014. ** This header file is #include-ed by sqliteInt.h and thus ends up
  13015. ** being included by every source file.
  13016. */
  13017. #ifndef _SQLITE_OS_H_
  13018. #define _SQLITE_OS_H_
  13019. /*
  13020. ** Attempt to automatically detect the operating system and setup the
  13021. ** necessary pre-processor macros for it.
  13022. */
  13023. /************** Include os_setup.h in the middle of os.h *********************/
  13024. /************** Begin file os_setup.h ****************************************/
  13025. /*
  13026. ** 2013 November 25
  13027. **
  13028. ** The author disclaims copyright to this source code. In place of
  13029. ** a legal notice, here is a blessing:
  13030. **
  13031. ** May you do good and not evil.
  13032. ** May you find forgiveness for yourself and forgive others.
  13033. ** May you share freely, never taking more than you give.
  13034. **
  13035. ******************************************************************************
  13036. **
  13037. ** This file contains pre-processor directives related to operating system
  13038. ** detection and/or setup.
  13039. */
  13040. #ifndef SQLITE_OS_SETUP_H
  13041. #define SQLITE_OS_SETUP_H
  13042. /*
  13043. ** Figure out if we are dealing with Unix, Windows, or some other operating
  13044. ** system.
  13045. **
  13046. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  13047. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  13048. ** the three will be 1. The other two will be 0.
  13049. */
  13050. #if defined(SQLITE_OS_OTHER)
  13051. # if SQLITE_OS_OTHER==1
  13052. # undef SQLITE_OS_UNIX
  13053. # define SQLITE_OS_UNIX 0
  13054. # undef SQLITE_OS_WIN
  13055. # define SQLITE_OS_WIN 0
  13056. # else
  13057. # undef SQLITE_OS_OTHER
  13058. # endif
  13059. #endif
  13060. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  13061. # define SQLITE_OS_OTHER 0
  13062. # ifndef SQLITE_OS_WIN
  13063. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  13064. defined(__MINGW32__) || defined(__BORLANDC__)
  13065. # define SQLITE_OS_WIN 1
  13066. # define SQLITE_OS_UNIX 0
  13067. # else
  13068. # define SQLITE_OS_WIN 0
  13069. # define SQLITE_OS_UNIX 1
  13070. # endif
  13071. # else
  13072. # define SQLITE_OS_UNIX 0
  13073. # endif
  13074. #else
  13075. # ifndef SQLITE_OS_WIN
  13076. # define SQLITE_OS_WIN 0
  13077. # endif
  13078. #endif
  13079. #endif /* SQLITE_OS_SETUP_H */
  13080. /************** End of os_setup.h ********************************************/
  13081. /************** Continuing where we left off in os.h *************************/
  13082. /* If the SET_FULLSYNC macro is not defined above, then make it
  13083. ** a no-op
  13084. */
  13085. #ifndef SET_FULLSYNC
  13086. # define SET_FULLSYNC(x,y)
  13087. #endif
  13088. /*
  13089. ** The default size of a disk sector
  13090. */
  13091. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  13092. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  13093. #endif
  13094. /*
  13095. ** Temporary files are named starting with this prefix followed by 16 random
  13096. ** alphanumeric characters, and no file extension. They are stored in the
  13097. ** OS's standard temporary file directory, and are deleted prior to exit.
  13098. ** If sqlite is being embedded in another program, you may wish to change the
  13099. ** prefix to reflect your program's name, so that if your program exits
  13100. ** prematurely, old temporary files can be easily identified. This can be done
  13101. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  13102. **
  13103. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  13104. ** Mcafee started using SQLite in their anti-virus product and it
  13105. ** started putting files with the "sqlite" name in the c:/temp folder.
  13106. ** This annoyed many windows users. Those users would then do a
  13107. ** Google search for "sqlite", find the telephone numbers of the
  13108. ** developers and call to wake them up at night and complain.
  13109. ** For this reason, the default name prefix is changed to be "sqlite"
  13110. ** spelled backwards. So the temp files are still identified, but
  13111. ** anybody smart enough to figure out the code is also likely smart
  13112. ** enough to know that calling the developer will not help get rid
  13113. ** of the file.
  13114. */
  13115. #ifndef SQLITE_TEMP_FILE_PREFIX
  13116. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  13117. #endif
  13118. /*
  13119. ** The following values may be passed as the second argument to
  13120. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  13121. **
  13122. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  13123. ** RESERVED: A single process may hold a RESERVED lock on a file at
  13124. ** any time. Other processes may hold and obtain new SHARED locks.
  13125. ** PENDING: A single process may hold a PENDING lock on a file at
  13126. ** any one time. Existing SHARED locks may persist, but no new
  13127. ** SHARED locks may be obtained by other processes.
  13128. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  13129. **
  13130. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  13131. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  13132. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  13133. ** sqlite3OsLock().
  13134. */
  13135. #define NO_LOCK 0
  13136. #define SHARED_LOCK 1
  13137. #define RESERVED_LOCK 2
  13138. #define PENDING_LOCK 3
  13139. #define EXCLUSIVE_LOCK 4
  13140. /*
  13141. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  13142. **
  13143. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  13144. ** those functions are not available. So we use only LockFile() and
  13145. ** UnlockFile().
  13146. **
  13147. ** LockFile() prevents not just writing but also reading by other processes.
  13148. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  13149. ** byte out of a specific range of bytes. The lock byte is obtained at
  13150. ** random so two separate readers can probably access the file at the
  13151. ** same time, unless they are unlucky and choose the same lock byte.
  13152. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  13153. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  13154. ** a single byte of the file that is designated as the reserved lock byte.
  13155. ** A PENDING_LOCK is obtained by locking a designated byte different from
  13156. ** the RESERVED_LOCK byte.
  13157. **
  13158. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  13159. ** which means we can use reader/writer locks. When reader/writer locks
  13160. ** are used, the lock is placed on the same range of bytes that is used
  13161. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  13162. ** will support two or more Win95 readers or two or more WinNT readers.
  13163. ** But a single Win95 reader will lock out all WinNT readers and a single
  13164. ** WinNT reader will lock out all other Win95 readers.
  13165. **
  13166. ** The following #defines specify the range of bytes used for locking.
  13167. ** SHARED_SIZE is the number of bytes available in the pool from which
  13168. ** a random byte is selected for a shared lock. The pool of bytes for
  13169. ** shared locks begins at SHARED_FIRST.
  13170. **
  13171. ** The same locking strategy and
  13172. ** byte ranges are used for Unix. This leaves open the possibility of having
  13173. ** clients on win95, winNT, and unix all talking to the same shared file
  13174. ** and all locking correctly. To do so would require that samba (or whatever
  13175. ** tool is being used for file sharing) implements locks correctly between
  13176. ** windows and unix. I'm guessing that isn't likely to happen, but by
  13177. ** using the same locking range we are at least open to the possibility.
  13178. **
  13179. ** Locking in windows is manditory. For this reason, we cannot store
  13180. ** actual data in the bytes used for locking. The pager never allocates
  13181. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  13182. ** that all locks will fit on a single page even at the minimum page size.
  13183. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  13184. ** is set high so that we don't have to allocate an unused page except
  13185. ** for very large databases. But one should test the page skipping logic
  13186. ** by setting PENDING_BYTE low and running the entire regression suite.
  13187. **
  13188. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  13189. ** file format. Depending on how it is changed, you might not notice
  13190. ** the incompatibility right away, even running a full regression test.
  13191. ** The default location of PENDING_BYTE is the first byte past the
  13192. ** 1GB boundary.
  13193. **
  13194. */
  13195. #ifdef SQLITE_OMIT_WSD
  13196. # define PENDING_BYTE (0x40000000)
  13197. #else
  13198. # define PENDING_BYTE sqlite3PendingByte
  13199. #endif
  13200. #define RESERVED_BYTE (PENDING_BYTE+1)
  13201. #define SHARED_FIRST (PENDING_BYTE+2)
  13202. #define SHARED_SIZE 510
  13203. /*
  13204. ** Wrapper around OS specific sqlite3_os_init() function.
  13205. */
  13206. SQLITE_PRIVATE int sqlite3OsInit(void);
  13207. /*
  13208. ** Functions for accessing sqlite3_file methods
  13209. */
  13210. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
  13211. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  13212. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  13213. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  13214. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  13215. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  13216. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  13217. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  13218. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  13219. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  13220. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  13221. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  13222. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  13223. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  13224. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  13225. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  13226. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  13227. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  13228. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  13229. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  13230. /*
  13231. ** Functions for accessing sqlite3_vfs methods
  13232. */
  13233. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  13234. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  13235. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  13236. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  13237. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  13238. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  13239. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  13240. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  13241. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  13242. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  13243. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  13244. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  13245. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  13246. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  13247. /*
  13248. ** Convenience functions for opening and closing files using
  13249. ** sqlite3_malloc() to obtain space for the file-handle structure.
  13250. */
  13251. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  13252. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
  13253. #endif /* _SQLITE_OS_H_ */
  13254. /************** End of os.h **************************************************/
  13255. /************** Continuing where we left off in sqliteInt.h ******************/
  13256. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  13257. /************** Begin file mutex.h *******************************************/
  13258. /*
  13259. ** 2007 August 28
  13260. **
  13261. ** The author disclaims copyright to this source code. In place of
  13262. ** a legal notice, here is a blessing:
  13263. **
  13264. ** May you do good and not evil.
  13265. ** May you find forgiveness for yourself and forgive others.
  13266. ** May you share freely, never taking more than you give.
  13267. **
  13268. *************************************************************************
  13269. **
  13270. ** This file contains the common header for all mutex implementations.
  13271. ** The sqliteInt.h header #includes this file so that it is available
  13272. ** to all source files. We break it out in an effort to keep the code
  13273. ** better organized.
  13274. **
  13275. ** NOTE: source files should *not* #include this header file directly.
  13276. ** Source files should #include the sqliteInt.h file and let that file
  13277. ** include this one indirectly.
  13278. */
  13279. /*
  13280. ** Figure out what version of the code to use. The choices are
  13281. **
  13282. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  13283. ** mutexes implementation cannot be overridden
  13284. ** at start-time.
  13285. **
  13286. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  13287. ** mutual exclusion is provided. But this
  13288. ** implementation can be overridden at
  13289. ** start-time.
  13290. **
  13291. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  13292. **
  13293. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  13294. */
  13295. #if !SQLITE_THREADSAFE
  13296. # define SQLITE_MUTEX_OMIT
  13297. #endif
  13298. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  13299. # if SQLITE_OS_UNIX
  13300. # define SQLITE_MUTEX_PTHREADS
  13301. # elif SQLITE_OS_WIN
  13302. # define SQLITE_MUTEX_W32
  13303. # else
  13304. # define SQLITE_MUTEX_NOOP
  13305. # endif
  13306. #endif
  13307. #ifdef SQLITE_MUTEX_OMIT
  13308. /*
  13309. ** If this is a no-op implementation, implement everything as macros.
  13310. */
  13311. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  13312. #define sqlite3_mutex_free(X)
  13313. #define sqlite3_mutex_enter(X)
  13314. #define sqlite3_mutex_try(X) SQLITE_OK
  13315. #define sqlite3_mutex_leave(X)
  13316. #define sqlite3_mutex_held(X) ((void)(X),1)
  13317. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  13318. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  13319. #define sqlite3MutexInit() SQLITE_OK
  13320. #define sqlite3MutexEnd()
  13321. #define MUTEX_LOGIC(X)
  13322. #else
  13323. #define MUTEX_LOGIC(X) X
  13324. #endif /* defined(SQLITE_MUTEX_OMIT) */
  13325. /************** End of mutex.h ***********************************************/
  13326. /************** Continuing where we left off in sqliteInt.h ******************/
  13327. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  13328. ** synchronous setting to EXTRA. It is no longer supported.
  13329. */
  13330. #ifdef SQLITE_EXTRA_DURABLE
  13331. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  13332. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  13333. #endif
  13334. /*
  13335. ** Default synchronous levels.
  13336. **
  13337. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  13338. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  13339. **
  13340. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  13341. ** OFF 1 0
  13342. ** NORMAL 2 1
  13343. ** FULL 3 2
  13344. ** EXTRA 4 3
  13345. **
  13346. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  13347. ** In other words, the zero-based numbers are used for all external interfaces
  13348. ** and the one-based values are used internally.
  13349. */
  13350. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  13351. # define SQLITE_DEFAULT_SYNCHRONOUS 2
  13352. #endif
  13353. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  13354. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  13355. #endif
  13356. /*
  13357. ** Each database file to be accessed by the system is an instance
  13358. ** of the following structure. There are normally two of these structures
  13359. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  13360. ** aDb[1] is the database file used to hold temporary tables. Additional
  13361. ** databases may be attached.
  13362. */
  13363. struct Db {
  13364. char *zDbSName; /* Name of this database. (schema name, not filename) */
  13365. Btree *pBt; /* The B*Tree structure for this database file */
  13366. u8 safety_level; /* How aggressive at syncing data to disk */
  13367. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  13368. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  13369. };
  13370. /*
  13371. ** An instance of the following structure stores a database schema.
  13372. **
  13373. ** Most Schema objects are associated with a Btree. The exception is
  13374. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  13375. ** In shared cache mode, a single Schema object can be shared by multiple
  13376. ** Btrees that refer to the same underlying BtShared object.
  13377. **
  13378. ** Schema objects are automatically deallocated when the last Btree that
  13379. ** references them is destroyed. The TEMP Schema is manually freed by
  13380. ** sqlite3_close().
  13381. *
  13382. ** A thread must be holding a mutex on the corresponding Btree in order
  13383. ** to access Schema content. This implies that the thread must also be
  13384. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  13385. ** For a TEMP Schema, only the connection mutex is required.
  13386. */
  13387. struct Schema {
  13388. int schema_cookie; /* Database schema version number for this file */
  13389. int iGeneration; /* Generation counter. Incremented with each change */
  13390. Hash tblHash; /* All tables indexed by name */
  13391. Hash idxHash; /* All (named) indices indexed by name */
  13392. Hash trigHash; /* All triggers indexed by name */
  13393. Hash fkeyHash; /* All foreign keys by referenced table name */
  13394. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  13395. u8 file_format; /* Schema format version for this file */
  13396. u8 enc; /* Text encoding used by this database */
  13397. u16 schemaFlags; /* Flags associated with this schema */
  13398. int cache_size; /* Number of pages to use in the cache */
  13399. };
  13400. /*
  13401. ** These macros can be used to test, set, or clear bits in the
  13402. ** Db.pSchema->flags field.
  13403. */
  13404. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  13405. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  13406. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  13407. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  13408. /*
  13409. ** Allowed values for the DB.pSchema->flags field.
  13410. **
  13411. ** The DB_SchemaLoaded flag is set after the database schema has been
  13412. ** read into internal hash tables.
  13413. **
  13414. ** DB_UnresetViews means that one or more views have column names that
  13415. ** have been filled out. If the schema changes, these column names might
  13416. ** changes and so the view will need to be reset.
  13417. */
  13418. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  13419. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  13420. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  13421. /*
  13422. ** The number of different kinds of things that can be limited
  13423. ** using the sqlite3_limit() interface.
  13424. */
  13425. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  13426. /*
  13427. ** Lookaside malloc is a set of fixed-size buffers that can be used
  13428. ** to satisfy small transient memory allocation requests for objects
  13429. ** associated with a particular database connection. The use of
  13430. ** lookaside malloc provides a significant performance enhancement
  13431. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  13432. ** SQL statements.
  13433. **
  13434. ** The Lookaside structure holds configuration information about the
  13435. ** lookaside malloc subsystem. Each available memory allocation in
  13436. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  13437. ** objects.
  13438. **
  13439. ** Lookaside allocations are only allowed for objects that are associated
  13440. ** with a particular database connection. Hence, schema information cannot
  13441. ** be stored in lookaside because in shared cache mode the schema information
  13442. ** is shared by multiple database connections. Therefore, while parsing
  13443. ** schema information, the Lookaside.bEnabled flag is cleared so that
  13444. ** lookaside allocations are not used to construct the schema objects.
  13445. */
  13446. struct Lookaside {
  13447. u32 bDisable; /* Only operate the lookaside when zero */
  13448. u16 sz; /* Size of each buffer in bytes */
  13449. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  13450. int nOut; /* Number of buffers currently checked out */
  13451. int mxOut; /* Highwater mark for nOut */
  13452. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  13453. LookasideSlot *pFree; /* List of available buffers */
  13454. void *pStart; /* First byte of available memory space */
  13455. void *pEnd; /* First byte past end of available space */
  13456. };
  13457. struct LookasideSlot {
  13458. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  13459. };
  13460. /*
  13461. ** A hash table for built-in function definitions. (Application-defined
  13462. ** functions use a regular table table from hash.h.)
  13463. **
  13464. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  13465. ** Collisions are on the FuncDef.u.pHash chain.
  13466. */
  13467. #define SQLITE_FUNC_HASH_SZ 23
  13468. struct FuncDefHash {
  13469. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  13470. };
  13471. #ifdef SQLITE_USER_AUTHENTICATION
  13472. /*
  13473. ** Information held in the "sqlite3" database connection object and used
  13474. ** to manage user authentication.
  13475. */
  13476. typedef struct sqlite3_userauth sqlite3_userauth;
  13477. struct sqlite3_userauth {
  13478. u8 authLevel; /* Current authentication level */
  13479. int nAuthPW; /* Size of the zAuthPW in bytes */
  13480. char *zAuthPW; /* Password used to authenticate */
  13481. char *zAuthUser; /* User name used to authenticate */
  13482. };
  13483. /* Allowed values for sqlite3_userauth.authLevel */
  13484. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  13485. #define UAUTH_Fail 1 /* User authentication failed */
  13486. #define UAUTH_User 2 /* Authenticated as a normal user */
  13487. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  13488. /* Functions used only by user authorization logic */
  13489. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  13490. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  13491. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  13492. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  13493. #endif /* SQLITE_USER_AUTHENTICATION */
  13494. /*
  13495. ** typedef for the authorization callback function.
  13496. */
  13497. #ifdef SQLITE_USER_AUTHENTICATION
  13498. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  13499. const char*, const char*);
  13500. #else
  13501. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  13502. const char*);
  13503. #endif
  13504. #ifndef SQLITE_OMIT_DEPRECATED
  13505. /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
  13506. ** in the style of sqlite3_trace()
  13507. */
  13508. #define SQLITE_TRACE_LEGACY 0x80
  13509. #else
  13510. #define SQLITE_TRACE_LEGACY 0
  13511. #endif /* SQLITE_OMIT_DEPRECATED */
  13512. /*
  13513. ** Each database connection is an instance of the following structure.
  13514. */
  13515. struct sqlite3 {
  13516. sqlite3_vfs *pVfs; /* OS Interface */
  13517. struct Vdbe *pVdbe; /* List of active virtual machines */
  13518. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  13519. sqlite3_mutex *mutex; /* Connection mutex */
  13520. Db *aDb; /* All backends */
  13521. int nDb; /* Number of backends currently in use */
  13522. int flags; /* Miscellaneous flags. See below */
  13523. i64 lastRowid; /* ROWID of most recent insert (see above) */
  13524. i64 szMmap; /* Default mmap_size setting */
  13525. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  13526. int errCode; /* Most recent error code (SQLITE_*) */
  13527. int errMask; /* & result codes with this before returning */
  13528. int iSysErrno; /* Errno value from last system error */
  13529. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  13530. u8 enc; /* Text encoding */
  13531. u8 autoCommit; /* The auto-commit flag. */
  13532. u8 temp_store; /* 1: file 2: memory 0: default */
  13533. u8 mallocFailed; /* True if we have seen a malloc failure */
  13534. u8 bBenignMalloc; /* Do not require OOMs if true */
  13535. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  13536. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  13537. u8 suppressErr; /* Do not issue error messages if true */
  13538. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  13539. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  13540. u8 mTrace; /* zero or more SQLITE_TRACE flags */
  13541. u8 skipBtreeMutex; /* True if no shared-cache backends */
  13542. u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
  13543. int nextPagesize; /* Pagesize after VACUUM if >0 */
  13544. u32 magic; /* Magic number for detect library misuse */
  13545. int nChange; /* Value returned by sqlite3_changes() */
  13546. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  13547. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  13548. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  13549. struct sqlite3InitInfo { /* Information used during initialization */
  13550. int newTnum; /* Rootpage of table being initialized */
  13551. u8 iDb; /* Which db file is being initialized */
  13552. u8 busy; /* TRUE if currently initializing */
  13553. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  13554. u8 imposterTable; /* Building an imposter table */
  13555. } init;
  13556. int nVdbeActive; /* Number of VDBEs currently running */
  13557. int nVdbeRead; /* Number of active VDBEs that read or write */
  13558. int nVdbeWrite; /* Number of active VDBEs that read and write */
  13559. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  13560. int nVDestroy; /* Number of active OP_VDestroy operations */
  13561. int nExtension; /* Number of loaded extensions */
  13562. void **aExtension; /* Array of shared library handles */
  13563. int (*xTrace)(u32,void*,void*,void*); /* Trace function */
  13564. void *pTraceArg; /* Argument to the trace function */
  13565. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  13566. void *pProfileArg; /* Argument to profile function */
  13567. void *pCommitArg; /* Argument to xCommitCallback() */
  13568. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  13569. void *pRollbackArg; /* Argument to xRollbackCallback() */
  13570. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  13571. void *pUpdateArg;
  13572. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  13573. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  13574. void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
  13575. void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
  13576. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
  13577. );
  13578. PreUpdate *pPreUpdate; /* Context for active pre-update callback */
  13579. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  13580. #ifndef SQLITE_OMIT_WAL
  13581. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  13582. void *pWalArg;
  13583. #endif
  13584. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  13585. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  13586. void *pCollNeededArg;
  13587. sqlite3_value *pErr; /* Most recent error message */
  13588. union {
  13589. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  13590. double notUsed1; /* Spacer */
  13591. } u1;
  13592. Lookaside lookaside; /* Lookaside malloc configuration */
  13593. #ifndef SQLITE_OMIT_AUTHORIZATION
  13594. sqlite3_xauth xAuth; /* Access authorization function */
  13595. void *pAuthArg; /* 1st argument to the access auth function */
  13596. #endif
  13597. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  13598. int (*xProgress)(void *); /* The progress callback */
  13599. void *pProgressArg; /* Argument to the progress callback */
  13600. unsigned nProgressOps; /* Number of opcodes for progress callback */
  13601. #endif
  13602. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13603. int nVTrans; /* Allocated size of aVTrans */
  13604. Hash aModule; /* populated by sqlite3_create_module() */
  13605. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  13606. VTable **aVTrans; /* Virtual tables with open transactions */
  13607. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  13608. #endif
  13609. Hash aFunc; /* Hash table of connection functions */
  13610. Hash aCollSeq; /* All collating sequences */
  13611. BusyHandler busyHandler; /* Busy callback */
  13612. Db aDbStatic[2]; /* Static space for the 2 default backends */
  13613. Savepoint *pSavepoint; /* List of active savepoints */
  13614. int busyTimeout; /* Busy handler timeout, in msec */
  13615. int nSavepoint; /* Number of non-transaction savepoints */
  13616. int nStatement; /* Number of nested statement-transactions */
  13617. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  13618. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  13619. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  13620. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  13621. /* The following variables are all protected by the STATIC_MASTER
  13622. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  13623. **
  13624. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  13625. ** unlock so that it can proceed.
  13626. **
  13627. ** When X.pBlockingConnection==Y, that means that something that X tried
  13628. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  13629. ** held by Y.
  13630. */
  13631. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  13632. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  13633. void *pUnlockArg; /* Argument to xUnlockNotify */
  13634. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  13635. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  13636. #endif
  13637. #ifdef SQLITE_USER_AUTHENTICATION
  13638. sqlite3_userauth auth; /* User authentication information */
  13639. #endif
  13640. };
  13641. /*
  13642. ** A macro to discover the encoding of a database.
  13643. */
  13644. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  13645. #define ENC(db) ((db)->enc)
  13646. /*
  13647. ** Possible values for the sqlite3.flags.
  13648. **
  13649. ** Value constraints (enforced via assert()):
  13650. ** SQLITE_FullFSync == PAGER_FULLFSYNC
  13651. ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
  13652. ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
  13653. */
  13654. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  13655. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  13656. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  13657. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  13658. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  13659. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  13660. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  13661. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  13662. /* DELETE, or UPDATE and return */
  13663. /* the count using a callback. */
  13664. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  13665. /* result set is empty */
  13666. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  13667. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  13668. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  13669. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  13670. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  13671. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  13672. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  13673. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  13674. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  13675. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  13676. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  13677. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  13678. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  13679. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  13680. #define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */
  13681. #define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */
  13682. #define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */
  13683. #define SQLITE_QueryOnly 0x04000000 /* Disable database changes */
  13684. #define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */
  13685. #define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */
  13686. #define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */
  13687. #define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */
  13688. #define SQLITE_NoCkptOnClose 0x80000000 /* No checkpoint on close()/DETACH */
  13689. /*
  13690. ** Bits of the sqlite3.dbOptFlags field that are used by the
  13691. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  13692. ** selectively disable various optimizations.
  13693. */
  13694. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  13695. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  13696. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  13697. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  13698. /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
  13699. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  13700. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  13701. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  13702. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  13703. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  13704. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  13705. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  13706. #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */
  13707. #define SQLITE_AllOpts 0xffff /* All optimizations */
  13708. /*
  13709. ** Macros for testing whether or not optimizations are enabled or disabled.
  13710. */
  13711. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  13712. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  13713. /*
  13714. ** Return true if it OK to factor constant expressions into the initialization
  13715. ** code. The argument is a Parse object for the code generator.
  13716. */
  13717. #define ConstFactorOk(P) ((P)->okConstFactor)
  13718. /*
  13719. ** Possible values for the sqlite.magic field.
  13720. ** The numbers are obtained at random and have no special meaning, other
  13721. ** than being distinct from one another.
  13722. */
  13723. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  13724. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  13725. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  13726. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  13727. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  13728. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  13729. /*
  13730. ** Each SQL function is defined by an instance of the following
  13731. ** structure. For global built-in functions (ex: substr(), max(), count())
  13732. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  13733. ** For per-connection application-defined functions, a pointer to this
  13734. ** structure is held in the db->aHash hash table.
  13735. **
  13736. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  13737. ** field is used by per-connection app-def functions.
  13738. */
  13739. struct FuncDef {
  13740. i8 nArg; /* Number of arguments. -1 means unlimited */
  13741. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  13742. void *pUserData; /* User data parameter */
  13743. FuncDef *pNext; /* Next function with same name */
  13744. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  13745. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  13746. const char *zName; /* SQL name of the function. */
  13747. union {
  13748. FuncDef *pHash; /* Next with a different name but the same hash */
  13749. FuncDestructor *pDestructor; /* Reference counted destructor function */
  13750. } u;
  13751. };
  13752. /*
  13753. ** This structure encapsulates a user-function destructor callback (as
  13754. ** configured using create_function_v2()) and a reference counter. When
  13755. ** create_function_v2() is called to create a function with a destructor,
  13756. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  13757. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  13758. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  13759. ** member of each of the new FuncDef objects is set to point to the allocated
  13760. ** FuncDestructor.
  13761. **
  13762. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  13763. ** count on this object is decremented. When it reaches 0, the destructor
  13764. ** is invoked and the FuncDestructor structure freed.
  13765. */
  13766. struct FuncDestructor {
  13767. int nRef;
  13768. void (*xDestroy)(void *);
  13769. void *pUserData;
  13770. };
  13771. /*
  13772. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  13773. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  13774. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  13775. ** are assert() statements in the code to verify this.
  13776. **
  13777. ** Value constraints (enforced via assert()):
  13778. ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
  13779. ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
  13780. ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
  13781. ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
  13782. ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
  13783. */
  13784. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  13785. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  13786. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  13787. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  13788. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  13789. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  13790. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  13791. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  13792. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  13793. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  13794. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  13795. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  13796. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  13797. ** single query - might change over time */
  13798. #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
  13799. /*
  13800. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  13801. ** used to create the initializers for the FuncDef structures.
  13802. **
  13803. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  13804. ** Used to create a scalar function definition of a function zName
  13805. ** implemented by C function xFunc that accepts nArg arguments. The
  13806. ** value passed as iArg is cast to a (void*) and made available
  13807. ** as the user-data (sqlite3_user_data()) for the function. If
  13808. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  13809. **
  13810. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  13811. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  13812. **
  13813. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  13814. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  13815. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  13816. ** and functions like sqlite_version() that can change, but not during
  13817. ** a single query.
  13818. **
  13819. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  13820. ** Used to create an aggregate function definition implemented by
  13821. ** the C functions xStep and xFinal. The first four parameters
  13822. ** are interpreted in the same way as the first 4 parameters to
  13823. ** FUNCTION().
  13824. **
  13825. ** LIKEFUNC(zName, nArg, pArg, flags)
  13826. ** Used to create a scalar function definition of a function zName
  13827. ** that accepts nArg arguments and is implemented by a call to C
  13828. ** function likeFunc. Argument pArg is cast to a (void *) and made
  13829. ** available as the function user-data (sqlite3_user_data()). The
  13830. ** FuncDef.flags variable is set to the value passed as the flags
  13831. ** parameter.
  13832. */
  13833. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  13834. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  13835. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  13836. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  13837. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  13838. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  13839. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  13840. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  13841. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  13842. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  13843. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  13844. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  13845. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  13846. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  13847. pArg, 0, xFunc, 0, #zName, }
  13848. #define LIKEFUNC(zName, nArg, arg, flags) \
  13849. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  13850. (void *)arg, 0, likeFunc, 0, #zName, {0} }
  13851. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  13852. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  13853. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  13854. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  13855. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  13856. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  13857. /*
  13858. ** All current savepoints are stored in a linked list starting at
  13859. ** sqlite3.pSavepoint. The first element in the list is the most recently
  13860. ** opened savepoint. Savepoints are added to the list by the vdbe
  13861. ** OP_Savepoint instruction.
  13862. */
  13863. struct Savepoint {
  13864. char *zName; /* Savepoint name (nul-terminated) */
  13865. i64 nDeferredCons; /* Number of deferred fk violations */
  13866. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  13867. Savepoint *pNext; /* Parent savepoint (if any) */
  13868. };
  13869. /*
  13870. ** The following are used as the second parameter to sqlite3Savepoint(),
  13871. ** and as the P1 argument to the OP_Savepoint instruction.
  13872. */
  13873. #define SAVEPOINT_BEGIN 0
  13874. #define SAVEPOINT_RELEASE 1
  13875. #define SAVEPOINT_ROLLBACK 2
  13876. /*
  13877. ** Each SQLite module (virtual table definition) is defined by an
  13878. ** instance of the following structure, stored in the sqlite3.aModule
  13879. ** hash table.
  13880. */
  13881. struct Module {
  13882. const sqlite3_module *pModule; /* Callback pointers */
  13883. const char *zName; /* Name passed to create_module() */
  13884. void *pAux; /* pAux passed to create_module() */
  13885. void (*xDestroy)(void *); /* Module destructor function */
  13886. Table *pEpoTab; /* Eponymous table for this module */
  13887. };
  13888. /*
  13889. ** information about each column of an SQL table is held in an instance
  13890. ** of this structure.
  13891. */
  13892. struct Column {
  13893. char *zName; /* Name of this column, \000, then the type */
  13894. Expr *pDflt; /* Default value of this column */
  13895. char *zColl; /* Collating sequence. If NULL, use the default */
  13896. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  13897. char affinity; /* One of the SQLITE_AFF_... values */
  13898. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  13899. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  13900. };
  13901. /* Allowed values for Column.colFlags:
  13902. */
  13903. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  13904. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  13905. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  13906. /*
  13907. ** A "Collating Sequence" is defined by an instance of the following
  13908. ** structure. Conceptually, a collating sequence consists of a name and
  13909. ** a comparison routine that defines the order of that sequence.
  13910. **
  13911. ** If CollSeq.xCmp is NULL, it means that the
  13912. ** collating sequence is undefined. Indices built on an undefined
  13913. ** collating sequence may not be read or written.
  13914. */
  13915. struct CollSeq {
  13916. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  13917. u8 enc; /* Text encoding handled by xCmp() */
  13918. void *pUser; /* First argument to xCmp() */
  13919. int (*xCmp)(void*,int, const void*, int, const void*);
  13920. void (*xDel)(void*); /* Destructor for pUser */
  13921. };
  13922. /*
  13923. ** A sort order can be either ASC or DESC.
  13924. */
  13925. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  13926. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  13927. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  13928. /*
  13929. ** Column affinity types.
  13930. **
  13931. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  13932. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  13933. ** the speed a little by numbering the values consecutively.
  13934. **
  13935. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  13936. ** when multiple affinity types are concatenated into a string and
  13937. ** used as the P4 operand, they will be more readable.
  13938. **
  13939. ** Note also that the numeric types are grouped together so that testing
  13940. ** for a numeric type is a single comparison. And the BLOB type is first.
  13941. */
  13942. #define SQLITE_AFF_BLOB 'A'
  13943. #define SQLITE_AFF_TEXT 'B'
  13944. #define SQLITE_AFF_NUMERIC 'C'
  13945. #define SQLITE_AFF_INTEGER 'D'
  13946. #define SQLITE_AFF_REAL 'E'
  13947. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  13948. /*
  13949. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  13950. ** affinity value.
  13951. */
  13952. #define SQLITE_AFF_MASK 0x47
  13953. /*
  13954. ** Additional bit values that can be ORed with an affinity without
  13955. ** changing the affinity.
  13956. **
  13957. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  13958. ** It causes an assert() to fire if either operand to a comparison
  13959. ** operator is NULL. It is added to certain comparison operators to
  13960. ** prove that the operands are always NOT NULL.
  13961. */
  13962. #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
  13963. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  13964. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  13965. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  13966. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  13967. /*
  13968. ** An object of this type is created for each virtual table present in
  13969. ** the database schema.
  13970. **
  13971. ** If the database schema is shared, then there is one instance of this
  13972. ** structure for each database connection (sqlite3*) that uses the shared
  13973. ** schema. This is because each database connection requires its own unique
  13974. ** instance of the sqlite3_vtab* handle used to access the virtual table
  13975. ** implementation. sqlite3_vtab* handles can not be shared between
  13976. ** database connections, even when the rest of the in-memory database
  13977. ** schema is shared, as the implementation often stores the database
  13978. ** connection handle passed to it via the xConnect() or xCreate() method
  13979. ** during initialization internally. This database connection handle may
  13980. ** then be used by the virtual table implementation to access real tables
  13981. ** within the database. So that they appear as part of the callers
  13982. ** transaction, these accesses need to be made via the same database
  13983. ** connection as that used to execute SQL operations on the virtual table.
  13984. **
  13985. ** All VTable objects that correspond to a single table in a shared
  13986. ** database schema are initially stored in a linked-list pointed to by
  13987. ** the Table.pVTable member variable of the corresponding Table object.
  13988. ** When an sqlite3_prepare() operation is required to access the virtual
  13989. ** table, it searches the list for the VTable that corresponds to the
  13990. ** database connection doing the preparing so as to use the correct
  13991. ** sqlite3_vtab* handle in the compiled query.
  13992. **
  13993. ** When an in-memory Table object is deleted (for example when the
  13994. ** schema is being reloaded for some reason), the VTable objects are not
  13995. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  13996. ** immediately. Instead, they are moved from the Table.pVTable list to
  13997. ** another linked list headed by the sqlite3.pDisconnect member of the
  13998. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  13999. ** next time a statement is prepared using said sqlite3*. This is done
  14000. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  14001. ** Refer to comments above function sqlite3VtabUnlockList() for an
  14002. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  14003. ** list without holding the corresponding sqlite3.mutex mutex.
  14004. **
  14005. ** The memory for objects of this type is always allocated by
  14006. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  14007. ** the first argument.
  14008. */
  14009. struct VTable {
  14010. sqlite3 *db; /* Database connection associated with this table */
  14011. Module *pMod; /* Pointer to module implementation */
  14012. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  14013. int nRef; /* Number of pointers to this structure */
  14014. u8 bConstraint; /* True if constraints are supported */
  14015. int iSavepoint; /* Depth of the SAVEPOINT stack */
  14016. VTable *pNext; /* Next in linked list (see above) */
  14017. };
  14018. /*
  14019. ** The schema for each SQL table and view is represented in memory
  14020. ** by an instance of the following structure.
  14021. */
  14022. struct Table {
  14023. char *zName; /* Name of the table or view */
  14024. Column *aCol; /* Information about each column */
  14025. Index *pIndex; /* List of SQL indexes on this table. */
  14026. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  14027. FKey *pFKey; /* Linked list of all foreign keys in this table */
  14028. char *zColAff; /* String defining the affinity of each column */
  14029. ExprList *pCheck; /* All CHECK constraints */
  14030. /* ... also used as column name list in a VIEW */
  14031. int tnum; /* Root BTree page for this table */
  14032. u32 nTabRef; /* Number of pointers to this Table */
  14033. u32 tabFlags; /* Mask of TF_* values */
  14034. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  14035. i16 nCol; /* Number of columns in this table */
  14036. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  14037. LogEst szTabRow; /* Estimated size of each table row in bytes */
  14038. #ifdef SQLITE_ENABLE_COSTMULT
  14039. LogEst costMult; /* Cost multiplier for using this table */
  14040. #endif
  14041. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  14042. #ifndef SQLITE_OMIT_ALTERTABLE
  14043. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  14044. #endif
  14045. #ifndef SQLITE_OMIT_VIRTUALTABLE
  14046. int nModuleArg; /* Number of arguments to the module */
  14047. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  14048. VTable *pVTable; /* List of VTable objects. */
  14049. #endif
  14050. Trigger *pTrigger; /* List of triggers stored in pSchema */
  14051. Schema *pSchema; /* Schema that contains this table */
  14052. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  14053. };
  14054. /*
  14055. ** Allowed values for Table.tabFlags.
  14056. **
  14057. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  14058. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  14059. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  14060. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  14061. ** special handling during INSERT processing.
  14062. */
  14063. #define TF_Readonly 0x0001 /* Read-only system table */
  14064. #define TF_Ephemeral 0x0002 /* An ephemeral table */
  14065. #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
  14066. #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
  14067. #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
  14068. #define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
  14069. #define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
  14070. #define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
  14071. #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
  14072. ** Index.aiRowLogEst[] values */
  14073. #define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
  14074. /*
  14075. ** Test to see whether or not a table is a virtual table. This is
  14076. ** done as a macro so that it will be optimized out when virtual
  14077. ** table support is omitted from the build.
  14078. */
  14079. #ifndef SQLITE_OMIT_VIRTUALTABLE
  14080. # define IsVirtual(X) ((X)->nModuleArg)
  14081. #else
  14082. # define IsVirtual(X) 0
  14083. #endif
  14084. /*
  14085. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  14086. ** only works for non-virtual tables (ordinary tables and views) and is
  14087. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  14088. ** IsHiddenColumn() macro is general purpose.
  14089. */
  14090. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  14091. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  14092. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  14093. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  14094. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  14095. # define IsOrdinaryHiddenColumn(X) 0
  14096. #else
  14097. # define IsHiddenColumn(X) 0
  14098. # define IsOrdinaryHiddenColumn(X) 0
  14099. #endif
  14100. /* Does the table have a rowid */
  14101. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  14102. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  14103. /*
  14104. ** Each foreign key constraint is an instance of the following structure.
  14105. **
  14106. ** A foreign key is associated with two tables. The "from" table is
  14107. ** the table that contains the REFERENCES clause that creates the foreign
  14108. ** key. The "to" table is the table that is named in the REFERENCES clause.
  14109. ** Consider this example:
  14110. **
  14111. ** CREATE TABLE ex1(
  14112. ** a INTEGER PRIMARY KEY,
  14113. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  14114. ** );
  14115. **
  14116. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  14117. ** Equivalent names:
  14118. **
  14119. ** from-table == child-table
  14120. ** to-table == parent-table
  14121. **
  14122. ** Each REFERENCES clause generates an instance of the following structure
  14123. ** which is attached to the from-table. The to-table need not exist when
  14124. ** the from-table is created. The existence of the to-table is not checked.
  14125. **
  14126. ** The list of all parents for child Table X is held at X.pFKey.
  14127. **
  14128. ** A list of all children for a table named Z (which might not even exist)
  14129. ** is held in Schema.fkeyHash with a hash key of Z.
  14130. */
  14131. struct FKey {
  14132. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  14133. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  14134. char *zTo; /* Name of table that the key points to (aka: Parent) */
  14135. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  14136. FKey *pPrevTo; /* Previous with the same zTo */
  14137. int nCol; /* Number of columns in this key */
  14138. /* EV: R-30323-21917 */
  14139. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  14140. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  14141. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  14142. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  14143. int iFrom; /* Index of column in pFrom */
  14144. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  14145. } aCol[1]; /* One entry for each of nCol columns */
  14146. };
  14147. /*
  14148. ** SQLite supports many different ways to resolve a constraint
  14149. ** error. ROLLBACK processing means that a constraint violation
  14150. ** causes the operation in process to fail and for the current transaction
  14151. ** to be rolled back. ABORT processing means the operation in process
  14152. ** fails and any prior changes from that one operation are backed out,
  14153. ** but the transaction is not rolled back. FAIL processing means that
  14154. ** the operation in progress stops and returns an error code. But prior
  14155. ** changes due to the same operation are not backed out and no rollback
  14156. ** occurs. IGNORE means that the particular row that caused the constraint
  14157. ** error is not inserted or updated. Processing continues and no error
  14158. ** is returned. REPLACE means that preexisting database rows that caused
  14159. ** a UNIQUE constraint violation are removed so that the new insert or
  14160. ** update can proceed. Processing continues and no error is reported.
  14161. **
  14162. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  14163. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  14164. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  14165. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  14166. ** referenced table row is propagated into the row that holds the
  14167. ** foreign key.
  14168. **
  14169. ** The following symbolic values are used to record which type
  14170. ** of action to take.
  14171. */
  14172. #define OE_None 0 /* There is no constraint to check */
  14173. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  14174. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  14175. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  14176. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  14177. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  14178. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  14179. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  14180. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  14181. #define OE_Cascade 9 /* Cascade the changes */
  14182. #define OE_Default 10 /* Do whatever the default action is */
  14183. /*
  14184. ** An instance of the following structure is passed as the first
  14185. ** argument to sqlite3VdbeKeyCompare and is used to control the
  14186. ** comparison of the two index keys.
  14187. **
  14188. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  14189. ** are nField slots for the columns of an index then one extra slot
  14190. ** for the rowid at the end.
  14191. */
  14192. struct KeyInfo {
  14193. u32 nRef; /* Number of references to this KeyInfo object */
  14194. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  14195. u16 nField; /* Number of key columns in the index */
  14196. u16 nXField; /* Number of columns beyond the key columns */
  14197. sqlite3 *db; /* The database connection */
  14198. u8 *aSortOrder; /* Sort order for each column. */
  14199. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  14200. };
  14201. /*
  14202. ** This object holds a record which has been parsed out into individual
  14203. ** fields, for the purposes of doing a comparison.
  14204. **
  14205. ** A record is an object that contains one or more fields of data.
  14206. ** Records are used to store the content of a table row and to store
  14207. ** the key of an index. A blob encoding of a record is created by
  14208. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  14209. ** OP_Column opcode.
  14210. **
  14211. ** An instance of this object serves as a "key" for doing a search on
  14212. ** an index b+tree. The goal of the search is to find the entry that
  14213. ** is closed to the key described by this object. This object might hold
  14214. ** just a prefix of the key. The number of fields is given by
  14215. ** pKeyInfo->nField.
  14216. **
  14217. ** The r1 and r2 fields are the values to return if this key is less than
  14218. ** or greater than a key in the btree, respectively. These are normally
  14219. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  14220. ** is in DESC order.
  14221. **
  14222. ** The key comparison functions actually return default_rc when they find
  14223. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  14224. ** multiple entries in the b-tree with the same key (when only looking
  14225. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  14226. ** cause the search to find the last match, or +1 to cause the search to
  14227. ** find the first match.
  14228. **
  14229. ** The key comparison functions will set eqSeen to true if they ever
  14230. ** get and equal results when comparing this structure to a b-tree record.
  14231. ** When default_rc!=0, the search might end up on the record immediately
  14232. ** before the first match or immediately after the last match. The
  14233. ** eqSeen field will indicate whether or not an exact match exists in the
  14234. ** b-tree.
  14235. */
  14236. struct UnpackedRecord {
  14237. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  14238. Mem *aMem; /* Values */
  14239. u16 nField; /* Number of entries in apMem[] */
  14240. i8 default_rc; /* Comparison result if keys are equal */
  14241. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  14242. i8 r1; /* Value to return if (lhs > rhs) */
  14243. i8 r2; /* Value to return if (rhs < lhs) */
  14244. u8 eqSeen; /* True if an equality comparison has been seen */
  14245. };
  14246. /*
  14247. ** Each SQL index is represented in memory by an
  14248. ** instance of the following structure.
  14249. **
  14250. ** The columns of the table that are to be indexed are described
  14251. ** by the aiColumn[] field of this structure. For example, suppose
  14252. ** we have the following table and index:
  14253. **
  14254. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  14255. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  14256. **
  14257. ** In the Table structure describing Ex1, nCol==3 because there are
  14258. ** three columns in the table. In the Index structure describing
  14259. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  14260. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  14261. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  14262. ** The second column to be indexed (c1) has an index of 0 in
  14263. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  14264. **
  14265. ** The Index.onError field determines whether or not the indexed columns
  14266. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  14267. ** it means this is not a unique index. Otherwise it is a unique index
  14268. ** and the value of Index.onError indicate the which conflict resolution
  14269. ** algorithm to employ whenever an attempt is made to insert a non-unique
  14270. ** element.
  14271. **
  14272. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  14273. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  14274. ** table as part of parsing an existing database schema), transient instances
  14275. ** of this structure may be created. In this case the Index.tnum variable is
  14276. ** used to store the address of a VDBE instruction, not a database page
  14277. ** number (it cannot - the database page is not allocated until the VDBE
  14278. ** program is executed). See convertToWithoutRowidTable() for details.
  14279. */
  14280. struct Index {
  14281. char *zName; /* Name of this index */
  14282. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  14283. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  14284. Table *pTable; /* The SQL table being indexed */
  14285. char *zColAff; /* String defining the affinity of each column */
  14286. Index *pNext; /* The next index associated with the same table */
  14287. Schema *pSchema; /* Schema containing this index */
  14288. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  14289. const char **azColl; /* Array of collation sequence names for index */
  14290. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  14291. ExprList *aColExpr; /* Column expressions */
  14292. int tnum; /* DB Page containing root of this index */
  14293. LogEst szIdxRow; /* Estimated average row size in bytes */
  14294. u16 nKeyCol; /* Number of columns forming the key */
  14295. u16 nColumn; /* Number of columns stored in the index */
  14296. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  14297. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  14298. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  14299. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  14300. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  14301. unsigned isCovering:1; /* True if this is a covering index */
  14302. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  14303. unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
  14304. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  14305. int nSample; /* Number of elements in aSample[] */
  14306. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  14307. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  14308. IndexSample *aSample; /* Samples of the left-most key */
  14309. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  14310. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  14311. #endif
  14312. };
  14313. /*
  14314. ** Allowed values for Index.idxType
  14315. */
  14316. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  14317. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  14318. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  14319. /* Return true if index X is a PRIMARY KEY index */
  14320. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  14321. /* Return true if index X is a UNIQUE index */
  14322. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  14323. /* The Index.aiColumn[] values are normally positive integer. But
  14324. ** there are some negative values that have special meaning:
  14325. */
  14326. #define XN_ROWID (-1) /* Indexed column is the rowid */
  14327. #define XN_EXPR (-2) /* Indexed column is an expression */
  14328. /*
  14329. ** Each sample stored in the sqlite_stat3 table is represented in memory
  14330. ** using a structure of this type. See documentation at the top of the
  14331. ** analyze.c source file for additional information.
  14332. */
  14333. struct IndexSample {
  14334. void *p; /* Pointer to sampled record */
  14335. int n; /* Size of record in bytes */
  14336. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  14337. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  14338. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  14339. };
  14340. /*
  14341. ** Each token coming out of the lexer is an instance of
  14342. ** this structure. Tokens are also used as part of an expression.
  14343. **
  14344. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  14345. ** may contain random values. Do not make any assumptions about Token.dyn
  14346. ** and Token.n when Token.z==0.
  14347. */
  14348. struct Token {
  14349. const char *z; /* Text of the token. Not NULL-terminated! */
  14350. unsigned int n; /* Number of characters in this token */
  14351. };
  14352. /*
  14353. ** An instance of this structure contains information needed to generate
  14354. ** code for a SELECT that contains aggregate functions.
  14355. **
  14356. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  14357. ** pointer to this structure. The Expr.iColumn field is the index in
  14358. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  14359. ** code for that node.
  14360. **
  14361. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  14362. ** original Select structure that describes the SELECT statement. These
  14363. ** fields do not need to be freed when deallocating the AggInfo structure.
  14364. */
  14365. struct AggInfo {
  14366. u8 directMode; /* Direct rendering mode means take data directly
  14367. ** from source tables rather than from accumulators */
  14368. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  14369. ** than the source table */
  14370. int sortingIdx; /* Cursor number of the sorting index */
  14371. int sortingIdxPTab; /* Cursor number of pseudo-table */
  14372. int nSortingColumn; /* Number of columns in the sorting index */
  14373. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  14374. ExprList *pGroupBy; /* The group by clause */
  14375. struct AggInfo_col { /* For each column used in source tables */
  14376. Table *pTab; /* Source table */
  14377. int iTable; /* Cursor number of the source table */
  14378. int iColumn; /* Column number within the source table */
  14379. int iSorterColumn; /* Column number in the sorting index */
  14380. int iMem; /* Memory location that acts as accumulator */
  14381. Expr *pExpr; /* The original expression */
  14382. } *aCol;
  14383. int nColumn; /* Number of used entries in aCol[] */
  14384. int nAccumulator; /* Number of columns that show through to the output.
  14385. ** Additional columns are used only as parameters to
  14386. ** aggregate functions */
  14387. struct AggInfo_func { /* For each aggregate function */
  14388. Expr *pExpr; /* Expression encoding the function */
  14389. FuncDef *pFunc; /* The aggregate function implementation */
  14390. int iMem; /* Memory location that acts as accumulator */
  14391. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  14392. } *aFunc;
  14393. int nFunc; /* Number of entries in aFunc[] */
  14394. };
  14395. /*
  14396. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  14397. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  14398. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  14399. ** it uses less memory in the Expr object, which is a big memory user
  14400. ** in systems with lots of prepared statements. And few applications
  14401. ** need more than about 10 or 20 variables. But some extreme users want
  14402. ** to have prepared statements with over 32767 variables, and for them
  14403. ** the option is available (at compile-time).
  14404. */
  14405. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  14406. typedef i16 ynVar;
  14407. #else
  14408. typedef int ynVar;
  14409. #endif
  14410. /*
  14411. ** Each node of an expression in the parse tree is an instance
  14412. ** of this structure.
  14413. **
  14414. ** Expr.op is the opcode. The integer parser token codes are reused
  14415. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  14416. ** code representing the ">=" operator. This same integer code is reused
  14417. ** to represent the greater-than-or-equal-to operator in the expression
  14418. ** tree.
  14419. **
  14420. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  14421. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  14422. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  14423. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  14424. ** then Expr.token contains the name of the function.
  14425. **
  14426. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  14427. ** binary operator. Either or both may be NULL.
  14428. **
  14429. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  14430. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  14431. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  14432. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  14433. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  14434. ** valid.
  14435. **
  14436. ** An expression of the form ID or ID.ID refers to a column in a table.
  14437. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  14438. ** the integer cursor number of a VDBE cursor pointing to that table and
  14439. ** Expr.iColumn is the column number for the specific column. If the
  14440. ** expression is used as a result in an aggregate SELECT, then the
  14441. ** value is also stored in the Expr.iAgg column in the aggregate so that
  14442. ** it can be accessed after all aggregates are computed.
  14443. **
  14444. ** If the expression is an unbound variable marker (a question mark
  14445. ** character '?' in the original SQL) then the Expr.iTable holds the index
  14446. ** number for that variable.
  14447. **
  14448. ** If the expression is a subquery then Expr.iColumn holds an integer
  14449. ** register number containing the result of the subquery. If the
  14450. ** subquery gives a constant result, then iTable is -1. If the subquery
  14451. ** gives a different answer at different times during statement processing
  14452. ** then iTable is the address of a subroutine that computes the subquery.
  14453. **
  14454. ** If the Expr is of type OP_Column, and the table it is selecting from
  14455. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  14456. ** corresponding table definition.
  14457. **
  14458. ** ALLOCATION NOTES:
  14459. **
  14460. ** Expr objects can use a lot of memory space in database schema. To
  14461. ** help reduce memory requirements, sometimes an Expr object will be
  14462. ** truncated. And to reduce the number of memory allocations, sometimes
  14463. ** two or more Expr objects will be stored in a single memory allocation,
  14464. ** together with Expr.zToken strings.
  14465. **
  14466. ** If the EP_Reduced and EP_TokenOnly flags are set when
  14467. ** an Expr object is truncated. When EP_Reduced is set, then all
  14468. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  14469. ** are contained within the same memory allocation. Note, however, that
  14470. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  14471. ** allocated, regardless of whether or not EP_Reduced is set.
  14472. */
  14473. struct Expr {
  14474. u8 op; /* Operation performed by this node */
  14475. char affinity; /* The affinity of the column or 0 if not a column */
  14476. u32 flags; /* Various flags. EP_* See below */
  14477. union {
  14478. char *zToken; /* Token value. Zero terminated and dequoted */
  14479. int iValue; /* Non-negative integer value if EP_IntValue */
  14480. } u;
  14481. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  14482. ** space is allocated for the fields below this point. An attempt to
  14483. ** access them will result in a segfault or malfunction.
  14484. *********************************************************************/
  14485. Expr *pLeft; /* Left subnode */
  14486. Expr *pRight; /* Right subnode */
  14487. union {
  14488. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  14489. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  14490. } x;
  14491. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  14492. ** space is allocated for the fields below this point. An attempt to
  14493. ** access them will result in a segfault or malfunction.
  14494. *********************************************************************/
  14495. #if SQLITE_MAX_EXPR_DEPTH>0
  14496. int nHeight; /* Height of the tree headed by this node */
  14497. #endif
  14498. int iTable; /* TK_COLUMN: cursor number of table holding column
  14499. ** TK_REGISTER: register number
  14500. ** TK_TRIGGER: 1 -> new, 0 -> old
  14501. ** EP_Unlikely: 134217728 times likelihood
  14502. ** TK_SELECT: 1st register of result vector */
  14503. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  14504. ** TK_VARIABLE: variable number (always >= 1).
  14505. ** TK_SELECT_COLUMN: column of the result vector */
  14506. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  14507. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  14508. u8 op2; /* TK_REGISTER: original value of Expr.op
  14509. ** TK_COLUMN: the value of p5 for OP_Column
  14510. ** TK_AGG_FUNCTION: nesting depth */
  14511. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  14512. Table *pTab; /* Table for TK_COLUMN expressions. */
  14513. };
  14514. /*
  14515. ** The following are the meanings of bits in the Expr.flags field.
  14516. */
  14517. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  14518. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  14519. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  14520. #define EP_Error 0x000008 /* Expression contains one or more errors */
  14521. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  14522. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  14523. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  14524. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  14525. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  14526. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  14527. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  14528. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  14529. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  14530. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  14531. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  14532. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  14533. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  14534. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  14535. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  14536. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  14537. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  14538. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  14539. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  14540. #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
  14541. /*
  14542. ** Combinations of two or more EP_* flags
  14543. */
  14544. #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
  14545. /*
  14546. ** These macros can be used to test, set, or clear bits in the
  14547. ** Expr.flags field.
  14548. */
  14549. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  14550. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  14551. #define ExprSetProperty(E,P) (E)->flags|=(P)
  14552. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  14553. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  14554. ** and Accreditation only. It works like ExprSetProperty() during VVA
  14555. ** processes but is a no-op for delivery.
  14556. */
  14557. #ifdef SQLITE_DEBUG
  14558. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  14559. #else
  14560. # define ExprSetVVAProperty(E,P)
  14561. #endif
  14562. /*
  14563. ** Macros to determine the number of bytes required by a normal Expr
  14564. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  14565. ** and an Expr struct with the EP_TokenOnly flag set.
  14566. */
  14567. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  14568. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  14569. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  14570. /*
  14571. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  14572. ** above sqlite3ExprDup() for details.
  14573. */
  14574. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  14575. /*
  14576. ** A list of expressions. Each expression may optionally have a
  14577. ** name. An expr/name combination can be used in several ways, such
  14578. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  14579. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  14580. ** also be used as the argument to a function, in which case the a.zName
  14581. ** field is not used.
  14582. **
  14583. ** By default the Expr.zSpan field holds a human-readable description of
  14584. ** the expression that is used in the generation of error messages and
  14585. ** column labels. In this case, Expr.zSpan is typically the text of a
  14586. ** column expression as it exists in a SELECT statement. However, if
  14587. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  14588. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  14589. ** form is used for name resolution with nested FROM clauses.
  14590. */
  14591. struct ExprList {
  14592. int nExpr; /* Number of expressions on the list */
  14593. int nAlloc; /* Number of a[] slots allocated */
  14594. struct ExprList_item { /* For each expression in the list */
  14595. Expr *pExpr; /* The parse tree for this expression */
  14596. char *zName; /* Token associated with this expression */
  14597. char *zSpan; /* Original text of the expression */
  14598. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  14599. unsigned done :1; /* A flag to indicate when processing is finished */
  14600. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  14601. unsigned reusable :1; /* Constant expression is reusable */
  14602. union {
  14603. struct {
  14604. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  14605. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  14606. } x;
  14607. int iConstExprReg; /* Register in which Expr value is cached */
  14608. } u;
  14609. } a[1]; /* One slot for each expression in the list */
  14610. };
  14611. /*
  14612. ** An instance of this structure is used by the parser to record both
  14613. ** the parse tree for an expression and the span of input text for an
  14614. ** expression.
  14615. */
  14616. struct ExprSpan {
  14617. Expr *pExpr; /* The expression parse tree */
  14618. const char *zStart; /* First character of input text */
  14619. const char *zEnd; /* One character past the end of input text */
  14620. };
  14621. /*
  14622. ** An instance of this structure can hold a simple list of identifiers,
  14623. ** such as the list "a,b,c" in the following statements:
  14624. **
  14625. ** INSERT INTO t(a,b,c) VALUES ...;
  14626. ** CREATE INDEX idx ON t(a,b,c);
  14627. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  14628. **
  14629. ** The IdList.a.idx field is used when the IdList represents the list of
  14630. ** column names after a table name in an INSERT statement. In the statement
  14631. **
  14632. ** INSERT INTO t(a,b,c) ...
  14633. **
  14634. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  14635. */
  14636. struct IdList {
  14637. struct IdList_item {
  14638. char *zName; /* Name of the identifier */
  14639. int idx; /* Index in some Table.aCol[] of a column named zName */
  14640. } *a;
  14641. int nId; /* Number of identifiers on the list */
  14642. };
  14643. /*
  14644. ** The bitmask datatype defined below is used for various optimizations.
  14645. **
  14646. ** Changing this from a 64-bit to a 32-bit type limits the number of
  14647. ** tables in a join to 32 instead of 64. But it also reduces the size
  14648. ** of the library by 738 bytes on ix86.
  14649. */
  14650. #ifdef SQLITE_BITMASK_TYPE
  14651. typedef SQLITE_BITMASK_TYPE Bitmask;
  14652. #else
  14653. typedef u64 Bitmask;
  14654. #endif
  14655. /*
  14656. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  14657. */
  14658. #define BMS ((int)(sizeof(Bitmask)*8))
  14659. /*
  14660. ** A bit in a Bitmask
  14661. */
  14662. #define MASKBIT(n) (((Bitmask)1)<<(n))
  14663. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  14664. #define ALLBITS ((Bitmask)-1)
  14665. /*
  14666. ** The following structure describes the FROM clause of a SELECT statement.
  14667. ** Each table or subquery in the FROM clause is a separate element of
  14668. ** the SrcList.a[] array.
  14669. **
  14670. ** With the addition of multiple database support, the following structure
  14671. ** can also be used to describe a particular table such as the table that
  14672. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  14673. ** such a table must be a simple name: ID. But in SQLite, the table can
  14674. ** now be identified by a database name, a dot, then the table name: ID.ID.
  14675. **
  14676. ** The jointype starts out showing the join type between the current table
  14677. ** and the next table on the list. The parser builds the list this way.
  14678. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  14679. ** jointype expresses the join between the table and the previous table.
  14680. **
  14681. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  14682. ** contains more than 63 columns and the 64-th or later column is used.
  14683. */
  14684. struct SrcList {
  14685. int nSrc; /* Number of tables or subqueries in the FROM clause */
  14686. u32 nAlloc; /* Number of entries allocated in a[] below */
  14687. struct SrcList_item {
  14688. Schema *pSchema; /* Schema to which this item is fixed */
  14689. char *zDatabase; /* Name of database holding this table */
  14690. char *zName; /* Name of the table */
  14691. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  14692. Table *pTab; /* An SQL table corresponding to zName */
  14693. Select *pSelect; /* A SELECT statement used in place of a table name */
  14694. int addrFillSub; /* Address of subroutine to manifest a subquery */
  14695. int regReturn; /* Register holding return address of addrFillSub */
  14696. int regResult; /* Registers holding results of a co-routine */
  14697. struct {
  14698. u8 jointype; /* Type of join between this table and the previous */
  14699. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  14700. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  14701. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  14702. unsigned isCorrelated :1; /* True if sub-query is correlated */
  14703. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  14704. unsigned isRecursive :1; /* True for recursive reference in WITH */
  14705. } fg;
  14706. #ifndef SQLITE_OMIT_EXPLAIN
  14707. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  14708. #endif
  14709. int iCursor; /* The VDBE cursor number used to access this table */
  14710. Expr *pOn; /* The ON clause of a join */
  14711. IdList *pUsing; /* The USING clause of a join */
  14712. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  14713. union {
  14714. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  14715. ExprList *pFuncArg; /* Arguments to table-valued-function */
  14716. } u1;
  14717. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  14718. } a[1]; /* One entry for each identifier on the list */
  14719. };
  14720. /*
  14721. ** Permitted values of the SrcList.a.jointype field
  14722. */
  14723. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  14724. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  14725. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  14726. #define JT_LEFT 0x0008 /* Left outer join */
  14727. #define JT_RIGHT 0x0010 /* Right outer join */
  14728. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  14729. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  14730. /*
  14731. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  14732. ** and the WhereInfo.wctrlFlags member.
  14733. **
  14734. ** Value constraints (enforced via assert()):
  14735. ** WHERE_USE_LIMIT == SF_FixedLimit
  14736. */
  14737. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  14738. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  14739. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  14740. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  14741. #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
  14742. #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
  14743. #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
  14744. ** the OR optimization */
  14745. #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
  14746. #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
  14747. #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
  14748. #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
  14749. #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
  14750. #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
  14751. #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
  14752. /* 0x2000 not currently used */
  14753. #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
  14754. /* 0x8000 not currently used */
  14755. /* Allowed return values from sqlite3WhereIsDistinct()
  14756. */
  14757. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  14758. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  14759. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  14760. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  14761. /*
  14762. ** A NameContext defines a context in which to resolve table and column
  14763. ** names. The context consists of a list of tables (the pSrcList) field and
  14764. ** a list of named expression (pEList). The named expression list may
  14765. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  14766. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  14767. ** pEList corresponds to the result set of a SELECT and is NULL for
  14768. ** other statements.
  14769. **
  14770. ** NameContexts can be nested. When resolving names, the inner-most
  14771. ** context is searched first. If no match is found, the next outer
  14772. ** context is checked. If there is still no match, the next context
  14773. ** is checked. This process continues until either a match is found
  14774. ** or all contexts are check. When a match is found, the nRef member of
  14775. ** the context containing the match is incremented.
  14776. **
  14777. ** Each subquery gets a new NameContext. The pNext field points to the
  14778. ** NameContext in the parent query. Thus the process of scanning the
  14779. ** NameContext list corresponds to searching through successively outer
  14780. ** subqueries looking for a match.
  14781. */
  14782. struct NameContext {
  14783. Parse *pParse; /* The parser */
  14784. SrcList *pSrcList; /* One or more tables used to resolve names */
  14785. ExprList *pEList; /* Optional list of result-set columns */
  14786. AggInfo *pAggInfo; /* Information about aggregates at this level */
  14787. NameContext *pNext; /* Next outer name context. NULL for outermost */
  14788. int nRef; /* Number of names resolved by this context */
  14789. int nErr; /* Number of errors encountered while resolving names */
  14790. u16 ncFlags; /* Zero or more NC_* flags defined below */
  14791. };
  14792. /*
  14793. ** Allowed values for the NameContext, ncFlags field.
  14794. **
  14795. ** Value constraints (all checked via assert()):
  14796. ** NC_HasAgg == SF_HasAgg
  14797. ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
  14798. **
  14799. */
  14800. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  14801. #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
  14802. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  14803. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  14804. #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
  14805. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  14806. #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
  14807. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  14808. /*
  14809. ** An instance of the following structure contains all information
  14810. ** needed to generate code for a single SELECT statement.
  14811. **
  14812. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  14813. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  14814. ** limit and nOffset to the value of the offset (or 0 if there is not
  14815. ** offset). But later on, nLimit and nOffset become the memory locations
  14816. ** in the VDBE that record the limit and offset counters.
  14817. **
  14818. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  14819. ** These addresses must be stored so that we can go back and fill in
  14820. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  14821. ** the number of columns in P2 can be computed at the same time
  14822. ** as the OP_OpenEphm instruction is coded because not
  14823. ** enough information about the compound query is known at that point.
  14824. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  14825. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  14826. ** sequences for the ORDER BY clause.
  14827. */
  14828. struct Select {
  14829. ExprList *pEList; /* The fields of the result */
  14830. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  14831. LogEst nSelectRow; /* Estimated number of result rows */
  14832. u32 selFlags; /* Various SF_* values */
  14833. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  14834. #if SELECTTRACE_ENABLED
  14835. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  14836. #endif
  14837. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  14838. SrcList *pSrc; /* The FROM clause */
  14839. Expr *pWhere; /* The WHERE clause */
  14840. ExprList *pGroupBy; /* The GROUP BY clause */
  14841. Expr *pHaving; /* The HAVING clause */
  14842. ExprList *pOrderBy; /* The ORDER BY clause */
  14843. Select *pPrior; /* Prior select in a compound select statement */
  14844. Select *pNext; /* Next select to the left in a compound */
  14845. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  14846. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  14847. With *pWith; /* WITH clause attached to this select. Or NULL. */
  14848. };
  14849. /*
  14850. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  14851. ** "Select Flag".
  14852. **
  14853. ** Value constraints (all checked via assert())
  14854. ** SF_HasAgg == NC_HasAgg
  14855. ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
  14856. ** SF_FixedLimit == WHERE_USE_LIMIT
  14857. */
  14858. #define SF_Distinct 0x00001 /* Output should be DISTINCT */
  14859. #define SF_All 0x00002 /* Includes the ALL keyword */
  14860. #define SF_Resolved 0x00004 /* Identifiers have been resolved */
  14861. #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
  14862. #define SF_HasAgg 0x00010 /* Contains aggregate functions */
  14863. #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
  14864. #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
  14865. #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
  14866. #define SF_Compound 0x00100 /* Part of a compound query */
  14867. #define SF_Values 0x00200 /* Synthesized from VALUES clause */
  14868. #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
  14869. #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
  14870. #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
  14871. #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
  14872. #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
  14873. #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
  14874. #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
  14875. #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
  14876. /*
  14877. ** The results of a SELECT can be distributed in several ways, as defined
  14878. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  14879. ** Type".
  14880. **
  14881. ** SRT_Union Store results as a key in a temporary index
  14882. ** identified by pDest->iSDParm.
  14883. **
  14884. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  14885. **
  14886. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  14887. ** set is not empty.
  14888. **
  14889. ** SRT_Discard Throw the results away. This is used by SELECT
  14890. ** statements within triggers whose only purpose is
  14891. ** the side-effects of functions.
  14892. **
  14893. ** All of the above are free to ignore their ORDER BY clause. Those that
  14894. ** follow must honor the ORDER BY clause.
  14895. **
  14896. ** SRT_Output Generate a row of output (using the OP_ResultRow
  14897. ** opcode) for each row in the result set.
  14898. **
  14899. ** SRT_Mem Only valid if the result is a single column.
  14900. ** Store the first column of the first result row
  14901. ** in register pDest->iSDParm then abandon the rest
  14902. ** of the query. This destination implies "LIMIT 1".
  14903. **
  14904. ** SRT_Set The result must be a single column. Store each
  14905. ** row of result as the key in table pDest->iSDParm.
  14906. ** Apply the affinity pDest->affSdst before storing
  14907. ** results. Used to implement "IN (SELECT ...)".
  14908. **
  14909. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  14910. ** the result there. The cursor is left open after
  14911. ** returning. This is like SRT_Table except that
  14912. ** this destination uses OP_OpenEphemeral to create
  14913. ** the table first.
  14914. **
  14915. ** SRT_Coroutine Generate a co-routine that returns a new row of
  14916. ** results each time it is invoked. The entry point
  14917. ** of the co-routine is stored in register pDest->iSDParm
  14918. ** and the result row is stored in pDest->nDest registers
  14919. ** starting with pDest->iSdst.
  14920. **
  14921. ** SRT_Table Store results in temporary table pDest->iSDParm.
  14922. ** SRT_Fifo This is like SRT_EphemTab except that the table
  14923. ** is assumed to already be open. SRT_Fifo has
  14924. ** the additional property of being able to ignore
  14925. ** the ORDER BY clause.
  14926. **
  14927. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  14928. ** But also use temporary table pDest->iSDParm+1 as
  14929. ** a record of all prior results and ignore any duplicate
  14930. ** rows. Name means: "Distinct Fifo".
  14931. **
  14932. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  14933. ** an index). Append a sequence number so that all entries
  14934. ** are distinct.
  14935. **
  14936. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  14937. ** the same record has never been stored before. The
  14938. ** index at pDest->iSDParm+1 hold all prior stores.
  14939. */
  14940. #define SRT_Union 1 /* Store result as keys in an index */
  14941. #define SRT_Except 2 /* Remove result from a UNION index */
  14942. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  14943. #define SRT_Discard 4 /* Do not save the results anywhere */
  14944. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  14945. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  14946. #define SRT_Queue 7 /* Store result in an queue */
  14947. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  14948. /* The ORDER BY clause is ignored for all of the above */
  14949. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  14950. #define SRT_Output 9 /* Output each row of result */
  14951. #define SRT_Mem 10 /* Store result in a memory cell */
  14952. #define SRT_Set 11 /* Store results as keys in an index */
  14953. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  14954. #define SRT_Coroutine 13 /* Generate a single row of result */
  14955. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  14956. /*
  14957. ** An instance of this object describes where to put of the results of
  14958. ** a SELECT statement.
  14959. */
  14960. struct SelectDest {
  14961. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  14962. char *zAffSdst; /* Affinity used when eDest==SRT_Set */
  14963. int iSDParm; /* A parameter used by the eDest disposal method */
  14964. int iSdst; /* Base register where results are written */
  14965. int nSdst; /* Number of registers allocated */
  14966. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  14967. };
  14968. /*
  14969. ** During code generation of statements that do inserts into AUTOINCREMENT
  14970. ** tables, the following information is attached to the Table.u.autoInc.p
  14971. ** pointer of each autoincrement table to record some side information that
  14972. ** the code generator needs. We have to keep per-table autoincrement
  14973. ** information in case inserts are done within triggers. Triggers do not
  14974. ** normally coordinate their activities, but we do need to coordinate the
  14975. ** loading and saving of autoincrement information.
  14976. */
  14977. struct AutoincInfo {
  14978. AutoincInfo *pNext; /* Next info block in a list of them all */
  14979. Table *pTab; /* Table this info block refers to */
  14980. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  14981. int regCtr; /* Memory register holding the rowid counter */
  14982. };
  14983. /*
  14984. ** Size of the column cache
  14985. */
  14986. #ifndef SQLITE_N_COLCACHE
  14987. # define SQLITE_N_COLCACHE 10
  14988. #endif
  14989. /*
  14990. ** At least one instance of the following structure is created for each
  14991. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  14992. ** statement. All such objects are stored in the linked list headed at
  14993. ** Parse.pTriggerPrg and deleted once statement compilation has been
  14994. ** completed.
  14995. **
  14996. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  14997. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  14998. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  14999. ** The Parse.pTriggerPrg list never contains two entries with the same
  15000. ** values for both pTrigger and orconf.
  15001. **
  15002. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  15003. ** accessed (or set to 0 for triggers fired as a result of INSERT
  15004. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  15005. ** a mask of new.* columns used by the program.
  15006. */
  15007. struct TriggerPrg {
  15008. Trigger *pTrigger; /* Trigger this program was coded from */
  15009. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  15010. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  15011. int orconf; /* Default ON CONFLICT policy */
  15012. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  15013. };
  15014. /*
  15015. ** The yDbMask datatype for the bitmask of all attached databases.
  15016. */
  15017. #if SQLITE_MAX_ATTACHED>30
  15018. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  15019. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  15020. # define DbMaskZero(M) memset((M),0,sizeof(M))
  15021. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  15022. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  15023. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  15024. #else
  15025. typedef unsigned int yDbMask;
  15026. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  15027. # define DbMaskZero(M) (M)=0
  15028. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  15029. # define DbMaskAllZero(M) (M)==0
  15030. # define DbMaskNonZero(M) (M)!=0
  15031. #endif
  15032. /*
  15033. ** An SQL parser context. A copy of this structure is passed through
  15034. ** the parser and down into all the parser action routine in order to
  15035. ** carry around information that is global to the entire parse.
  15036. **
  15037. ** The structure is divided into two parts. When the parser and code
  15038. ** generate call themselves recursively, the first part of the structure
  15039. ** is constant but the second part is reset at the beginning and end of
  15040. ** each recursion.
  15041. **
  15042. ** The nTableLock and aTableLock variables are only used if the shared-cache
  15043. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  15044. ** used to store the set of table-locks required by the statement being
  15045. ** compiled. Function sqlite3TableLock() is used to add entries to the
  15046. ** list.
  15047. */
  15048. struct Parse {
  15049. sqlite3 *db; /* The main database structure */
  15050. char *zErrMsg; /* An error message */
  15051. Vdbe *pVdbe; /* An engine for executing database bytecode */
  15052. int rc; /* Return code from execution */
  15053. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  15054. u8 checkSchema; /* Causes schema cookie check after an error */
  15055. u8 nested; /* Number of nested calls to the parser/code generator */
  15056. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  15057. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  15058. u8 mayAbort; /* True if statement may throw an ABORT exception */
  15059. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  15060. u8 okConstFactor; /* OK to factor out constants */
  15061. u8 disableLookaside; /* Number of times lookaside has been disabled */
  15062. u8 nColCache; /* Number of entries in aColCache[] */
  15063. int nRangeReg; /* Size of the temporary register block */
  15064. int iRangeReg; /* First register in temporary register block */
  15065. int nErr; /* Number of errors seen */
  15066. int nTab; /* Number of previously allocated VDBE cursors */
  15067. int nMem; /* Number of memory cells used so far */
  15068. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  15069. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  15070. int ckBase; /* Base register of data during check constraints */
  15071. int iSelfTab; /* Table of an index whose exprs are being coded */
  15072. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  15073. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  15074. int nLabel; /* Number of labels used */
  15075. int *aLabel; /* Space to hold the labels */
  15076. ExprList *pConstExpr;/* Constant expressions */
  15077. Token constraintName;/* Name of the constraint currently being parsed */
  15078. yDbMask writeMask; /* Start a write transaction on these databases */
  15079. yDbMask cookieMask; /* Bitmask of schema verified databases */
  15080. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  15081. int regRoot; /* Register holding root page number for new objects */
  15082. int nMaxArg; /* Max args passed to user function by sub-program */
  15083. #if SELECTTRACE_ENABLED
  15084. int nSelect; /* Number of SELECT statements seen */
  15085. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  15086. #endif
  15087. #ifndef SQLITE_OMIT_SHARED_CACHE
  15088. int nTableLock; /* Number of locks in aTableLock */
  15089. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  15090. #endif
  15091. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  15092. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  15093. Table *pTriggerTab; /* Table triggers are being coded for */
  15094. int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
  15095. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  15096. u32 oldmask; /* Mask of old.* columns referenced */
  15097. u32 newmask; /* Mask of new.* columns referenced */
  15098. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  15099. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  15100. u8 disableTriggers; /* True to disable triggers */
  15101. /**************************************************************************
  15102. ** Fields above must be initialized to zero. The fields that follow,
  15103. ** down to the beginning of the recursive section, do not need to be
  15104. ** initialized as they will be set before being used. The boundary is
  15105. ** determined by offsetof(Parse,aColCache).
  15106. **************************************************************************/
  15107. struct yColCache {
  15108. int iTable; /* Table cursor number */
  15109. i16 iColumn; /* Table column number */
  15110. u8 tempReg; /* iReg is a temp register that needs to be freed */
  15111. int iLevel; /* Nesting level */
  15112. int iReg; /* Reg with value of this column. 0 means none. */
  15113. int lru; /* Least recently used entry has the smallest value */
  15114. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  15115. int aTempReg[8]; /* Holding area for temporary registers */
  15116. Token sNameToken; /* Token with unqualified schema object name */
  15117. /************************************************************************
  15118. ** Above is constant between recursions. Below is reset before and after
  15119. ** each recursion. The boundary between these two regions is determined
  15120. ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
  15121. ** first field in the recursive region.
  15122. ************************************************************************/
  15123. Token sLastToken; /* The last token parsed */
  15124. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  15125. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  15126. u8 explain; /* True if the EXPLAIN flag is found on the query */
  15127. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15128. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  15129. int nVtabLock; /* Number of virtual tables to lock */
  15130. #endif
  15131. int nHeight; /* Expression tree height of current sub-select */
  15132. #ifndef SQLITE_OMIT_EXPLAIN
  15133. int iSelectId; /* ID of current select for EXPLAIN output */
  15134. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  15135. #endif
  15136. VList *pVList; /* Mapping between variable names and numbers */
  15137. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  15138. const char *zTail; /* All SQL text past the last semicolon parsed */
  15139. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  15140. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  15141. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  15142. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15143. Token sArg; /* Complete text of a module argument */
  15144. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  15145. #endif
  15146. Table *pZombieTab; /* List of Table objects to delete after code gen */
  15147. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  15148. With *pWith; /* Current WITH clause, or NULL */
  15149. With *pWithToFree; /* Free this WITH object at the end of the parse */
  15150. };
  15151. /*
  15152. ** Sizes and pointers of various parts of the Parse object.
  15153. */
  15154. #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
  15155. #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
  15156. #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
  15157. #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
  15158. /*
  15159. ** Return true if currently inside an sqlite3_declare_vtab() call.
  15160. */
  15161. #ifdef SQLITE_OMIT_VIRTUALTABLE
  15162. #define IN_DECLARE_VTAB 0
  15163. #else
  15164. #define IN_DECLARE_VTAB (pParse->declareVtab)
  15165. #endif
  15166. /*
  15167. ** An instance of the following structure can be declared on a stack and used
  15168. ** to save the Parse.zAuthContext value so that it can be restored later.
  15169. */
  15170. struct AuthContext {
  15171. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  15172. Parse *pParse; /* The Parse structure */
  15173. };
  15174. /*
  15175. ** Bitfield flags for P5 value in various opcodes.
  15176. **
  15177. ** Value constraints (enforced via assert()):
  15178. ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
  15179. ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
  15180. ** OPFLAG_BULKCSR == BTREE_BULKLOAD
  15181. ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
  15182. ** OPFLAG_FORDELETE == BTREE_FORDELETE
  15183. ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
  15184. ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
  15185. */
  15186. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  15187. /* Also used in P2 (not P5) of OP_Delete */
  15188. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  15189. #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
  15190. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  15191. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  15192. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  15193. #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
  15194. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  15195. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  15196. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  15197. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  15198. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  15199. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  15200. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  15201. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
  15202. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  15203. /*
  15204. * Each trigger present in the database schema is stored as an instance of
  15205. * struct Trigger.
  15206. *
  15207. * Pointers to instances of struct Trigger are stored in two ways.
  15208. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  15209. * database). This allows Trigger structures to be retrieved by name.
  15210. * 2. All triggers associated with a single table form a linked list, using the
  15211. * pNext member of struct Trigger. A pointer to the first element of the
  15212. * linked list is stored as the "pTrigger" member of the associated
  15213. * struct Table.
  15214. *
  15215. * The "step_list" member points to the first element of a linked list
  15216. * containing the SQL statements specified as the trigger program.
  15217. */
  15218. struct Trigger {
  15219. char *zName; /* The name of the trigger */
  15220. char *table; /* The table or view to which the trigger applies */
  15221. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  15222. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  15223. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  15224. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  15225. the <column-list> is stored here */
  15226. Schema *pSchema; /* Schema containing the trigger */
  15227. Schema *pTabSchema; /* Schema containing the table */
  15228. TriggerStep *step_list; /* Link list of trigger program steps */
  15229. Trigger *pNext; /* Next trigger associated with the table */
  15230. };
  15231. /*
  15232. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  15233. ** determine which.
  15234. **
  15235. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  15236. ** In that cases, the constants below can be ORed together.
  15237. */
  15238. #define TRIGGER_BEFORE 1
  15239. #define TRIGGER_AFTER 2
  15240. /*
  15241. * An instance of struct TriggerStep is used to store a single SQL statement
  15242. * that is a part of a trigger-program.
  15243. *
  15244. * Instances of struct TriggerStep are stored in a singly linked list (linked
  15245. * using the "pNext" member) referenced by the "step_list" member of the
  15246. * associated struct Trigger instance. The first element of the linked list is
  15247. * the first step of the trigger-program.
  15248. *
  15249. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  15250. * "SELECT" statement. The meanings of the other members is determined by the
  15251. * value of "op" as follows:
  15252. *
  15253. * (op == TK_INSERT)
  15254. * orconf -> stores the ON CONFLICT algorithm
  15255. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  15256. * this stores a pointer to the SELECT statement. Otherwise NULL.
  15257. * zTarget -> Dequoted name of the table to insert into.
  15258. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  15259. * this stores values to be inserted. Otherwise NULL.
  15260. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  15261. * statement, then this stores the column-names to be
  15262. * inserted into.
  15263. *
  15264. * (op == TK_DELETE)
  15265. * zTarget -> Dequoted name of the table to delete from.
  15266. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  15267. * Otherwise NULL.
  15268. *
  15269. * (op == TK_UPDATE)
  15270. * zTarget -> Dequoted name of the table to update.
  15271. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  15272. * Otherwise NULL.
  15273. * pExprList -> A list of the columns to update and the expressions to update
  15274. * them to. See sqlite3Update() documentation of "pChanges"
  15275. * argument.
  15276. *
  15277. */
  15278. struct TriggerStep {
  15279. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  15280. u8 orconf; /* OE_Rollback etc. */
  15281. Trigger *pTrig; /* The trigger that this step is a part of */
  15282. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  15283. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  15284. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  15285. ExprList *pExprList; /* SET clause for UPDATE. */
  15286. IdList *pIdList; /* Column names for INSERT */
  15287. TriggerStep *pNext; /* Next in the link-list */
  15288. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  15289. };
  15290. /*
  15291. ** The following structure contains information used by the sqliteFix...
  15292. ** routines as they walk the parse tree to make database references
  15293. ** explicit.
  15294. */
  15295. typedef struct DbFixer DbFixer;
  15296. struct DbFixer {
  15297. Parse *pParse; /* The parsing context. Error messages written here */
  15298. Schema *pSchema; /* Fix items to this schema */
  15299. int bVarOnly; /* Check for variable references only */
  15300. const char *zDb; /* Make sure all objects are contained in this database */
  15301. const char *zType; /* Type of the container - used for error messages */
  15302. const Token *pName; /* Name of the container - used for error messages */
  15303. };
  15304. /*
  15305. ** An objected used to accumulate the text of a string where we
  15306. ** do not necessarily know how big the string will be in the end.
  15307. */
  15308. struct StrAccum {
  15309. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  15310. char *zBase; /* A base allocation. Not from malloc. */
  15311. char *zText; /* The string collected so far */
  15312. u32 nChar; /* Length of the string so far */
  15313. u32 nAlloc; /* Amount of space allocated in zText */
  15314. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  15315. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  15316. u8 printfFlags; /* SQLITE_PRINTF flags below */
  15317. };
  15318. #define STRACCUM_NOMEM 1
  15319. #define STRACCUM_TOOBIG 2
  15320. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  15321. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  15322. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  15323. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  15324. /*
  15325. ** A pointer to this structure is used to communicate information
  15326. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  15327. */
  15328. typedef struct {
  15329. sqlite3 *db; /* The database being initialized */
  15330. char **pzErrMsg; /* Error message stored here */
  15331. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  15332. int rc; /* Result code stored here */
  15333. } InitData;
  15334. /*
  15335. ** Structure containing global configuration data for the SQLite library.
  15336. **
  15337. ** This structure also contains some state information.
  15338. */
  15339. struct Sqlite3Config {
  15340. int bMemstat; /* True to enable memory status */
  15341. int bCoreMutex; /* True to enable core mutexing */
  15342. int bFullMutex; /* True to enable full mutexing */
  15343. int bOpenUri; /* True to interpret filenames as URIs */
  15344. int bUseCis; /* Use covering indices for full-scans */
  15345. int mxStrlen; /* Maximum string length */
  15346. int neverCorrupt; /* Database is always well-formed */
  15347. int szLookaside; /* Default lookaside buffer size */
  15348. int nLookaside; /* Default lookaside buffer count */
  15349. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  15350. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  15351. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  15352. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  15353. void *pHeap; /* Heap storage space */
  15354. int nHeap; /* Size of pHeap[] */
  15355. int mnReq, mxReq; /* Min and max heap requests sizes */
  15356. sqlite3_int64 szMmap; /* mmap() space per open file */
  15357. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  15358. void *pScratch; /* Scratch memory */
  15359. int szScratch; /* Size of each scratch buffer */
  15360. int nScratch; /* Number of scratch buffers */
  15361. void *pPage; /* Page cache memory */
  15362. int szPage; /* Size of each page in pPage[] */
  15363. int nPage; /* Number of pages in pPage[] */
  15364. int mxParserStack; /* maximum depth of the parser stack */
  15365. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  15366. u32 szPma; /* Maximum Sorter PMA size */
  15367. /* The above might be initialized to non-zero. The following need to always
  15368. ** initially be zero, however. */
  15369. int isInit; /* True after initialization has finished */
  15370. int inProgress; /* True while initialization in progress */
  15371. int isMutexInit; /* True after mutexes are initialized */
  15372. int isMallocInit; /* True after malloc is initialized */
  15373. int isPCacheInit; /* True after malloc is initialized */
  15374. int nRefInitMutex; /* Number of users of pInitMutex */
  15375. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  15376. void (*xLog)(void*,int,const char*); /* Function for logging */
  15377. void *pLogArg; /* First argument to xLog() */
  15378. #ifdef SQLITE_ENABLE_SQLLOG
  15379. void(*xSqllog)(void*,sqlite3*,const char*, int);
  15380. void *pSqllogArg;
  15381. #endif
  15382. #ifdef SQLITE_VDBE_COVERAGE
  15383. /* The following callback (if not NULL) is invoked on every VDBE branch
  15384. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  15385. */
  15386. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  15387. void *pVdbeBranchArg; /* 1st argument */
  15388. #endif
  15389. #ifndef SQLITE_UNTESTABLE
  15390. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  15391. #endif
  15392. int bLocaltimeFault; /* True to fail localtime() calls */
  15393. int iOnceResetThreshold; /* When to reset OP_Once counters */
  15394. };
  15395. /*
  15396. ** This macro is used inside of assert() statements to indicate that
  15397. ** the assert is only valid on a well-formed database. Instead of:
  15398. **
  15399. ** assert( X );
  15400. **
  15401. ** One writes:
  15402. **
  15403. ** assert( X || CORRUPT_DB );
  15404. **
  15405. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  15406. ** that the database is definitely corrupt, only that it might be corrupt.
  15407. ** For most test cases, CORRUPT_DB is set to false using a special
  15408. ** sqlite3_test_control(). This enables assert() statements to prove
  15409. ** things that are always true for well-formed databases.
  15410. */
  15411. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  15412. /*
  15413. ** Context pointer passed down through the tree-walk.
  15414. */
  15415. struct Walker {
  15416. Parse *pParse; /* Parser context. */
  15417. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  15418. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  15419. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  15420. int walkerDepth; /* Number of subqueries */
  15421. u8 eCode; /* A small processing code */
  15422. union { /* Extra data for callback */
  15423. NameContext *pNC; /* Naming context */
  15424. int n; /* A counter */
  15425. int iCur; /* A cursor number */
  15426. SrcList *pSrcList; /* FROM clause */
  15427. struct SrcCount *pSrcCount; /* Counting column references */
  15428. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  15429. int *aiCol; /* array of column indexes */
  15430. struct IdxCover *pIdxCover; /* Check for index coverage */
  15431. struct IdxExprTrans *pIdxTrans; /* Convert indexed expr to column */
  15432. ExprList *pGroupBy; /* GROUP BY clause */
  15433. struct HavingToWhereCtx *pHavingCtx; /* HAVING to WHERE clause ctx */
  15434. } u;
  15435. };
  15436. /* Forward declarations */
  15437. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  15438. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  15439. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  15440. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  15441. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  15442. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  15443. /*
  15444. ** Return code from the parse-tree walking primitives and their
  15445. ** callbacks.
  15446. */
  15447. #define WRC_Continue 0 /* Continue down into children */
  15448. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  15449. #define WRC_Abort 2 /* Abandon the tree walk */
  15450. /*
  15451. ** An instance of this structure represents a set of one or more CTEs
  15452. ** (common table expressions) created by a single WITH clause.
  15453. */
  15454. struct With {
  15455. int nCte; /* Number of CTEs in the WITH clause */
  15456. With *pOuter; /* Containing WITH clause, or NULL */
  15457. struct Cte { /* For each CTE in the WITH clause.... */
  15458. char *zName; /* Name of this CTE */
  15459. ExprList *pCols; /* List of explicit column names, or NULL */
  15460. Select *pSelect; /* The definition of this CTE */
  15461. const char *zCteErr; /* Error message for circular references */
  15462. } a[1];
  15463. };
  15464. #ifdef SQLITE_DEBUG
  15465. /*
  15466. ** An instance of the TreeView object is used for printing the content of
  15467. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  15468. */
  15469. struct TreeView {
  15470. int iLevel; /* Which level of the tree we are on */
  15471. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  15472. };
  15473. #endif /* SQLITE_DEBUG */
  15474. /*
  15475. ** Assuming zIn points to the first byte of a UTF-8 character,
  15476. ** advance zIn to point to the first byte of the next UTF-8 character.
  15477. */
  15478. #define SQLITE_SKIP_UTF8(zIn) { \
  15479. if( (*(zIn++))>=0xc0 ){ \
  15480. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  15481. } \
  15482. }
  15483. /*
  15484. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  15485. ** the same name but without the _BKPT suffix. These macros invoke
  15486. ** routines that report the line-number on which the error originated
  15487. ** using sqlite3_log(). The routines also provide a convenient place
  15488. ** to set a debugger breakpoint.
  15489. */
  15490. SQLITE_PRIVATE int sqlite3CorruptError(int);
  15491. SQLITE_PRIVATE int sqlite3MisuseError(int);
  15492. SQLITE_PRIVATE int sqlite3CantopenError(int);
  15493. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  15494. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  15495. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  15496. #ifdef SQLITE_DEBUG
  15497. SQLITE_PRIVATE int sqlite3NomemError(int);
  15498. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  15499. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  15500. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  15501. #else
  15502. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  15503. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  15504. #endif
  15505. /*
  15506. ** FTS3 and FTS4 both require virtual table support
  15507. */
  15508. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  15509. # undef SQLITE_ENABLE_FTS3
  15510. # undef SQLITE_ENABLE_FTS4
  15511. #endif
  15512. /*
  15513. ** FTS4 is really an extension for FTS3. It is enabled using the
  15514. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  15515. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  15516. */
  15517. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  15518. # define SQLITE_ENABLE_FTS3 1
  15519. #endif
  15520. /*
  15521. ** The ctype.h header is needed for non-ASCII systems. It is also
  15522. ** needed by FTS3 when FTS3 is included in the amalgamation.
  15523. */
  15524. #if !defined(SQLITE_ASCII) || \
  15525. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  15526. # include <ctype.h>
  15527. #endif
  15528. /*
  15529. ** The following macros mimic the standard library functions toupper(),
  15530. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  15531. ** sqlite versions only work for ASCII characters, regardless of locale.
  15532. */
  15533. #ifdef SQLITE_ASCII
  15534. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  15535. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  15536. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  15537. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  15538. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  15539. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  15540. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  15541. # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
  15542. #else
  15543. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  15544. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  15545. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  15546. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  15547. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  15548. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  15549. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  15550. # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
  15551. #endif
  15552. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  15553. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  15554. #endif
  15555. /*
  15556. ** Internal function prototypes
  15557. */
  15558. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  15559. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  15560. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  15561. #define sqlite3StrNICmp sqlite3_strnicmp
  15562. SQLITE_PRIVATE int sqlite3MallocInit(void);
  15563. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  15564. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  15565. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  15566. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  15567. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  15568. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  15569. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  15570. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  15571. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  15572. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  15573. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  15574. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  15575. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
  15576. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  15577. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  15578. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  15579. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  15580. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  15581. SQLITE_PRIVATE void sqlite3PageFree(void*);
  15582. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  15583. #ifndef SQLITE_UNTESTABLE
  15584. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  15585. #endif
  15586. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  15587. /*
  15588. ** On systems with ample stack space and that support alloca(), make
  15589. ** use of alloca() to obtain space for large automatic objects. By default,
  15590. ** obtain space from malloc().
  15591. **
  15592. ** The alloca() routine never returns NULL. This will cause code paths
  15593. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  15594. */
  15595. #ifdef SQLITE_USE_ALLOCA
  15596. # define sqlite3StackAllocRaw(D,N) alloca(N)
  15597. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  15598. # define sqlite3StackFree(D,P)
  15599. #else
  15600. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  15601. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  15602. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  15603. #endif
  15604. /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
  15605. ** are, disable MEMSYS3
  15606. */
  15607. #ifdef SQLITE_ENABLE_MEMSYS5
  15608. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  15609. #undef SQLITE_ENABLE_MEMSYS3
  15610. #endif
  15611. #ifdef SQLITE_ENABLE_MEMSYS3
  15612. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  15613. #endif
  15614. #ifndef SQLITE_MUTEX_OMIT
  15615. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  15616. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  15617. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  15618. SQLITE_PRIVATE int sqlite3MutexInit(void);
  15619. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  15620. #endif
  15621. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  15622. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  15623. #else
  15624. # define sqlite3MemoryBarrier()
  15625. #endif
  15626. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  15627. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  15628. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  15629. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  15630. /* Access to mutexes used by sqlite3_status() */
  15631. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  15632. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  15633. #ifndef SQLITE_OMIT_FLOATING_POINT
  15634. SQLITE_PRIVATE int sqlite3IsNaN(double);
  15635. #else
  15636. # define sqlite3IsNaN(X) 0
  15637. #endif
  15638. /*
  15639. ** An instance of the following structure holds information about SQL
  15640. ** functions arguments that are the parameters to the printf() function.
  15641. */
  15642. struct PrintfArguments {
  15643. int nArg; /* Total number of arguments */
  15644. int nUsed; /* Number of arguments used so far */
  15645. sqlite3_value **apArg; /* The argument values */
  15646. };
  15647. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
  15648. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  15649. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  15650. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  15651. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  15652. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  15653. #endif
  15654. #if defined(SQLITE_TEST)
  15655. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  15656. #endif
  15657. #if defined(SQLITE_DEBUG)
  15658. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  15659. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
  15660. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  15661. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  15662. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  15663. #endif
  15664. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  15665. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  15666. SQLITE_PRIVATE void sqlite3Dequote(char*);
  15667. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  15668. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  15669. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  15670. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  15671. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  15672. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  15673. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  15674. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  15675. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  15676. #ifdef SQLITE_DEBUG
  15677. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  15678. #endif
  15679. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  15680. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  15681. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  15682. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
  15683. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
  15684. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  15685. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  15686. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
  15687. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  15688. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  15689. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
  15690. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  15691. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  15692. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  15693. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  15694. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  15695. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  15696. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  15697. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  15698. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15699. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
  15700. #endif
  15701. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  15702. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  15703. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  15704. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  15705. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  15706. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  15707. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
  15708. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  15709. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  15710. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  15711. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  15712. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  15713. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  15714. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  15715. #else
  15716. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  15717. #endif
  15718. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  15719. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  15720. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  15721. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  15722. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  15723. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  15724. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  15725. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  15726. sqlite3_vfs**,char**,char **);
  15727. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  15728. #ifdef SQLITE_UNTESTABLE
  15729. # define sqlite3FaultSim(X) SQLITE_OK
  15730. #else
  15731. SQLITE_PRIVATE int sqlite3FaultSim(int);
  15732. #endif
  15733. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  15734. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  15735. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  15736. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  15737. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  15738. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  15739. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  15740. #ifndef SQLITE_UNTESTABLE
  15741. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  15742. #endif
  15743. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  15744. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  15745. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  15746. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  15747. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  15748. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  15749. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  15750. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  15751. #else
  15752. # define sqlite3ViewGetColumnNames(A,B) 0
  15753. #endif
  15754. #if SQLITE_MAX_ATTACHED>30
  15755. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  15756. #endif
  15757. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  15758. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  15759. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  15760. #ifndef SQLITE_OMIT_AUTOINCREMENT
  15761. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  15762. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  15763. #else
  15764. # define sqlite3AutoincrementBegin(X)
  15765. # define sqlite3AutoincrementEnd(X)
  15766. #endif
  15767. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  15768. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  15769. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  15770. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  15771. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  15772. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  15773. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  15774. Token*, Select*, Expr*, IdList*);
  15775. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  15776. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  15777. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  15778. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  15779. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  15780. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  15781. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  15782. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  15783. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  15784. Expr*, int, int, u8);
  15785. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  15786. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  15787. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  15788. Expr*,ExprList*,u32,Expr*,Expr*);
  15789. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  15790. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  15791. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  15792. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  15793. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  15794. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  15795. #endif
  15796. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  15797. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  15798. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  15799. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  15800. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  15801. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  15802. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  15803. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
  15804. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  15805. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  15806. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  15807. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  15808. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  15809. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  15810. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  15811. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  15812. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  15813. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
  15814. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  15815. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  15816. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  15817. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  15818. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  15819. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  15820. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  15821. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  15822. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  15823. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  15824. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  15825. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
  15826. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  15827. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  15828. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  15829. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  15830. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  15831. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  15832. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  15833. #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
  15834. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  15835. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  15836. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  15837. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  15838. #define LOCATE_VIEW 0x01
  15839. #define LOCATE_NOERR 0x02
  15840. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  15841. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  15842. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  15843. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  15844. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  15845. SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
  15846. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
  15847. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  15848. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  15849. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
  15850. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  15851. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  15852. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  15853. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  15854. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
  15855. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  15856. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  15857. #ifndef SQLITE_UNTESTABLE
  15858. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  15859. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  15860. #endif
  15861. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  15862. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  15863. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  15864. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  15865. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  15866. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  15867. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  15868. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  15869. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  15870. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  15871. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  15872. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  15873. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
  15874. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  15875. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  15876. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  15877. #endif
  15878. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  15879. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  15880. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  15881. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  15882. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  15883. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  15884. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  15885. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  15886. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  15887. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  15888. u8,u8,int,int*,int*);
  15889. #ifdef SQLITE_ENABLE_NULL_TRIM
  15890. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
  15891. #else
  15892. # define sqlite3SetMakeRecordP5(A,B)
  15893. #endif
  15894. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  15895. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  15896. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  15897. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  15898. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  15899. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  15900. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  15901. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  15902. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  15903. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  15904. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  15905. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  15906. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  15907. #if SELECTTRACE_ENABLED
  15908. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  15909. #else
  15910. # define sqlite3SelectSetName(A,B)
  15911. #endif
  15912. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  15913. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  15914. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  15915. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  15916. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  15917. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  15918. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  15919. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  15920. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  15921. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  15922. #endif
  15923. #ifndef SQLITE_OMIT_TRIGGER
  15924. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  15925. Expr*,int, int);
  15926. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  15927. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  15928. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  15929. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  15930. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  15931. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  15932. int, int, int);
  15933. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  15934. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  15935. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  15936. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  15937. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  15938. Select*,u8);
  15939. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  15940. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  15941. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  15942. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  15943. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  15944. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  15945. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  15946. #else
  15947. # define sqlite3TriggersExist(B,C,D,E,F) 0
  15948. # define sqlite3DeleteTrigger(A,B)
  15949. # define sqlite3DropTriggerPtr(A,B)
  15950. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  15951. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  15952. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  15953. # define sqlite3TriggerList(X, Y) 0
  15954. # define sqlite3ParseToplevel(p) p
  15955. # define sqlite3IsToplevel(p) 1
  15956. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  15957. #endif
  15958. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  15959. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  15960. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  15961. #ifndef SQLITE_OMIT_AUTHORIZATION
  15962. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  15963. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  15964. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  15965. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  15966. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  15967. #else
  15968. # define sqlite3AuthRead(a,b,c,d)
  15969. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  15970. # define sqlite3AuthContextPush(a,b,c)
  15971. # define sqlite3AuthContextPop(a) ((void)(a))
  15972. #endif
  15973. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  15974. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  15975. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  15976. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  15977. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  15978. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  15979. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  15980. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  15981. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  15982. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  15983. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  15984. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  15985. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  15986. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  15987. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  15988. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  15989. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15990. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  15991. #endif
  15992. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  15993. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  15994. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  15995. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  15996. #endif
  15997. SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
  15998. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
  15999. SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
  16000. /*
  16001. ** Routines to read and write variable-length integers. These used to
  16002. ** be defined locally, but now we use the varint routines in the util.c
  16003. ** file.
  16004. */
  16005. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  16006. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  16007. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  16008. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  16009. /*
  16010. ** The common case is for a varint to be a single byte. They following
  16011. ** macros handle the common case without a procedure call, but then call
  16012. ** the procedure for larger varints.
  16013. */
  16014. #define getVarint32(A,B) \
  16015. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  16016. #define putVarint32(A,B) \
  16017. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  16018. sqlite3PutVarint((A),(B)))
  16019. #define getVarint sqlite3GetVarint
  16020. #define putVarint sqlite3PutVarint
  16021. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  16022. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  16023. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  16024. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  16025. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
  16026. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  16027. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  16028. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  16029. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  16030. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  16031. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  16032. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  16033. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  16034. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  16035. #if defined(SQLITE_NEED_ERR_NAME)
  16036. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  16037. #endif
  16038. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  16039. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  16040. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  16041. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  16042. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  16043. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  16044. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  16045. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  16046. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  16047. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  16048. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  16049. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  16050. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  16051. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  16052. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  16053. #ifdef SQLITE_ENABLE_8_3_NAMES
  16054. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  16055. #else
  16056. # define sqlite3FileSuffix3(X,Y)
  16057. #endif
  16058. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  16059. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  16060. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  16061. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  16062. void(*)(void*));
  16063. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  16064. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  16065. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  16066. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  16067. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  16068. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  16069. #ifndef SQLITE_AMALGAMATION
  16070. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  16071. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  16072. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  16073. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  16074. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  16075. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  16076. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  16077. #ifndef SQLITE_OMIT_WSD
  16078. SQLITE_PRIVATE int sqlite3PendingByte;
  16079. #endif
  16080. #endif
  16081. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  16082. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  16083. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  16084. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  16085. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  16086. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  16087. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  16088. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
  16089. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  16090. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  16091. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  16092. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  16093. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  16094. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  16095. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  16096. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  16097. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  16098. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  16099. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  16100. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  16101. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  16102. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  16103. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  16104. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  16105. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  16106. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  16107. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  16108. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  16109. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  16110. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  16111. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  16112. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  16113. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  16114. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  16115. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  16116. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  16117. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  16118. #ifdef SQLITE_DEBUG
  16119. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  16120. #endif
  16121. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  16122. void (*)(sqlite3_context*,int,sqlite3_value **),
  16123. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  16124. FuncDestructor *pDestructor
  16125. );
  16126. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  16127. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  16128. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  16129. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  16130. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  16131. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  16132. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  16133. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  16134. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  16135. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  16136. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  16137. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  16138. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  16139. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  16140. #ifndef SQLITE_OMIT_SUBQUERY
  16141. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
  16142. #else
  16143. # define sqlite3ExprCheckIN(x,y) SQLITE_OK
  16144. #endif
  16145. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  16146. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  16147. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  16148. Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
  16149. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  16150. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  16151. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  16152. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
  16153. #endif
  16154. /*
  16155. ** The interface to the LEMON-generated parser
  16156. */
  16157. #ifndef SQLITE_AMALGAMATION
  16158. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  16159. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  16160. #endif
  16161. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  16162. #ifdef YYTRACKMAXSTACKDEPTH
  16163. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  16164. #endif
  16165. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  16166. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  16167. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  16168. #else
  16169. # define sqlite3CloseExtensions(X)
  16170. #endif
  16171. #ifndef SQLITE_OMIT_SHARED_CACHE
  16172. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  16173. #else
  16174. #define sqlite3TableLock(v,w,x,y,z)
  16175. #endif
  16176. #ifdef SQLITE_TEST
  16177. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  16178. #endif
  16179. #ifdef SQLITE_OMIT_VIRTUALTABLE
  16180. # define sqlite3VtabClear(Y)
  16181. # define sqlite3VtabSync(X,Y) SQLITE_OK
  16182. # define sqlite3VtabRollback(X)
  16183. # define sqlite3VtabCommit(X)
  16184. # define sqlite3VtabInSync(db) 0
  16185. # define sqlite3VtabLock(X)
  16186. # define sqlite3VtabUnlock(X)
  16187. # define sqlite3VtabUnlockList(X)
  16188. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  16189. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  16190. #else
  16191. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  16192. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  16193. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  16194. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  16195. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  16196. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  16197. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  16198. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  16199. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  16200. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  16201. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  16202. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  16203. sqlite3*,
  16204. const char*,
  16205. const sqlite3_module*,
  16206. void*,
  16207. void(*)(void*)
  16208. );
  16209. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  16210. #endif
  16211. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  16212. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  16213. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  16214. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  16215. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  16216. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  16217. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  16218. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  16219. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  16220. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  16221. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  16222. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  16223. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  16224. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  16225. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  16226. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  16227. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  16228. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  16229. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  16230. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  16231. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  16232. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  16233. #ifndef SQLITE_OMIT_WAL
  16234. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  16235. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  16236. #endif
  16237. #ifndef SQLITE_OMIT_CTE
  16238. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  16239. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  16240. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  16241. #else
  16242. #define sqlite3WithPush(x,y,z)
  16243. #define sqlite3WithDelete(x,y)
  16244. #endif
  16245. /* Declarations for functions in fkey.c. All of these are replaced by
  16246. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  16247. ** key functionality is available. If OMIT_TRIGGER is defined but
  16248. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  16249. ** this case foreign keys are parsed, but no other functionality is
  16250. ** provided (enforcement of FK constraints requires the triggers sub-system).
  16251. */
  16252. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  16253. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  16254. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  16255. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  16256. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  16257. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  16258. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  16259. #else
  16260. #define sqlite3FkActions(a,b,c,d,e,f)
  16261. #define sqlite3FkCheck(a,b,c,d,e,f)
  16262. #define sqlite3FkDropTable(a,b,c)
  16263. #define sqlite3FkOldmask(a,b) 0
  16264. #define sqlite3FkRequired(a,b,c,d) 0
  16265. #define sqlite3FkReferences(a) 0
  16266. #endif
  16267. #ifndef SQLITE_OMIT_FOREIGN_KEY
  16268. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  16269. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  16270. #else
  16271. #define sqlite3FkDelete(a,b)
  16272. #define sqlite3FkLocateIndex(a,b,c,d,e)
  16273. #endif
  16274. /*
  16275. ** Available fault injectors. Should be numbered beginning with 0.
  16276. */
  16277. #define SQLITE_FAULTINJECTOR_MALLOC 0
  16278. #define SQLITE_FAULTINJECTOR_COUNT 1
  16279. /*
  16280. ** The interface to the code in fault.c used for identifying "benign"
  16281. ** malloc failures. This is only present if SQLITE_UNTESTABLE
  16282. ** is not defined.
  16283. */
  16284. #ifndef SQLITE_UNTESTABLE
  16285. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  16286. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  16287. #else
  16288. #define sqlite3BeginBenignMalloc()
  16289. #define sqlite3EndBenignMalloc()
  16290. #endif
  16291. /*
  16292. ** Allowed return values from sqlite3FindInIndex()
  16293. */
  16294. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  16295. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  16296. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  16297. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  16298. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  16299. /*
  16300. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  16301. */
  16302. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  16303. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  16304. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  16305. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
  16306. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  16307. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  16308. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  16309. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  16310. #endif
  16311. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  16312. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  16313. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  16314. #if SQLITE_MAX_EXPR_DEPTH>0
  16315. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  16316. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  16317. #else
  16318. #define sqlite3SelectExprHeight(x) 0
  16319. #define sqlite3ExprCheckHeight(x,y)
  16320. #endif
  16321. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  16322. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  16323. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  16324. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  16325. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  16326. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  16327. #else
  16328. #define sqlite3ConnectionBlocked(x,y)
  16329. #define sqlite3ConnectionUnlocked(x)
  16330. #define sqlite3ConnectionClosed(x)
  16331. #endif
  16332. #ifdef SQLITE_DEBUG
  16333. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  16334. #endif
  16335. /*
  16336. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  16337. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  16338. ** print I/O tracing messages.
  16339. */
  16340. #ifdef SQLITE_ENABLE_IOTRACE
  16341. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  16342. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  16343. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  16344. #else
  16345. # define IOTRACE(A)
  16346. # define sqlite3VdbeIOTraceSql(X)
  16347. #endif
  16348. /*
  16349. ** These routines are available for the mem2.c debugging memory allocator
  16350. ** only. They are used to verify that different "types" of memory
  16351. ** allocations are properly tracked by the system.
  16352. **
  16353. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  16354. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  16355. ** a single bit set.
  16356. **
  16357. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  16358. ** argument match the type set by the previous sqlite3MemdebugSetType().
  16359. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  16360. **
  16361. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  16362. ** argument match the type set by the previous sqlite3MemdebugSetType().
  16363. **
  16364. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  16365. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  16366. ** it might have been allocated by lookaside, except the allocation was
  16367. ** too large or lookaside was already full. It is important to verify
  16368. ** that allocations that might have been satisfied by lookaside are not
  16369. ** passed back to non-lookaside free() routines. Asserts such as the
  16370. ** example above are placed on the non-lookaside free() routines to verify
  16371. ** this constraint.
  16372. **
  16373. ** All of this is no-op for a production build. It only comes into
  16374. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  16375. */
  16376. #ifdef SQLITE_MEMDEBUG
  16377. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  16378. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  16379. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  16380. #else
  16381. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  16382. # define sqlite3MemdebugHasType(X,Y) 1
  16383. # define sqlite3MemdebugNoType(X,Y) 1
  16384. #endif
  16385. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  16386. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  16387. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  16388. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  16389. /*
  16390. ** Threading interface
  16391. */
  16392. #if SQLITE_MAX_WORKER_THREADS>0
  16393. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  16394. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  16395. #endif
  16396. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  16397. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  16398. #endif
  16399. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
  16400. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
  16401. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
  16402. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
  16403. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
  16404. #endif /* SQLITEINT_H */
  16405. /************** End of sqliteInt.h *******************************************/
  16406. /************** Begin file global.c ******************************************/
  16407. /*
  16408. ** 2008 June 13
  16409. **
  16410. ** The author disclaims copyright to this source code. In place of
  16411. ** a legal notice, here is a blessing:
  16412. **
  16413. ** May you do good and not evil.
  16414. ** May you find forgiveness for yourself and forgive others.
  16415. ** May you share freely, never taking more than you give.
  16416. **
  16417. *************************************************************************
  16418. **
  16419. ** This file contains definitions of global variables and constants.
  16420. */
  16421. /* #include "sqliteInt.h" */
  16422. /* An array to map all upper-case characters into their corresponding
  16423. ** lower-case character.
  16424. **
  16425. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  16426. ** handle case conversions for the UTF character set since the tables
  16427. ** involved are nearly as big or bigger than SQLite itself.
  16428. */
  16429. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  16430. #ifdef SQLITE_ASCII
  16431. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  16432. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  16433. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  16434. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  16435. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  16436. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  16437. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  16438. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  16439. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  16440. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  16441. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  16442. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  16443. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  16444. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  16445. 252,253,254,255
  16446. #endif
  16447. #ifdef SQLITE_EBCDIC
  16448. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  16449. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  16450. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  16451. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  16452. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  16453. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  16454. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  16455. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  16456. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  16457. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  16458. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  16459. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  16460. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  16461. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  16462. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  16463. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  16464. #endif
  16465. };
  16466. /*
  16467. ** The following 256 byte lookup table is used to support SQLites built-in
  16468. ** equivalents to the following standard library functions:
  16469. **
  16470. ** isspace() 0x01
  16471. ** isalpha() 0x02
  16472. ** isdigit() 0x04
  16473. ** isalnum() 0x06
  16474. ** isxdigit() 0x08
  16475. ** toupper() 0x20
  16476. ** SQLite identifier character 0x40
  16477. ** Quote character 0x80
  16478. **
  16479. ** Bit 0x20 is set if the mapped character requires translation to upper
  16480. ** case. i.e. if the character is a lower-case ASCII character.
  16481. ** If x is a lower-case ASCII character, then its upper-case equivalent
  16482. ** is (x - 0x20). Therefore toupper() can be implemented as:
  16483. **
  16484. ** (x & ~(map[x]&0x20))
  16485. **
  16486. ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
  16487. ** array. tolower() is used more often than toupper() by SQLite.
  16488. **
  16489. ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
  16490. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  16491. ** non-ASCII UTF character. Hence the test for whether or not a character is
  16492. ** part of an identifier is 0x46.
  16493. */
  16494. #ifdef SQLITE_ASCII
  16495. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  16496. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  16497. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  16498. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  16499. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  16500. 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
  16501. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  16502. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  16503. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  16504. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  16505. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  16506. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  16507. 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  16508. 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  16509. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  16510. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  16511. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  16512. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  16513. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  16514. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  16515. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  16516. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  16517. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  16518. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  16519. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  16520. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  16521. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  16522. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  16523. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  16524. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  16525. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  16526. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  16527. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  16528. };
  16529. #endif
  16530. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  16531. ** compatibility for legacy applications, the URI filename capability is
  16532. ** disabled by default.
  16533. **
  16534. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  16535. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  16536. **
  16537. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  16538. ** disabled. The default value may be changed by compiling with the
  16539. ** SQLITE_USE_URI symbol defined.
  16540. **
  16541. ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
  16542. ** enabled.
  16543. */
  16544. #ifndef SQLITE_USE_URI
  16545. # ifdef SQLITE_HAS_CODEC
  16546. # define SQLITE_USE_URI 1
  16547. # else
  16548. # define SQLITE_USE_URI 0
  16549. # endif
  16550. #endif
  16551. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  16552. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  16553. ** that compile-time option is omitted.
  16554. */
  16555. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  16556. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  16557. #endif
  16558. /* The minimum PMA size is set to this value multiplied by the database
  16559. ** page size in bytes.
  16560. */
  16561. #ifndef SQLITE_SORTER_PMASZ
  16562. # define SQLITE_SORTER_PMASZ 250
  16563. #endif
  16564. /* Statement journals spill to disk when their size exceeds the following
  16565. ** threshold (in bytes). 0 means that statement journals are created and
  16566. ** written to disk immediately (the default behavior for SQLite versions
  16567. ** before 3.12.0). -1 means always keep the entire statement journal in
  16568. ** memory. (The statement journal is also always held entirely in memory
  16569. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  16570. ** setting.)
  16571. */
  16572. #ifndef SQLITE_STMTJRNL_SPILL
  16573. # define SQLITE_STMTJRNL_SPILL (64*1024)
  16574. #endif
  16575. /*
  16576. ** The default lookaside-configuration, the format "SZ,N". SZ is the
  16577. ** number of bytes in each lookaside slot (should be a multiple of 8)
  16578. ** and N is the number of slots. The lookaside-configuration can be
  16579. ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
  16580. ** or at run-time for an individual database connection using
  16581. ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
  16582. */
  16583. #ifndef SQLITE_DEFAULT_LOOKASIDE
  16584. # define SQLITE_DEFAULT_LOOKASIDE 1200,100
  16585. #endif
  16586. /*
  16587. ** The following singleton contains the global configuration for
  16588. ** the SQLite library.
  16589. */
  16590. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  16591. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  16592. 1, /* bCoreMutex */
  16593. SQLITE_THREADSAFE==1, /* bFullMutex */
  16594. SQLITE_USE_URI, /* bOpenUri */
  16595. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  16596. 0x7ffffffe, /* mxStrlen */
  16597. 0, /* neverCorrupt */
  16598. SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
  16599. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  16600. {0,0,0,0,0,0,0,0}, /* m */
  16601. {0,0,0,0,0,0,0,0,0}, /* mutex */
  16602. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  16603. (void*)0, /* pHeap */
  16604. 0, /* nHeap */
  16605. 0, 0, /* mnHeap, mxHeap */
  16606. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  16607. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  16608. (void*)0, /* pScratch */
  16609. 0, /* szScratch */
  16610. 0, /* nScratch */
  16611. (void*)0, /* pPage */
  16612. 0, /* szPage */
  16613. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  16614. 0, /* mxParserStack */
  16615. 0, /* sharedCacheEnabled */
  16616. SQLITE_SORTER_PMASZ, /* szPma */
  16617. /* All the rest should always be initialized to zero */
  16618. 0, /* isInit */
  16619. 0, /* inProgress */
  16620. 0, /* isMutexInit */
  16621. 0, /* isMallocInit */
  16622. 0, /* isPCacheInit */
  16623. 0, /* nRefInitMutex */
  16624. 0, /* pInitMutex */
  16625. 0, /* xLog */
  16626. 0, /* pLogArg */
  16627. #ifdef SQLITE_ENABLE_SQLLOG
  16628. 0, /* xSqllog */
  16629. 0, /* pSqllogArg */
  16630. #endif
  16631. #ifdef SQLITE_VDBE_COVERAGE
  16632. 0, /* xVdbeBranch */
  16633. 0, /* pVbeBranchArg */
  16634. #endif
  16635. #ifndef SQLITE_UNTESTABLE
  16636. 0, /* xTestCallback */
  16637. #endif
  16638. 0, /* bLocaltimeFault */
  16639. 0x7ffffffe /* iOnceResetThreshold */
  16640. };
  16641. /*
  16642. ** Hash table for global functions - functions common to all
  16643. ** database connections. After initialization, this table is
  16644. ** read-only.
  16645. */
  16646. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  16647. /*
  16648. ** Constant tokens for values 0 and 1.
  16649. */
  16650. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  16651. { "0", 1 },
  16652. { "1", 1 }
  16653. };
  16654. /*
  16655. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  16656. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  16657. ** the database page that contains the pending byte. It never attempts
  16658. ** to read or write that page. The pending byte page is set aside
  16659. ** for use by the VFS layers as space for managing file locks.
  16660. **
  16661. ** During testing, it is often desirable to move the pending byte to
  16662. ** a different position in the file. This allows code that has to
  16663. ** deal with the pending byte to run on files that are much smaller
  16664. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  16665. ** move the pending byte.
  16666. **
  16667. ** IMPORTANT: Changing the pending byte to any value other than
  16668. ** 0x40000000 results in an incompatible database file format!
  16669. ** Changing the pending byte during operation will result in undefined
  16670. ** and incorrect behavior.
  16671. */
  16672. #ifndef SQLITE_OMIT_WSD
  16673. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  16674. #endif
  16675. /* #include "opcodes.h" */
  16676. /*
  16677. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  16678. ** created by mkopcodeh.awk during compilation. Data is obtained
  16679. ** from the comments following the "case OP_xxxx:" statements in
  16680. ** the vdbe.c file.
  16681. */
  16682. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  16683. /*
  16684. ** Name of the default collating sequence
  16685. */
  16686. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  16687. /************** End of global.c **********************************************/
  16688. /************** Begin file ctime.c *******************************************/
  16689. /*
  16690. ** 2010 February 23
  16691. **
  16692. ** The author disclaims copyright to this source code. In place of
  16693. ** a legal notice, here is a blessing:
  16694. **
  16695. ** May you do good and not evil.
  16696. ** May you find forgiveness for yourself and forgive others.
  16697. ** May you share freely, never taking more than you give.
  16698. **
  16699. *************************************************************************
  16700. **
  16701. ** This file implements routines used to report what compile-time options
  16702. ** SQLite was built with.
  16703. */
  16704. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  16705. /* #include "sqliteInt.h" */
  16706. /*
  16707. ** An array of names of all compile-time options. This array should
  16708. ** be sorted A-Z.
  16709. **
  16710. ** This array looks large, but in a typical installation actually uses
  16711. ** only a handful of compile-time options, so most times this array is usually
  16712. ** rather short and uses little memory space.
  16713. */
  16714. static const char * const azCompileOpt[] = {
  16715. /* These macros are provided to "stringify" the value of the define
  16716. ** for those options in which the value is meaningful. */
  16717. #define CTIMEOPT_VAL_(opt) #opt
  16718. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  16719. #if SQLITE_32BIT_ROWID
  16720. "32BIT_ROWID",
  16721. #endif
  16722. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  16723. "4_BYTE_ALIGNED_MALLOC",
  16724. #endif
  16725. #if SQLITE_CASE_SENSITIVE_LIKE
  16726. "CASE_SENSITIVE_LIKE",
  16727. #endif
  16728. #if SQLITE_CHECK_PAGES
  16729. "CHECK_PAGES",
  16730. #endif
  16731. #if defined(__clang__) && defined(__clang_major__)
  16732. "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
  16733. CTIMEOPT_VAL(__clang_minor__) "."
  16734. CTIMEOPT_VAL(__clang_patchlevel__),
  16735. #elif defined(_MSC_VER)
  16736. "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
  16737. #elif defined(__GNUC__) && defined(__VERSION__)
  16738. "COMPILER=gcc-" __VERSION__,
  16739. #endif
  16740. #if SQLITE_COVERAGE_TEST
  16741. "COVERAGE_TEST",
  16742. #endif
  16743. #ifdef SQLITE_DEBUG
  16744. "DEBUG",
  16745. #endif
  16746. #if SQLITE_DEFAULT_LOCKING_MODE
  16747. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  16748. #endif
  16749. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  16750. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  16751. #endif
  16752. #if SQLITE_DEFAULT_SYNCHRONOUS
  16753. "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
  16754. #endif
  16755. #if SQLITE_DEFAULT_WAL_SYNCHRONOUS
  16756. "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
  16757. #endif
  16758. #if SQLITE_DIRECT_OVERFLOW_READ
  16759. "DIRECT_OVERFLOW_READ",
  16760. #endif
  16761. #if SQLITE_DISABLE_DIRSYNC
  16762. "DISABLE_DIRSYNC",
  16763. #endif
  16764. #if SQLITE_DISABLE_LFS
  16765. "DISABLE_LFS",
  16766. #endif
  16767. #if SQLITE_ENABLE_8_3_NAMES
  16768. "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
  16769. #endif
  16770. #if SQLITE_ENABLE_API_ARMOR
  16771. "ENABLE_API_ARMOR",
  16772. #endif
  16773. #if SQLITE_ENABLE_ATOMIC_WRITE
  16774. "ENABLE_ATOMIC_WRITE",
  16775. #endif
  16776. #if SQLITE_ENABLE_CEROD
  16777. "ENABLE_CEROD",
  16778. #endif
  16779. #if SQLITE_ENABLE_COLUMN_METADATA
  16780. "ENABLE_COLUMN_METADATA",
  16781. #endif
  16782. #if SQLITE_ENABLE_DBSTAT_VTAB
  16783. "ENABLE_DBSTAT_VTAB",
  16784. #endif
  16785. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  16786. "ENABLE_EXPENSIVE_ASSERT",
  16787. #endif
  16788. #if SQLITE_ENABLE_FTS1
  16789. "ENABLE_FTS1",
  16790. #endif
  16791. #if SQLITE_ENABLE_FTS2
  16792. "ENABLE_FTS2",
  16793. #endif
  16794. #if SQLITE_ENABLE_FTS3
  16795. "ENABLE_FTS3",
  16796. #endif
  16797. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  16798. "ENABLE_FTS3_PARENTHESIS",
  16799. #endif
  16800. #if SQLITE_ENABLE_FTS4
  16801. "ENABLE_FTS4",
  16802. #endif
  16803. #if SQLITE_ENABLE_FTS5
  16804. "ENABLE_FTS5",
  16805. #endif
  16806. #if SQLITE_ENABLE_ICU
  16807. "ENABLE_ICU",
  16808. #endif
  16809. #if SQLITE_ENABLE_IOTRACE
  16810. "ENABLE_IOTRACE",
  16811. #endif
  16812. #if SQLITE_ENABLE_JSON1
  16813. "ENABLE_JSON1",
  16814. #endif
  16815. #if SQLITE_ENABLE_LOAD_EXTENSION
  16816. "ENABLE_LOAD_EXTENSION",
  16817. #endif
  16818. #if SQLITE_ENABLE_LOCKING_STYLE
  16819. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  16820. #endif
  16821. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  16822. "ENABLE_MEMORY_MANAGEMENT",
  16823. #endif
  16824. #if SQLITE_ENABLE_MEMSYS3
  16825. "ENABLE_MEMSYS3",
  16826. #endif
  16827. #if SQLITE_ENABLE_MEMSYS5
  16828. "ENABLE_MEMSYS5",
  16829. #endif
  16830. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  16831. "ENABLE_OVERSIZE_CELL_CHECK",
  16832. #endif
  16833. #if SQLITE_ENABLE_RTREE
  16834. "ENABLE_RTREE",
  16835. #endif
  16836. #if defined(SQLITE_ENABLE_STAT4)
  16837. "ENABLE_STAT4",
  16838. #elif defined(SQLITE_ENABLE_STAT3)
  16839. "ENABLE_STAT3",
  16840. #endif
  16841. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  16842. "ENABLE_UNLOCK_NOTIFY",
  16843. #endif
  16844. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  16845. "ENABLE_UPDATE_DELETE_LIMIT",
  16846. #endif
  16847. #if defined(SQLITE_ENABLE_URI_00_ERROR)
  16848. "ENABLE_URI_00_ERROR",
  16849. #endif
  16850. #if SQLITE_HAS_CODEC
  16851. "HAS_CODEC",
  16852. #endif
  16853. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  16854. "HAVE_ISNAN",
  16855. #endif
  16856. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  16857. "HOMEGROWN_RECURSIVE_MUTEX",
  16858. #endif
  16859. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  16860. "IGNORE_AFP_LOCK_ERRORS",
  16861. #endif
  16862. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  16863. "IGNORE_FLOCK_LOCK_ERRORS",
  16864. #endif
  16865. #ifdef SQLITE_INT64_TYPE
  16866. "INT64_TYPE",
  16867. #endif
  16868. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  16869. "LIKE_DOESNT_MATCH_BLOBS",
  16870. #endif
  16871. #if SQLITE_LOCK_TRACE
  16872. "LOCK_TRACE",
  16873. #endif
  16874. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  16875. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  16876. #endif
  16877. #ifdef SQLITE_MAX_SCHEMA_RETRY
  16878. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  16879. #endif
  16880. #if SQLITE_MEMDEBUG
  16881. "MEMDEBUG",
  16882. #endif
  16883. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  16884. "MIXED_ENDIAN_64BIT_FLOAT",
  16885. #endif
  16886. #if SQLITE_NO_SYNC
  16887. "NO_SYNC",
  16888. #endif
  16889. #if SQLITE_OMIT_ALTERTABLE
  16890. "OMIT_ALTERTABLE",
  16891. #endif
  16892. #if SQLITE_OMIT_ANALYZE
  16893. "OMIT_ANALYZE",
  16894. #endif
  16895. #if SQLITE_OMIT_ATTACH
  16896. "OMIT_ATTACH",
  16897. #endif
  16898. #if SQLITE_OMIT_AUTHORIZATION
  16899. "OMIT_AUTHORIZATION",
  16900. #endif
  16901. #if SQLITE_OMIT_AUTOINCREMENT
  16902. "OMIT_AUTOINCREMENT",
  16903. #endif
  16904. #if SQLITE_OMIT_AUTOINIT
  16905. "OMIT_AUTOINIT",
  16906. #endif
  16907. #if SQLITE_OMIT_AUTOMATIC_INDEX
  16908. "OMIT_AUTOMATIC_INDEX",
  16909. #endif
  16910. #if SQLITE_OMIT_AUTORESET
  16911. "OMIT_AUTORESET",
  16912. #endif
  16913. #if SQLITE_OMIT_AUTOVACUUM
  16914. "OMIT_AUTOVACUUM",
  16915. #endif
  16916. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  16917. "OMIT_BETWEEN_OPTIMIZATION",
  16918. #endif
  16919. #if SQLITE_OMIT_BLOB_LITERAL
  16920. "OMIT_BLOB_LITERAL",
  16921. #endif
  16922. #if SQLITE_OMIT_BTREECOUNT
  16923. "OMIT_BTREECOUNT",
  16924. #endif
  16925. #if SQLITE_OMIT_CAST
  16926. "OMIT_CAST",
  16927. #endif
  16928. #if SQLITE_OMIT_CHECK
  16929. "OMIT_CHECK",
  16930. #endif
  16931. #if SQLITE_OMIT_COMPLETE
  16932. "OMIT_COMPLETE",
  16933. #endif
  16934. #if SQLITE_OMIT_COMPOUND_SELECT
  16935. "OMIT_COMPOUND_SELECT",
  16936. #endif
  16937. #if SQLITE_OMIT_CTE
  16938. "OMIT_CTE",
  16939. #endif
  16940. #if SQLITE_OMIT_DATETIME_FUNCS
  16941. "OMIT_DATETIME_FUNCS",
  16942. #endif
  16943. #if SQLITE_OMIT_DECLTYPE
  16944. "OMIT_DECLTYPE",
  16945. #endif
  16946. #if SQLITE_OMIT_DEPRECATED
  16947. "OMIT_DEPRECATED",
  16948. #endif
  16949. #if SQLITE_OMIT_DISKIO
  16950. "OMIT_DISKIO",
  16951. #endif
  16952. #if SQLITE_OMIT_EXPLAIN
  16953. "OMIT_EXPLAIN",
  16954. #endif
  16955. #if SQLITE_OMIT_FLAG_PRAGMAS
  16956. "OMIT_FLAG_PRAGMAS",
  16957. #endif
  16958. #if SQLITE_OMIT_FLOATING_POINT
  16959. "OMIT_FLOATING_POINT",
  16960. #endif
  16961. #if SQLITE_OMIT_FOREIGN_KEY
  16962. "OMIT_FOREIGN_KEY",
  16963. #endif
  16964. #if SQLITE_OMIT_GET_TABLE
  16965. "OMIT_GET_TABLE",
  16966. #endif
  16967. #if SQLITE_OMIT_INCRBLOB
  16968. "OMIT_INCRBLOB",
  16969. #endif
  16970. #if SQLITE_OMIT_INTEGRITY_CHECK
  16971. "OMIT_INTEGRITY_CHECK",
  16972. #endif
  16973. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  16974. "OMIT_LIKE_OPTIMIZATION",
  16975. #endif
  16976. #if SQLITE_OMIT_LOAD_EXTENSION
  16977. "OMIT_LOAD_EXTENSION",
  16978. #endif
  16979. #if SQLITE_OMIT_LOCALTIME
  16980. "OMIT_LOCALTIME",
  16981. #endif
  16982. #if SQLITE_OMIT_LOOKASIDE
  16983. "OMIT_LOOKASIDE",
  16984. #endif
  16985. #if SQLITE_OMIT_MEMORYDB
  16986. "OMIT_MEMORYDB",
  16987. #endif
  16988. #if SQLITE_OMIT_OR_OPTIMIZATION
  16989. "OMIT_OR_OPTIMIZATION",
  16990. #endif
  16991. #if SQLITE_OMIT_PAGER_PRAGMAS
  16992. "OMIT_PAGER_PRAGMAS",
  16993. #endif
  16994. #if SQLITE_OMIT_PRAGMA
  16995. "OMIT_PRAGMA",
  16996. #endif
  16997. #if SQLITE_OMIT_PROGRESS_CALLBACK
  16998. "OMIT_PROGRESS_CALLBACK",
  16999. #endif
  17000. #if SQLITE_OMIT_QUICKBALANCE
  17001. "OMIT_QUICKBALANCE",
  17002. #endif
  17003. #if SQLITE_OMIT_REINDEX
  17004. "OMIT_REINDEX",
  17005. #endif
  17006. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  17007. "OMIT_SCHEMA_PRAGMAS",
  17008. #endif
  17009. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  17010. "OMIT_SCHEMA_VERSION_PRAGMAS",
  17011. #endif
  17012. #if SQLITE_OMIT_SHARED_CACHE
  17013. "OMIT_SHARED_CACHE",
  17014. #endif
  17015. #if SQLITE_OMIT_SUBQUERY
  17016. "OMIT_SUBQUERY",
  17017. #endif
  17018. #if SQLITE_OMIT_TCL_VARIABLE
  17019. "OMIT_TCL_VARIABLE",
  17020. #endif
  17021. #if SQLITE_OMIT_TEMPDB
  17022. "OMIT_TEMPDB",
  17023. #endif
  17024. #if SQLITE_OMIT_TRACE
  17025. "OMIT_TRACE",
  17026. #endif
  17027. #if SQLITE_OMIT_TRIGGER
  17028. "OMIT_TRIGGER",
  17029. #endif
  17030. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  17031. "OMIT_TRUNCATE_OPTIMIZATION",
  17032. #endif
  17033. #if SQLITE_OMIT_UTF16
  17034. "OMIT_UTF16",
  17035. #endif
  17036. #if SQLITE_OMIT_VACUUM
  17037. "OMIT_VACUUM",
  17038. #endif
  17039. #if SQLITE_OMIT_VIEW
  17040. "OMIT_VIEW",
  17041. #endif
  17042. #if SQLITE_OMIT_VIRTUALTABLE
  17043. "OMIT_VIRTUALTABLE",
  17044. #endif
  17045. #if SQLITE_OMIT_WAL
  17046. "OMIT_WAL",
  17047. #endif
  17048. #if SQLITE_OMIT_WSD
  17049. "OMIT_WSD",
  17050. #endif
  17051. #if SQLITE_OMIT_XFER_OPT
  17052. "OMIT_XFER_OPT",
  17053. #endif
  17054. #if SQLITE_PERFORMANCE_TRACE
  17055. "PERFORMANCE_TRACE",
  17056. #endif
  17057. #if SQLITE_PROXY_DEBUG
  17058. "PROXY_DEBUG",
  17059. #endif
  17060. #if SQLITE_RTREE_INT_ONLY
  17061. "RTREE_INT_ONLY",
  17062. #endif
  17063. #if SQLITE_SECURE_DELETE
  17064. "SECURE_DELETE",
  17065. #endif
  17066. #if SQLITE_SMALL_STACK
  17067. "SMALL_STACK",
  17068. #endif
  17069. #if SQLITE_SOUNDEX
  17070. "SOUNDEX",
  17071. #endif
  17072. #if SQLITE_SYSTEM_MALLOC
  17073. "SYSTEM_MALLOC",
  17074. #endif
  17075. #if SQLITE_TCL
  17076. "TCL",
  17077. #endif
  17078. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  17079. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  17080. #endif
  17081. #if SQLITE_TEST
  17082. "TEST",
  17083. #endif
  17084. #if defined(SQLITE_THREADSAFE)
  17085. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  17086. #endif
  17087. #if SQLITE_UNTESTABLE
  17088. "UNTESTABLE"
  17089. #endif
  17090. #if SQLITE_USE_ALLOCA
  17091. "USE_ALLOCA",
  17092. #endif
  17093. #if SQLITE_USER_AUTHENTICATION
  17094. "USER_AUTHENTICATION",
  17095. #endif
  17096. #if SQLITE_WIN32_MALLOC
  17097. "WIN32_MALLOC",
  17098. #endif
  17099. #if SQLITE_ZERO_MALLOC
  17100. "ZERO_MALLOC"
  17101. #endif
  17102. };
  17103. /*
  17104. ** Given the name of a compile-time option, return true if that option
  17105. ** was used and false if not.
  17106. **
  17107. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  17108. ** is not required for a match.
  17109. */
  17110. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  17111. int i, n;
  17112. #if SQLITE_ENABLE_API_ARMOR
  17113. if( zOptName==0 ){
  17114. (void)SQLITE_MISUSE_BKPT;
  17115. return 0;
  17116. }
  17117. #endif
  17118. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  17119. n = sqlite3Strlen30(zOptName);
  17120. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  17121. ** linear search is adequate. No need for a binary search. */
  17122. for(i=0; i<ArraySize(azCompileOpt); i++){
  17123. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  17124. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  17125. ){
  17126. return 1;
  17127. }
  17128. }
  17129. return 0;
  17130. }
  17131. /*
  17132. ** Return the N-th compile-time option string. If N is out of range,
  17133. ** return a NULL pointer.
  17134. */
  17135. SQLITE_API const char *sqlite3_compileoption_get(int N){
  17136. if( N>=0 && N<ArraySize(azCompileOpt) ){
  17137. return azCompileOpt[N];
  17138. }
  17139. return 0;
  17140. }
  17141. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  17142. /************** End of ctime.c ***********************************************/
  17143. /************** Begin file status.c ******************************************/
  17144. /*
  17145. ** 2008 June 18
  17146. **
  17147. ** The author disclaims copyright to this source code. In place of
  17148. ** a legal notice, here is a blessing:
  17149. **
  17150. ** May you do good and not evil.
  17151. ** May you find forgiveness for yourself and forgive others.
  17152. ** May you share freely, never taking more than you give.
  17153. **
  17154. *************************************************************************
  17155. **
  17156. ** This module implements the sqlite3_status() interface and related
  17157. ** functionality.
  17158. */
  17159. /* #include "sqliteInt.h" */
  17160. /************** Include vdbeInt.h in the middle of status.c ******************/
  17161. /************** Begin file vdbeInt.h *****************************************/
  17162. /*
  17163. ** 2003 September 6
  17164. **
  17165. ** The author disclaims copyright to this source code. In place of
  17166. ** a legal notice, here is a blessing:
  17167. **
  17168. ** May you do good and not evil.
  17169. ** May you find forgiveness for yourself and forgive others.
  17170. ** May you share freely, never taking more than you give.
  17171. **
  17172. *************************************************************************
  17173. ** This is the header file for information that is private to the
  17174. ** VDBE. This information used to all be at the top of the single
  17175. ** source code file "vdbe.c". When that file became too big (over
  17176. ** 6000 lines long) it was split up into several smaller files and
  17177. ** this header information was factored out.
  17178. */
  17179. #ifndef SQLITE_VDBEINT_H
  17180. #define SQLITE_VDBEINT_H
  17181. /*
  17182. ** The maximum number of times that a statement will try to reparse
  17183. ** itself before giving up and returning SQLITE_SCHEMA.
  17184. */
  17185. #ifndef SQLITE_MAX_SCHEMA_RETRY
  17186. # define SQLITE_MAX_SCHEMA_RETRY 50
  17187. #endif
  17188. /*
  17189. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  17190. ** "explain" P4 display logic is enabled.
  17191. */
  17192. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  17193. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  17194. # define VDBE_DISPLAY_P4 1
  17195. #else
  17196. # define VDBE_DISPLAY_P4 0
  17197. #endif
  17198. /*
  17199. ** SQL is translated into a sequence of instructions to be
  17200. ** executed by a virtual machine. Each instruction is an instance
  17201. ** of the following structure.
  17202. */
  17203. typedef struct VdbeOp Op;
  17204. /*
  17205. ** Boolean values
  17206. */
  17207. typedef unsigned Bool;
  17208. /* Opaque type used by code in vdbesort.c */
  17209. typedef struct VdbeSorter VdbeSorter;
  17210. /* Elements of the linked list at Vdbe.pAuxData */
  17211. typedef struct AuxData AuxData;
  17212. /* Types of VDBE cursors */
  17213. #define CURTYPE_BTREE 0
  17214. #define CURTYPE_SORTER 1
  17215. #define CURTYPE_VTAB 2
  17216. #define CURTYPE_PSEUDO 3
  17217. /*
  17218. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  17219. **
  17220. ** * A b-tree cursor
  17221. ** - In the main database or in an ephemeral database
  17222. ** - On either an index or a table
  17223. ** * A sorter
  17224. ** * A virtual table
  17225. ** * A one-row "pseudotable" stored in a single register
  17226. */
  17227. typedef struct VdbeCursor VdbeCursor;
  17228. struct VdbeCursor {
  17229. u8 eCurType; /* One of the CURTYPE_* values above */
  17230. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  17231. u8 nullRow; /* True if pointing to a row with no data */
  17232. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  17233. u8 isTable; /* True for rowid tables. False for indexes */
  17234. #ifdef SQLITE_DEBUG
  17235. u8 seekOp; /* Most recent seek operation on this cursor */
  17236. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  17237. #endif
  17238. Bool isEphemeral:1; /* True for an ephemeral table */
  17239. Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
  17240. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  17241. Btree *pBtx; /* Separate file holding temporary table */
  17242. i64 seqCount; /* Sequence counter */
  17243. int *aAltMap; /* Mapping from table to index column numbers */
  17244. /* Cached OP_Column parse information is only valid if cacheStatus matches
  17245. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  17246. ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
  17247. ** the cache is out of date. */
  17248. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  17249. int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
  17250. ** if there have been no prior seeks on the cursor. */
  17251. /* NB: seekResult does not distinguish between "no seeks have ever occurred
  17252. ** on this cursor" and "the most recent seek was an exact match". */
  17253. /* When a new VdbeCursor is allocated, only the fields above are zeroed.
  17254. ** The fields that follow are uninitialized, and must be individually
  17255. ** initialized prior to first use. */
  17256. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  17257. union {
  17258. BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */
  17259. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  17260. int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */
  17261. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  17262. } uc;
  17263. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  17264. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  17265. Pgno pgnoRoot; /* Root page of the open btree cursor */
  17266. i16 nField; /* Number of fields in the header */
  17267. u16 nHdrParsed; /* Number of header fields parsed so far */
  17268. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  17269. u32 *aOffset; /* Pointer to aType[nField] */
  17270. const u8 *aRow; /* Data for the current row, if all on one page */
  17271. u32 payloadSize; /* Total number of bytes in the record */
  17272. u32 szRow; /* Byte available in aRow */
  17273. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  17274. u64 maskUsed; /* Mask of columns used by this cursor */
  17275. #endif
  17276. /* 2*nField extra array elements allocated for aType[], beyond the one
  17277. ** static element declared in the structure. nField total array slots for
  17278. ** aType[] and nField+1 array slots for aOffset[] */
  17279. u32 aType[1]; /* Type values record decode. MUST BE LAST */
  17280. };
  17281. /*
  17282. ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
  17283. */
  17284. #define CACHE_STALE 0
  17285. /*
  17286. ** When a sub-program is executed (OP_Program), a structure of this type
  17287. ** is allocated to store the current value of the program counter, as
  17288. ** well as the current memory cell array and various other frame specific
  17289. ** values stored in the Vdbe struct. When the sub-program is finished,
  17290. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  17291. ** restoring the state of the VM to as it was before the sub-program
  17292. ** began executing.
  17293. **
  17294. ** The memory for a VdbeFrame object is allocated and managed by a memory
  17295. ** cell in the parent (calling) frame. When the memory cell is deleted or
  17296. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  17297. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  17298. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  17299. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  17300. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  17301. ** child frame are released.
  17302. **
  17303. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  17304. ** set to NULL if the currently executing frame is the main program.
  17305. */
  17306. typedef struct VdbeFrame VdbeFrame;
  17307. struct VdbeFrame {
  17308. Vdbe *v; /* VM this frame belongs to */
  17309. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  17310. Op *aOp; /* Program instructions for parent frame */
  17311. i64 *anExec; /* Event counters from parent frame */
  17312. Mem *aMem; /* Array of memory cells for parent frame */
  17313. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  17314. u8 *aOnce; /* Bitmask used by OP_Once */
  17315. void *token; /* Copy of SubProgram.token */
  17316. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  17317. AuxData *pAuxData; /* Linked list of auxdata allocations */
  17318. int nCursor; /* Number of entries in apCsr */
  17319. int pc; /* Program Counter in parent (calling) frame */
  17320. int nOp; /* Size of aOp array */
  17321. int nMem; /* Number of entries in aMem */
  17322. int nChildMem; /* Number of memory cells for child frame */
  17323. int nChildCsr; /* Number of cursors for child frame */
  17324. int nChange; /* Statement changes (Vdbe.nChange) */
  17325. int nDbChange; /* Value of db->nChange */
  17326. };
  17327. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  17328. /*
  17329. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  17330. ** structures. Each Mem struct may cache multiple representations (string,
  17331. ** integer etc.) of the same value.
  17332. */
  17333. struct sqlite3_value {
  17334. union MemValue {
  17335. double r; /* Real value used when MEM_Real is set in flags */
  17336. i64 i; /* Integer value used when MEM_Int is set in flags */
  17337. int nZero; /* Used when bit MEM_Zero is set in flags */
  17338. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  17339. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  17340. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  17341. } u;
  17342. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  17343. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  17344. u8 eSubtype; /* Subtype for this value */
  17345. int n; /* Number of characters in string value, excluding '\0' */
  17346. char *z; /* String or BLOB value */
  17347. /* ShallowCopy only needs to copy the information above */
  17348. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  17349. int szMalloc; /* Size of the zMalloc allocation */
  17350. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  17351. sqlite3 *db; /* The associated database connection */
  17352. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  17353. #ifdef SQLITE_DEBUG
  17354. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  17355. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  17356. #endif
  17357. };
  17358. /*
  17359. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  17360. ** follows.
  17361. */
  17362. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  17363. /* One or more of the following flags are set to indicate the validOK
  17364. ** representations of the value stored in the Mem struct.
  17365. **
  17366. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  17367. ** No other flags may be set in this case.
  17368. **
  17369. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  17370. ** Usually this is encoded in the same unicode encoding as the main
  17371. ** database (see below for exceptions). If the MEM_Term flag is also
  17372. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  17373. ** flags may coexist with the MEM_Str flag.
  17374. */
  17375. #define MEM_Null 0x0001 /* Value is NULL */
  17376. #define MEM_Str 0x0002 /* Value is a string */
  17377. #define MEM_Int 0x0004 /* Value is an integer */
  17378. #define MEM_Real 0x0008 /* Value is a real number */
  17379. #define MEM_Blob 0x0010 /* Value is a BLOB */
  17380. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  17381. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  17382. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  17383. #define MEM_Undefined 0x0080 /* Value is undefined */
  17384. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  17385. #define MEM_TypeMask 0x81ff /* Mask of type bits */
  17386. /* Whenever Mem contains a valid string or blob representation, one of
  17387. ** the following flags must be set to determine the memory management
  17388. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  17389. ** string is \000 or \u0000 terminated
  17390. */
  17391. #define MEM_Term 0x0200 /* String rep is nul terminated */
  17392. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  17393. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  17394. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  17395. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  17396. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  17397. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  17398. #ifdef SQLITE_OMIT_INCRBLOB
  17399. #undef MEM_Zero
  17400. #define MEM_Zero 0x0000
  17401. #endif
  17402. /* Return TRUE if Mem X contains dynamically allocated content - anything
  17403. ** that needs to be deallocated to avoid a leak.
  17404. */
  17405. #define VdbeMemDynamic(X) \
  17406. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  17407. /*
  17408. ** Clear any existing type flags from a Mem and replace them with f
  17409. */
  17410. #define MemSetTypeFlag(p, f) \
  17411. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  17412. /*
  17413. ** Return true if a memory cell is not marked as invalid. This macro
  17414. ** is for use inside assert() statements only.
  17415. */
  17416. #ifdef SQLITE_DEBUG
  17417. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  17418. #endif
  17419. /*
  17420. ** Each auxiliary data pointer stored by a user defined function
  17421. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  17422. ** of this structure. All such structures associated with a single VM
  17423. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  17424. ** when the VM is halted (if not before).
  17425. */
  17426. struct AuxData {
  17427. int iAuxOp; /* Instruction number of OP_Function opcode */
  17428. int iAuxArg; /* Index of function argument. */
  17429. void *pAux; /* Aux data pointer */
  17430. void (*xDeleteAux)(void*); /* Destructor for the aux data */
  17431. AuxData *pNextAux; /* Next element in list */
  17432. };
  17433. /*
  17434. ** The "context" argument for an installable function. A pointer to an
  17435. ** instance of this structure is the first argument to the routines used
  17436. ** implement the SQL functions.
  17437. **
  17438. ** There is a typedef for this structure in sqlite.h. So all routines,
  17439. ** even the public interface to SQLite, can use a pointer to this structure.
  17440. ** But this file is the only place where the internal details of this
  17441. ** structure are known.
  17442. **
  17443. ** This structure is defined inside of vdbeInt.h because it uses substructures
  17444. ** (Mem) which are only defined there.
  17445. */
  17446. struct sqlite3_context {
  17447. Mem *pOut; /* The return value is stored here */
  17448. FuncDef *pFunc; /* Pointer to function information */
  17449. Mem *pMem; /* Memory cell used to store aggregate context */
  17450. Vdbe *pVdbe; /* The VM that owns this context */
  17451. int iOp; /* Instruction number of OP_Function */
  17452. int isError; /* Error code returned by the function. */
  17453. u8 skipFlag; /* Skip accumulator loading if true */
  17454. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  17455. u8 argc; /* Number of arguments */
  17456. sqlite3_value *argv[1]; /* Argument set */
  17457. };
  17458. /* A bitfield type for use inside of structures. Always follow with :N where
  17459. ** N is the number of bits.
  17460. */
  17461. typedef unsigned bft; /* Bit Field Type */
  17462. typedef struct ScanStatus ScanStatus;
  17463. struct ScanStatus {
  17464. int addrExplain; /* OP_Explain for loop */
  17465. int addrLoop; /* Address of "loops" counter */
  17466. int addrVisit; /* Address of "rows visited" counter */
  17467. int iSelectID; /* The "Select-ID" for this loop */
  17468. LogEst nEst; /* Estimated output rows per loop */
  17469. char *zName; /* Name of table or index */
  17470. };
  17471. /*
  17472. ** An instance of the virtual machine. This structure contains the complete
  17473. ** state of the virtual machine.
  17474. **
  17475. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  17476. ** is really a pointer to an instance of this structure.
  17477. */
  17478. struct Vdbe {
  17479. sqlite3 *db; /* The database connection that owns this statement */
  17480. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  17481. Parse *pParse; /* Parsing context used to create this Vdbe */
  17482. ynVar nVar; /* Number of entries in aVar[] */
  17483. u32 magic; /* Magic number for sanity checking */
  17484. int nMem; /* Number of memory locations currently allocated */
  17485. int nCursor; /* Number of slots in apCsr[] */
  17486. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  17487. int pc; /* The program counter */
  17488. int rc; /* Value to return */
  17489. int nChange; /* Number of db changes made since last reset */
  17490. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  17491. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  17492. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  17493. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  17494. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  17495. /* When allocating a new Vdbe object, all of the fields below should be
  17496. ** initialized to zero or NULL */
  17497. Op *aOp; /* Space to hold the virtual machine's program */
  17498. Mem *aMem; /* The memory locations */
  17499. Mem **apArg; /* Arguments to currently executing user function */
  17500. Mem *aColName; /* Column names to return */
  17501. Mem *pResultSet; /* Pointer to an array of results */
  17502. char *zErrMsg; /* Error message written here */
  17503. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  17504. Mem *aVar; /* Values for the OP_Variable opcode. */
  17505. VList *pVList; /* Name of variables */
  17506. #ifndef SQLITE_OMIT_TRACE
  17507. i64 startTime; /* Time when query started - used for profiling */
  17508. #endif
  17509. int nOp; /* Number of instructions in the program */
  17510. #ifdef SQLITE_DEBUG
  17511. int rcApp; /* errcode set by sqlite3_result_error_code() */
  17512. #endif
  17513. u16 nResColumn; /* Number of columns in one row of the result set */
  17514. u8 errorAction; /* Recovery action to do in case of an error */
  17515. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  17516. bft expired:1; /* True if the VM needs to be recompiled */
  17517. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  17518. bft explain:2; /* True if EXPLAIN present on SQL command */
  17519. bft changeCntOn:1; /* True to update the change-counter */
  17520. bft runOnlyOnce:1; /* Automatically expire on reset */
  17521. bft usesStmtJournal:1; /* True if uses a statement journal */
  17522. bft readOnly:1; /* True for statements that do not write */
  17523. bft bIsReader:1; /* True for statements that read */
  17524. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  17525. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  17526. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  17527. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  17528. char *zSql; /* Text of the SQL statement that generated this */
  17529. void *pFree; /* Free this when deleting the vdbe */
  17530. VdbeFrame *pFrame; /* Parent frame */
  17531. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  17532. int nFrame; /* Number of frames in pFrame list */
  17533. u32 expmask; /* Binding to these vars invalidates VM */
  17534. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  17535. AuxData *pAuxData; /* Linked list of auxdata allocations */
  17536. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  17537. i64 *anExec; /* Number of times each op has been executed */
  17538. int nScan; /* Entries in aScan[] */
  17539. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  17540. #endif
  17541. };
  17542. /*
  17543. ** The following are allowed values for Vdbe.magic
  17544. */
  17545. #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
  17546. #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
  17547. #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
  17548. #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
  17549. #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
  17550. /*
  17551. ** Structure used to store the context required by the
  17552. ** sqlite3_preupdate_*() API functions.
  17553. */
  17554. struct PreUpdate {
  17555. Vdbe *v;
  17556. VdbeCursor *pCsr; /* Cursor to read old values from */
  17557. int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
  17558. u8 *aRecord; /* old.* database record */
  17559. KeyInfo keyinfo;
  17560. UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
  17561. UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
  17562. int iNewReg; /* Register for new.* values */
  17563. i64 iKey1; /* First key value passed to hook */
  17564. i64 iKey2; /* Second key value passed to hook */
  17565. Mem *aNew; /* Array of new.* values */
  17566. Table *pTab; /* Schema object being upated */
  17567. Index *pPk; /* PK index if pTab is WITHOUT ROWID */
  17568. };
  17569. /*
  17570. ** Function prototypes
  17571. */
  17572. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  17573. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  17574. void sqliteVdbePopStack(Vdbe*,int);
  17575. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  17576. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  17577. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  17578. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  17579. #endif
  17580. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  17581. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  17582. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  17583. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  17584. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  17585. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  17586. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  17587. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  17588. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  17589. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  17590. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  17591. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  17592. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  17593. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  17594. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  17595. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  17596. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  17597. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  17598. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  17599. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  17600. #ifdef SQLITE_OMIT_FLOATING_POINT
  17601. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  17602. #else
  17603. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  17604. #endif
  17605. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  17606. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  17607. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  17608. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  17609. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  17610. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  17611. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  17612. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  17613. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  17614. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  17615. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  17616. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  17617. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  17618. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
  17619. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  17620. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  17621. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  17622. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  17623. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  17624. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  17625. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  17626. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  17627. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  17628. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
  17629. #endif
  17630. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  17631. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  17632. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  17633. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  17634. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  17635. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  17636. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  17637. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  17638. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  17639. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  17640. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  17641. #else
  17642. # define sqlite3VdbeEnter(X)
  17643. #endif
  17644. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  17645. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  17646. #else
  17647. # define sqlite3VdbeLeave(X)
  17648. #endif
  17649. #ifdef SQLITE_DEBUG
  17650. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  17651. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  17652. #endif
  17653. #ifndef SQLITE_OMIT_FOREIGN_KEY
  17654. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  17655. #else
  17656. # define sqlite3VdbeCheckFk(p,i) 0
  17657. #endif
  17658. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  17659. #ifdef SQLITE_DEBUG
  17660. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  17661. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  17662. #endif
  17663. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  17664. #ifndef SQLITE_OMIT_INCRBLOB
  17665. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  17666. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  17667. #else
  17668. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  17669. #define ExpandBlob(P) SQLITE_OK
  17670. #endif
  17671. #endif /* !defined(SQLITE_VDBEINT_H) */
  17672. /************** End of vdbeInt.h *********************************************/
  17673. /************** Continuing where we left off in status.c *********************/
  17674. /*
  17675. ** Variables in which to record status information.
  17676. */
  17677. #if SQLITE_PTRSIZE>4
  17678. typedef sqlite3_int64 sqlite3StatValueType;
  17679. #else
  17680. typedef u32 sqlite3StatValueType;
  17681. #endif
  17682. typedef struct sqlite3StatType sqlite3StatType;
  17683. static SQLITE_WSD struct sqlite3StatType {
  17684. sqlite3StatValueType nowValue[10]; /* Current value */
  17685. sqlite3StatValueType mxValue[10]; /* Maximum value */
  17686. } sqlite3Stat = { {0,}, {0,} };
  17687. /*
  17688. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  17689. ** mutex, or by the pcache1 mutex. The following array determines which.
  17690. */
  17691. static const char statMutex[] = {
  17692. 0, /* SQLITE_STATUS_MEMORY_USED */
  17693. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  17694. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  17695. 0, /* SQLITE_STATUS_SCRATCH_USED */
  17696. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  17697. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  17698. 0, /* SQLITE_STATUS_PARSER_STACK */
  17699. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  17700. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  17701. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  17702. };
  17703. /* The "wsdStat" macro will resolve to the status information
  17704. ** state vector. If writable static data is unsupported on the target,
  17705. ** we have to locate the state vector at run-time. In the more common
  17706. ** case where writable static data is supported, wsdStat can refer directly
  17707. ** to the "sqlite3Stat" state vector declared above.
  17708. */
  17709. #ifdef SQLITE_OMIT_WSD
  17710. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  17711. # define wsdStat x[0]
  17712. #else
  17713. # define wsdStatInit
  17714. # define wsdStat sqlite3Stat
  17715. #endif
  17716. /*
  17717. ** Return the current value of a status parameter. The caller must
  17718. ** be holding the appropriate mutex.
  17719. */
  17720. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  17721. wsdStatInit;
  17722. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  17723. assert( op>=0 && op<ArraySize(statMutex) );
  17724. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  17725. : sqlite3MallocMutex()) );
  17726. return wsdStat.nowValue[op];
  17727. }
  17728. /*
  17729. ** Add N to the value of a status record. The caller must hold the
  17730. ** appropriate mutex. (Locking is checked by assert()).
  17731. **
  17732. ** The StatusUp() routine can accept positive or negative values for N.
  17733. ** The value of N is added to the current status value and the high-water
  17734. ** mark is adjusted if necessary.
  17735. **
  17736. ** The StatusDown() routine lowers the current value by N. The highwater
  17737. ** mark is unchanged. N must be non-negative for StatusDown().
  17738. */
  17739. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  17740. wsdStatInit;
  17741. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  17742. assert( op>=0 && op<ArraySize(statMutex) );
  17743. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  17744. : sqlite3MallocMutex()) );
  17745. wsdStat.nowValue[op] += N;
  17746. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  17747. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  17748. }
  17749. }
  17750. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  17751. wsdStatInit;
  17752. assert( N>=0 );
  17753. assert( op>=0 && op<ArraySize(statMutex) );
  17754. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  17755. : sqlite3MallocMutex()) );
  17756. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  17757. wsdStat.nowValue[op] -= N;
  17758. }
  17759. /*
  17760. ** Adjust the highwater mark if necessary.
  17761. ** The caller must hold the appropriate mutex.
  17762. */
  17763. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  17764. sqlite3StatValueType newValue;
  17765. wsdStatInit;
  17766. assert( X>=0 );
  17767. newValue = (sqlite3StatValueType)X;
  17768. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  17769. assert( op>=0 && op<ArraySize(statMutex) );
  17770. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  17771. : sqlite3MallocMutex()) );
  17772. assert( op==SQLITE_STATUS_MALLOC_SIZE
  17773. || op==SQLITE_STATUS_PAGECACHE_SIZE
  17774. || op==SQLITE_STATUS_SCRATCH_SIZE
  17775. || op==SQLITE_STATUS_PARSER_STACK );
  17776. if( newValue>wsdStat.mxValue[op] ){
  17777. wsdStat.mxValue[op] = newValue;
  17778. }
  17779. }
  17780. /*
  17781. ** Query status information.
  17782. */
  17783. SQLITE_API int sqlite3_status64(
  17784. int op,
  17785. sqlite3_int64 *pCurrent,
  17786. sqlite3_int64 *pHighwater,
  17787. int resetFlag
  17788. ){
  17789. sqlite3_mutex *pMutex;
  17790. wsdStatInit;
  17791. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  17792. return SQLITE_MISUSE_BKPT;
  17793. }
  17794. #ifdef SQLITE_ENABLE_API_ARMOR
  17795. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  17796. #endif
  17797. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  17798. sqlite3_mutex_enter(pMutex);
  17799. *pCurrent = wsdStat.nowValue[op];
  17800. *pHighwater = wsdStat.mxValue[op];
  17801. if( resetFlag ){
  17802. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  17803. }
  17804. sqlite3_mutex_leave(pMutex);
  17805. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  17806. return SQLITE_OK;
  17807. }
  17808. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  17809. sqlite3_int64 iCur = 0, iHwtr = 0;
  17810. int rc;
  17811. #ifdef SQLITE_ENABLE_API_ARMOR
  17812. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  17813. #endif
  17814. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  17815. if( rc==0 ){
  17816. *pCurrent = (int)iCur;
  17817. *pHighwater = (int)iHwtr;
  17818. }
  17819. return rc;
  17820. }
  17821. /*
  17822. ** Query status information for a single database connection
  17823. */
  17824. SQLITE_API int sqlite3_db_status(
  17825. sqlite3 *db, /* The database connection whose status is desired */
  17826. int op, /* Status verb */
  17827. int *pCurrent, /* Write current value here */
  17828. int *pHighwater, /* Write high-water mark here */
  17829. int resetFlag /* Reset high-water mark if true */
  17830. ){
  17831. int rc = SQLITE_OK; /* Return code */
  17832. #ifdef SQLITE_ENABLE_API_ARMOR
  17833. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  17834. return SQLITE_MISUSE_BKPT;
  17835. }
  17836. #endif
  17837. sqlite3_mutex_enter(db->mutex);
  17838. switch( op ){
  17839. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  17840. *pCurrent = db->lookaside.nOut;
  17841. *pHighwater = db->lookaside.mxOut;
  17842. if( resetFlag ){
  17843. db->lookaside.mxOut = db->lookaside.nOut;
  17844. }
  17845. break;
  17846. }
  17847. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  17848. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  17849. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  17850. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  17851. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  17852. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  17853. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  17854. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  17855. *pCurrent = 0;
  17856. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  17857. if( resetFlag ){
  17858. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  17859. }
  17860. break;
  17861. }
  17862. /*
  17863. ** Return an approximation for the amount of memory currently used
  17864. ** by all pagers associated with the given database connection. The
  17865. ** highwater mark is meaningless and is returned as zero.
  17866. */
  17867. case SQLITE_DBSTATUS_CACHE_USED_SHARED:
  17868. case SQLITE_DBSTATUS_CACHE_USED: {
  17869. int totalUsed = 0;
  17870. int i;
  17871. sqlite3BtreeEnterAll(db);
  17872. for(i=0; i<db->nDb; i++){
  17873. Btree *pBt = db->aDb[i].pBt;
  17874. if( pBt ){
  17875. Pager *pPager = sqlite3BtreePager(pBt);
  17876. int nByte = sqlite3PagerMemUsed(pPager);
  17877. if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
  17878. nByte = nByte / sqlite3BtreeConnectionCount(pBt);
  17879. }
  17880. totalUsed += nByte;
  17881. }
  17882. }
  17883. sqlite3BtreeLeaveAll(db);
  17884. *pCurrent = totalUsed;
  17885. *pHighwater = 0;
  17886. break;
  17887. }
  17888. /*
  17889. ** *pCurrent gets an accurate estimate of the amount of memory used
  17890. ** to store the schema for all databases (main, temp, and any ATTACHed
  17891. ** databases. *pHighwater is set to zero.
  17892. */
  17893. case SQLITE_DBSTATUS_SCHEMA_USED: {
  17894. int i; /* Used to iterate through schemas */
  17895. int nByte = 0; /* Used to accumulate return value */
  17896. sqlite3BtreeEnterAll(db);
  17897. db->pnBytesFreed = &nByte;
  17898. for(i=0; i<db->nDb; i++){
  17899. Schema *pSchema = db->aDb[i].pSchema;
  17900. if( ALWAYS(pSchema!=0) ){
  17901. HashElem *p;
  17902. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  17903. pSchema->tblHash.count
  17904. + pSchema->trigHash.count
  17905. + pSchema->idxHash.count
  17906. + pSchema->fkeyHash.count
  17907. );
  17908. nByte += sqlite3_msize(pSchema->tblHash.ht);
  17909. nByte += sqlite3_msize(pSchema->trigHash.ht);
  17910. nByte += sqlite3_msize(pSchema->idxHash.ht);
  17911. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  17912. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  17913. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  17914. }
  17915. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  17916. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  17917. }
  17918. }
  17919. }
  17920. db->pnBytesFreed = 0;
  17921. sqlite3BtreeLeaveAll(db);
  17922. *pHighwater = 0;
  17923. *pCurrent = nByte;
  17924. break;
  17925. }
  17926. /*
  17927. ** *pCurrent gets an accurate estimate of the amount of memory used
  17928. ** to store all prepared statements.
  17929. ** *pHighwater is set to zero.
  17930. */
  17931. case SQLITE_DBSTATUS_STMT_USED: {
  17932. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  17933. int nByte = 0; /* Used to accumulate return value */
  17934. db->pnBytesFreed = &nByte;
  17935. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  17936. sqlite3VdbeClearObject(db, pVdbe);
  17937. sqlite3DbFree(db, pVdbe);
  17938. }
  17939. db->pnBytesFreed = 0;
  17940. *pHighwater = 0; /* IMP: R-64479-57858 */
  17941. *pCurrent = nByte;
  17942. break;
  17943. }
  17944. /*
  17945. ** Set *pCurrent to the total cache hits or misses encountered by all
  17946. ** pagers the database handle is connected to. *pHighwater is always set
  17947. ** to zero.
  17948. */
  17949. case SQLITE_DBSTATUS_CACHE_HIT:
  17950. case SQLITE_DBSTATUS_CACHE_MISS:
  17951. case SQLITE_DBSTATUS_CACHE_WRITE:{
  17952. int i;
  17953. int nRet = 0;
  17954. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  17955. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  17956. for(i=0; i<db->nDb; i++){
  17957. if( db->aDb[i].pBt ){
  17958. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  17959. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  17960. }
  17961. }
  17962. *pHighwater = 0; /* IMP: R-42420-56072 */
  17963. /* IMP: R-54100-20147 */
  17964. /* IMP: R-29431-39229 */
  17965. *pCurrent = nRet;
  17966. break;
  17967. }
  17968. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  17969. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  17970. ** have been satisfied. The *pHighwater is always set to zero.
  17971. */
  17972. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  17973. *pHighwater = 0; /* IMP: R-11967-56545 */
  17974. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  17975. break;
  17976. }
  17977. default: {
  17978. rc = SQLITE_ERROR;
  17979. }
  17980. }
  17981. sqlite3_mutex_leave(db->mutex);
  17982. return rc;
  17983. }
  17984. /************** End of status.c **********************************************/
  17985. /************** Begin file date.c ********************************************/
  17986. /*
  17987. ** 2003 October 31
  17988. **
  17989. ** The author disclaims copyright to this source code. In place of
  17990. ** a legal notice, here is a blessing:
  17991. **
  17992. ** May you do good and not evil.
  17993. ** May you find forgiveness for yourself and forgive others.
  17994. ** May you share freely, never taking more than you give.
  17995. **
  17996. *************************************************************************
  17997. ** This file contains the C functions that implement date and time
  17998. ** functions for SQLite.
  17999. **
  18000. ** There is only one exported symbol in this file - the function
  18001. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  18002. ** All other code has file scope.
  18003. **
  18004. ** SQLite processes all times and dates as julian day numbers. The
  18005. ** dates and times are stored as the number of days since noon
  18006. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  18007. ** calendar system.
  18008. **
  18009. ** 1970-01-01 00:00:00 is JD 2440587.5
  18010. ** 2000-01-01 00:00:00 is JD 2451544.5
  18011. **
  18012. ** This implementation requires years to be expressed as a 4-digit number
  18013. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  18014. ** be represented, even though julian day numbers allow a much wider
  18015. ** range of dates.
  18016. **
  18017. ** The Gregorian calendar system is used for all dates and times,
  18018. ** even those that predate the Gregorian calendar. Historians usually
  18019. ** use the julian calendar for dates prior to 1582-10-15 and for some
  18020. ** dates afterwards, depending on locale. Beware of this difference.
  18021. **
  18022. ** The conversion algorithms are implemented based on descriptions
  18023. ** in the following text:
  18024. **
  18025. ** Jean Meeus
  18026. ** Astronomical Algorithms, 2nd Edition, 1998
  18027. ** ISBM 0-943396-61-1
  18028. ** Willmann-Bell, Inc
  18029. ** Richmond, Virginia (USA)
  18030. */
  18031. /* #include "sqliteInt.h" */
  18032. /* #include <stdlib.h> */
  18033. /* #include <assert.h> */
  18034. #include <time.h>
  18035. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  18036. /*
  18037. ** The MSVC CRT on Windows CE may not have a localtime() function.
  18038. ** So declare a substitute. The substitute function itself is
  18039. ** defined in "os_win.c".
  18040. */
  18041. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  18042. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  18043. struct tm *__cdecl localtime(const time_t *);
  18044. #endif
  18045. /*
  18046. ** A structure for holding a single date and time.
  18047. */
  18048. typedef struct DateTime DateTime;
  18049. struct DateTime {
  18050. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  18051. int Y, M, D; /* Year, month, and day */
  18052. int h, m; /* Hour and minutes */
  18053. int tz; /* Timezone offset in minutes */
  18054. double s; /* Seconds */
  18055. char validJD; /* True (1) if iJD is valid */
  18056. char rawS; /* Raw numeric value stored in s */
  18057. char validYMD; /* True (1) if Y,M,D are valid */
  18058. char validHMS; /* True (1) if h,m,s are valid */
  18059. char validTZ; /* True (1) if tz is valid */
  18060. char tzSet; /* Timezone was set explicitly */
  18061. char isError; /* An overflow has occurred */
  18062. };
  18063. /*
  18064. ** Convert zDate into one or more integers according to the conversion
  18065. ** specifier zFormat.
  18066. **
  18067. ** zFormat[] contains 4 characters for each integer converted, except for
  18068. ** the last integer which is specified by three characters. The meaning
  18069. ** of a four-character format specifiers ABCD is:
  18070. **
  18071. ** A: number of digits to convert. Always "2" or "4".
  18072. ** B: minimum value. Always "0" or "1".
  18073. ** C: maximum value, decoded as:
  18074. ** a: 12
  18075. ** b: 14
  18076. ** c: 24
  18077. ** d: 31
  18078. ** e: 59
  18079. ** f: 9999
  18080. ** D: the separator character, or \000 to indicate this is the
  18081. ** last number to convert.
  18082. **
  18083. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  18084. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  18085. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  18086. ** the 2-digit day which is the last integer in the set.
  18087. **
  18088. ** The function returns the number of successful conversions.
  18089. */
  18090. static int getDigits(const char *zDate, const char *zFormat, ...){
  18091. /* The aMx[] array translates the 3rd character of each format
  18092. ** spec into a max size: a b c d e f */
  18093. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  18094. va_list ap;
  18095. int cnt = 0;
  18096. char nextC;
  18097. va_start(ap, zFormat);
  18098. do{
  18099. char N = zFormat[0] - '0';
  18100. char min = zFormat[1] - '0';
  18101. int val = 0;
  18102. u16 max;
  18103. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  18104. max = aMx[zFormat[2] - 'a'];
  18105. nextC = zFormat[3];
  18106. val = 0;
  18107. while( N-- ){
  18108. if( !sqlite3Isdigit(*zDate) ){
  18109. goto end_getDigits;
  18110. }
  18111. val = val*10 + *zDate - '0';
  18112. zDate++;
  18113. }
  18114. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  18115. goto end_getDigits;
  18116. }
  18117. *va_arg(ap,int*) = val;
  18118. zDate++;
  18119. cnt++;
  18120. zFormat += 4;
  18121. }while( nextC );
  18122. end_getDigits:
  18123. va_end(ap);
  18124. return cnt;
  18125. }
  18126. /*
  18127. ** Parse a timezone extension on the end of a date-time.
  18128. ** The extension is of the form:
  18129. **
  18130. ** (+/-)HH:MM
  18131. **
  18132. ** Or the "zulu" notation:
  18133. **
  18134. ** Z
  18135. **
  18136. ** If the parse is successful, write the number of minutes
  18137. ** of change in p->tz and return 0. If a parser error occurs,
  18138. ** return non-zero.
  18139. **
  18140. ** A missing specifier is not considered an error.
  18141. */
  18142. static int parseTimezone(const char *zDate, DateTime *p){
  18143. int sgn = 0;
  18144. int nHr, nMn;
  18145. int c;
  18146. while( sqlite3Isspace(*zDate) ){ zDate++; }
  18147. p->tz = 0;
  18148. c = *zDate;
  18149. if( c=='-' ){
  18150. sgn = -1;
  18151. }else if( c=='+' ){
  18152. sgn = +1;
  18153. }else if( c=='Z' || c=='z' ){
  18154. zDate++;
  18155. goto zulu_time;
  18156. }else{
  18157. return c!=0;
  18158. }
  18159. zDate++;
  18160. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  18161. return 1;
  18162. }
  18163. zDate += 5;
  18164. p->tz = sgn*(nMn + nHr*60);
  18165. zulu_time:
  18166. while( sqlite3Isspace(*zDate) ){ zDate++; }
  18167. p->tzSet = 1;
  18168. return *zDate!=0;
  18169. }
  18170. /*
  18171. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  18172. ** The HH, MM, and SS must each be exactly 2 digits. The
  18173. ** fractional seconds FFFF can be one or more digits.
  18174. **
  18175. ** Return 1 if there is a parsing error and 0 on success.
  18176. */
  18177. static int parseHhMmSs(const char *zDate, DateTime *p){
  18178. int h, m, s;
  18179. double ms = 0.0;
  18180. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  18181. return 1;
  18182. }
  18183. zDate += 5;
  18184. if( *zDate==':' ){
  18185. zDate++;
  18186. if( getDigits(zDate, "20e", &s)!=1 ){
  18187. return 1;
  18188. }
  18189. zDate += 2;
  18190. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  18191. double rScale = 1.0;
  18192. zDate++;
  18193. while( sqlite3Isdigit(*zDate) ){
  18194. ms = ms*10.0 + *zDate - '0';
  18195. rScale *= 10.0;
  18196. zDate++;
  18197. }
  18198. ms /= rScale;
  18199. }
  18200. }else{
  18201. s = 0;
  18202. }
  18203. p->validJD = 0;
  18204. p->rawS = 0;
  18205. p->validHMS = 1;
  18206. p->h = h;
  18207. p->m = m;
  18208. p->s = s + ms;
  18209. if( parseTimezone(zDate, p) ) return 1;
  18210. p->validTZ = (p->tz!=0)?1:0;
  18211. return 0;
  18212. }
  18213. /*
  18214. ** Put the DateTime object into its error state.
  18215. */
  18216. static void datetimeError(DateTime *p){
  18217. memset(p, 0, sizeof(*p));
  18218. p->isError = 1;
  18219. }
  18220. /*
  18221. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  18222. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  18223. **
  18224. ** Reference: Meeus page 61
  18225. */
  18226. static void computeJD(DateTime *p){
  18227. int Y, M, D, A, B, X1, X2;
  18228. if( p->validJD ) return;
  18229. if( p->validYMD ){
  18230. Y = p->Y;
  18231. M = p->M;
  18232. D = p->D;
  18233. }else{
  18234. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  18235. M = 1;
  18236. D = 1;
  18237. }
  18238. if( Y<-4713 || Y>9999 || p->rawS ){
  18239. datetimeError(p);
  18240. return;
  18241. }
  18242. if( M<=2 ){
  18243. Y--;
  18244. M += 12;
  18245. }
  18246. A = Y/100;
  18247. B = 2 - A + (A/4);
  18248. X1 = 36525*(Y+4716)/100;
  18249. X2 = 306001*(M+1)/10000;
  18250. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  18251. p->validJD = 1;
  18252. if( p->validHMS ){
  18253. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  18254. if( p->validTZ ){
  18255. p->iJD -= p->tz*60000;
  18256. p->validYMD = 0;
  18257. p->validHMS = 0;
  18258. p->validTZ = 0;
  18259. }
  18260. }
  18261. }
  18262. /*
  18263. ** Parse dates of the form
  18264. **
  18265. ** YYYY-MM-DD HH:MM:SS.FFF
  18266. ** YYYY-MM-DD HH:MM:SS
  18267. ** YYYY-MM-DD HH:MM
  18268. ** YYYY-MM-DD
  18269. **
  18270. ** Write the result into the DateTime structure and return 0
  18271. ** on success and 1 if the input string is not a well-formed
  18272. ** date.
  18273. */
  18274. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  18275. int Y, M, D, neg;
  18276. if( zDate[0]=='-' ){
  18277. zDate++;
  18278. neg = 1;
  18279. }else{
  18280. neg = 0;
  18281. }
  18282. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  18283. return 1;
  18284. }
  18285. zDate += 10;
  18286. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  18287. if( parseHhMmSs(zDate, p)==0 ){
  18288. /* We got the time */
  18289. }else if( *zDate==0 ){
  18290. p->validHMS = 0;
  18291. }else{
  18292. return 1;
  18293. }
  18294. p->validJD = 0;
  18295. p->validYMD = 1;
  18296. p->Y = neg ? -Y : Y;
  18297. p->M = M;
  18298. p->D = D;
  18299. if( p->validTZ ){
  18300. computeJD(p);
  18301. }
  18302. return 0;
  18303. }
  18304. /*
  18305. ** Set the time to the current time reported by the VFS.
  18306. **
  18307. ** Return the number of errors.
  18308. */
  18309. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  18310. p->iJD = sqlite3StmtCurrentTime(context);
  18311. if( p->iJD>0 ){
  18312. p->validJD = 1;
  18313. return 0;
  18314. }else{
  18315. return 1;
  18316. }
  18317. }
  18318. /*
  18319. ** Input "r" is a numeric quantity which might be a julian day number,
  18320. ** or the number of seconds since 1970. If the value if r is within
  18321. ** range of a julian day number, install it as such and set validJD.
  18322. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
  18323. */
  18324. static void setRawDateNumber(DateTime *p, double r){
  18325. p->s = r;
  18326. p->rawS = 1;
  18327. if( r>=0.0 && r<5373484.5 ){
  18328. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  18329. p->validJD = 1;
  18330. }
  18331. }
  18332. /*
  18333. ** Attempt to parse the given string into a julian day number. Return
  18334. ** the number of errors.
  18335. **
  18336. ** The following are acceptable forms for the input string:
  18337. **
  18338. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  18339. ** DDDD.DD
  18340. ** now
  18341. **
  18342. ** In the first form, the +/-HH:MM is always optional. The fractional
  18343. ** seconds extension (the ".FFF") is optional. The seconds portion
  18344. ** (":SS.FFF") is option. The year and date can be omitted as long
  18345. ** as there is a time string. The time string can be omitted as long
  18346. ** as there is a year and date.
  18347. */
  18348. static int parseDateOrTime(
  18349. sqlite3_context *context,
  18350. const char *zDate,
  18351. DateTime *p
  18352. ){
  18353. double r;
  18354. if( parseYyyyMmDd(zDate,p)==0 ){
  18355. return 0;
  18356. }else if( parseHhMmSs(zDate, p)==0 ){
  18357. return 0;
  18358. }else if( sqlite3StrICmp(zDate,"now")==0){
  18359. return setDateTimeToCurrent(context, p);
  18360. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  18361. setRawDateNumber(p, r);
  18362. return 0;
  18363. }
  18364. return 1;
  18365. }
  18366. /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
  18367. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
  18368. ** for DateTime.iJD.
  18369. **
  18370. ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
  18371. ** such a large integer literal, so we have to encode it.
  18372. */
  18373. #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
  18374. /*
  18375. ** Return TRUE if the given julian day number is within range.
  18376. **
  18377. ** The input is the JulianDay times 86400000.
  18378. */
  18379. static int validJulianDay(sqlite3_int64 iJD){
  18380. return iJD>=0 && iJD<=INT_464269060799999;
  18381. }
  18382. /*
  18383. ** Compute the Year, Month, and Day from the julian day number.
  18384. */
  18385. static void computeYMD(DateTime *p){
  18386. int Z, A, B, C, D, E, X1;
  18387. if( p->validYMD ) return;
  18388. if( !p->validJD ){
  18389. p->Y = 2000;
  18390. p->M = 1;
  18391. p->D = 1;
  18392. }else if( !validJulianDay(p->iJD) ){
  18393. datetimeError(p);
  18394. return;
  18395. }else{
  18396. Z = (int)((p->iJD + 43200000)/86400000);
  18397. A = (int)((Z - 1867216.25)/36524.25);
  18398. A = Z + 1 + A - (A/4);
  18399. B = A + 1524;
  18400. C = (int)((B - 122.1)/365.25);
  18401. D = (36525*(C&32767))/100;
  18402. E = (int)((B-D)/30.6001);
  18403. X1 = (int)(30.6001*E);
  18404. p->D = B - D - X1;
  18405. p->M = E<14 ? E-1 : E-13;
  18406. p->Y = p->M>2 ? C - 4716 : C - 4715;
  18407. }
  18408. p->validYMD = 1;
  18409. }
  18410. /*
  18411. ** Compute the Hour, Minute, and Seconds from the julian day number.
  18412. */
  18413. static void computeHMS(DateTime *p){
  18414. int s;
  18415. if( p->validHMS ) return;
  18416. computeJD(p);
  18417. s = (int)((p->iJD + 43200000) % 86400000);
  18418. p->s = s/1000.0;
  18419. s = (int)p->s;
  18420. p->s -= s;
  18421. p->h = s/3600;
  18422. s -= p->h*3600;
  18423. p->m = s/60;
  18424. p->s += s - p->m*60;
  18425. p->rawS = 0;
  18426. p->validHMS = 1;
  18427. }
  18428. /*
  18429. ** Compute both YMD and HMS
  18430. */
  18431. static void computeYMD_HMS(DateTime *p){
  18432. computeYMD(p);
  18433. computeHMS(p);
  18434. }
  18435. /*
  18436. ** Clear the YMD and HMS and the TZ
  18437. */
  18438. static void clearYMD_HMS_TZ(DateTime *p){
  18439. p->validYMD = 0;
  18440. p->validHMS = 0;
  18441. p->validTZ = 0;
  18442. }
  18443. #ifndef SQLITE_OMIT_LOCALTIME
  18444. /*
  18445. ** On recent Windows platforms, the localtime_s() function is available
  18446. ** as part of the "Secure CRT". It is essentially equivalent to
  18447. ** localtime_r() available under most POSIX platforms, except that the
  18448. ** order of the parameters is reversed.
  18449. **
  18450. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  18451. **
  18452. ** If the user has not indicated to use localtime_r() or localtime_s()
  18453. ** already, check for an MSVC build environment that provides
  18454. ** localtime_s().
  18455. */
  18456. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  18457. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  18458. #undef HAVE_LOCALTIME_S
  18459. #define HAVE_LOCALTIME_S 1
  18460. #endif
  18461. /*
  18462. ** The following routine implements the rough equivalent of localtime_r()
  18463. ** using whatever operating-system specific localtime facility that
  18464. ** is available. This routine returns 0 on success and
  18465. ** non-zero on any kind of error.
  18466. **
  18467. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  18468. ** routine will always fail.
  18469. **
  18470. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  18471. ** library function localtime_r() is used to assist in the calculation of
  18472. ** local time.
  18473. */
  18474. static int osLocaltime(time_t *t, struct tm *pTm){
  18475. int rc;
  18476. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  18477. struct tm *pX;
  18478. #if SQLITE_THREADSAFE>0
  18479. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  18480. #endif
  18481. sqlite3_mutex_enter(mutex);
  18482. pX = localtime(t);
  18483. #ifndef SQLITE_UNTESTABLE
  18484. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  18485. #endif
  18486. if( pX ) *pTm = *pX;
  18487. sqlite3_mutex_leave(mutex);
  18488. rc = pX==0;
  18489. #else
  18490. #ifndef SQLITE_UNTESTABLE
  18491. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  18492. #endif
  18493. #if HAVE_LOCALTIME_R
  18494. rc = localtime_r(t, pTm)==0;
  18495. #else
  18496. rc = localtime_s(pTm, t);
  18497. #endif /* HAVE_LOCALTIME_R */
  18498. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  18499. return rc;
  18500. }
  18501. #endif /* SQLITE_OMIT_LOCALTIME */
  18502. #ifndef SQLITE_OMIT_LOCALTIME
  18503. /*
  18504. ** Compute the difference (in milliseconds) between localtime and UTC
  18505. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  18506. ** return this value and set *pRc to SQLITE_OK.
  18507. **
  18508. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  18509. ** is undefined in this case.
  18510. */
  18511. static sqlite3_int64 localtimeOffset(
  18512. DateTime *p, /* Date at which to calculate offset */
  18513. sqlite3_context *pCtx, /* Write error here if one occurs */
  18514. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  18515. ){
  18516. DateTime x, y;
  18517. time_t t;
  18518. struct tm sLocal;
  18519. /* Initialize the contents of sLocal to avoid a compiler warning. */
  18520. memset(&sLocal, 0, sizeof(sLocal));
  18521. x = *p;
  18522. computeYMD_HMS(&x);
  18523. if( x.Y<1971 || x.Y>=2038 ){
  18524. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  18525. ** works for years between 1970 and 2037. For dates outside this range,
  18526. ** SQLite attempts to map the year into an equivalent year within this
  18527. ** range, do the calculation, then map the year back.
  18528. */
  18529. x.Y = 2000;
  18530. x.M = 1;
  18531. x.D = 1;
  18532. x.h = 0;
  18533. x.m = 0;
  18534. x.s = 0.0;
  18535. } else {
  18536. int s = (int)(x.s + 0.5);
  18537. x.s = s;
  18538. }
  18539. x.tz = 0;
  18540. x.validJD = 0;
  18541. computeJD(&x);
  18542. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  18543. if( osLocaltime(&t, &sLocal) ){
  18544. sqlite3_result_error(pCtx, "local time unavailable", -1);
  18545. *pRc = SQLITE_ERROR;
  18546. return 0;
  18547. }
  18548. y.Y = sLocal.tm_year + 1900;
  18549. y.M = sLocal.tm_mon + 1;
  18550. y.D = sLocal.tm_mday;
  18551. y.h = sLocal.tm_hour;
  18552. y.m = sLocal.tm_min;
  18553. y.s = sLocal.tm_sec;
  18554. y.validYMD = 1;
  18555. y.validHMS = 1;
  18556. y.validJD = 0;
  18557. y.rawS = 0;
  18558. y.validTZ = 0;
  18559. y.isError = 0;
  18560. computeJD(&y);
  18561. *pRc = SQLITE_OK;
  18562. return y.iJD - x.iJD;
  18563. }
  18564. #endif /* SQLITE_OMIT_LOCALTIME */
  18565. /*
  18566. ** The following table defines various date transformations of the form
  18567. **
  18568. ** 'NNN days'
  18569. **
  18570. ** Where NNN is an arbitrary floating-point number and "days" can be one
  18571. ** of several units of time.
  18572. */
  18573. static const struct {
  18574. u8 eType; /* Transformation type code */
  18575. u8 nName; /* Length of th name */
  18576. char *zName; /* Name of the transformation */
  18577. double rLimit; /* Maximum NNN value for this transform */
  18578. double rXform; /* Constant used for this transform */
  18579. } aXformType[] = {
  18580. { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
  18581. { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
  18582. { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
  18583. { 0, 3, "day", 5373485.0, 86400000.0 },
  18584. { 1, 5, "month", 176546.0, 30.0*86400000.0 },
  18585. { 2, 4, "year", 14713.0, 365.0*86400000.0 },
  18586. };
  18587. /*
  18588. ** Process a modifier to a date-time stamp. The modifiers are
  18589. ** as follows:
  18590. **
  18591. ** NNN days
  18592. ** NNN hours
  18593. ** NNN minutes
  18594. ** NNN.NNNN seconds
  18595. ** NNN months
  18596. ** NNN years
  18597. ** start of month
  18598. ** start of year
  18599. ** start of week
  18600. ** start of day
  18601. ** weekday N
  18602. ** unixepoch
  18603. ** localtime
  18604. ** utc
  18605. **
  18606. ** Return 0 on success and 1 if there is any kind of error. If the error
  18607. ** is in a system call (i.e. localtime()), then an error message is written
  18608. ** to context pCtx. If the error is an unrecognized modifier, no error is
  18609. ** written to pCtx.
  18610. */
  18611. static int parseModifier(
  18612. sqlite3_context *pCtx, /* Function context */
  18613. const char *z, /* The text of the modifier */
  18614. int n, /* Length of zMod in bytes */
  18615. DateTime *p /* The date/time value to be modified */
  18616. ){
  18617. int rc = 1;
  18618. double r;
  18619. switch(sqlite3UpperToLower[(u8)z[0]] ){
  18620. #ifndef SQLITE_OMIT_LOCALTIME
  18621. case 'l': {
  18622. /* localtime
  18623. **
  18624. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  18625. ** show local time.
  18626. */
  18627. if( sqlite3_stricmp(z, "localtime")==0 ){
  18628. computeJD(p);
  18629. p->iJD += localtimeOffset(p, pCtx, &rc);
  18630. clearYMD_HMS_TZ(p);
  18631. }
  18632. break;
  18633. }
  18634. #endif
  18635. case 'u': {
  18636. /*
  18637. ** unixepoch
  18638. **
  18639. ** Treat the current value of p->s as the number of
  18640. ** seconds since 1970. Convert to a real julian day number.
  18641. */
  18642. if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
  18643. r = p->s*1000.0 + 210866760000000.0;
  18644. if( r>=0.0 && r<464269060800000.0 ){
  18645. clearYMD_HMS_TZ(p);
  18646. p->iJD = (sqlite3_int64)r;
  18647. p->validJD = 1;
  18648. p->rawS = 0;
  18649. rc = 0;
  18650. }
  18651. }
  18652. #ifndef SQLITE_OMIT_LOCALTIME
  18653. else if( sqlite3_stricmp(z, "utc")==0 ){
  18654. if( p->tzSet==0 ){
  18655. sqlite3_int64 c1;
  18656. computeJD(p);
  18657. c1 = localtimeOffset(p, pCtx, &rc);
  18658. if( rc==SQLITE_OK ){
  18659. p->iJD -= c1;
  18660. clearYMD_HMS_TZ(p);
  18661. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  18662. }
  18663. p->tzSet = 1;
  18664. }else{
  18665. rc = SQLITE_OK;
  18666. }
  18667. }
  18668. #endif
  18669. break;
  18670. }
  18671. case 'w': {
  18672. /*
  18673. ** weekday N
  18674. **
  18675. ** Move the date to the same time on the next occurrence of
  18676. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  18677. ** date is already on the appropriate weekday, this is a no-op.
  18678. */
  18679. if( sqlite3_strnicmp(z, "weekday ", 8)==0
  18680. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  18681. && (n=(int)r)==r && n>=0 && r<7 ){
  18682. sqlite3_int64 Z;
  18683. computeYMD_HMS(p);
  18684. p->validTZ = 0;
  18685. p->validJD = 0;
  18686. computeJD(p);
  18687. Z = ((p->iJD + 129600000)/86400000) % 7;
  18688. if( Z>n ) Z -= 7;
  18689. p->iJD += (n - Z)*86400000;
  18690. clearYMD_HMS_TZ(p);
  18691. rc = 0;
  18692. }
  18693. break;
  18694. }
  18695. case 's': {
  18696. /*
  18697. ** start of TTTTT
  18698. **
  18699. ** Move the date backwards to the beginning of the current day,
  18700. ** or month or year.
  18701. */
  18702. if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
  18703. if( !p->validJD && !p->validYMD && !p->validHMS ) break;
  18704. z += 9;
  18705. computeYMD(p);
  18706. p->validHMS = 1;
  18707. p->h = p->m = 0;
  18708. p->s = 0.0;
  18709. p->rawS = 0;
  18710. p->validTZ = 0;
  18711. p->validJD = 0;
  18712. if( sqlite3_stricmp(z,"month")==0 ){
  18713. p->D = 1;
  18714. rc = 0;
  18715. }else if( sqlite3_stricmp(z,"year")==0 ){
  18716. p->M = 1;
  18717. p->D = 1;
  18718. rc = 0;
  18719. }else if( sqlite3_stricmp(z,"day")==0 ){
  18720. rc = 0;
  18721. }
  18722. break;
  18723. }
  18724. case '+':
  18725. case '-':
  18726. case '0':
  18727. case '1':
  18728. case '2':
  18729. case '3':
  18730. case '4':
  18731. case '5':
  18732. case '6':
  18733. case '7':
  18734. case '8':
  18735. case '9': {
  18736. double rRounder;
  18737. int i;
  18738. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  18739. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  18740. rc = 1;
  18741. break;
  18742. }
  18743. if( z[n]==':' ){
  18744. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  18745. ** specified number of hours, minutes, seconds, and fractional seconds
  18746. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  18747. ** omitted.
  18748. */
  18749. const char *z2 = z;
  18750. DateTime tx;
  18751. sqlite3_int64 day;
  18752. if( !sqlite3Isdigit(*z2) ) z2++;
  18753. memset(&tx, 0, sizeof(tx));
  18754. if( parseHhMmSs(z2, &tx) ) break;
  18755. computeJD(&tx);
  18756. tx.iJD -= 43200000;
  18757. day = tx.iJD/86400000;
  18758. tx.iJD -= day*86400000;
  18759. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  18760. computeJD(p);
  18761. clearYMD_HMS_TZ(p);
  18762. p->iJD += tx.iJD;
  18763. rc = 0;
  18764. break;
  18765. }
  18766. /* If control reaches this point, it means the transformation is
  18767. ** one of the forms like "+NNN days". */
  18768. z += n;
  18769. while( sqlite3Isspace(*z) ) z++;
  18770. n = sqlite3Strlen30(z);
  18771. if( n>10 || n<3 ) break;
  18772. if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
  18773. computeJD(p);
  18774. rc = 1;
  18775. rRounder = r<0 ? -0.5 : +0.5;
  18776. for(i=0; i<ArraySize(aXformType); i++){
  18777. if( aXformType[i].nName==n
  18778. && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
  18779. && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
  18780. ){
  18781. switch( aXformType[i].eType ){
  18782. case 1: { /* Special processing to add months */
  18783. int x;
  18784. computeYMD_HMS(p);
  18785. p->M += (int)r;
  18786. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  18787. p->Y += x;
  18788. p->M -= x*12;
  18789. p->validJD = 0;
  18790. r -= (int)r;
  18791. break;
  18792. }
  18793. case 2: { /* Special processing to add years */
  18794. int y = (int)r;
  18795. computeYMD_HMS(p);
  18796. p->Y += y;
  18797. p->validJD = 0;
  18798. r -= (int)r;
  18799. break;
  18800. }
  18801. }
  18802. computeJD(p);
  18803. p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
  18804. rc = 0;
  18805. break;
  18806. }
  18807. }
  18808. clearYMD_HMS_TZ(p);
  18809. break;
  18810. }
  18811. default: {
  18812. break;
  18813. }
  18814. }
  18815. return rc;
  18816. }
  18817. /*
  18818. ** Process time function arguments. argv[0] is a date-time stamp.
  18819. ** argv[1] and following are modifiers. Parse them all and write
  18820. ** the resulting time into the DateTime structure p. Return 0
  18821. ** on success and 1 if there are any errors.
  18822. **
  18823. ** If there are zero parameters (if even argv[0] is undefined)
  18824. ** then assume a default value of "now" for argv[0].
  18825. */
  18826. static int isDate(
  18827. sqlite3_context *context,
  18828. int argc,
  18829. sqlite3_value **argv,
  18830. DateTime *p
  18831. ){
  18832. int i, n;
  18833. const unsigned char *z;
  18834. int eType;
  18835. memset(p, 0, sizeof(*p));
  18836. if( argc==0 ){
  18837. return setDateTimeToCurrent(context, p);
  18838. }
  18839. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  18840. || eType==SQLITE_INTEGER ){
  18841. setRawDateNumber(p, sqlite3_value_double(argv[0]));
  18842. }else{
  18843. z = sqlite3_value_text(argv[0]);
  18844. if( !z || parseDateOrTime(context, (char*)z, p) ){
  18845. return 1;
  18846. }
  18847. }
  18848. for(i=1; i<argc; i++){
  18849. z = sqlite3_value_text(argv[i]);
  18850. n = sqlite3_value_bytes(argv[i]);
  18851. if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
  18852. }
  18853. computeJD(p);
  18854. if( p->isError || !validJulianDay(p->iJD) ) return 1;
  18855. return 0;
  18856. }
  18857. /*
  18858. ** The following routines implement the various date and time functions
  18859. ** of SQLite.
  18860. */
  18861. /*
  18862. ** julianday( TIMESTRING, MOD, MOD, ...)
  18863. **
  18864. ** Return the julian day number of the date specified in the arguments
  18865. */
  18866. static void juliandayFunc(
  18867. sqlite3_context *context,
  18868. int argc,
  18869. sqlite3_value **argv
  18870. ){
  18871. DateTime x;
  18872. if( isDate(context, argc, argv, &x)==0 ){
  18873. computeJD(&x);
  18874. sqlite3_result_double(context, x.iJD/86400000.0);
  18875. }
  18876. }
  18877. /*
  18878. ** datetime( TIMESTRING, MOD, MOD, ...)
  18879. **
  18880. ** Return YYYY-MM-DD HH:MM:SS
  18881. */
  18882. static void datetimeFunc(
  18883. sqlite3_context *context,
  18884. int argc,
  18885. sqlite3_value **argv
  18886. ){
  18887. DateTime x;
  18888. if( isDate(context, argc, argv, &x)==0 ){
  18889. char zBuf[100];
  18890. computeYMD_HMS(&x);
  18891. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  18892. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  18893. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  18894. }
  18895. }
  18896. /*
  18897. ** time( TIMESTRING, MOD, MOD, ...)
  18898. **
  18899. ** Return HH:MM:SS
  18900. */
  18901. static void timeFunc(
  18902. sqlite3_context *context,
  18903. int argc,
  18904. sqlite3_value **argv
  18905. ){
  18906. DateTime x;
  18907. if( isDate(context, argc, argv, &x)==0 ){
  18908. char zBuf[100];
  18909. computeHMS(&x);
  18910. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  18911. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  18912. }
  18913. }
  18914. /*
  18915. ** date( TIMESTRING, MOD, MOD, ...)
  18916. **
  18917. ** Return YYYY-MM-DD
  18918. */
  18919. static void dateFunc(
  18920. sqlite3_context *context,
  18921. int argc,
  18922. sqlite3_value **argv
  18923. ){
  18924. DateTime x;
  18925. if( isDate(context, argc, argv, &x)==0 ){
  18926. char zBuf[100];
  18927. computeYMD(&x);
  18928. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  18929. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  18930. }
  18931. }
  18932. /*
  18933. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  18934. **
  18935. ** Return a string described by FORMAT. Conversions as follows:
  18936. **
  18937. ** %d day of month
  18938. ** %f ** fractional seconds SS.SSS
  18939. ** %H hour 00-24
  18940. ** %j day of year 000-366
  18941. ** %J ** julian day number
  18942. ** %m month 01-12
  18943. ** %M minute 00-59
  18944. ** %s seconds since 1970-01-01
  18945. ** %S seconds 00-59
  18946. ** %w day of week 0-6 sunday==0
  18947. ** %W week of year 00-53
  18948. ** %Y year 0000-9999
  18949. ** %% %
  18950. */
  18951. static void strftimeFunc(
  18952. sqlite3_context *context,
  18953. int argc,
  18954. sqlite3_value **argv
  18955. ){
  18956. DateTime x;
  18957. u64 n;
  18958. size_t i,j;
  18959. char *z;
  18960. sqlite3 *db;
  18961. const char *zFmt;
  18962. char zBuf[100];
  18963. if( argc==0 ) return;
  18964. zFmt = (const char*)sqlite3_value_text(argv[0]);
  18965. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  18966. db = sqlite3_context_db_handle(context);
  18967. for(i=0, n=1; zFmt[i]; i++, n++){
  18968. if( zFmt[i]=='%' ){
  18969. switch( zFmt[i+1] ){
  18970. case 'd':
  18971. case 'H':
  18972. case 'm':
  18973. case 'M':
  18974. case 'S':
  18975. case 'W':
  18976. n++;
  18977. /* fall thru */
  18978. case 'w':
  18979. case '%':
  18980. break;
  18981. case 'f':
  18982. n += 8;
  18983. break;
  18984. case 'j':
  18985. n += 3;
  18986. break;
  18987. case 'Y':
  18988. n += 8;
  18989. break;
  18990. case 's':
  18991. case 'J':
  18992. n += 50;
  18993. break;
  18994. default:
  18995. return; /* ERROR. return a NULL */
  18996. }
  18997. i++;
  18998. }
  18999. }
  19000. testcase( n==sizeof(zBuf)-1 );
  19001. testcase( n==sizeof(zBuf) );
  19002. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  19003. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  19004. if( n<sizeof(zBuf) ){
  19005. z = zBuf;
  19006. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  19007. sqlite3_result_error_toobig(context);
  19008. return;
  19009. }else{
  19010. z = sqlite3DbMallocRawNN(db, (int)n);
  19011. if( z==0 ){
  19012. sqlite3_result_error_nomem(context);
  19013. return;
  19014. }
  19015. }
  19016. computeJD(&x);
  19017. computeYMD_HMS(&x);
  19018. for(i=j=0; zFmt[i]; i++){
  19019. if( zFmt[i]!='%' ){
  19020. z[j++] = zFmt[i];
  19021. }else{
  19022. i++;
  19023. switch( zFmt[i] ){
  19024. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  19025. case 'f': {
  19026. double s = x.s;
  19027. if( s>59.999 ) s = 59.999;
  19028. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  19029. j += sqlite3Strlen30(&z[j]);
  19030. break;
  19031. }
  19032. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  19033. case 'W': /* Fall thru */
  19034. case 'j': {
  19035. int nDay; /* Number of days since 1st day of year */
  19036. DateTime y = x;
  19037. y.validJD = 0;
  19038. y.M = 1;
  19039. y.D = 1;
  19040. computeJD(&y);
  19041. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  19042. if( zFmt[i]=='W' ){
  19043. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  19044. wd = (int)(((x.iJD+43200000)/86400000)%7);
  19045. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  19046. j += 2;
  19047. }else{
  19048. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  19049. j += 3;
  19050. }
  19051. break;
  19052. }
  19053. case 'J': {
  19054. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  19055. j+=sqlite3Strlen30(&z[j]);
  19056. break;
  19057. }
  19058. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  19059. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  19060. case 's': {
  19061. sqlite3_snprintf(30,&z[j],"%lld",
  19062. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  19063. j += sqlite3Strlen30(&z[j]);
  19064. break;
  19065. }
  19066. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  19067. case 'w': {
  19068. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  19069. break;
  19070. }
  19071. case 'Y': {
  19072. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  19073. break;
  19074. }
  19075. default: z[j++] = '%'; break;
  19076. }
  19077. }
  19078. }
  19079. z[j] = 0;
  19080. sqlite3_result_text(context, z, -1,
  19081. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  19082. }
  19083. /*
  19084. ** current_time()
  19085. **
  19086. ** This function returns the same value as time('now').
  19087. */
  19088. static void ctimeFunc(
  19089. sqlite3_context *context,
  19090. int NotUsed,
  19091. sqlite3_value **NotUsed2
  19092. ){
  19093. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19094. timeFunc(context, 0, 0);
  19095. }
  19096. /*
  19097. ** current_date()
  19098. **
  19099. ** This function returns the same value as date('now').
  19100. */
  19101. static void cdateFunc(
  19102. sqlite3_context *context,
  19103. int NotUsed,
  19104. sqlite3_value **NotUsed2
  19105. ){
  19106. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19107. dateFunc(context, 0, 0);
  19108. }
  19109. /*
  19110. ** current_timestamp()
  19111. **
  19112. ** This function returns the same value as datetime('now').
  19113. */
  19114. static void ctimestampFunc(
  19115. sqlite3_context *context,
  19116. int NotUsed,
  19117. sqlite3_value **NotUsed2
  19118. ){
  19119. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19120. datetimeFunc(context, 0, 0);
  19121. }
  19122. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  19123. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  19124. /*
  19125. ** If the library is compiled to omit the full-scale date and time
  19126. ** handling (to get a smaller binary), the following minimal version
  19127. ** of the functions current_time(), current_date() and current_timestamp()
  19128. ** are included instead. This is to support column declarations that
  19129. ** include "DEFAULT CURRENT_TIME" etc.
  19130. **
  19131. ** This function uses the C-library functions time(), gmtime()
  19132. ** and strftime(). The format string to pass to strftime() is supplied
  19133. ** as the user-data for the function.
  19134. */
  19135. static void currentTimeFunc(
  19136. sqlite3_context *context,
  19137. int argc,
  19138. sqlite3_value **argv
  19139. ){
  19140. time_t t;
  19141. char *zFormat = (char *)sqlite3_user_data(context);
  19142. sqlite3_int64 iT;
  19143. struct tm *pTm;
  19144. struct tm sNow;
  19145. char zBuf[20];
  19146. UNUSED_PARAMETER(argc);
  19147. UNUSED_PARAMETER(argv);
  19148. iT = sqlite3StmtCurrentTime(context);
  19149. if( iT<=0 ) return;
  19150. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  19151. #if HAVE_GMTIME_R
  19152. pTm = gmtime_r(&t, &sNow);
  19153. #else
  19154. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  19155. pTm = gmtime(&t);
  19156. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  19157. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  19158. #endif
  19159. if( pTm ){
  19160. strftime(zBuf, 20, zFormat, &sNow);
  19161. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  19162. }
  19163. }
  19164. #endif
  19165. /*
  19166. ** This function registered all of the above C functions as SQL
  19167. ** functions. This should be the only routine in this file with
  19168. ** external linkage.
  19169. */
  19170. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  19171. static FuncDef aDateTimeFuncs[] = {
  19172. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  19173. DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  19174. DFUNCTION(date, -1, 0, 0, dateFunc ),
  19175. DFUNCTION(time, -1, 0, 0, timeFunc ),
  19176. DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  19177. DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  19178. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  19179. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  19180. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  19181. #else
  19182. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  19183. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  19184. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  19185. #endif
  19186. };
  19187. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  19188. }
  19189. /************** End of date.c ************************************************/
  19190. /************** Begin file os.c **********************************************/
  19191. /*
  19192. ** 2005 November 29
  19193. **
  19194. ** The author disclaims copyright to this source code. In place of
  19195. ** a legal notice, here is a blessing:
  19196. **
  19197. ** May you do good and not evil.
  19198. ** May you find forgiveness for yourself and forgive others.
  19199. ** May you share freely, never taking more than you give.
  19200. **
  19201. ******************************************************************************
  19202. **
  19203. ** This file contains OS interface code that is common to all
  19204. ** architectures.
  19205. */
  19206. /* #include "sqliteInt.h" */
  19207. /*
  19208. ** If we compile with the SQLITE_TEST macro set, then the following block
  19209. ** of code will give us the ability to simulate a disk I/O error. This
  19210. ** is used for testing the I/O recovery logic.
  19211. */
  19212. #if defined(SQLITE_TEST)
  19213. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  19214. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  19215. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  19216. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  19217. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  19218. SQLITE_API int sqlite3_diskfull_pending = 0;
  19219. SQLITE_API int sqlite3_diskfull = 0;
  19220. #endif /* defined(SQLITE_TEST) */
  19221. /*
  19222. ** When testing, also keep a count of the number of open files.
  19223. */
  19224. #if defined(SQLITE_TEST)
  19225. SQLITE_API int sqlite3_open_file_count = 0;
  19226. #endif /* defined(SQLITE_TEST) */
  19227. /*
  19228. ** The default SQLite sqlite3_vfs implementations do not allocate
  19229. ** memory (actually, os_unix.c allocates a small amount of memory
  19230. ** from within OsOpen()), but some third-party implementations may.
  19231. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  19232. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  19233. **
  19234. ** The following functions are instrumented for malloc() failure
  19235. ** testing:
  19236. **
  19237. ** sqlite3OsRead()
  19238. ** sqlite3OsWrite()
  19239. ** sqlite3OsSync()
  19240. ** sqlite3OsFileSize()
  19241. ** sqlite3OsLock()
  19242. ** sqlite3OsCheckReservedLock()
  19243. ** sqlite3OsFileControl()
  19244. ** sqlite3OsShmMap()
  19245. ** sqlite3OsOpen()
  19246. ** sqlite3OsDelete()
  19247. ** sqlite3OsAccess()
  19248. ** sqlite3OsFullPathname()
  19249. **
  19250. */
  19251. #if defined(SQLITE_TEST)
  19252. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  19253. #define DO_OS_MALLOC_TEST(x) \
  19254. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  19255. void *pTstAlloc = sqlite3Malloc(10); \
  19256. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  19257. sqlite3_free(pTstAlloc); \
  19258. }
  19259. #else
  19260. #define DO_OS_MALLOC_TEST(x)
  19261. #endif
  19262. /*
  19263. ** The following routines are convenience wrappers around methods
  19264. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  19265. ** of this would be completely automatic if SQLite were coded using
  19266. ** C++ instead of plain old C.
  19267. */
  19268. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
  19269. if( pId->pMethods ){
  19270. pId->pMethods->xClose(pId);
  19271. pId->pMethods = 0;
  19272. }
  19273. }
  19274. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  19275. DO_OS_MALLOC_TEST(id);
  19276. return id->pMethods->xRead(id, pBuf, amt, offset);
  19277. }
  19278. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  19279. DO_OS_MALLOC_TEST(id);
  19280. return id->pMethods->xWrite(id, pBuf, amt, offset);
  19281. }
  19282. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  19283. return id->pMethods->xTruncate(id, size);
  19284. }
  19285. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  19286. DO_OS_MALLOC_TEST(id);
  19287. return id->pMethods->xSync(id, flags);
  19288. }
  19289. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  19290. DO_OS_MALLOC_TEST(id);
  19291. return id->pMethods->xFileSize(id, pSize);
  19292. }
  19293. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  19294. DO_OS_MALLOC_TEST(id);
  19295. return id->pMethods->xLock(id, lockType);
  19296. }
  19297. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  19298. return id->pMethods->xUnlock(id, lockType);
  19299. }
  19300. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  19301. DO_OS_MALLOC_TEST(id);
  19302. return id->pMethods->xCheckReservedLock(id, pResOut);
  19303. }
  19304. /*
  19305. ** Use sqlite3OsFileControl() when we are doing something that might fail
  19306. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  19307. ** when simply tossing information over the wall to the VFS and we do not
  19308. ** really care if the VFS receives and understands the information since it
  19309. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  19310. ** routine has no return value since the return value would be meaningless.
  19311. */
  19312. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  19313. #ifdef SQLITE_TEST
  19314. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  19315. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  19316. ** is using a regular VFS, it is called after the corresponding
  19317. ** transaction has been committed. Injecting a fault at this point
  19318. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  19319. ** but the transaction is committed anyway.
  19320. **
  19321. ** The core must call OsFileControl() though, not OsFileControlHint(),
  19322. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  19323. ** means the commit really has failed and an error should be returned
  19324. ** to the user. */
  19325. DO_OS_MALLOC_TEST(id);
  19326. }
  19327. #endif
  19328. return id->pMethods->xFileControl(id, op, pArg);
  19329. }
  19330. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  19331. (void)id->pMethods->xFileControl(id, op, pArg);
  19332. }
  19333. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  19334. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  19335. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  19336. }
  19337. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  19338. return id->pMethods->xDeviceCharacteristics(id);
  19339. }
  19340. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  19341. return id->pMethods->xShmLock(id, offset, n, flags);
  19342. }
  19343. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  19344. id->pMethods->xShmBarrier(id);
  19345. }
  19346. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  19347. return id->pMethods->xShmUnmap(id, deleteFlag);
  19348. }
  19349. SQLITE_PRIVATE int sqlite3OsShmMap(
  19350. sqlite3_file *id, /* Database file handle */
  19351. int iPage,
  19352. int pgsz,
  19353. int bExtend, /* True to extend file if necessary */
  19354. void volatile **pp /* OUT: Pointer to mapping */
  19355. ){
  19356. DO_OS_MALLOC_TEST(id);
  19357. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  19358. }
  19359. #if SQLITE_MAX_MMAP_SIZE>0
  19360. /* The real implementation of xFetch and xUnfetch */
  19361. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  19362. DO_OS_MALLOC_TEST(id);
  19363. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  19364. }
  19365. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  19366. return id->pMethods->xUnfetch(id, iOff, p);
  19367. }
  19368. #else
  19369. /* No-op stubs to use when memory-mapped I/O is disabled */
  19370. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  19371. *pp = 0;
  19372. return SQLITE_OK;
  19373. }
  19374. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  19375. return SQLITE_OK;
  19376. }
  19377. #endif
  19378. /*
  19379. ** The next group of routines are convenience wrappers around the
  19380. ** VFS methods.
  19381. */
  19382. SQLITE_PRIVATE int sqlite3OsOpen(
  19383. sqlite3_vfs *pVfs,
  19384. const char *zPath,
  19385. sqlite3_file *pFile,
  19386. int flags,
  19387. int *pFlagsOut
  19388. ){
  19389. int rc;
  19390. DO_OS_MALLOC_TEST(0);
  19391. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  19392. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  19393. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  19394. ** reaching the VFS. */
  19395. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  19396. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  19397. return rc;
  19398. }
  19399. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  19400. DO_OS_MALLOC_TEST(0);
  19401. assert( dirSync==0 || dirSync==1 );
  19402. return pVfs->xDelete(pVfs, zPath, dirSync);
  19403. }
  19404. SQLITE_PRIVATE int sqlite3OsAccess(
  19405. sqlite3_vfs *pVfs,
  19406. const char *zPath,
  19407. int flags,
  19408. int *pResOut
  19409. ){
  19410. DO_OS_MALLOC_TEST(0);
  19411. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  19412. }
  19413. SQLITE_PRIVATE int sqlite3OsFullPathname(
  19414. sqlite3_vfs *pVfs,
  19415. const char *zPath,
  19416. int nPathOut,
  19417. char *zPathOut
  19418. ){
  19419. DO_OS_MALLOC_TEST(0);
  19420. zPathOut[0] = 0;
  19421. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  19422. }
  19423. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  19424. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  19425. return pVfs->xDlOpen(pVfs, zPath);
  19426. }
  19427. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  19428. pVfs->xDlError(pVfs, nByte, zBufOut);
  19429. }
  19430. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  19431. return pVfs->xDlSym(pVfs, pHdle, zSym);
  19432. }
  19433. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  19434. pVfs->xDlClose(pVfs, pHandle);
  19435. }
  19436. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  19437. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  19438. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  19439. }
  19440. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  19441. return pVfs->xSleep(pVfs, nMicro);
  19442. }
  19443. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  19444. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  19445. }
  19446. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  19447. int rc;
  19448. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  19449. ** method to get the current date and time if that method is available
  19450. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  19451. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  19452. ** unavailable.
  19453. */
  19454. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  19455. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  19456. }else{
  19457. double r;
  19458. rc = pVfs->xCurrentTime(pVfs, &r);
  19459. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  19460. }
  19461. return rc;
  19462. }
  19463. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  19464. sqlite3_vfs *pVfs,
  19465. const char *zFile,
  19466. sqlite3_file **ppFile,
  19467. int flags,
  19468. int *pOutFlags
  19469. ){
  19470. int rc;
  19471. sqlite3_file *pFile;
  19472. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  19473. if( pFile ){
  19474. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  19475. if( rc!=SQLITE_OK ){
  19476. sqlite3_free(pFile);
  19477. }else{
  19478. *ppFile = pFile;
  19479. }
  19480. }else{
  19481. rc = SQLITE_NOMEM_BKPT;
  19482. }
  19483. return rc;
  19484. }
  19485. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
  19486. assert( pFile );
  19487. sqlite3OsClose(pFile);
  19488. sqlite3_free(pFile);
  19489. }
  19490. /*
  19491. ** This function is a wrapper around the OS specific implementation of
  19492. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  19493. ** ability to simulate a malloc failure, so that the handling of an
  19494. ** error in sqlite3_os_init() by the upper layers can be tested.
  19495. */
  19496. SQLITE_PRIVATE int sqlite3OsInit(void){
  19497. void *p = sqlite3_malloc(10);
  19498. if( p==0 ) return SQLITE_NOMEM_BKPT;
  19499. sqlite3_free(p);
  19500. return sqlite3_os_init();
  19501. }
  19502. /*
  19503. ** The list of all registered VFS implementations.
  19504. */
  19505. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  19506. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  19507. /*
  19508. ** Locate a VFS by name. If no name is given, simply return the
  19509. ** first VFS on the list.
  19510. */
  19511. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  19512. sqlite3_vfs *pVfs = 0;
  19513. #if SQLITE_THREADSAFE
  19514. sqlite3_mutex *mutex;
  19515. #endif
  19516. #ifndef SQLITE_OMIT_AUTOINIT
  19517. int rc = sqlite3_initialize();
  19518. if( rc ) return 0;
  19519. #endif
  19520. #if SQLITE_THREADSAFE
  19521. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  19522. #endif
  19523. sqlite3_mutex_enter(mutex);
  19524. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  19525. if( zVfs==0 ) break;
  19526. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  19527. }
  19528. sqlite3_mutex_leave(mutex);
  19529. return pVfs;
  19530. }
  19531. /*
  19532. ** Unlink a VFS from the linked list
  19533. */
  19534. static void vfsUnlink(sqlite3_vfs *pVfs){
  19535. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  19536. if( pVfs==0 ){
  19537. /* No-op */
  19538. }else if( vfsList==pVfs ){
  19539. vfsList = pVfs->pNext;
  19540. }else if( vfsList ){
  19541. sqlite3_vfs *p = vfsList;
  19542. while( p->pNext && p->pNext!=pVfs ){
  19543. p = p->pNext;
  19544. }
  19545. if( p->pNext==pVfs ){
  19546. p->pNext = pVfs->pNext;
  19547. }
  19548. }
  19549. }
  19550. /*
  19551. ** Register a VFS with the system. It is harmless to register the same
  19552. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  19553. ** true.
  19554. */
  19555. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  19556. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  19557. #ifndef SQLITE_OMIT_AUTOINIT
  19558. int rc = sqlite3_initialize();
  19559. if( rc ) return rc;
  19560. #endif
  19561. #ifdef SQLITE_ENABLE_API_ARMOR
  19562. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  19563. #endif
  19564. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  19565. sqlite3_mutex_enter(mutex);
  19566. vfsUnlink(pVfs);
  19567. if( makeDflt || vfsList==0 ){
  19568. pVfs->pNext = vfsList;
  19569. vfsList = pVfs;
  19570. }else{
  19571. pVfs->pNext = vfsList->pNext;
  19572. vfsList->pNext = pVfs;
  19573. }
  19574. assert(vfsList);
  19575. sqlite3_mutex_leave(mutex);
  19576. return SQLITE_OK;
  19577. }
  19578. /*
  19579. ** Unregister a VFS so that it is no longer accessible.
  19580. */
  19581. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  19582. #if SQLITE_THREADSAFE
  19583. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  19584. #endif
  19585. sqlite3_mutex_enter(mutex);
  19586. vfsUnlink(pVfs);
  19587. sqlite3_mutex_leave(mutex);
  19588. return SQLITE_OK;
  19589. }
  19590. /************** End of os.c **************************************************/
  19591. /************** Begin file fault.c *******************************************/
  19592. /*
  19593. ** 2008 Jan 22
  19594. **
  19595. ** The author disclaims copyright to this source code. In place of
  19596. ** a legal notice, here is a blessing:
  19597. **
  19598. ** May you do good and not evil.
  19599. ** May you find forgiveness for yourself and forgive others.
  19600. ** May you share freely, never taking more than you give.
  19601. **
  19602. *************************************************************************
  19603. **
  19604. ** This file contains code to support the concept of "benign"
  19605. ** malloc failures (when the xMalloc() or xRealloc() method of the
  19606. ** sqlite3_mem_methods structure fails to allocate a block of memory
  19607. ** and returns 0).
  19608. **
  19609. ** Most malloc failures are non-benign. After they occur, SQLite
  19610. ** abandons the current operation and returns an error code (usually
  19611. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  19612. ** fatal. For example, if a malloc fails while resizing a hash table, this
  19613. ** is completely recoverable simply by not carrying out the resize. The
  19614. ** hash table will continue to function normally. So a malloc failure
  19615. ** during a hash table resize is a benign fault.
  19616. */
  19617. /* #include "sqliteInt.h" */
  19618. #ifndef SQLITE_UNTESTABLE
  19619. /*
  19620. ** Global variables.
  19621. */
  19622. typedef struct BenignMallocHooks BenignMallocHooks;
  19623. static SQLITE_WSD struct BenignMallocHooks {
  19624. void (*xBenignBegin)(void);
  19625. void (*xBenignEnd)(void);
  19626. } sqlite3Hooks = { 0, 0 };
  19627. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  19628. ** structure. If writable static data is unsupported on the target,
  19629. ** we have to locate the state vector at run-time. In the more common
  19630. ** case where writable static data is supported, wsdHooks can refer directly
  19631. ** to the "sqlite3Hooks" state vector declared above.
  19632. */
  19633. #ifdef SQLITE_OMIT_WSD
  19634. # define wsdHooksInit \
  19635. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  19636. # define wsdHooks x[0]
  19637. #else
  19638. # define wsdHooksInit
  19639. # define wsdHooks sqlite3Hooks
  19640. #endif
  19641. /*
  19642. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  19643. ** sqlite3EndBenignMalloc() are called, respectively.
  19644. */
  19645. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  19646. void (*xBenignBegin)(void),
  19647. void (*xBenignEnd)(void)
  19648. ){
  19649. wsdHooksInit;
  19650. wsdHooks.xBenignBegin = xBenignBegin;
  19651. wsdHooks.xBenignEnd = xBenignEnd;
  19652. }
  19653. /*
  19654. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  19655. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  19656. ** indicates that subsequent malloc failures are non-benign.
  19657. */
  19658. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  19659. wsdHooksInit;
  19660. if( wsdHooks.xBenignBegin ){
  19661. wsdHooks.xBenignBegin();
  19662. }
  19663. }
  19664. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  19665. wsdHooksInit;
  19666. if( wsdHooks.xBenignEnd ){
  19667. wsdHooks.xBenignEnd();
  19668. }
  19669. }
  19670. #endif /* #ifndef SQLITE_UNTESTABLE */
  19671. /************** End of fault.c ***********************************************/
  19672. /************** Begin file mem0.c ********************************************/
  19673. /*
  19674. ** 2008 October 28
  19675. **
  19676. ** The author disclaims copyright to this source code. In place of
  19677. ** a legal notice, here is a blessing:
  19678. **
  19679. ** May you do good and not evil.
  19680. ** May you find forgiveness for yourself and forgive others.
  19681. ** May you share freely, never taking more than you give.
  19682. **
  19683. *************************************************************************
  19684. **
  19685. ** This file contains a no-op memory allocation drivers for use when
  19686. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  19687. ** here always fail. SQLite will not operate with these drivers. These
  19688. ** are merely placeholders. Real drivers must be substituted using
  19689. ** sqlite3_config() before SQLite will operate.
  19690. */
  19691. /* #include "sqliteInt.h" */
  19692. /*
  19693. ** This version of the memory allocator is the default. It is
  19694. ** used when no other memory allocator is specified using compile-time
  19695. ** macros.
  19696. */
  19697. #ifdef SQLITE_ZERO_MALLOC
  19698. /*
  19699. ** No-op versions of all memory allocation routines
  19700. */
  19701. static void *sqlite3MemMalloc(int nByte){ return 0; }
  19702. static void sqlite3MemFree(void *pPrior){ return; }
  19703. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  19704. static int sqlite3MemSize(void *pPrior){ return 0; }
  19705. static int sqlite3MemRoundup(int n){ return n; }
  19706. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  19707. static void sqlite3MemShutdown(void *NotUsed){ return; }
  19708. /*
  19709. ** This routine is the only routine in this file with external linkage.
  19710. **
  19711. ** Populate the low-level memory allocation function pointers in
  19712. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  19713. */
  19714. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  19715. static const sqlite3_mem_methods defaultMethods = {
  19716. sqlite3MemMalloc,
  19717. sqlite3MemFree,
  19718. sqlite3MemRealloc,
  19719. sqlite3MemSize,
  19720. sqlite3MemRoundup,
  19721. sqlite3MemInit,
  19722. sqlite3MemShutdown,
  19723. 0
  19724. };
  19725. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  19726. }
  19727. #endif /* SQLITE_ZERO_MALLOC */
  19728. /************** End of mem0.c ************************************************/
  19729. /************** Begin file mem1.c ********************************************/
  19730. /*
  19731. ** 2007 August 14
  19732. **
  19733. ** The author disclaims copyright to this source code. In place of
  19734. ** a legal notice, here is a blessing:
  19735. **
  19736. ** May you do good and not evil.
  19737. ** May you find forgiveness for yourself and forgive others.
  19738. ** May you share freely, never taking more than you give.
  19739. **
  19740. *************************************************************************
  19741. **
  19742. ** This file contains low-level memory allocation drivers for when
  19743. ** SQLite will use the standard C-library malloc/realloc/free interface
  19744. ** to obtain the memory it needs.
  19745. **
  19746. ** This file contains implementations of the low-level memory allocation
  19747. ** routines specified in the sqlite3_mem_methods object. The content of
  19748. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  19749. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  19750. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  19751. ** default configuration is to use memory allocation routines in this
  19752. ** file.
  19753. **
  19754. ** C-preprocessor macro summary:
  19755. **
  19756. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  19757. ** the malloc_usable_size() interface exists
  19758. ** on the target platform. Or, this symbol
  19759. ** can be set manually, if desired.
  19760. ** If an equivalent interface exists by
  19761. ** a different name, using a separate -D
  19762. ** option to rename it.
  19763. **
  19764. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  19765. ** memory allocator. Set this symbol to enable
  19766. ** building on older macs.
  19767. **
  19768. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  19769. ** _msize() on windows systems. This might
  19770. ** be necessary when compiling for Delphi,
  19771. ** for example.
  19772. */
  19773. /* #include "sqliteInt.h" */
  19774. /*
  19775. ** This version of the memory allocator is the default. It is
  19776. ** used when no other memory allocator is specified using compile-time
  19777. ** macros.
  19778. */
  19779. #ifdef SQLITE_SYSTEM_MALLOC
  19780. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  19781. /*
  19782. ** Use the zone allocator available on apple products unless the
  19783. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  19784. */
  19785. #include <sys/sysctl.h>
  19786. #include <malloc/malloc.h>
  19787. #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
  19788. #include <libkern/OSAtomic.h>
  19789. #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
  19790. static malloc_zone_t* _sqliteZone_;
  19791. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  19792. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  19793. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  19794. #define SQLITE_MALLOCSIZE(x) \
  19795. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  19796. #else /* if not __APPLE__ */
  19797. /*
  19798. ** Use standard C library malloc and free on non-Apple systems.
  19799. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  19800. */
  19801. #define SQLITE_MALLOC(x) malloc(x)
  19802. #define SQLITE_FREE(x) free(x)
  19803. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  19804. /*
  19805. ** The malloc.h header file is needed for malloc_usable_size() function
  19806. ** on some systems (e.g. Linux).
  19807. */
  19808. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  19809. # define SQLITE_USE_MALLOC_H 1
  19810. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  19811. /*
  19812. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  19813. ** use of _msize() is automatic, but can be disabled by compiling with
  19814. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  19815. ** the malloc.h header file.
  19816. */
  19817. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  19818. # define SQLITE_USE_MALLOC_H
  19819. # define SQLITE_USE_MSIZE
  19820. #endif
  19821. /*
  19822. ** Include the malloc.h header file, if necessary. Also set define macro
  19823. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  19824. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  19825. ** The memory size function can always be overridden manually by defining
  19826. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  19827. */
  19828. #if defined(SQLITE_USE_MALLOC_H)
  19829. # include <malloc.h>
  19830. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  19831. # if !defined(SQLITE_MALLOCSIZE)
  19832. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  19833. # endif
  19834. # elif defined(SQLITE_USE_MSIZE)
  19835. # if !defined(SQLITE_MALLOCSIZE)
  19836. # define SQLITE_MALLOCSIZE _msize
  19837. # endif
  19838. # endif
  19839. #endif /* defined(SQLITE_USE_MALLOC_H) */
  19840. #endif /* __APPLE__ or not __APPLE__ */
  19841. /*
  19842. ** Like malloc(), but remember the size of the allocation
  19843. ** so that we can find it later using sqlite3MemSize().
  19844. **
  19845. ** For this low-level routine, we are guaranteed that nByte>0 because
  19846. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  19847. ** routines.
  19848. */
  19849. static void *sqlite3MemMalloc(int nByte){
  19850. #ifdef SQLITE_MALLOCSIZE
  19851. void *p;
  19852. testcase( ROUND8(nByte)==nByte );
  19853. p = SQLITE_MALLOC( nByte );
  19854. if( p==0 ){
  19855. testcase( sqlite3GlobalConfig.xLog!=0 );
  19856. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  19857. }
  19858. return p;
  19859. #else
  19860. sqlite3_int64 *p;
  19861. assert( nByte>0 );
  19862. testcase( ROUND8(nByte)!=nByte );
  19863. p = SQLITE_MALLOC( nByte+8 );
  19864. if( p ){
  19865. p[0] = nByte;
  19866. p++;
  19867. }else{
  19868. testcase( sqlite3GlobalConfig.xLog!=0 );
  19869. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  19870. }
  19871. return (void *)p;
  19872. #endif
  19873. }
  19874. /*
  19875. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  19876. ** or sqlite3MemRealloc().
  19877. **
  19878. ** For this low-level routine, we already know that pPrior!=0 since
  19879. ** cases where pPrior==0 will have been intecepted and dealt with
  19880. ** by higher-level routines.
  19881. */
  19882. static void sqlite3MemFree(void *pPrior){
  19883. #ifdef SQLITE_MALLOCSIZE
  19884. SQLITE_FREE(pPrior);
  19885. #else
  19886. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  19887. assert( pPrior!=0 );
  19888. p--;
  19889. SQLITE_FREE(p);
  19890. #endif
  19891. }
  19892. /*
  19893. ** Report the allocated size of a prior return from xMalloc()
  19894. ** or xRealloc().
  19895. */
  19896. static int sqlite3MemSize(void *pPrior){
  19897. #ifdef SQLITE_MALLOCSIZE
  19898. assert( pPrior!=0 );
  19899. return (int)SQLITE_MALLOCSIZE(pPrior);
  19900. #else
  19901. sqlite3_int64 *p;
  19902. assert( pPrior!=0 );
  19903. p = (sqlite3_int64*)pPrior;
  19904. p--;
  19905. return (int)p[0];
  19906. #endif
  19907. }
  19908. /*
  19909. ** Like realloc(). Resize an allocation previously obtained from
  19910. ** sqlite3MemMalloc().
  19911. **
  19912. ** For this low-level interface, we know that pPrior!=0. Cases where
  19913. ** pPrior==0 while have been intercepted by higher-level routine and
  19914. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  19915. ** cases where nByte<=0 will have been intercepted by higher-level
  19916. ** routines and redirected to xFree.
  19917. */
  19918. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  19919. #ifdef SQLITE_MALLOCSIZE
  19920. void *p = SQLITE_REALLOC(pPrior, nByte);
  19921. if( p==0 ){
  19922. testcase( sqlite3GlobalConfig.xLog!=0 );
  19923. sqlite3_log(SQLITE_NOMEM,
  19924. "failed memory resize %u to %u bytes",
  19925. SQLITE_MALLOCSIZE(pPrior), nByte);
  19926. }
  19927. return p;
  19928. #else
  19929. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  19930. assert( pPrior!=0 && nByte>0 );
  19931. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  19932. p--;
  19933. p = SQLITE_REALLOC(p, nByte+8 );
  19934. if( p ){
  19935. p[0] = nByte;
  19936. p++;
  19937. }else{
  19938. testcase( sqlite3GlobalConfig.xLog!=0 );
  19939. sqlite3_log(SQLITE_NOMEM,
  19940. "failed memory resize %u to %u bytes",
  19941. sqlite3MemSize(pPrior), nByte);
  19942. }
  19943. return (void*)p;
  19944. #endif
  19945. }
  19946. /*
  19947. ** Round up a request size to the next valid allocation size.
  19948. */
  19949. static int sqlite3MemRoundup(int n){
  19950. return ROUND8(n);
  19951. }
  19952. /*
  19953. ** Initialize this module.
  19954. */
  19955. static int sqlite3MemInit(void *NotUsed){
  19956. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  19957. int cpuCount;
  19958. size_t len;
  19959. if( _sqliteZone_ ){
  19960. return SQLITE_OK;
  19961. }
  19962. len = sizeof(cpuCount);
  19963. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  19964. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  19965. if( cpuCount>1 ){
  19966. /* defer MT decisions to system malloc */
  19967. _sqliteZone_ = malloc_default_zone();
  19968. }else{
  19969. /* only 1 core, use our own zone to contention over global locks,
  19970. ** e.g. we have our own dedicated locks */
  19971. _sqliteZone_ = malloc_create_zone(4096, 0);
  19972. malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
  19973. }
  19974. #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
  19975. UNUSED_PARAMETER(NotUsed);
  19976. return SQLITE_OK;
  19977. }
  19978. /*
  19979. ** Deinitialize this module.
  19980. */
  19981. static void sqlite3MemShutdown(void *NotUsed){
  19982. UNUSED_PARAMETER(NotUsed);
  19983. return;
  19984. }
  19985. /*
  19986. ** This routine is the only routine in this file with external linkage.
  19987. **
  19988. ** Populate the low-level memory allocation function pointers in
  19989. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  19990. */
  19991. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  19992. static const sqlite3_mem_methods defaultMethods = {
  19993. sqlite3MemMalloc,
  19994. sqlite3MemFree,
  19995. sqlite3MemRealloc,
  19996. sqlite3MemSize,
  19997. sqlite3MemRoundup,
  19998. sqlite3MemInit,
  19999. sqlite3MemShutdown,
  20000. 0
  20001. };
  20002. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  20003. }
  20004. #endif /* SQLITE_SYSTEM_MALLOC */
  20005. /************** End of mem1.c ************************************************/
  20006. /************** Begin file mem2.c ********************************************/
  20007. /*
  20008. ** 2007 August 15
  20009. **
  20010. ** The author disclaims copyright to this source code. In place of
  20011. ** a legal notice, here is a blessing:
  20012. **
  20013. ** May you do good and not evil.
  20014. ** May you find forgiveness for yourself and forgive others.
  20015. ** May you share freely, never taking more than you give.
  20016. **
  20017. *************************************************************************
  20018. **
  20019. ** This file contains low-level memory allocation drivers for when
  20020. ** SQLite will use the standard C-library malloc/realloc/free interface
  20021. ** to obtain the memory it needs while adding lots of additional debugging
  20022. ** information to each allocation in order to help detect and fix memory
  20023. ** leaks and memory usage errors.
  20024. **
  20025. ** This file contains implementations of the low-level memory allocation
  20026. ** routines specified in the sqlite3_mem_methods object.
  20027. */
  20028. /* #include "sqliteInt.h" */
  20029. /*
  20030. ** This version of the memory allocator is used only if the
  20031. ** SQLITE_MEMDEBUG macro is defined
  20032. */
  20033. #ifdef SQLITE_MEMDEBUG
  20034. /*
  20035. ** The backtrace functionality is only available with GLIBC
  20036. */
  20037. #ifdef __GLIBC__
  20038. extern int backtrace(void**,int);
  20039. extern void backtrace_symbols_fd(void*const*,int,int);
  20040. #else
  20041. # define backtrace(A,B) 1
  20042. # define backtrace_symbols_fd(A,B,C)
  20043. #endif
  20044. /* #include <stdio.h> */
  20045. /*
  20046. ** Each memory allocation looks like this:
  20047. **
  20048. ** ------------------------------------------------------------------------
  20049. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  20050. ** ------------------------------------------------------------------------
  20051. **
  20052. ** The application code sees only a pointer to the allocation. We have
  20053. ** to back up from the allocation pointer to find the MemBlockHdr. The
  20054. ** MemBlockHdr tells us the size of the allocation and the number of
  20055. ** backtrace pointers. There is also a guard word at the end of the
  20056. ** MemBlockHdr.
  20057. */
  20058. struct MemBlockHdr {
  20059. i64 iSize; /* Size of this allocation */
  20060. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  20061. char nBacktrace; /* Number of backtraces on this alloc */
  20062. char nBacktraceSlots; /* Available backtrace slots */
  20063. u8 nTitle; /* Bytes of title; includes '\0' */
  20064. u8 eType; /* Allocation type code */
  20065. int iForeGuard; /* Guard word for sanity */
  20066. };
  20067. /*
  20068. ** Guard words
  20069. */
  20070. #define FOREGUARD 0x80F5E153
  20071. #define REARGUARD 0xE4676B53
  20072. /*
  20073. ** Number of malloc size increments to track.
  20074. */
  20075. #define NCSIZE 1000
  20076. /*
  20077. ** All of the static variables used by this module are collected
  20078. ** into a single structure named "mem". This is to keep the
  20079. ** static variables organized and to reduce namespace pollution
  20080. ** when this module is combined with other in the amalgamation.
  20081. */
  20082. static struct {
  20083. /*
  20084. ** Mutex to control access to the memory allocation subsystem.
  20085. */
  20086. sqlite3_mutex *mutex;
  20087. /*
  20088. ** Head and tail of a linked list of all outstanding allocations
  20089. */
  20090. struct MemBlockHdr *pFirst;
  20091. struct MemBlockHdr *pLast;
  20092. /*
  20093. ** The number of levels of backtrace to save in new allocations.
  20094. */
  20095. int nBacktrace;
  20096. void (*xBacktrace)(int, int, void **);
  20097. /*
  20098. ** Title text to insert in front of each block
  20099. */
  20100. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  20101. char zTitle[100]; /* The title text */
  20102. /*
  20103. ** sqlite3MallocDisallow() increments the following counter.
  20104. ** sqlite3MallocAllow() decrements it.
  20105. */
  20106. int disallow; /* Do not allow memory allocation */
  20107. /*
  20108. ** Gather statistics on the sizes of memory allocations.
  20109. ** nAlloc[i] is the number of allocation attempts of i*8
  20110. ** bytes. i==NCSIZE is the number of allocation attempts for
  20111. ** sizes more than NCSIZE*8 bytes.
  20112. */
  20113. int nAlloc[NCSIZE]; /* Total number of allocations */
  20114. int nCurrent[NCSIZE]; /* Current number of allocations */
  20115. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  20116. } mem;
  20117. /*
  20118. ** Adjust memory usage statistics
  20119. */
  20120. static void adjustStats(int iSize, int increment){
  20121. int i = ROUND8(iSize)/8;
  20122. if( i>NCSIZE-1 ){
  20123. i = NCSIZE - 1;
  20124. }
  20125. if( increment>0 ){
  20126. mem.nAlloc[i]++;
  20127. mem.nCurrent[i]++;
  20128. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  20129. mem.mxCurrent[i] = mem.nCurrent[i];
  20130. }
  20131. }else{
  20132. mem.nCurrent[i]--;
  20133. assert( mem.nCurrent[i]>=0 );
  20134. }
  20135. }
  20136. /*
  20137. ** Given an allocation, find the MemBlockHdr for that allocation.
  20138. **
  20139. ** This routine checks the guards at either end of the allocation and
  20140. ** if they are incorrect it asserts.
  20141. */
  20142. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  20143. struct MemBlockHdr *p;
  20144. int *pInt;
  20145. u8 *pU8;
  20146. int nReserve;
  20147. p = (struct MemBlockHdr*)pAllocation;
  20148. p--;
  20149. assert( p->iForeGuard==(int)FOREGUARD );
  20150. nReserve = ROUND8(p->iSize);
  20151. pInt = (int*)pAllocation;
  20152. pU8 = (u8*)pAllocation;
  20153. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  20154. /* This checks any of the "extra" bytes allocated due
  20155. ** to rounding up to an 8 byte boundary to ensure
  20156. ** they haven't been overwritten.
  20157. */
  20158. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  20159. return p;
  20160. }
  20161. /*
  20162. ** Return the number of bytes currently allocated at address p.
  20163. */
  20164. static int sqlite3MemSize(void *p){
  20165. struct MemBlockHdr *pHdr;
  20166. if( !p ){
  20167. return 0;
  20168. }
  20169. pHdr = sqlite3MemsysGetHeader(p);
  20170. return (int)pHdr->iSize;
  20171. }
  20172. /*
  20173. ** Initialize the memory allocation subsystem.
  20174. */
  20175. static int sqlite3MemInit(void *NotUsed){
  20176. UNUSED_PARAMETER(NotUsed);
  20177. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  20178. if( !sqlite3GlobalConfig.bMemstat ){
  20179. /* If memory status is enabled, then the malloc.c wrapper will already
  20180. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  20181. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  20182. }
  20183. return SQLITE_OK;
  20184. }
  20185. /*
  20186. ** Deinitialize the memory allocation subsystem.
  20187. */
  20188. static void sqlite3MemShutdown(void *NotUsed){
  20189. UNUSED_PARAMETER(NotUsed);
  20190. mem.mutex = 0;
  20191. }
  20192. /*
  20193. ** Round up a request size to the next valid allocation size.
  20194. */
  20195. static int sqlite3MemRoundup(int n){
  20196. return ROUND8(n);
  20197. }
  20198. /*
  20199. ** Fill a buffer with pseudo-random bytes. This is used to preset
  20200. ** the content of a new memory allocation to unpredictable values and
  20201. ** to clear the content of a freed allocation to unpredictable values.
  20202. */
  20203. static void randomFill(char *pBuf, int nByte){
  20204. unsigned int x, y, r;
  20205. x = SQLITE_PTR_TO_INT(pBuf);
  20206. y = nByte | 1;
  20207. while( nByte >= 4 ){
  20208. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  20209. y = y*1103515245 + 12345;
  20210. r = x ^ y;
  20211. *(int*)pBuf = r;
  20212. pBuf += 4;
  20213. nByte -= 4;
  20214. }
  20215. while( nByte-- > 0 ){
  20216. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  20217. y = y*1103515245 + 12345;
  20218. r = x ^ y;
  20219. *(pBuf++) = r & 0xff;
  20220. }
  20221. }
  20222. /*
  20223. ** Allocate nByte bytes of memory.
  20224. */
  20225. static void *sqlite3MemMalloc(int nByte){
  20226. struct MemBlockHdr *pHdr;
  20227. void **pBt;
  20228. char *z;
  20229. int *pInt;
  20230. void *p = 0;
  20231. int totalSize;
  20232. int nReserve;
  20233. sqlite3_mutex_enter(mem.mutex);
  20234. assert( mem.disallow==0 );
  20235. nReserve = ROUND8(nByte);
  20236. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  20237. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  20238. p = malloc(totalSize);
  20239. if( p ){
  20240. z = p;
  20241. pBt = (void**)&z[mem.nTitle];
  20242. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  20243. pHdr->pNext = 0;
  20244. pHdr->pPrev = mem.pLast;
  20245. if( mem.pLast ){
  20246. mem.pLast->pNext = pHdr;
  20247. }else{
  20248. mem.pFirst = pHdr;
  20249. }
  20250. mem.pLast = pHdr;
  20251. pHdr->iForeGuard = FOREGUARD;
  20252. pHdr->eType = MEMTYPE_HEAP;
  20253. pHdr->nBacktraceSlots = mem.nBacktrace;
  20254. pHdr->nTitle = mem.nTitle;
  20255. if( mem.nBacktrace ){
  20256. void *aAddr[40];
  20257. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  20258. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  20259. assert(pBt[0]);
  20260. if( mem.xBacktrace ){
  20261. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  20262. }
  20263. }else{
  20264. pHdr->nBacktrace = 0;
  20265. }
  20266. if( mem.nTitle ){
  20267. memcpy(z, mem.zTitle, mem.nTitle);
  20268. }
  20269. pHdr->iSize = nByte;
  20270. adjustStats(nByte, +1);
  20271. pInt = (int*)&pHdr[1];
  20272. pInt[nReserve/sizeof(int)] = REARGUARD;
  20273. randomFill((char*)pInt, nByte);
  20274. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  20275. p = (void*)pInt;
  20276. }
  20277. sqlite3_mutex_leave(mem.mutex);
  20278. return p;
  20279. }
  20280. /*
  20281. ** Free memory.
  20282. */
  20283. static void sqlite3MemFree(void *pPrior){
  20284. struct MemBlockHdr *pHdr;
  20285. void **pBt;
  20286. char *z;
  20287. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  20288. || mem.mutex!=0 );
  20289. pHdr = sqlite3MemsysGetHeader(pPrior);
  20290. pBt = (void**)pHdr;
  20291. pBt -= pHdr->nBacktraceSlots;
  20292. sqlite3_mutex_enter(mem.mutex);
  20293. if( pHdr->pPrev ){
  20294. assert( pHdr->pPrev->pNext==pHdr );
  20295. pHdr->pPrev->pNext = pHdr->pNext;
  20296. }else{
  20297. assert( mem.pFirst==pHdr );
  20298. mem.pFirst = pHdr->pNext;
  20299. }
  20300. if( pHdr->pNext ){
  20301. assert( pHdr->pNext->pPrev==pHdr );
  20302. pHdr->pNext->pPrev = pHdr->pPrev;
  20303. }else{
  20304. assert( mem.pLast==pHdr );
  20305. mem.pLast = pHdr->pPrev;
  20306. }
  20307. z = (char*)pBt;
  20308. z -= pHdr->nTitle;
  20309. adjustStats((int)pHdr->iSize, -1);
  20310. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  20311. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  20312. free(z);
  20313. sqlite3_mutex_leave(mem.mutex);
  20314. }
  20315. /*
  20316. ** Change the size of an existing memory allocation.
  20317. **
  20318. ** For this debugging implementation, we *always* make a copy of the
  20319. ** allocation into a new place in memory. In this way, if the
  20320. ** higher level code is using pointer to the old allocation, it is
  20321. ** much more likely to break and we are much more liking to find
  20322. ** the error.
  20323. */
  20324. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  20325. struct MemBlockHdr *pOldHdr;
  20326. void *pNew;
  20327. assert( mem.disallow==0 );
  20328. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  20329. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  20330. pNew = sqlite3MemMalloc(nByte);
  20331. if( pNew ){
  20332. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  20333. if( nByte>pOldHdr->iSize ){
  20334. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  20335. }
  20336. sqlite3MemFree(pPrior);
  20337. }
  20338. return pNew;
  20339. }
  20340. /*
  20341. ** Populate the low-level memory allocation function pointers in
  20342. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  20343. */
  20344. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  20345. static const sqlite3_mem_methods defaultMethods = {
  20346. sqlite3MemMalloc,
  20347. sqlite3MemFree,
  20348. sqlite3MemRealloc,
  20349. sqlite3MemSize,
  20350. sqlite3MemRoundup,
  20351. sqlite3MemInit,
  20352. sqlite3MemShutdown,
  20353. 0
  20354. };
  20355. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  20356. }
  20357. /*
  20358. ** Set the "type" of an allocation.
  20359. */
  20360. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  20361. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  20362. struct MemBlockHdr *pHdr;
  20363. pHdr = sqlite3MemsysGetHeader(p);
  20364. assert( pHdr->iForeGuard==FOREGUARD );
  20365. pHdr->eType = eType;
  20366. }
  20367. }
  20368. /*
  20369. ** Return TRUE if the mask of type in eType matches the type of the
  20370. ** allocation p. Also return true if p==NULL.
  20371. **
  20372. ** This routine is designed for use within an assert() statement, to
  20373. ** verify the type of an allocation. For example:
  20374. **
  20375. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20376. */
  20377. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  20378. int rc = 1;
  20379. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  20380. struct MemBlockHdr *pHdr;
  20381. pHdr = sqlite3MemsysGetHeader(p);
  20382. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  20383. if( (pHdr->eType&eType)==0 ){
  20384. rc = 0;
  20385. }
  20386. }
  20387. return rc;
  20388. }
  20389. /*
  20390. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  20391. ** allocation p. Also return true if p==NULL.
  20392. **
  20393. ** This routine is designed for use within an assert() statement, to
  20394. ** verify the type of an allocation. For example:
  20395. **
  20396. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  20397. */
  20398. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  20399. int rc = 1;
  20400. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  20401. struct MemBlockHdr *pHdr;
  20402. pHdr = sqlite3MemsysGetHeader(p);
  20403. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  20404. if( (pHdr->eType&eType)!=0 ){
  20405. rc = 0;
  20406. }
  20407. }
  20408. return rc;
  20409. }
  20410. /*
  20411. ** Set the number of backtrace levels kept for each allocation.
  20412. ** A value of zero turns off backtracing. The number is always rounded
  20413. ** up to a multiple of 2.
  20414. */
  20415. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  20416. if( depth<0 ){ depth = 0; }
  20417. if( depth>20 ){ depth = 20; }
  20418. depth = (depth+1)&0xfe;
  20419. mem.nBacktrace = depth;
  20420. }
  20421. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  20422. mem.xBacktrace = xBacktrace;
  20423. }
  20424. /*
  20425. ** Set the title string for subsequent allocations.
  20426. */
  20427. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  20428. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  20429. sqlite3_mutex_enter(mem.mutex);
  20430. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  20431. memcpy(mem.zTitle, zTitle, n);
  20432. mem.zTitle[n] = 0;
  20433. mem.nTitle = ROUND8(n);
  20434. sqlite3_mutex_leave(mem.mutex);
  20435. }
  20436. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  20437. struct MemBlockHdr *pHdr;
  20438. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  20439. void **pBt = (void**)pHdr;
  20440. pBt -= pHdr->nBacktraceSlots;
  20441. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  20442. }
  20443. }
  20444. /*
  20445. ** Open the file indicated and write a log of all unfreed memory
  20446. ** allocations into that log.
  20447. */
  20448. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  20449. FILE *out;
  20450. struct MemBlockHdr *pHdr;
  20451. void **pBt;
  20452. int i;
  20453. out = fopen(zFilename, "w");
  20454. if( out==0 ){
  20455. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  20456. zFilename);
  20457. return;
  20458. }
  20459. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  20460. char *z = (char*)pHdr;
  20461. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  20462. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  20463. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  20464. if( pHdr->nBacktrace ){
  20465. fflush(out);
  20466. pBt = (void**)pHdr;
  20467. pBt -= pHdr->nBacktraceSlots;
  20468. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  20469. fprintf(out, "\n");
  20470. }
  20471. }
  20472. fprintf(out, "COUNTS:\n");
  20473. for(i=0; i<NCSIZE-1; i++){
  20474. if( mem.nAlloc[i] ){
  20475. fprintf(out, " %5d: %10d %10d %10d\n",
  20476. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  20477. }
  20478. }
  20479. if( mem.nAlloc[NCSIZE-1] ){
  20480. fprintf(out, " %5d: %10d %10d %10d\n",
  20481. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  20482. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  20483. }
  20484. fclose(out);
  20485. }
  20486. /*
  20487. ** Return the number of times sqlite3MemMalloc() has been called.
  20488. */
  20489. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  20490. int i;
  20491. int nTotal = 0;
  20492. for(i=0; i<NCSIZE; i++){
  20493. nTotal += mem.nAlloc[i];
  20494. }
  20495. return nTotal;
  20496. }
  20497. #endif /* SQLITE_MEMDEBUG */
  20498. /************** End of mem2.c ************************************************/
  20499. /************** Begin file mem3.c ********************************************/
  20500. /*
  20501. ** 2007 October 14
  20502. **
  20503. ** The author disclaims copyright to this source code. In place of
  20504. ** a legal notice, here is a blessing:
  20505. **
  20506. ** May you do good and not evil.
  20507. ** May you find forgiveness for yourself and forgive others.
  20508. ** May you share freely, never taking more than you give.
  20509. **
  20510. *************************************************************************
  20511. ** This file contains the C functions that implement a memory
  20512. ** allocation subsystem for use by SQLite.
  20513. **
  20514. ** This version of the memory allocation subsystem omits all
  20515. ** use of malloc(). The SQLite user supplies a block of memory
  20516. ** before calling sqlite3_initialize() from which allocations
  20517. ** are made and returned by the xMalloc() and xRealloc()
  20518. ** implementations. Once sqlite3_initialize() has been called,
  20519. ** the amount of memory available to SQLite is fixed and cannot
  20520. ** be changed.
  20521. **
  20522. ** This version of the memory allocation subsystem is included
  20523. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  20524. */
  20525. /* #include "sqliteInt.h" */
  20526. /*
  20527. ** This version of the memory allocator is only built into the library
  20528. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  20529. ** mean that the library will use a memory-pool by default, just that
  20530. ** it is available. The mempool allocator is activated by calling
  20531. ** sqlite3_config().
  20532. */
  20533. #ifdef SQLITE_ENABLE_MEMSYS3
  20534. /*
  20535. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  20536. */
  20537. #define MX_SMALL 10
  20538. /*
  20539. ** Number of freelist hash slots
  20540. */
  20541. #define N_HASH 61
  20542. /*
  20543. ** A memory allocation (also called a "chunk") consists of two or
  20544. ** more blocks where each block is 8 bytes. The first 8 bytes are
  20545. ** a header that is not returned to the user.
  20546. **
  20547. ** A chunk is two or more blocks that is either checked out or
  20548. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  20549. ** size of the allocation in blocks if the allocation is free.
  20550. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  20551. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  20552. ** is true if the previous chunk is checked out and false if the
  20553. ** previous chunk is free. The u.hdr.prevSize field is the size of
  20554. ** the previous chunk in blocks if the previous chunk is on the
  20555. ** freelist. If the previous chunk is checked out, then
  20556. ** u.hdr.prevSize can be part of the data for that chunk and should
  20557. ** not be read or written.
  20558. **
  20559. ** We often identify a chunk by its index in mem3.aPool[]. When
  20560. ** this is done, the chunk index refers to the second block of
  20561. ** the chunk. In this way, the first chunk has an index of 1.
  20562. ** A chunk index of 0 means "no such chunk" and is the equivalent
  20563. ** of a NULL pointer.
  20564. **
  20565. ** The second block of free chunks is of the form u.list. The
  20566. ** two fields form a double-linked list of chunks of related sizes.
  20567. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  20568. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  20569. **
  20570. ** The second block of a chunk is user data if the chunk is checked
  20571. ** out. If a chunk is checked out, the user data may extend into
  20572. ** the u.hdr.prevSize value of the following chunk.
  20573. */
  20574. typedef struct Mem3Block Mem3Block;
  20575. struct Mem3Block {
  20576. union {
  20577. struct {
  20578. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  20579. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  20580. } hdr;
  20581. struct {
  20582. u32 next; /* Index in mem3.aPool[] of next free chunk */
  20583. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  20584. } list;
  20585. } u;
  20586. };
  20587. /*
  20588. ** All of the static variables used by this module are collected
  20589. ** into a single structure named "mem3". This is to keep the
  20590. ** static variables organized and to reduce namespace pollution
  20591. ** when this module is combined with other in the amalgamation.
  20592. */
  20593. static SQLITE_WSD struct Mem3Global {
  20594. /*
  20595. ** Memory available for allocation. nPool is the size of the array
  20596. ** (in Mem3Blocks) pointed to by aPool less 2.
  20597. */
  20598. u32 nPool;
  20599. Mem3Block *aPool;
  20600. /*
  20601. ** True if we are evaluating an out-of-memory callback.
  20602. */
  20603. int alarmBusy;
  20604. /*
  20605. ** Mutex to control access to the memory allocation subsystem.
  20606. */
  20607. sqlite3_mutex *mutex;
  20608. /*
  20609. ** The minimum amount of free space that we have seen.
  20610. */
  20611. u32 mnMaster;
  20612. /*
  20613. ** iMaster is the index of the master chunk. Most new allocations
  20614. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  20615. ** of the current master. iMaster is 0 if there is not master chunk.
  20616. ** The master chunk is not in either the aiHash[] or aiSmall[].
  20617. */
  20618. u32 iMaster;
  20619. u32 szMaster;
  20620. /*
  20621. ** Array of lists of free blocks according to the block size
  20622. ** for smaller chunks, or a hash on the block size for larger
  20623. ** chunks.
  20624. */
  20625. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  20626. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  20627. } mem3 = { 97535575 };
  20628. #define mem3 GLOBAL(struct Mem3Global, mem3)
  20629. /*
  20630. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  20631. ** on. *pRoot is the list that i is a member of.
  20632. */
  20633. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  20634. u32 next = mem3.aPool[i].u.list.next;
  20635. u32 prev = mem3.aPool[i].u.list.prev;
  20636. assert( sqlite3_mutex_held(mem3.mutex) );
  20637. if( prev==0 ){
  20638. *pRoot = next;
  20639. }else{
  20640. mem3.aPool[prev].u.list.next = next;
  20641. }
  20642. if( next ){
  20643. mem3.aPool[next].u.list.prev = prev;
  20644. }
  20645. mem3.aPool[i].u.list.next = 0;
  20646. mem3.aPool[i].u.list.prev = 0;
  20647. }
  20648. /*
  20649. ** Unlink the chunk at index i from
  20650. ** whatever list is currently a member of.
  20651. */
  20652. static void memsys3Unlink(u32 i){
  20653. u32 size, hash;
  20654. assert( sqlite3_mutex_held(mem3.mutex) );
  20655. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  20656. assert( i>=1 );
  20657. size = mem3.aPool[i-1].u.hdr.size4x/4;
  20658. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  20659. assert( size>=2 );
  20660. if( size <= MX_SMALL ){
  20661. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  20662. }else{
  20663. hash = size % N_HASH;
  20664. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  20665. }
  20666. }
  20667. /*
  20668. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  20669. ** at *pRoot.
  20670. */
  20671. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  20672. assert( sqlite3_mutex_held(mem3.mutex) );
  20673. mem3.aPool[i].u.list.next = *pRoot;
  20674. mem3.aPool[i].u.list.prev = 0;
  20675. if( *pRoot ){
  20676. mem3.aPool[*pRoot].u.list.prev = i;
  20677. }
  20678. *pRoot = i;
  20679. }
  20680. /*
  20681. ** Link the chunk at index i into either the appropriate
  20682. ** small chunk list, or into the large chunk hash table.
  20683. */
  20684. static void memsys3Link(u32 i){
  20685. u32 size, hash;
  20686. assert( sqlite3_mutex_held(mem3.mutex) );
  20687. assert( i>=1 );
  20688. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  20689. size = mem3.aPool[i-1].u.hdr.size4x/4;
  20690. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  20691. assert( size>=2 );
  20692. if( size <= MX_SMALL ){
  20693. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  20694. }else{
  20695. hash = size % N_HASH;
  20696. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  20697. }
  20698. }
  20699. /*
  20700. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  20701. ** will already be held (obtained by code in malloc.c) if
  20702. ** sqlite3GlobalConfig.bMemStat is true.
  20703. */
  20704. static void memsys3Enter(void){
  20705. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  20706. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  20707. }
  20708. sqlite3_mutex_enter(mem3.mutex);
  20709. }
  20710. static void memsys3Leave(void){
  20711. sqlite3_mutex_leave(mem3.mutex);
  20712. }
  20713. /*
  20714. ** Called when we are unable to satisfy an allocation of nBytes.
  20715. */
  20716. static void memsys3OutOfMemory(int nByte){
  20717. if( !mem3.alarmBusy ){
  20718. mem3.alarmBusy = 1;
  20719. assert( sqlite3_mutex_held(mem3.mutex) );
  20720. sqlite3_mutex_leave(mem3.mutex);
  20721. sqlite3_release_memory(nByte);
  20722. sqlite3_mutex_enter(mem3.mutex);
  20723. mem3.alarmBusy = 0;
  20724. }
  20725. }
  20726. /*
  20727. ** Chunk i is a free chunk that has been unlinked. Adjust its
  20728. ** size parameters for check-out and return a pointer to the
  20729. ** user portion of the chunk.
  20730. */
  20731. static void *memsys3Checkout(u32 i, u32 nBlock){
  20732. u32 x;
  20733. assert( sqlite3_mutex_held(mem3.mutex) );
  20734. assert( i>=1 );
  20735. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  20736. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  20737. x = mem3.aPool[i-1].u.hdr.size4x;
  20738. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  20739. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  20740. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  20741. return &mem3.aPool[i];
  20742. }
  20743. /*
  20744. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  20745. ** Return a pointer to the new allocation. Or, if the master chunk
  20746. ** is not large enough, return 0.
  20747. */
  20748. static void *memsys3FromMaster(u32 nBlock){
  20749. assert( sqlite3_mutex_held(mem3.mutex) );
  20750. assert( mem3.szMaster>=nBlock );
  20751. if( nBlock>=mem3.szMaster-1 ){
  20752. /* Use the entire master */
  20753. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  20754. mem3.iMaster = 0;
  20755. mem3.szMaster = 0;
  20756. mem3.mnMaster = 0;
  20757. return p;
  20758. }else{
  20759. /* Split the master block. Return the tail. */
  20760. u32 newi, x;
  20761. newi = mem3.iMaster + mem3.szMaster - nBlock;
  20762. assert( newi > mem3.iMaster+1 );
  20763. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  20764. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  20765. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  20766. mem3.szMaster -= nBlock;
  20767. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  20768. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  20769. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  20770. if( mem3.szMaster < mem3.mnMaster ){
  20771. mem3.mnMaster = mem3.szMaster;
  20772. }
  20773. return (void*)&mem3.aPool[newi];
  20774. }
  20775. }
  20776. /*
  20777. ** *pRoot is the head of a list of free chunks of the same size
  20778. ** or same size hash. In other words, *pRoot is an entry in either
  20779. ** mem3.aiSmall[] or mem3.aiHash[].
  20780. **
  20781. ** This routine examines all entries on the given list and tries
  20782. ** to coalesce each entries with adjacent free chunks.
  20783. **
  20784. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  20785. ** the current mem3.iMaster with the new larger chunk. In order for
  20786. ** this mem3.iMaster replacement to work, the master chunk must be
  20787. ** linked into the hash tables. That is not the normal state of
  20788. ** affairs, of course. The calling routine must link the master
  20789. ** chunk before invoking this routine, then must unlink the (possibly
  20790. ** changed) master chunk once this routine has finished.
  20791. */
  20792. static void memsys3Merge(u32 *pRoot){
  20793. u32 iNext, prev, size, i, x;
  20794. assert( sqlite3_mutex_held(mem3.mutex) );
  20795. for(i=*pRoot; i>0; i=iNext){
  20796. iNext = mem3.aPool[i].u.list.next;
  20797. size = mem3.aPool[i-1].u.hdr.size4x;
  20798. assert( (size&1)==0 );
  20799. if( (size&2)==0 ){
  20800. memsys3UnlinkFromList(i, pRoot);
  20801. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  20802. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  20803. if( prev==iNext ){
  20804. iNext = mem3.aPool[prev].u.list.next;
  20805. }
  20806. memsys3Unlink(prev);
  20807. size = i + size/4 - prev;
  20808. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  20809. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  20810. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  20811. memsys3Link(prev);
  20812. i = prev;
  20813. }else{
  20814. size /= 4;
  20815. }
  20816. if( size>mem3.szMaster ){
  20817. mem3.iMaster = i;
  20818. mem3.szMaster = size;
  20819. }
  20820. }
  20821. }
  20822. /*
  20823. ** Return a block of memory of at least nBytes in size.
  20824. ** Return NULL if unable.
  20825. **
  20826. ** This function assumes that the necessary mutexes, if any, are
  20827. ** already held by the caller. Hence "Unsafe".
  20828. */
  20829. static void *memsys3MallocUnsafe(int nByte){
  20830. u32 i;
  20831. u32 nBlock;
  20832. u32 toFree;
  20833. assert( sqlite3_mutex_held(mem3.mutex) );
  20834. assert( sizeof(Mem3Block)==8 );
  20835. if( nByte<=12 ){
  20836. nBlock = 2;
  20837. }else{
  20838. nBlock = (nByte + 11)/8;
  20839. }
  20840. assert( nBlock>=2 );
  20841. /* STEP 1:
  20842. ** Look for an entry of the correct size in either the small
  20843. ** chunk table or in the large chunk hash table. This is
  20844. ** successful most of the time (about 9 times out of 10).
  20845. */
  20846. if( nBlock <= MX_SMALL ){
  20847. i = mem3.aiSmall[nBlock-2];
  20848. if( i>0 ){
  20849. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  20850. return memsys3Checkout(i, nBlock);
  20851. }
  20852. }else{
  20853. int hash = nBlock % N_HASH;
  20854. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  20855. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  20856. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  20857. return memsys3Checkout(i, nBlock);
  20858. }
  20859. }
  20860. }
  20861. /* STEP 2:
  20862. ** Try to satisfy the allocation by carving a piece off of the end
  20863. ** of the master chunk. This step usually works if step 1 fails.
  20864. */
  20865. if( mem3.szMaster>=nBlock ){
  20866. return memsys3FromMaster(nBlock);
  20867. }
  20868. /* STEP 3:
  20869. ** Loop through the entire memory pool. Coalesce adjacent free
  20870. ** chunks. Recompute the master chunk as the largest free chunk.
  20871. ** Then try again to satisfy the allocation by carving a piece off
  20872. ** of the end of the master chunk. This step happens very
  20873. ** rarely (we hope!)
  20874. */
  20875. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  20876. memsys3OutOfMemory(toFree);
  20877. if( mem3.iMaster ){
  20878. memsys3Link(mem3.iMaster);
  20879. mem3.iMaster = 0;
  20880. mem3.szMaster = 0;
  20881. }
  20882. for(i=0; i<N_HASH; i++){
  20883. memsys3Merge(&mem3.aiHash[i]);
  20884. }
  20885. for(i=0; i<MX_SMALL-1; i++){
  20886. memsys3Merge(&mem3.aiSmall[i]);
  20887. }
  20888. if( mem3.szMaster ){
  20889. memsys3Unlink(mem3.iMaster);
  20890. if( mem3.szMaster>=nBlock ){
  20891. return memsys3FromMaster(nBlock);
  20892. }
  20893. }
  20894. }
  20895. /* If none of the above worked, then we fail. */
  20896. return 0;
  20897. }
  20898. /*
  20899. ** Free an outstanding memory allocation.
  20900. **
  20901. ** This function assumes that the necessary mutexes, if any, are
  20902. ** already held by the caller. Hence "Unsafe".
  20903. */
  20904. static void memsys3FreeUnsafe(void *pOld){
  20905. Mem3Block *p = (Mem3Block*)pOld;
  20906. int i;
  20907. u32 size, x;
  20908. assert( sqlite3_mutex_held(mem3.mutex) );
  20909. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  20910. i = p - mem3.aPool;
  20911. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  20912. size = mem3.aPool[i-1].u.hdr.size4x/4;
  20913. assert( i+size<=mem3.nPool+1 );
  20914. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  20915. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  20916. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  20917. memsys3Link(i);
  20918. /* Try to expand the master using the newly freed chunk */
  20919. if( mem3.iMaster ){
  20920. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  20921. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  20922. mem3.iMaster -= size;
  20923. mem3.szMaster += size;
  20924. memsys3Unlink(mem3.iMaster);
  20925. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  20926. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  20927. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  20928. }
  20929. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  20930. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  20931. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  20932. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  20933. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  20934. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  20935. }
  20936. }
  20937. }
  20938. /*
  20939. ** Return the size of an outstanding allocation, in bytes. The
  20940. ** size returned omits the 8-byte header overhead. This only
  20941. ** works for chunks that are currently checked out.
  20942. */
  20943. static int memsys3Size(void *p){
  20944. Mem3Block *pBlock;
  20945. assert( p!=0 );
  20946. pBlock = (Mem3Block*)p;
  20947. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  20948. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  20949. }
  20950. /*
  20951. ** Round up a request size to the next valid allocation size.
  20952. */
  20953. static int memsys3Roundup(int n){
  20954. if( n<=12 ){
  20955. return 12;
  20956. }else{
  20957. return ((n+11)&~7) - 4;
  20958. }
  20959. }
  20960. /*
  20961. ** Allocate nBytes of memory.
  20962. */
  20963. static void *memsys3Malloc(int nBytes){
  20964. sqlite3_int64 *p;
  20965. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  20966. memsys3Enter();
  20967. p = memsys3MallocUnsafe(nBytes);
  20968. memsys3Leave();
  20969. return (void*)p;
  20970. }
  20971. /*
  20972. ** Free memory.
  20973. */
  20974. static void memsys3Free(void *pPrior){
  20975. assert( pPrior );
  20976. memsys3Enter();
  20977. memsys3FreeUnsafe(pPrior);
  20978. memsys3Leave();
  20979. }
  20980. /*
  20981. ** Change the size of an existing memory allocation
  20982. */
  20983. static void *memsys3Realloc(void *pPrior, int nBytes){
  20984. int nOld;
  20985. void *p;
  20986. if( pPrior==0 ){
  20987. return sqlite3_malloc(nBytes);
  20988. }
  20989. if( nBytes<=0 ){
  20990. sqlite3_free(pPrior);
  20991. return 0;
  20992. }
  20993. nOld = memsys3Size(pPrior);
  20994. if( nBytes<=nOld && nBytes>=nOld-128 ){
  20995. return pPrior;
  20996. }
  20997. memsys3Enter();
  20998. p = memsys3MallocUnsafe(nBytes);
  20999. if( p ){
  21000. if( nOld<nBytes ){
  21001. memcpy(p, pPrior, nOld);
  21002. }else{
  21003. memcpy(p, pPrior, nBytes);
  21004. }
  21005. memsys3FreeUnsafe(pPrior);
  21006. }
  21007. memsys3Leave();
  21008. return p;
  21009. }
  21010. /*
  21011. ** Initialize this module.
  21012. */
  21013. static int memsys3Init(void *NotUsed){
  21014. UNUSED_PARAMETER(NotUsed);
  21015. if( !sqlite3GlobalConfig.pHeap ){
  21016. return SQLITE_ERROR;
  21017. }
  21018. /* Store a pointer to the memory block in global structure mem3. */
  21019. assert( sizeof(Mem3Block)==8 );
  21020. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  21021. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  21022. /* Initialize the master block. */
  21023. mem3.szMaster = mem3.nPool;
  21024. mem3.mnMaster = mem3.szMaster;
  21025. mem3.iMaster = 1;
  21026. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  21027. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  21028. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  21029. return SQLITE_OK;
  21030. }
  21031. /*
  21032. ** Deinitialize this module.
  21033. */
  21034. static void memsys3Shutdown(void *NotUsed){
  21035. UNUSED_PARAMETER(NotUsed);
  21036. mem3.mutex = 0;
  21037. return;
  21038. }
  21039. /*
  21040. ** Open the file indicated and write a log of all unfreed memory
  21041. ** allocations into that log.
  21042. */
  21043. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  21044. #ifdef SQLITE_DEBUG
  21045. FILE *out;
  21046. u32 i, j;
  21047. u32 size;
  21048. if( zFilename==0 || zFilename[0]==0 ){
  21049. out = stdout;
  21050. }else{
  21051. out = fopen(zFilename, "w");
  21052. if( out==0 ){
  21053. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  21054. zFilename);
  21055. return;
  21056. }
  21057. }
  21058. memsys3Enter();
  21059. fprintf(out, "CHUNKS:\n");
  21060. for(i=1; i<=mem3.nPool; i+=size/4){
  21061. size = mem3.aPool[i-1].u.hdr.size4x;
  21062. if( size/4<=1 ){
  21063. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  21064. assert( 0 );
  21065. break;
  21066. }
  21067. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  21068. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  21069. assert( 0 );
  21070. break;
  21071. }
  21072. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  21073. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  21074. assert( 0 );
  21075. break;
  21076. }
  21077. if( size&1 ){
  21078. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  21079. }else{
  21080. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  21081. i==mem3.iMaster ? " **master**" : "");
  21082. }
  21083. }
  21084. for(i=0; i<MX_SMALL-1; i++){
  21085. if( mem3.aiSmall[i]==0 ) continue;
  21086. fprintf(out, "small(%2d):", i);
  21087. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  21088. fprintf(out, " %p(%d)", &mem3.aPool[j],
  21089. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  21090. }
  21091. fprintf(out, "\n");
  21092. }
  21093. for(i=0; i<N_HASH; i++){
  21094. if( mem3.aiHash[i]==0 ) continue;
  21095. fprintf(out, "hash(%2d):", i);
  21096. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  21097. fprintf(out, " %p(%d)", &mem3.aPool[j],
  21098. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  21099. }
  21100. fprintf(out, "\n");
  21101. }
  21102. fprintf(out, "master=%d\n", mem3.iMaster);
  21103. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  21104. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  21105. sqlite3_mutex_leave(mem3.mutex);
  21106. if( out==stdout ){
  21107. fflush(stdout);
  21108. }else{
  21109. fclose(out);
  21110. }
  21111. #else
  21112. UNUSED_PARAMETER(zFilename);
  21113. #endif
  21114. }
  21115. /*
  21116. ** This routine is the only routine in this file with external
  21117. ** linkage.
  21118. **
  21119. ** Populate the low-level memory allocation function pointers in
  21120. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  21121. ** arguments specify the block of memory to manage.
  21122. **
  21123. ** This routine is only called by sqlite3_config(), and therefore
  21124. ** is not required to be threadsafe (it is not).
  21125. */
  21126. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  21127. static const sqlite3_mem_methods mempoolMethods = {
  21128. memsys3Malloc,
  21129. memsys3Free,
  21130. memsys3Realloc,
  21131. memsys3Size,
  21132. memsys3Roundup,
  21133. memsys3Init,
  21134. memsys3Shutdown,
  21135. 0
  21136. };
  21137. return &mempoolMethods;
  21138. }
  21139. #endif /* SQLITE_ENABLE_MEMSYS3 */
  21140. /************** End of mem3.c ************************************************/
  21141. /************** Begin file mem5.c ********************************************/
  21142. /*
  21143. ** 2007 October 14
  21144. **
  21145. ** The author disclaims copyright to this source code. In place of
  21146. ** a legal notice, here is a blessing:
  21147. **
  21148. ** May you do good and not evil.
  21149. ** May you find forgiveness for yourself and forgive others.
  21150. ** May you share freely, never taking more than you give.
  21151. **
  21152. *************************************************************************
  21153. ** This file contains the C functions that implement a memory
  21154. ** allocation subsystem for use by SQLite.
  21155. **
  21156. ** This version of the memory allocation subsystem omits all
  21157. ** use of malloc(). The application gives SQLite a block of memory
  21158. ** before calling sqlite3_initialize() from which allocations
  21159. ** are made and returned by the xMalloc() and xRealloc()
  21160. ** implementations. Once sqlite3_initialize() has been called,
  21161. ** the amount of memory available to SQLite is fixed and cannot
  21162. ** be changed.
  21163. **
  21164. ** This version of the memory allocation subsystem is included
  21165. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  21166. **
  21167. ** This memory allocator uses the following algorithm:
  21168. **
  21169. ** 1. All memory allocation sizes are rounded up to a power of 2.
  21170. **
  21171. ** 2. If two adjacent free blocks are the halves of a larger block,
  21172. ** then the two blocks are coalesced into the single larger block.
  21173. **
  21174. ** 3. New memory is allocated from the first available free block.
  21175. **
  21176. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  21177. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  21178. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  21179. **
  21180. ** Let n be the size of the largest allocation divided by the minimum
  21181. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  21182. ** be the maximum amount of memory ever outstanding at one time. Let
  21183. ** N be the total amount of memory available for allocation. Robson
  21184. ** proved that this memory allocator will never breakdown due to
  21185. ** fragmentation as long as the following constraint holds:
  21186. **
  21187. ** N >= M*(1 + log2(n)/2) - n + 1
  21188. **
  21189. ** The sqlite3_status() logic tracks the maximum values of n and M so
  21190. ** that an application can, at any time, verify this constraint.
  21191. */
  21192. /* #include "sqliteInt.h" */
  21193. /*
  21194. ** This version of the memory allocator is used only when
  21195. ** SQLITE_ENABLE_MEMSYS5 is defined.
  21196. */
  21197. #ifdef SQLITE_ENABLE_MEMSYS5
  21198. /*
  21199. ** A minimum allocation is an instance of the following structure.
  21200. ** Larger allocations are an array of these structures where the
  21201. ** size of the array is a power of 2.
  21202. **
  21203. ** The size of this object must be a power of two. That fact is
  21204. ** verified in memsys5Init().
  21205. */
  21206. typedef struct Mem5Link Mem5Link;
  21207. struct Mem5Link {
  21208. int next; /* Index of next free chunk */
  21209. int prev; /* Index of previous free chunk */
  21210. };
  21211. /*
  21212. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  21213. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  21214. ** it is not actually possible to reach this limit.
  21215. */
  21216. #define LOGMAX 30
  21217. /*
  21218. ** Masks used for mem5.aCtrl[] elements.
  21219. */
  21220. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  21221. #define CTRL_FREE 0x20 /* True if not checked out */
  21222. /*
  21223. ** All of the static variables used by this module are collected
  21224. ** into a single structure named "mem5". This is to keep the
  21225. ** static variables organized and to reduce namespace pollution
  21226. ** when this module is combined with other in the amalgamation.
  21227. */
  21228. static SQLITE_WSD struct Mem5Global {
  21229. /*
  21230. ** Memory available for allocation
  21231. */
  21232. int szAtom; /* Smallest possible allocation in bytes */
  21233. int nBlock; /* Number of szAtom sized blocks in zPool */
  21234. u8 *zPool; /* Memory available to be allocated */
  21235. /*
  21236. ** Mutex to control access to the memory allocation subsystem.
  21237. */
  21238. sqlite3_mutex *mutex;
  21239. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21240. /*
  21241. ** Performance statistics
  21242. */
  21243. u64 nAlloc; /* Total number of calls to malloc */
  21244. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  21245. u64 totalExcess; /* Total internal fragmentation */
  21246. u32 currentOut; /* Current checkout, including internal fragmentation */
  21247. u32 currentCount; /* Current number of distinct checkouts */
  21248. u32 maxOut; /* Maximum instantaneous currentOut */
  21249. u32 maxCount; /* Maximum instantaneous currentCount */
  21250. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  21251. #endif
  21252. /*
  21253. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  21254. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  21255. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  21256. */
  21257. int aiFreelist[LOGMAX+1];
  21258. /*
  21259. ** Space for tracking which blocks are checked out and the size
  21260. ** of each block. One byte per block.
  21261. */
  21262. u8 *aCtrl;
  21263. } mem5;
  21264. /*
  21265. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  21266. */
  21267. #define mem5 GLOBAL(struct Mem5Global, mem5)
  21268. /*
  21269. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  21270. ** structures, return a pointer to the idx-th such link.
  21271. */
  21272. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  21273. /*
  21274. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  21275. ** on. It should be found on mem5.aiFreelist[iLogsize].
  21276. */
  21277. static void memsys5Unlink(int i, int iLogsize){
  21278. int next, prev;
  21279. assert( i>=0 && i<mem5.nBlock );
  21280. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  21281. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  21282. next = MEM5LINK(i)->next;
  21283. prev = MEM5LINK(i)->prev;
  21284. if( prev<0 ){
  21285. mem5.aiFreelist[iLogsize] = next;
  21286. }else{
  21287. MEM5LINK(prev)->next = next;
  21288. }
  21289. if( next>=0 ){
  21290. MEM5LINK(next)->prev = prev;
  21291. }
  21292. }
  21293. /*
  21294. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  21295. ** free list.
  21296. */
  21297. static void memsys5Link(int i, int iLogsize){
  21298. int x;
  21299. assert( sqlite3_mutex_held(mem5.mutex) );
  21300. assert( i>=0 && i<mem5.nBlock );
  21301. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  21302. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  21303. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  21304. MEM5LINK(i)->prev = -1;
  21305. if( x>=0 ){
  21306. assert( x<mem5.nBlock );
  21307. MEM5LINK(x)->prev = i;
  21308. }
  21309. mem5.aiFreelist[iLogsize] = i;
  21310. }
  21311. /*
  21312. ** Obtain or release the mutex needed to access global data structures.
  21313. */
  21314. static void memsys5Enter(void){
  21315. sqlite3_mutex_enter(mem5.mutex);
  21316. }
  21317. static void memsys5Leave(void){
  21318. sqlite3_mutex_leave(mem5.mutex);
  21319. }
  21320. /*
  21321. ** Return the size of an outstanding allocation, in bytes.
  21322. ** This only works for chunks that are currently checked out.
  21323. */
  21324. static int memsys5Size(void *p){
  21325. int iSize, i;
  21326. assert( p!=0 );
  21327. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  21328. assert( i>=0 && i<mem5.nBlock );
  21329. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  21330. return iSize;
  21331. }
  21332. /*
  21333. ** Return a block of memory of at least nBytes in size.
  21334. ** Return NULL if unable. Return NULL if nBytes==0.
  21335. **
  21336. ** The caller guarantees that nByte is positive.
  21337. **
  21338. ** The caller has obtained a mutex prior to invoking this
  21339. ** routine so there is never any chance that two or more
  21340. ** threads can be in this routine at the same time.
  21341. */
  21342. static void *memsys5MallocUnsafe(int nByte){
  21343. int i; /* Index of a mem5.aPool[] slot */
  21344. int iBin; /* Index into mem5.aiFreelist[] */
  21345. int iFullSz; /* Size of allocation rounded up to power of 2 */
  21346. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  21347. /* nByte must be a positive */
  21348. assert( nByte>0 );
  21349. /* No more than 1GiB per allocation */
  21350. if( nByte > 0x40000000 ) return 0;
  21351. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21352. /* Keep track of the maximum allocation request. Even unfulfilled
  21353. ** requests are counted */
  21354. if( (u32)nByte>mem5.maxRequest ){
  21355. mem5.maxRequest = nByte;
  21356. }
  21357. #endif
  21358. /* Round nByte up to the next valid power of two */
  21359. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  21360. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  21361. ** block. If not, then split a block of the next larger power of
  21362. ** two in order to create a new free block of size iLogsize.
  21363. */
  21364. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  21365. if( iBin>LOGMAX ){
  21366. testcase( sqlite3GlobalConfig.xLog!=0 );
  21367. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  21368. return 0;
  21369. }
  21370. i = mem5.aiFreelist[iBin];
  21371. memsys5Unlink(i, iBin);
  21372. while( iBin>iLogsize ){
  21373. int newSize;
  21374. iBin--;
  21375. newSize = 1 << iBin;
  21376. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  21377. memsys5Link(i+newSize, iBin);
  21378. }
  21379. mem5.aCtrl[i] = iLogsize;
  21380. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21381. /* Update allocator performance statistics. */
  21382. mem5.nAlloc++;
  21383. mem5.totalAlloc += iFullSz;
  21384. mem5.totalExcess += iFullSz - nByte;
  21385. mem5.currentCount++;
  21386. mem5.currentOut += iFullSz;
  21387. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  21388. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  21389. #endif
  21390. #ifdef SQLITE_DEBUG
  21391. /* Make sure the allocated memory does not assume that it is set to zero
  21392. ** or retains a value from a previous allocation */
  21393. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  21394. #endif
  21395. /* Return a pointer to the allocated memory. */
  21396. return (void*)&mem5.zPool[i*mem5.szAtom];
  21397. }
  21398. /*
  21399. ** Free an outstanding memory allocation.
  21400. */
  21401. static void memsys5FreeUnsafe(void *pOld){
  21402. u32 size, iLogsize;
  21403. int iBlock;
  21404. /* Set iBlock to the index of the block pointed to by pOld in
  21405. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  21406. */
  21407. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  21408. /* Check that the pointer pOld points to a valid, non-free block. */
  21409. assert( iBlock>=0 && iBlock<mem5.nBlock );
  21410. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  21411. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  21412. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  21413. size = 1<<iLogsize;
  21414. assert( iBlock+size-1<(u32)mem5.nBlock );
  21415. mem5.aCtrl[iBlock] |= CTRL_FREE;
  21416. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  21417. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21418. assert( mem5.currentCount>0 );
  21419. assert( mem5.currentOut>=(size*mem5.szAtom) );
  21420. mem5.currentCount--;
  21421. mem5.currentOut -= size*mem5.szAtom;
  21422. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  21423. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  21424. #endif
  21425. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  21426. while( ALWAYS(iLogsize<LOGMAX) ){
  21427. int iBuddy;
  21428. if( (iBlock>>iLogsize) & 1 ){
  21429. iBuddy = iBlock - size;
  21430. assert( iBuddy>=0 );
  21431. }else{
  21432. iBuddy = iBlock + size;
  21433. if( iBuddy>=mem5.nBlock ) break;
  21434. }
  21435. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  21436. memsys5Unlink(iBuddy, iLogsize);
  21437. iLogsize++;
  21438. if( iBuddy<iBlock ){
  21439. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  21440. mem5.aCtrl[iBlock] = 0;
  21441. iBlock = iBuddy;
  21442. }else{
  21443. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  21444. mem5.aCtrl[iBuddy] = 0;
  21445. }
  21446. size *= 2;
  21447. }
  21448. #ifdef SQLITE_DEBUG
  21449. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  21450. ** not used after being freed */
  21451. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  21452. #endif
  21453. memsys5Link(iBlock, iLogsize);
  21454. }
  21455. /*
  21456. ** Allocate nBytes of memory.
  21457. */
  21458. static void *memsys5Malloc(int nBytes){
  21459. sqlite3_int64 *p = 0;
  21460. if( nBytes>0 ){
  21461. memsys5Enter();
  21462. p = memsys5MallocUnsafe(nBytes);
  21463. memsys5Leave();
  21464. }
  21465. return (void*)p;
  21466. }
  21467. /*
  21468. ** Free memory.
  21469. **
  21470. ** The outer layer memory allocator prevents this routine from
  21471. ** being called with pPrior==0.
  21472. */
  21473. static void memsys5Free(void *pPrior){
  21474. assert( pPrior!=0 );
  21475. memsys5Enter();
  21476. memsys5FreeUnsafe(pPrior);
  21477. memsys5Leave();
  21478. }
  21479. /*
  21480. ** Change the size of an existing memory allocation.
  21481. **
  21482. ** The outer layer memory allocator prevents this routine from
  21483. ** being called with pPrior==0.
  21484. **
  21485. ** nBytes is always a value obtained from a prior call to
  21486. ** memsys5Round(). Hence nBytes is always a non-negative power
  21487. ** of two. If nBytes==0 that means that an oversize allocation
  21488. ** (an allocation larger than 0x40000000) was requested and this
  21489. ** routine should return 0 without freeing pPrior.
  21490. */
  21491. static void *memsys5Realloc(void *pPrior, int nBytes){
  21492. int nOld;
  21493. void *p;
  21494. assert( pPrior!=0 );
  21495. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  21496. assert( nBytes>=0 );
  21497. if( nBytes==0 ){
  21498. return 0;
  21499. }
  21500. nOld = memsys5Size(pPrior);
  21501. if( nBytes<=nOld ){
  21502. return pPrior;
  21503. }
  21504. p = memsys5Malloc(nBytes);
  21505. if( p ){
  21506. memcpy(p, pPrior, nOld);
  21507. memsys5Free(pPrior);
  21508. }
  21509. return p;
  21510. }
  21511. /*
  21512. ** Round up a request size to the next valid allocation size. If
  21513. ** the allocation is too large to be handled by this allocation system,
  21514. ** return 0.
  21515. **
  21516. ** All allocations must be a power of two and must be expressed by a
  21517. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  21518. ** or 1073741824 bytes.
  21519. */
  21520. static int memsys5Roundup(int n){
  21521. int iFullSz;
  21522. if( n > 0x40000000 ) return 0;
  21523. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  21524. return iFullSz;
  21525. }
  21526. /*
  21527. ** Return the ceiling of the logarithm base 2 of iValue.
  21528. **
  21529. ** Examples: memsys5Log(1) -> 0
  21530. ** memsys5Log(2) -> 1
  21531. ** memsys5Log(4) -> 2
  21532. ** memsys5Log(5) -> 3
  21533. ** memsys5Log(8) -> 3
  21534. ** memsys5Log(9) -> 4
  21535. */
  21536. static int memsys5Log(int iValue){
  21537. int iLog;
  21538. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  21539. return iLog;
  21540. }
  21541. /*
  21542. ** Initialize the memory allocator.
  21543. **
  21544. ** This routine is not threadsafe. The caller must be holding a mutex
  21545. ** to prevent multiple threads from entering at the same time.
  21546. */
  21547. static int memsys5Init(void *NotUsed){
  21548. int ii; /* Loop counter */
  21549. int nByte; /* Number of bytes of memory available to this allocator */
  21550. u8 *zByte; /* Memory usable by this allocator */
  21551. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  21552. int iOffset; /* An offset into mem5.aCtrl[] */
  21553. UNUSED_PARAMETER(NotUsed);
  21554. /* For the purposes of this routine, disable the mutex */
  21555. mem5.mutex = 0;
  21556. /* The size of a Mem5Link object must be a power of two. Verify that
  21557. ** this is case.
  21558. */
  21559. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  21560. nByte = sqlite3GlobalConfig.nHeap;
  21561. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  21562. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  21563. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  21564. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  21565. mem5.szAtom = (1<<nMinLog);
  21566. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  21567. mem5.szAtom = mem5.szAtom << 1;
  21568. }
  21569. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  21570. mem5.zPool = zByte;
  21571. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  21572. for(ii=0; ii<=LOGMAX; ii++){
  21573. mem5.aiFreelist[ii] = -1;
  21574. }
  21575. iOffset = 0;
  21576. for(ii=LOGMAX; ii>=0; ii--){
  21577. int nAlloc = (1<<ii);
  21578. if( (iOffset+nAlloc)<=mem5.nBlock ){
  21579. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  21580. memsys5Link(iOffset, ii);
  21581. iOffset += nAlloc;
  21582. }
  21583. assert((iOffset+nAlloc)>mem5.nBlock);
  21584. }
  21585. /* If a mutex is required for normal operation, allocate one */
  21586. if( sqlite3GlobalConfig.bMemstat==0 ){
  21587. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  21588. }
  21589. return SQLITE_OK;
  21590. }
  21591. /*
  21592. ** Deinitialize this module.
  21593. */
  21594. static void memsys5Shutdown(void *NotUsed){
  21595. UNUSED_PARAMETER(NotUsed);
  21596. mem5.mutex = 0;
  21597. return;
  21598. }
  21599. #ifdef SQLITE_TEST
  21600. /*
  21601. ** Open the file indicated and write a log of all unfreed memory
  21602. ** allocations into that log.
  21603. */
  21604. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  21605. FILE *out;
  21606. int i, j, n;
  21607. int nMinLog;
  21608. if( zFilename==0 || zFilename[0]==0 ){
  21609. out = stdout;
  21610. }else{
  21611. out = fopen(zFilename, "w");
  21612. if( out==0 ){
  21613. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  21614. zFilename);
  21615. return;
  21616. }
  21617. }
  21618. memsys5Enter();
  21619. nMinLog = memsys5Log(mem5.szAtom);
  21620. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  21621. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  21622. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  21623. }
  21624. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  21625. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  21626. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  21627. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  21628. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  21629. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  21630. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  21631. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  21632. memsys5Leave();
  21633. if( out==stdout ){
  21634. fflush(stdout);
  21635. }else{
  21636. fclose(out);
  21637. }
  21638. }
  21639. #endif
  21640. /*
  21641. ** This routine is the only routine in this file with external
  21642. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  21643. ** struct populated with the memsys5 methods.
  21644. */
  21645. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  21646. static const sqlite3_mem_methods memsys5Methods = {
  21647. memsys5Malloc,
  21648. memsys5Free,
  21649. memsys5Realloc,
  21650. memsys5Size,
  21651. memsys5Roundup,
  21652. memsys5Init,
  21653. memsys5Shutdown,
  21654. 0
  21655. };
  21656. return &memsys5Methods;
  21657. }
  21658. #endif /* SQLITE_ENABLE_MEMSYS5 */
  21659. /************** End of mem5.c ************************************************/
  21660. /************** Begin file mutex.c *******************************************/
  21661. /*
  21662. ** 2007 August 14
  21663. **
  21664. ** The author disclaims copyright to this source code. In place of
  21665. ** a legal notice, here is a blessing:
  21666. **
  21667. ** May you do good and not evil.
  21668. ** May you find forgiveness for yourself and forgive others.
  21669. ** May you share freely, never taking more than you give.
  21670. **
  21671. *************************************************************************
  21672. ** This file contains the C functions that implement mutexes.
  21673. **
  21674. ** This file contains code that is common across all mutex implementations.
  21675. */
  21676. /* #include "sqliteInt.h" */
  21677. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  21678. /*
  21679. ** For debugging purposes, record when the mutex subsystem is initialized
  21680. ** and uninitialized so that we can assert() if there is an attempt to
  21681. ** allocate a mutex while the system is uninitialized.
  21682. */
  21683. static SQLITE_WSD int mutexIsInit = 0;
  21684. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  21685. #ifndef SQLITE_MUTEX_OMIT
  21686. /*
  21687. ** Initialize the mutex system.
  21688. */
  21689. SQLITE_PRIVATE int sqlite3MutexInit(void){
  21690. int rc = SQLITE_OK;
  21691. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  21692. /* If the xMutexAlloc method has not been set, then the user did not
  21693. ** install a mutex implementation via sqlite3_config() prior to
  21694. ** sqlite3_initialize() being called. This block copies pointers to
  21695. ** the default implementation into the sqlite3GlobalConfig structure.
  21696. */
  21697. sqlite3_mutex_methods const *pFrom;
  21698. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  21699. if( sqlite3GlobalConfig.bCoreMutex ){
  21700. pFrom = sqlite3DefaultMutex();
  21701. }else{
  21702. pFrom = sqlite3NoopMutex();
  21703. }
  21704. pTo->xMutexInit = pFrom->xMutexInit;
  21705. pTo->xMutexEnd = pFrom->xMutexEnd;
  21706. pTo->xMutexFree = pFrom->xMutexFree;
  21707. pTo->xMutexEnter = pFrom->xMutexEnter;
  21708. pTo->xMutexTry = pFrom->xMutexTry;
  21709. pTo->xMutexLeave = pFrom->xMutexLeave;
  21710. pTo->xMutexHeld = pFrom->xMutexHeld;
  21711. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  21712. sqlite3MemoryBarrier();
  21713. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  21714. }
  21715. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  21716. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  21717. #ifdef SQLITE_DEBUG
  21718. GLOBAL(int, mutexIsInit) = 1;
  21719. #endif
  21720. return rc;
  21721. }
  21722. /*
  21723. ** Shutdown the mutex system. This call frees resources allocated by
  21724. ** sqlite3MutexInit().
  21725. */
  21726. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  21727. int rc = SQLITE_OK;
  21728. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  21729. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  21730. }
  21731. #ifdef SQLITE_DEBUG
  21732. GLOBAL(int, mutexIsInit) = 0;
  21733. #endif
  21734. return rc;
  21735. }
  21736. /*
  21737. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  21738. */
  21739. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  21740. #ifndef SQLITE_OMIT_AUTOINIT
  21741. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  21742. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  21743. #endif
  21744. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  21745. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  21746. }
  21747. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  21748. if( !sqlite3GlobalConfig.bCoreMutex ){
  21749. return 0;
  21750. }
  21751. assert( GLOBAL(int, mutexIsInit) );
  21752. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  21753. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  21754. }
  21755. /*
  21756. ** Free a dynamic mutex.
  21757. */
  21758. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  21759. if( p ){
  21760. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  21761. sqlite3GlobalConfig.mutex.xMutexFree(p);
  21762. }
  21763. }
  21764. /*
  21765. ** Obtain the mutex p. If some other thread already has the mutex, block
  21766. ** until it can be obtained.
  21767. */
  21768. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  21769. if( p ){
  21770. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  21771. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  21772. }
  21773. }
  21774. /*
  21775. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  21776. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  21777. */
  21778. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  21779. int rc = SQLITE_OK;
  21780. if( p ){
  21781. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  21782. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  21783. }
  21784. return rc;
  21785. }
  21786. /*
  21787. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  21788. ** entered by the same thread. The behavior is undefined if the mutex
  21789. ** is not currently entered. If a NULL pointer is passed as an argument
  21790. ** this function is a no-op.
  21791. */
  21792. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  21793. if( p ){
  21794. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  21795. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  21796. }
  21797. }
  21798. #ifndef NDEBUG
  21799. /*
  21800. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  21801. ** intended for use inside assert() statements.
  21802. */
  21803. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  21804. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  21805. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  21806. }
  21807. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  21808. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  21809. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  21810. }
  21811. #endif
  21812. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  21813. /************** End of mutex.c ***********************************************/
  21814. /************** Begin file mutex_noop.c **************************************/
  21815. /*
  21816. ** 2008 October 07
  21817. **
  21818. ** The author disclaims copyright to this source code. In place of
  21819. ** a legal notice, here is a blessing:
  21820. **
  21821. ** May you do good and not evil.
  21822. ** May you find forgiveness for yourself and forgive others.
  21823. ** May you share freely, never taking more than you give.
  21824. **
  21825. *************************************************************************
  21826. ** This file contains the C functions that implement mutexes.
  21827. **
  21828. ** This implementation in this file does not provide any mutual
  21829. ** exclusion and is thus suitable for use only in applications
  21830. ** that use SQLite in a single thread. The routines defined
  21831. ** here are place-holders. Applications can substitute working
  21832. ** mutex routines at start-time using the
  21833. **
  21834. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  21835. **
  21836. ** interface.
  21837. **
  21838. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  21839. ** that does error checking on mutexes to make sure they are being
  21840. ** called correctly.
  21841. */
  21842. /* #include "sqliteInt.h" */
  21843. #ifndef SQLITE_MUTEX_OMIT
  21844. #ifndef SQLITE_DEBUG
  21845. /*
  21846. ** Stub routines for all mutex methods.
  21847. **
  21848. ** This routines provide no mutual exclusion or error checking.
  21849. */
  21850. static int noopMutexInit(void){ return SQLITE_OK; }
  21851. static int noopMutexEnd(void){ return SQLITE_OK; }
  21852. static sqlite3_mutex *noopMutexAlloc(int id){
  21853. UNUSED_PARAMETER(id);
  21854. return (sqlite3_mutex*)8;
  21855. }
  21856. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  21857. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  21858. static int noopMutexTry(sqlite3_mutex *p){
  21859. UNUSED_PARAMETER(p);
  21860. return SQLITE_OK;
  21861. }
  21862. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  21863. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  21864. static const sqlite3_mutex_methods sMutex = {
  21865. noopMutexInit,
  21866. noopMutexEnd,
  21867. noopMutexAlloc,
  21868. noopMutexFree,
  21869. noopMutexEnter,
  21870. noopMutexTry,
  21871. noopMutexLeave,
  21872. 0,
  21873. 0,
  21874. };
  21875. return &sMutex;
  21876. }
  21877. #endif /* !SQLITE_DEBUG */
  21878. #ifdef SQLITE_DEBUG
  21879. /*
  21880. ** In this implementation, error checking is provided for testing
  21881. ** and debugging purposes. The mutexes still do not provide any
  21882. ** mutual exclusion.
  21883. */
  21884. /*
  21885. ** The mutex object
  21886. */
  21887. typedef struct sqlite3_debug_mutex {
  21888. int id; /* The mutex type */
  21889. int cnt; /* Number of entries without a matching leave */
  21890. } sqlite3_debug_mutex;
  21891. /*
  21892. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  21893. ** intended for use inside assert() statements.
  21894. */
  21895. static int debugMutexHeld(sqlite3_mutex *pX){
  21896. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21897. return p==0 || p->cnt>0;
  21898. }
  21899. static int debugMutexNotheld(sqlite3_mutex *pX){
  21900. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21901. return p==0 || p->cnt==0;
  21902. }
  21903. /*
  21904. ** Initialize and deinitialize the mutex subsystem.
  21905. */
  21906. static int debugMutexInit(void){ return SQLITE_OK; }
  21907. static int debugMutexEnd(void){ return SQLITE_OK; }
  21908. /*
  21909. ** The sqlite3_mutex_alloc() routine allocates a new
  21910. ** mutex and returns a pointer to it. If it returns NULL
  21911. ** that means that a mutex could not be allocated.
  21912. */
  21913. static sqlite3_mutex *debugMutexAlloc(int id){
  21914. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  21915. sqlite3_debug_mutex *pNew = 0;
  21916. switch( id ){
  21917. case SQLITE_MUTEX_FAST:
  21918. case SQLITE_MUTEX_RECURSIVE: {
  21919. pNew = sqlite3Malloc(sizeof(*pNew));
  21920. if( pNew ){
  21921. pNew->id = id;
  21922. pNew->cnt = 0;
  21923. }
  21924. break;
  21925. }
  21926. default: {
  21927. #ifdef SQLITE_ENABLE_API_ARMOR
  21928. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  21929. (void)SQLITE_MISUSE_BKPT;
  21930. return 0;
  21931. }
  21932. #endif
  21933. pNew = &aStatic[id-2];
  21934. pNew->id = id;
  21935. break;
  21936. }
  21937. }
  21938. return (sqlite3_mutex*)pNew;
  21939. }
  21940. /*
  21941. ** This routine deallocates a previously allocated mutex.
  21942. */
  21943. static void debugMutexFree(sqlite3_mutex *pX){
  21944. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21945. assert( p->cnt==0 );
  21946. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  21947. sqlite3_free(p);
  21948. }else{
  21949. #ifdef SQLITE_ENABLE_API_ARMOR
  21950. (void)SQLITE_MISUSE_BKPT;
  21951. #endif
  21952. }
  21953. }
  21954. /*
  21955. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  21956. ** to enter a mutex. If another thread is already within the mutex,
  21957. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  21958. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  21959. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  21960. ** be entered multiple times by the same thread. In such cases the,
  21961. ** mutex must be exited an equal number of times before another thread
  21962. ** can enter. If the same thread tries to enter any other kind of mutex
  21963. ** more than once, the behavior is undefined.
  21964. */
  21965. static void debugMutexEnter(sqlite3_mutex *pX){
  21966. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21967. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  21968. p->cnt++;
  21969. }
  21970. static int debugMutexTry(sqlite3_mutex *pX){
  21971. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21972. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  21973. p->cnt++;
  21974. return SQLITE_OK;
  21975. }
  21976. /*
  21977. ** The sqlite3_mutex_leave() routine exits a mutex that was
  21978. ** previously entered by the same thread. The behavior
  21979. ** is undefined if the mutex is not currently entered or
  21980. ** is not currently allocated. SQLite will never do either.
  21981. */
  21982. static void debugMutexLeave(sqlite3_mutex *pX){
  21983. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21984. assert( debugMutexHeld(pX) );
  21985. p->cnt--;
  21986. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  21987. }
  21988. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  21989. static const sqlite3_mutex_methods sMutex = {
  21990. debugMutexInit,
  21991. debugMutexEnd,
  21992. debugMutexAlloc,
  21993. debugMutexFree,
  21994. debugMutexEnter,
  21995. debugMutexTry,
  21996. debugMutexLeave,
  21997. debugMutexHeld,
  21998. debugMutexNotheld
  21999. };
  22000. return &sMutex;
  22001. }
  22002. #endif /* SQLITE_DEBUG */
  22003. /*
  22004. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  22005. ** is used regardless of the run-time threadsafety setting.
  22006. */
  22007. #ifdef SQLITE_MUTEX_NOOP
  22008. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  22009. return sqlite3NoopMutex();
  22010. }
  22011. #endif /* defined(SQLITE_MUTEX_NOOP) */
  22012. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  22013. /************** End of mutex_noop.c ******************************************/
  22014. /************** Begin file mutex_unix.c **************************************/
  22015. /*
  22016. ** 2007 August 28
  22017. **
  22018. ** The author disclaims copyright to this source code. In place of
  22019. ** a legal notice, here is a blessing:
  22020. **
  22021. ** May you do good and not evil.
  22022. ** May you find forgiveness for yourself and forgive others.
  22023. ** May you share freely, never taking more than you give.
  22024. **
  22025. *************************************************************************
  22026. ** This file contains the C functions that implement mutexes for pthreads
  22027. */
  22028. /* #include "sqliteInt.h" */
  22029. /*
  22030. ** The code in this file is only used if we are compiling threadsafe
  22031. ** under unix with pthreads.
  22032. **
  22033. ** Note that this implementation requires a version of pthreads that
  22034. ** supports recursive mutexes.
  22035. */
  22036. #ifdef SQLITE_MUTEX_PTHREADS
  22037. #include <pthread.h>
  22038. /*
  22039. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  22040. ** are necessary under two condidtions: (1) Debug builds and (2) using
  22041. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  22042. */
  22043. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  22044. # define SQLITE_MUTEX_NREF 1
  22045. #else
  22046. # define SQLITE_MUTEX_NREF 0
  22047. #endif
  22048. /*
  22049. ** Each recursive mutex is an instance of the following structure.
  22050. */
  22051. struct sqlite3_mutex {
  22052. pthread_mutex_t mutex; /* Mutex controlling the lock */
  22053. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  22054. int id; /* Mutex type */
  22055. #endif
  22056. #if SQLITE_MUTEX_NREF
  22057. volatile int nRef; /* Number of entrances */
  22058. volatile pthread_t owner; /* Thread that is within this mutex */
  22059. int trace; /* True to trace changes */
  22060. #endif
  22061. };
  22062. #if SQLITE_MUTEX_NREF
  22063. #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
  22064. #elif defined(SQLITE_ENABLE_API_ARMOR)
  22065. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
  22066. #else
  22067. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  22068. #endif
  22069. /*
  22070. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  22071. ** intended for use only inside assert() statements. On some platforms,
  22072. ** there might be race conditions that can cause these routines to
  22073. ** deliver incorrect results. In particular, if pthread_equal() is
  22074. ** not an atomic operation, then these routines might delivery
  22075. ** incorrect results. On most platforms, pthread_equal() is a
  22076. ** comparison of two integers and is therefore atomic. But we are
  22077. ** told that HPUX is not such a platform. If so, then these routines
  22078. ** will not always work correctly on HPUX.
  22079. **
  22080. ** On those platforms where pthread_equal() is not atomic, SQLite
  22081. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  22082. ** make sure no assert() statements are evaluated and hence these
  22083. ** routines are never called.
  22084. */
  22085. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  22086. static int pthreadMutexHeld(sqlite3_mutex *p){
  22087. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  22088. }
  22089. static int pthreadMutexNotheld(sqlite3_mutex *p){
  22090. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  22091. }
  22092. #endif
  22093. /*
  22094. ** Try to provide a memory barrier operation, needed for initialization
  22095. ** and also for the implementation of xShmBarrier in the VFS in cases
  22096. ** where SQLite is compiled without mutexes.
  22097. */
  22098. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  22099. #if defined(SQLITE_MEMORY_BARRIER)
  22100. SQLITE_MEMORY_BARRIER;
  22101. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  22102. __sync_synchronize();
  22103. #endif
  22104. }
  22105. /*
  22106. ** Initialize and deinitialize the mutex subsystem.
  22107. */
  22108. static int pthreadMutexInit(void){ return SQLITE_OK; }
  22109. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  22110. /*
  22111. ** The sqlite3_mutex_alloc() routine allocates a new
  22112. ** mutex and returns a pointer to it. If it returns NULL
  22113. ** that means that a mutex could not be allocated. SQLite
  22114. ** will unwind its stack and return an error. The argument
  22115. ** to sqlite3_mutex_alloc() is one of these integer constants:
  22116. **
  22117. ** <ul>
  22118. ** <li> SQLITE_MUTEX_FAST
  22119. ** <li> SQLITE_MUTEX_RECURSIVE
  22120. ** <li> SQLITE_MUTEX_STATIC_MASTER
  22121. ** <li> SQLITE_MUTEX_STATIC_MEM
  22122. ** <li> SQLITE_MUTEX_STATIC_OPEN
  22123. ** <li> SQLITE_MUTEX_STATIC_PRNG
  22124. ** <li> SQLITE_MUTEX_STATIC_LRU
  22125. ** <li> SQLITE_MUTEX_STATIC_PMEM
  22126. ** <li> SQLITE_MUTEX_STATIC_APP1
  22127. ** <li> SQLITE_MUTEX_STATIC_APP2
  22128. ** <li> SQLITE_MUTEX_STATIC_APP3
  22129. ** <li> SQLITE_MUTEX_STATIC_VFS1
  22130. ** <li> SQLITE_MUTEX_STATIC_VFS2
  22131. ** <li> SQLITE_MUTEX_STATIC_VFS3
  22132. ** </ul>
  22133. **
  22134. ** The first two constants cause sqlite3_mutex_alloc() to create
  22135. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  22136. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  22137. ** The mutex implementation does not need to make a distinction
  22138. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  22139. ** not want to. But SQLite will only request a recursive mutex in
  22140. ** cases where it really needs one. If a faster non-recursive mutex
  22141. ** implementation is available on the host platform, the mutex subsystem
  22142. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  22143. **
  22144. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  22145. ** a pointer to a static preexisting mutex. Six static mutexes are
  22146. ** used by the current version of SQLite. Future versions of SQLite
  22147. ** may add additional static mutexes. Static mutexes are for internal
  22148. ** use by SQLite only. Applications that use SQLite mutexes should
  22149. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  22150. ** SQLITE_MUTEX_RECURSIVE.
  22151. **
  22152. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  22153. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  22154. ** returns a different mutex on every call. But for the static
  22155. ** mutex types, the same mutex is returned on every call that has
  22156. ** the same type number.
  22157. */
  22158. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  22159. static sqlite3_mutex staticMutexes[] = {
  22160. SQLITE3_MUTEX_INITIALIZER,
  22161. SQLITE3_MUTEX_INITIALIZER,
  22162. SQLITE3_MUTEX_INITIALIZER,
  22163. SQLITE3_MUTEX_INITIALIZER,
  22164. SQLITE3_MUTEX_INITIALIZER,
  22165. SQLITE3_MUTEX_INITIALIZER,
  22166. SQLITE3_MUTEX_INITIALIZER,
  22167. SQLITE3_MUTEX_INITIALIZER,
  22168. SQLITE3_MUTEX_INITIALIZER,
  22169. SQLITE3_MUTEX_INITIALIZER,
  22170. SQLITE3_MUTEX_INITIALIZER,
  22171. SQLITE3_MUTEX_INITIALIZER
  22172. };
  22173. sqlite3_mutex *p;
  22174. switch( iType ){
  22175. case SQLITE_MUTEX_RECURSIVE: {
  22176. p = sqlite3MallocZero( sizeof(*p) );
  22177. if( p ){
  22178. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22179. /* If recursive mutexes are not available, we will have to
  22180. ** build our own. See below. */
  22181. pthread_mutex_init(&p->mutex, 0);
  22182. #else
  22183. /* Use a recursive mutex if it is available */
  22184. pthread_mutexattr_t recursiveAttr;
  22185. pthread_mutexattr_init(&recursiveAttr);
  22186. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  22187. pthread_mutex_init(&p->mutex, &recursiveAttr);
  22188. pthread_mutexattr_destroy(&recursiveAttr);
  22189. #endif
  22190. }
  22191. break;
  22192. }
  22193. case SQLITE_MUTEX_FAST: {
  22194. p = sqlite3MallocZero( sizeof(*p) );
  22195. if( p ){
  22196. pthread_mutex_init(&p->mutex, 0);
  22197. }
  22198. break;
  22199. }
  22200. default: {
  22201. #ifdef SQLITE_ENABLE_API_ARMOR
  22202. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  22203. (void)SQLITE_MISUSE_BKPT;
  22204. return 0;
  22205. }
  22206. #endif
  22207. p = &staticMutexes[iType-2];
  22208. break;
  22209. }
  22210. }
  22211. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  22212. if( p ) p->id = iType;
  22213. #endif
  22214. return p;
  22215. }
  22216. /*
  22217. ** This routine deallocates a previously
  22218. ** allocated mutex. SQLite is careful to deallocate every
  22219. ** mutex that it allocates.
  22220. */
  22221. static void pthreadMutexFree(sqlite3_mutex *p){
  22222. assert( p->nRef==0 );
  22223. #if SQLITE_ENABLE_API_ARMOR
  22224. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  22225. #endif
  22226. {
  22227. pthread_mutex_destroy(&p->mutex);
  22228. sqlite3_free(p);
  22229. }
  22230. #ifdef SQLITE_ENABLE_API_ARMOR
  22231. else{
  22232. (void)SQLITE_MISUSE_BKPT;
  22233. }
  22234. #endif
  22235. }
  22236. /*
  22237. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  22238. ** to enter a mutex. If another thread is already within the mutex,
  22239. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  22240. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  22241. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  22242. ** be entered multiple times by the same thread. In such cases the,
  22243. ** mutex must be exited an equal number of times before another thread
  22244. ** can enter. If the same thread tries to enter any other kind of mutex
  22245. ** more than once, the behavior is undefined.
  22246. */
  22247. static void pthreadMutexEnter(sqlite3_mutex *p){
  22248. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  22249. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22250. /* If recursive mutexes are not available, then we have to grow
  22251. ** our own. This implementation assumes that pthread_equal()
  22252. ** is atomic - that it cannot be deceived into thinking self
  22253. ** and p->owner are equal if p->owner changes between two values
  22254. ** that are not equal to self while the comparison is taking place.
  22255. ** This implementation also assumes a coherent cache - that
  22256. ** separate processes cannot read different values from the same
  22257. ** address at the same time. If either of these two conditions
  22258. ** are not met, then the mutexes will fail and problems will result.
  22259. */
  22260. {
  22261. pthread_t self = pthread_self();
  22262. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  22263. p->nRef++;
  22264. }else{
  22265. pthread_mutex_lock(&p->mutex);
  22266. assert( p->nRef==0 );
  22267. p->owner = self;
  22268. p->nRef = 1;
  22269. }
  22270. }
  22271. #else
  22272. /* Use the built-in recursive mutexes if they are available.
  22273. */
  22274. pthread_mutex_lock(&p->mutex);
  22275. #if SQLITE_MUTEX_NREF
  22276. assert( p->nRef>0 || p->owner==0 );
  22277. p->owner = pthread_self();
  22278. p->nRef++;
  22279. #endif
  22280. #endif
  22281. #ifdef SQLITE_DEBUG
  22282. if( p->trace ){
  22283. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  22284. }
  22285. #endif
  22286. }
  22287. static int pthreadMutexTry(sqlite3_mutex *p){
  22288. int rc;
  22289. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  22290. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22291. /* If recursive mutexes are not available, then we have to grow
  22292. ** our own. This implementation assumes that pthread_equal()
  22293. ** is atomic - that it cannot be deceived into thinking self
  22294. ** and p->owner are equal if p->owner changes between two values
  22295. ** that are not equal to self while the comparison is taking place.
  22296. ** This implementation also assumes a coherent cache - that
  22297. ** separate processes cannot read different values from the same
  22298. ** address at the same time. If either of these two conditions
  22299. ** are not met, then the mutexes will fail and problems will result.
  22300. */
  22301. {
  22302. pthread_t self = pthread_self();
  22303. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  22304. p->nRef++;
  22305. rc = SQLITE_OK;
  22306. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  22307. assert( p->nRef==0 );
  22308. p->owner = self;
  22309. p->nRef = 1;
  22310. rc = SQLITE_OK;
  22311. }else{
  22312. rc = SQLITE_BUSY;
  22313. }
  22314. }
  22315. #else
  22316. /* Use the built-in recursive mutexes if they are available.
  22317. */
  22318. if( pthread_mutex_trylock(&p->mutex)==0 ){
  22319. #if SQLITE_MUTEX_NREF
  22320. p->owner = pthread_self();
  22321. p->nRef++;
  22322. #endif
  22323. rc = SQLITE_OK;
  22324. }else{
  22325. rc = SQLITE_BUSY;
  22326. }
  22327. #endif
  22328. #ifdef SQLITE_DEBUG
  22329. if( rc==SQLITE_OK && p->trace ){
  22330. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  22331. }
  22332. #endif
  22333. return rc;
  22334. }
  22335. /*
  22336. ** The sqlite3_mutex_leave() routine exits a mutex that was
  22337. ** previously entered by the same thread. The behavior
  22338. ** is undefined if the mutex is not currently entered or
  22339. ** is not currently allocated. SQLite will never do either.
  22340. */
  22341. static void pthreadMutexLeave(sqlite3_mutex *p){
  22342. assert( pthreadMutexHeld(p) );
  22343. #if SQLITE_MUTEX_NREF
  22344. p->nRef--;
  22345. if( p->nRef==0 ) p->owner = 0;
  22346. #endif
  22347. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  22348. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22349. if( p->nRef==0 ){
  22350. pthread_mutex_unlock(&p->mutex);
  22351. }
  22352. #else
  22353. pthread_mutex_unlock(&p->mutex);
  22354. #endif
  22355. #ifdef SQLITE_DEBUG
  22356. if( p->trace ){
  22357. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  22358. }
  22359. #endif
  22360. }
  22361. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  22362. static const sqlite3_mutex_methods sMutex = {
  22363. pthreadMutexInit,
  22364. pthreadMutexEnd,
  22365. pthreadMutexAlloc,
  22366. pthreadMutexFree,
  22367. pthreadMutexEnter,
  22368. pthreadMutexTry,
  22369. pthreadMutexLeave,
  22370. #ifdef SQLITE_DEBUG
  22371. pthreadMutexHeld,
  22372. pthreadMutexNotheld
  22373. #else
  22374. 0,
  22375. 0
  22376. #endif
  22377. };
  22378. return &sMutex;
  22379. }
  22380. #endif /* SQLITE_MUTEX_PTHREADS */
  22381. /************** End of mutex_unix.c ******************************************/
  22382. /************** Begin file mutex_w32.c ***************************************/
  22383. /*
  22384. ** 2007 August 14
  22385. **
  22386. ** The author disclaims copyright to this source code. In place of
  22387. ** a legal notice, here is a blessing:
  22388. **
  22389. ** May you do good and not evil.
  22390. ** May you find forgiveness for yourself and forgive others.
  22391. ** May you share freely, never taking more than you give.
  22392. **
  22393. *************************************************************************
  22394. ** This file contains the C functions that implement mutexes for Win32.
  22395. */
  22396. /* #include "sqliteInt.h" */
  22397. #if SQLITE_OS_WIN
  22398. /*
  22399. ** Include code that is common to all os_*.c files
  22400. */
  22401. /************** Include os_common.h in the middle of mutex_w32.c *************/
  22402. /************** Begin file os_common.h ***************************************/
  22403. /*
  22404. ** 2004 May 22
  22405. **
  22406. ** The author disclaims copyright to this source code. In place of
  22407. ** a legal notice, here is a blessing:
  22408. **
  22409. ** May you do good and not evil.
  22410. ** May you find forgiveness for yourself and forgive others.
  22411. ** May you share freely, never taking more than you give.
  22412. **
  22413. ******************************************************************************
  22414. **
  22415. ** This file contains macros and a little bit of code that is common to
  22416. ** all of the platform-specific files (os_*.c) and is #included into those
  22417. ** files.
  22418. **
  22419. ** This file should be #included by the os_*.c files only. It is not a
  22420. ** general purpose header file.
  22421. */
  22422. #ifndef _OS_COMMON_H_
  22423. #define _OS_COMMON_H_
  22424. /*
  22425. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  22426. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  22427. ** switch. The following code should catch this problem at compile-time.
  22428. */
  22429. #ifdef MEMORY_DEBUG
  22430. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  22431. #endif
  22432. /*
  22433. ** Macros for performance tracing. Normally turned off. Only works
  22434. ** on i486 hardware.
  22435. */
  22436. #ifdef SQLITE_PERFORMANCE_TRACE
  22437. /*
  22438. ** hwtime.h contains inline assembler code for implementing
  22439. ** high-performance timing routines.
  22440. */
  22441. /************** Include hwtime.h in the middle of os_common.h ****************/
  22442. /************** Begin file hwtime.h ******************************************/
  22443. /*
  22444. ** 2008 May 27
  22445. **
  22446. ** The author disclaims copyright to this source code. In place of
  22447. ** a legal notice, here is a blessing:
  22448. **
  22449. ** May you do good and not evil.
  22450. ** May you find forgiveness for yourself and forgive others.
  22451. ** May you share freely, never taking more than you give.
  22452. **
  22453. ******************************************************************************
  22454. **
  22455. ** This file contains inline asm code for retrieving "high-performance"
  22456. ** counters for x86 class CPUs.
  22457. */
  22458. #ifndef SQLITE_HWTIME_H
  22459. #define SQLITE_HWTIME_H
  22460. /*
  22461. ** The following routine only works on pentium-class (or newer) processors.
  22462. ** It uses the RDTSC opcode to read the cycle count value out of the
  22463. ** processor and returns that value. This can be used for high-res
  22464. ** profiling.
  22465. */
  22466. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  22467. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  22468. #if defined(__GNUC__)
  22469. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22470. unsigned int lo, hi;
  22471. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  22472. return (sqlite_uint64)hi << 32 | lo;
  22473. }
  22474. #elif defined(_MSC_VER)
  22475. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  22476. __asm {
  22477. rdtsc
  22478. ret ; return value at EDX:EAX
  22479. }
  22480. }
  22481. #endif
  22482. #elif (defined(__GNUC__) && defined(__x86_64__))
  22483. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22484. unsigned long val;
  22485. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  22486. return val;
  22487. }
  22488. #elif (defined(__GNUC__) && defined(__ppc__))
  22489. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22490. unsigned long long retval;
  22491. unsigned long junk;
  22492. __asm__ __volatile__ ("\n\
  22493. 1: mftbu %1\n\
  22494. mftb %L0\n\
  22495. mftbu %0\n\
  22496. cmpw %0,%1\n\
  22497. bne 1b"
  22498. : "=r" (retval), "=r" (junk));
  22499. return retval;
  22500. }
  22501. #else
  22502. #error Need implementation of sqlite3Hwtime() for your platform.
  22503. /*
  22504. ** To compile without implementing sqlite3Hwtime() for your platform,
  22505. ** you can remove the above #error and use the following
  22506. ** stub function. You will lose timing support for many
  22507. ** of the debugging and testing utilities, but it should at
  22508. ** least compile and run.
  22509. */
  22510. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  22511. #endif
  22512. #endif /* !defined(SQLITE_HWTIME_H) */
  22513. /************** End of hwtime.h **********************************************/
  22514. /************** Continuing where we left off in os_common.h ******************/
  22515. static sqlite_uint64 g_start;
  22516. static sqlite_uint64 g_elapsed;
  22517. #define TIMER_START g_start=sqlite3Hwtime()
  22518. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  22519. #define TIMER_ELAPSED g_elapsed
  22520. #else
  22521. #define TIMER_START
  22522. #define TIMER_END
  22523. #define TIMER_ELAPSED ((sqlite_uint64)0)
  22524. #endif
  22525. /*
  22526. ** If we compile with the SQLITE_TEST macro set, then the following block
  22527. ** of code will give us the ability to simulate a disk I/O error. This
  22528. ** is used for testing the I/O recovery logic.
  22529. */
  22530. #if defined(SQLITE_TEST)
  22531. SQLITE_API extern int sqlite3_io_error_hit;
  22532. SQLITE_API extern int sqlite3_io_error_hardhit;
  22533. SQLITE_API extern int sqlite3_io_error_pending;
  22534. SQLITE_API extern int sqlite3_io_error_persist;
  22535. SQLITE_API extern int sqlite3_io_error_benign;
  22536. SQLITE_API extern int sqlite3_diskfull_pending;
  22537. SQLITE_API extern int sqlite3_diskfull;
  22538. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  22539. #define SimulateIOError(CODE) \
  22540. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  22541. || sqlite3_io_error_pending-- == 1 ) \
  22542. { local_ioerr(); CODE; }
  22543. static void local_ioerr(){
  22544. IOTRACE(("IOERR\n"));
  22545. sqlite3_io_error_hit++;
  22546. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  22547. }
  22548. #define SimulateDiskfullError(CODE) \
  22549. if( sqlite3_diskfull_pending ){ \
  22550. if( sqlite3_diskfull_pending == 1 ){ \
  22551. local_ioerr(); \
  22552. sqlite3_diskfull = 1; \
  22553. sqlite3_io_error_hit = 1; \
  22554. CODE; \
  22555. }else{ \
  22556. sqlite3_diskfull_pending--; \
  22557. } \
  22558. }
  22559. #else
  22560. #define SimulateIOErrorBenign(X)
  22561. #define SimulateIOError(A)
  22562. #define SimulateDiskfullError(A)
  22563. #endif /* defined(SQLITE_TEST) */
  22564. /*
  22565. ** When testing, keep a count of the number of open files.
  22566. */
  22567. #if defined(SQLITE_TEST)
  22568. SQLITE_API extern int sqlite3_open_file_count;
  22569. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  22570. #else
  22571. #define OpenCounter(X)
  22572. #endif /* defined(SQLITE_TEST) */
  22573. #endif /* !defined(_OS_COMMON_H_) */
  22574. /************** End of os_common.h *******************************************/
  22575. /************** Continuing where we left off in mutex_w32.c ******************/
  22576. /*
  22577. ** Include the header file for the Windows VFS.
  22578. */
  22579. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  22580. /************** Begin file os_win.h ******************************************/
  22581. /*
  22582. ** 2013 November 25
  22583. **
  22584. ** The author disclaims copyright to this source code. In place of
  22585. ** a legal notice, here is a blessing:
  22586. **
  22587. ** May you do good and not evil.
  22588. ** May you find forgiveness for yourself and forgive others.
  22589. ** May you share freely, never taking more than you give.
  22590. **
  22591. ******************************************************************************
  22592. **
  22593. ** This file contains code that is specific to Windows.
  22594. */
  22595. #ifndef SQLITE_OS_WIN_H
  22596. #define SQLITE_OS_WIN_H
  22597. /*
  22598. ** Include the primary Windows SDK header file.
  22599. */
  22600. #include "windows.h"
  22601. #ifdef __CYGWIN__
  22602. # include <sys/cygwin.h>
  22603. # include <errno.h> /* amalgamator: dontcache */
  22604. #endif
  22605. /*
  22606. ** Determine if we are dealing with Windows NT.
  22607. **
  22608. ** We ought to be able to determine if we are compiling for Windows 9x or
  22609. ** Windows NT using the _WIN32_WINNT macro as follows:
  22610. **
  22611. ** #if defined(_WIN32_WINNT)
  22612. ** # define SQLITE_OS_WINNT 1
  22613. ** #else
  22614. ** # define SQLITE_OS_WINNT 0
  22615. ** #endif
  22616. **
  22617. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  22618. ** it ought to, so the above test does not work. We'll just assume that
  22619. ** everything is Windows NT unless the programmer explicitly says otherwise
  22620. ** by setting SQLITE_OS_WINNT to 0.
  22621. */
  22622. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  22623. # define SQLITE_OS_WINNT 1
  22624. #endif
  22625. /*
  22626. ** Determine if we are dealing with Windows CE - which has a much reduced
  22627. ** API.
  22628. */
  22629. #if defined(_WIN32_WCE)
  22630. # define SQLITE_OS_WINCE 1
  22631. #else
  22632. # define SQLITE_OS_WINCE 0
  22633. #endif
  22634. /*
  22635. ** Determine if we are dealing with WinRT, which provides only a subset of
  22636. ** the full Win32 API.
  22637. */
  22638. #if !defined(SQLITE_OS_WINRT)
  22639. # define SQLITE_OS_WINRT 0
  22640. #endif
  22641. /*
  22642. ** For WinCE, some API function parameters do not appear to be declared as
  22643. ** volatile.
  22644. */
  22645. #if SQLITE_OS_WINCE
  22646. # define SQLITE_WIN32_VOLATILE
  22647. #else
  22648. # define SQLITE_WIN32_VOLATILE volatile
  22649. #endif
  22650. /*
  22651. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  22652. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  22653. */
  22654. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  22655. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  22656. # define SQLITE_OS_WIN_THREADS 1
  22657. #else
  22658. # define SQLITE_OS_WIN_THREADS 0
  22659. #endif
  22660. #endif /* SQLITE_OS_WIN_H */
  22661. /************** End of os_win.h **********************************************/
  22662. /************** Continuing where we left off in mutex_w32.c ******************/
  22663. #endif
  22664. /*
  22665. ** The code in this file is only used if we are compiling multithreaded
  22666. ** on a Win32 system.
  22667. */
  22668. #ifdef SQLITE_MUTEX_W32
  22669. /*
  22670. ** Each recursive mutex is an instance of the following structure.
  22671. */
  22672. struct sqlite3_mutex {
  22673. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  22674. int id; /* Mutex type */
  22675. #ifdef SQLITE_DEBUG
  22676. volatile int nRef; /* Number of enterances */
  22677. volatile DWORD owner; /* Thread holding this mutex */
  22678. volatile int trace; /* True to trace changes */
  22679. #endif
  22680. };
  22681. /*
  22682. ** These are the initializer values used when declaring a "static" mutex
  22683. ** on Win32. It should be noted that all mutexes require initialization
  22684. ** on the Win32 platform.
  22685. */
  22686. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  22687. #ifdef SQLITE_DEBUG
  22688. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  22689. 0L, (DWORD)0, 0 }
  22690. #else
  22691. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  22692. #endif
  22693. #ifdef SQLITE_DEBUG
  22694. /*
  22695. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  22696. ** intended for use only inside assert() statements.
  22697. */
  22698. static int winMutexHeld(sqlite3_mutex *p){
  22699. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  22700. }
  22701. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  22702. return p->nRef==0 || p->owner!=tid;
  22703. }
  22704. static int winMutexNotheld(sqlite3_mutex *p){
  22705. DWORD tid = GetCurrentThreadId();
  22706. return winMutexNotheld2(p, tid);
  22707. }
  22708. #endif
  22709. /*
  22710. ** Try to provide a memory barrier operation, needed for initialization
  22711. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  22712. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  22713. */
  22714. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  22715. #if defined(SQLITE_MEMORY_BARRIER)
  22716. SQLITE_MEMORY_BARRIER;
  22717. #elif defined(__GNUC__)
  22718. __sync_synchronize();
  22719. #elif MSVC_VERSION>=1300
  22720. _ReadWriteBarrier();
  22721. #elif defined(MemoryBarrier)
  22722. MemoryBarrier();
  22723. #endif
  22724. }
  22725. /*
  22726. ** Initialize and deinitialize the mutex subsystem.
  22727. */
  22728. static sqlite3_mutex winMutex_staticMutexes[] = {
  22729. SQLITE3_MUTEX_INITIALIZER,
  22730. SQLITE3_MUTEX_INITIALIZER,
  22731. SQLITE3_MUTEX_INITIALIZER,
  22732. SQLITE3_MUTEX_INITIALIZER,
  22733. SQLITE3_MUTEX_INITIALIZER,
  22734. SQLITE3_MUTEX_INITIALIZER,
  22735. SQLITE3_MUTEX_INITIALIZER,
  22736. SQLITE3_MUTEX_INITIALIZER,
  22737. SQLITE3_MUTEX_INITIALIZER,
  22738. SQLITE3_MUTEX_INITIALIZER,
  22739. SQLITE3_MUTEX_INITIALIZER,
  22740. SQLITE3_MUTEX_INITIALIZER
  22741. };
  22742. static int winMutex_isInit = 0;
  22743. static int winMutex_isNt = -1; /* <0 means "need to query" */
  22744. /* As the winMutexInit() and winMutexEnd() functions are called as part
  22745. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  22746. ** "interlocked" magic used here is probably not strictly necessary.
  22747. */
  22748. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  22749. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  22750. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  22751. static int winMutexInit(void){
  22752. /* The first to increment to 1 does actual initialization */
  22753. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  22754. int i;
  22755. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  22756. #if SQLITE_OS_WINRT
  22757. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  22758. #else
  22759. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  22760. #endif
  22761. }
  22762. winMutex_isInit = 1;
  22763. }else{
  22764. /* Another thread is (in the process of) initializing the static
  22765. ** mutexes */
  22766. while( !winMutex_isInit ){
  22767. sqlite3_win32_sleep(1);
  22768. }
  22769. }
  22770. return SQLITE_OK;
  22771. }
  22772. static int winMutexEnd(void){
  22773. /* The first to decrement to 0 does actual shutdown
  22774. ** (which should be the last to shutdown.) */
  22775. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  22776. if( winMutex_isInit==1 ){
  22777. int i;
  22778. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  22779. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  22780. }
  22781. winMutex_isInit = 0;
  22782. }
  22783. }
  22784. return SQLITE_OK;
  22785. }
  22786. /*
  22787. ** The sqlite3_mutex_alloc() routine allocates a new
  22788. ** mutex and returns a pointer to it. If it returns NULL
  22789. ** that means that a mutex could not be allocated. SQLite
  22790. ** will unwind its stack and return an error. The argument
  22791. ** to sqlite3_mutex_alloc() is one of these integer constants:
  22792. **
  22793. ** <ul>
  22794. ** <li> SQLITE_MUTEX_FAST
  22795. ** <li> SQLITE_MUTEX_RECURSIVE
  22796. ** <li> SQLITE_MUTEX_STATIC_MASTER
  22797. ** <li> SQLITE_MUTEX_STATIC_MEM
  22798. ** <li> SQLITE_MUTEX_STATIC_OPEN
  22799. ** <li> SQLITE_MUTEX_STATIC_PRNG
  22800. ** <li> SQLITE_MUTEX_STATIC_LRU
  22801. ** <li> SQLITE_MUTEX_STATIC_PMEM
  22802. ** <li> SQLITE_MUTEX_STATIC_APP1
  22803. ** <li> SQLITE_MUTEX_STATIC_APP2
  22804. ** <li> SQLITE_MUTEX_STATIC_APP3
  22805. ** <li> SQLITE_MUTEX_STATIC_VFS1
  22806. ** <li> SQLITE_MUTEX_STATIC_VFS2
  22807. ** <li> SQLITE_MUTEX_STATIC_VFS3
  22808. ** </ul>
  22809. **
  22810. ** The first two constants cause sqlite3_mutex_alloc() to create
  22811. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  22812. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  22813. ** The mutex implementation does not need to make a distinction
  22814. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  22815. ** not want to. But SQLite will only request a recursive mutex in
  22816. ** cases where it really needs one. If a faster non-recursive mutex
  22817. ** implementation is available on the host platform, the mutex subsystem
  22818. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  22819. **
  22820. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  22821. ** a pointer to a static preexisting mutex. Six static mutexes are
  22822. ** used by the current version of SQLite. Future versions of SQLite
  22823. ** may add additional static mutexes. Static mutexes are for internal
  22824. ** use by SQLite only. Applications that use SQLite mutexes should
  22825. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  22826. ** SQLITE_MUTEX_RECURSIVE.
  22827. **
  22828. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  22829. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  22830. ** returns a different mutex on every call. But for the static
  22831. ** mutex types, the same mutex is returned on every call that has
  22832. ** the same type number.
  22833. */
  22834. static sqlite3_mutex *winMutexAlloc(int iType){
  22835. sqlite3_mutex *p;
  22836. switch( iType ){
  22837. case SQLITE_MUTEX_FAST:
  22838. case SQLITE_MUTEX_RECURSIVE: {
  22839. p = sqlite3MallocZero( sizeof(*p) );
  22840. if( p ){
  22841. p->id = iType;
  22842. #ifdef SQLITE_DEBUG
  22843. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  22844. p->trace = 1;
  22845. #endif
  22846. #endif
  22847. #if SQLITE_OS_WINRT
  22848. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  22849. #else
  22850. InitializeCriticalSection(&p->mutex);
  22851. #endif
  22852. }
  22853. break;
  22854. }
  22855. default: {
  22856. #ifdef SQLITE_ENABLE_API_ARMOR
  22857. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  22858. (void)SQLITE_MISUSE_BKPT;
  22859. return 0;
  22860. }
  22861. #endif
  22862. p = &winMutex_staticMutexes[iType-2];
  22863. p->id = iType;
  22864. #ifdef SQLITE_DEBUG
  22865. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  22866. p->trace = 1;
  22867. #endif
  22868. #endif
  22869. break;
  22870. }
  22871. }
  22872. return p;
  22873. }
  22874. /*
  22875. ** This routine deallocates a previously
  22876. ** allocated mutex. SQLite is careful to deallocate every
  22877. ** mutex that it allocates.
  22878. */
  22879. static void winMutexFree(sqlite3_mutex *p){
  22880. assert( p );
  22881. assert( p->nRef==0 && p->owner==0 );
  22882. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  22883. DeleteCriticalSection(&p->mutex);
  22884. sqlite3_free(p);
  22885. }else{
  22886. #ifdef SQLITE_ENABLE_API_ARMOR
  22887. (void)SQLITE_MISUSE_BKPT;
  22888. #endif
  22889. }
  22890. }
  22891. /*
  22892. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  22893. ** to enter a mutex. If another thread is already within the mutex,
  22894. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  22895. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  22896. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  22897. ** be entered multiple times by the same thread. In such cases the,
  22898. ** mutex must be exited an equal number of times before another thread
  22899. ** can enter. If the same thread tries to enter any other kind of mutex
  22900. ** more than once, the behavior is undefined.
  22901. */
  22902. static void winMutexEnter(sqlite3_mutex *p){
  22903. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22904. DWORD tid = GetCurrentThreadId();
  22905. #endif
  22906. #ifdef SQLITE_DEBUG
  22907. assert( p );
  22908. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  22909. #else
  22910. assert( p );
  22911. #endif
  22912. assert( winMutex_isInit==1 );
  22913. EnterCriticalSection(&p->mutex);
  22914. #ifdef SQLITE_DEBUG
  22915. assert( p->nRef>0 || p->owner==0 );
  22916. p->owner = tid;
  22917. p->nRef++;
  22918. if( p->trace ){
  22919. OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  22920. tid, p->id, p, p->trace, p->nRef));
  22921. }
  22922. #endif
  22923. }
  22924. static int winMutexTry(sqlite3_mutex *p){
  22925. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22926. DWORD tid = GetCurrentThreadId();
  22927. #endif
  22928. int rc = SQLITE_BUSY;
  22929. assert( p );
  22930. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  22931. /*
  22932. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  22933. ** is used it is merely an optimization. So it is OK for it to always
  22934. ** fail.
  22935. **
  22936. ** The TryEnterCriticalSection() interface is only available on WinNT.
  22937. ** And some windows compilers complain if you try to use it without
  22938. ** first doing some #defines that prevent SQLite from building on Win98.
  22939. ** For that reason, we will omit this optimization for now. See
  22940. ** ticket #2685.
  22941. */
  22942. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  22943. assert( winMutex_isInit==1 );
  22944. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  22945. if( winMutex_isNt<0 ){
  22946. winMutex_isNt = sqlite3_win32_is_nt();
  22947. }
  22948. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  22949. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  22950. #ifdef SQLITE_DEBUG
  22951. p->owner = tid;
  22952. p->nRef++;
  22953. #endif
  22954. rc = SQLITE_OK;
  22955. }
  22956. #else
  22957. UNUSED_PARAMETER(p);
  22958. #endif
  22959. #ifdef SQLITE_DEBUG
  22960. if( p->trace ){
  22961. OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  22962. tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  22963. }
  22964. #endif
  22965. return rc;
  22966. }
  22967. /*
  22968. ** The sqlite3_mutex_leave() routine exits a mutex that was
  22969. ** previously entered by the same thread. The behavior
  22970. ** is undefined if the mutex is not currently entered or
  22971. ** is not currently allocated. SQLite will never do either.
  22972. */
  22973. static void winMutexLeave(sqlite3_mutex *p){
  22974. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22975. DWORD tid = GetCurrentThreadId();
  22976. #endif
  22977. assert( p );
  22978. #ifdef SQLITE_DEBUG
  22979. assert( p->nRef>0 );
  22980. assert( p->owner==tid );
  22981. p->nRef--;
  22982. if( p->nRef==0 ) p->owner = 0;
  22983. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  22984. #endif
  22985. assert( winMutex_isInit==1 );
  22986. LeaveCriticalSection(&p->mutex);
  22987. #ifdef SQLITE_DEBUG
  22988. if( p->trace ){
  22989. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  22990. tid, p->id, p, p->trace, p->nRef));
  22991. }
  22992. #endif
  22993. }
  22994. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  22995. static const sqlite3_mutex_methods sMutex = {
  22996. winMutexInit,
  22997. winMutexEnd,
  22998. winMutexAlloc,
  22999. winMutexFree,
  23000. winMutexEnter,
  23001. winMutexTry,
  23002. winMutexLeave,
  23003. #ifdef SQLITE_DEBUG
  23004. winMutexHeld,
  23005. winMutexNotheld
  23006. #else
  23007. 0,
  23008. 0
  23009. #endif
  23010. };
  23011. return &sMutex;
  23012. }
  23013. #endif /* SQLITE_MUTEX_W32 */
  23014. /************** End of mutex_w32.c *******************************************/
  23015. /************** Begin file malloc.c ******************************************/
  23016. /*
  23017. ** 2001 September 15
  23018. **
  23019. ** The author disclaims copyright to this source code. In place of
  23020. ** a legal notice, here is a blessing:
  23021. **
  23022. ** May you do good and not evil.
  23023. ** May you find forgiveness for yourself and forgive others.
  23024. ** May you share freely, never taking more than you give.
  23025. **
  23026. *************************************************************************
  23027. **
  23028. ** Memory allocation functions used throughout sqlite.
  23029. */
  23030. /* #include "sqliteInt.h" */
  23031. /* #include <stdarg.h> */
  23032. /*
  23033. ** Attempt to release up to n bytes of non-essential memory currently
  23034. ** held by SQLite. An example of non-essential memory is memory used to
  23035. ** cache database pages that are not currently in use.
  23036. */
  23037. SQLITE_API int sqlite3_release_memory(int n){
  23038. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  23039. return sqlite3PcacheReleaseMemory(n);
  23040. #else
  23041. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  23042. ** is a no-op returning zero if SQLite is not compiled with
  23043. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  23044. UNUSED_PARAMETER(n);
  23045. return 0;
  23046. #endif
  23047. }
  23048. /*
  23049. ** An instance of the following object records the location of
  23050. ** each unused scratch buffer.
  23051. */
  23052. typedef struct ScratchFreeslot {
  23053. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  23054. } ScratchFreeslot;
  23055. /*
  23056. ** State information local to the memory allocation subsystem.
  23057. */
  23058. static SQLITE_WSD struct Mem0Global {
  23059. sqlite3_mutex *mutex; /* Mutex to serialize access */
  23060. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  23061. /*
  23062. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  23063. ** (so that a range test can be used to determine if an allocation
  23064. ** being freed came from pScratch) and a pointer to the list of
  23065. ** unused scratch allocations.
  23066. */
  23067. void *pScratchEnd;
  23068. ScratchFreeslot *pScratchFree;
  23069. u32 nScratchFree;
  23070. /*
  23071. ** True if heap is nearly "full" where "full" is defined by the
  23072. ** sqlite3_soft_heap_limit() setting.
  23073. */
  23074. int nearlyFull;
  23075. } mem0 = { 0, 0, 0, 0, 0, 0 };
  23076. #define mem0 GLOBAL(struct Mem0Global, mem0)
  23077. /*
  23078. ** Return the memory allocator mutex. sqlite3_status() needs it.
  23079. */
  23080. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  23081. return mem0.mutex;
  23082. }
  23083. #ifndef SQLITE_OMIT_DEPRECATED
  23084. /*
  23085. ** Deprecated external interface. It used to set an alarm callback
  23086. ** that was invoked when memory usage grew too large. Now it is a
  23087. ** no-op.
  23088. */
  23089. SQLITE_API int sqlite3_memory_alarm(
  23090. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  23091. void *pArg,
  23092. sqlite3_int64 iThreshold
  23093. ){
  23094. (void)xCallback;
  23095. (void)pArg;
  23096. (void)iThreshold;
  23097. return SQLITE_OK;
  23098. }
  23099. #endif
  23100. /*
  23101. ** Set the soft heap-size limit for the library. Passing a zero or
  23102. ** negative value indicates no limit.
  23103. */
  23104. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  23105. sqlite3_int64 priorLimit;
  23106. sqlite3_int64 excess;
  23107. sqlite3_int64 nUsed;
  23108. #ifndef SQLITE_OMIT_AUTOINIT
  23109. int rc = sqlite3_initialize();
  23110. if( rc ) return -1;
  23111. #endif
  23112. sqlite3_mutex_enter(mem0.mutex);
  23113. priorLimit = mem0.alarmThreshold;
  23114. if( n<0 ){
  23115. sqlite3_mutex_leave(mem0.mutex);
  23116. return priorLimit;
  23117. }
  23118. mem0.alarmThreshold = n;
  23119. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  23120. mem0.nearlyFull = (n>0 && n<=nUsed);
  23121. sqlite3_mutex_leave(mem0.mutex);
  23122. excess = sqlite3_memory_used() - n;
  23123. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  23124. return priorLimit;
  23125. }
  23126. SQLITE_API void sqlite3_soft_heap_limit(int n){
  23127. if( n<0 ) n = 0;
  23128. sqlite3_soft_heap_limit64(n);
  23129. }
  23130. /*
  23131. ** Initialize the memory allocation subsystem.
  23132. */
  23133. SQLITE_PRIVATE int sqlite3MallocInit(void){
  23134. int rc;
  23135. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  23136. sqlite3MemSetDefault();
  23137. }
  23138. memset(&mem0, 0, sizeof(mem0));
  23139. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  23140. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  23141. && sqlite3GlobalConfig.nScratch>0 ){
  23142. int i, n, sz;
  23143. ScratchFreeslot *pSlot;
  23144. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  23145. sqlite3GlobalConfig.szScratch = sz;
  23146. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  23147. n = sqlite3GlobalConfig.nScratch;
  23148. mem0.pScratchFree = pSlot;
  23149. mem0.nScratchFree = n;
  23150. for(i=0; i<n-1; i++){
  23151. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  23152. pSlot = pSlot->pNext;
  23153. }
  23154. pSlot->pNext = 0;
  23155. mem0.pScratchEnd = (void*)&pSlot[1];
  23156. }else{
  23157. mem0.pScratchEnd = 0;
  23158. sqlite3GlobalConfig.pScratch = 0;
  23159. sqlite3GlobalConfig.szScratch = 0;
  23160. sqlite3GlobalConfig.nScratch = 0;
  23161. }
  23162. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  23163. || sqlite3GlobalConfig.nPage<=0 ){
  23164. sqlite3GlobalConfig.pPage = 0;
  23165. sqlite3GlobalConfig.szPage = 0;
  23166. }
  23167. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  23168. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  23169. return rc;
  23170. }
  23171. /*
  23172. ** Return true if the heap is currently under memory pressure - in other
  23173. ** words if the amount of heap used is close to the limit set by
  23174. ** sqlite3_soft_heap_limit().
  23175. */
  23176. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  23177. return mem0.nearlyFull;
  23178. }
  23179. /*
  23180. ** Deinitialize the memory allocation subsystem.
  23181. */
  23182. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  23183. if( sqlite3GlobalConfig.m.xShutdown ){
  23184. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  23185. }
  23186. memset(&mem0, 0, sizeof(mem0));
  23187. }
  23188. /*
  23189. ** Return the amount of memory currently checked out.
  23190. */
  23191. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  23192. sqlite3_int64 res, mx;
  23193. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  23194. return res;
  23195. }
  23196. /*
  23197. ** Return the maximum amount of memory that has ever been
  23198. ** checked out since either the beginning of this process
  23199. ** or since the most recent reset.
  23200. */
  23201. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  23202. sqlite3_int64 res, mx;
  23203. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  23204. return mx;
  23205. }
  23206. /*
  23207. ** Trigger the alarm
  23208. */
  23209. static void sqlite3MallocAlarm(int nByte){
  23210. if( mem0.alarmThreshold<=0 ) return;
  23211. sqlite3_mutex_leave(mem0.mutex);
  23212. sqlite3_release_memory(nByte);
  23213. sqlite3_mutex_enter(mem0.mutex);
  23214. }
  23215. /*
  23216. ** Do a memory allocation with statistics and alarms. Assume the
  23217. ** lock is already held.
  23218. */
  23219. static void mallocWithAlarm(int n, void **pp){
  23220. void *p;
  23221. int nFull;
  23222. assert( sqlite3_mutex_held(mem0.mutex) );
  23223. assert( n>0 );
  23224. /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
  23225. ** implementation of malloc_good_size(), which must be called in debug
  23226. ** mode and specifically when the DMD "Dark Matter Detector" is enabled
  23227. ** or else a crash results. Hence, do not attempt to optimize out the
  23228. ** following xRoundup() call. */
  23229. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  23230. #ifdef SQLITE_MAX_MEMORY
  23231. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
  23232. *pp = 0;
  23233. return;
  23234. }
  23235. #endif
  23236. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  23237. if( mem0.alarmThreshold>0 ){
  23238. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  23239. if( nUsed >= mem0.alarmThreshold - nFull ){
  23240. mem0.nearlyFull = 1;
  23241. sqlite3MallocAlarm(nFull);
  23242. }else{
  23243. mem0.nearlyFull = 0;
  23244. }
  23245. }
  23246. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  23247. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  23248. if( p==0 && mem0.alarmThreshold>0 ){
  23249. sqlite3MallocAlarm(nFull);
  23250. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  23251. }
  23252. #endif
  23253. if( p ){
  23254. nFull = sqlite3MallocSize(p);
  23255. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  23256. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  23257. }
  23258. *pp = p;
  23259. }
  23260. /*
  23261. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  23262. ** assumes the memory subsystem has already been initialized.
  23263. */
  23264. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  23265. void *p;
  23266. if( n==0 || n>=0x7fffff00 ){
  23267. /* A memory allocation of a number of bytes which is near the maximum
  23268. ** signed integer value might cause an integer overflow inside of the
  23269. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  23270. ** 255 bytes of overhead. SQLite itself will never use anything near
  23271. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  23272. p = 0;
  23273. }else if( sqlite3GlobalConfig.bMemstat ){
  23274. sqlite3_mutex_enter(mem0.mutex);
  23275. mallocWithAlarm((int)n, &p);
  23276. sqlite3_mutex_leave(mem0.mutex);
  23277. }else{
  23278. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  23279. }
  23280. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  23281. return p;
  23282. }
  23283. /*
  23284. ** This version of the memory allocation is for use by the application.
  23285. ** First make sure the memory subsystem is initialized, then do the
  23286. ** allocation.
  23287. */
  23288. SQLITE_API void *sqlite3_malloc(int n){
  23289. #ifndef SQLITE_OMIT_AUTOINIT
  23290. if( sqlite3_initialize() ) return 0;
  23291. #endif
  23292. return n<=0 ? 0 : sqlite3Malloc(n);
  23293. }
  23294. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  23295. #ifndef SQLITE_OMIT_AUTOINIT
  23296. if( sqlite3_initialize() ) return 0;
  23297. #endif
  23298. return sqlite3Malloc(n);
  23299. }
  23300. /*
  23301. ** Each thread may only have a single outstanding allocation from
  23302. ** xScratchMalloc(). We verify this constraint in the single-threaded
  23303. ** case by setting scratchAllocOut to 1 when an allocation
  23304. ** is outstanding clearing it when the allocation is freed.
  23305. */
  23306. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  23307. static int scratchAllocOut = 0;
  23308. #endif
  23309. /*
  23310. ** Allocate memory that is to be used and released right away.
  23311. ** This routine is similar to alloca() in that it is not intended
  23312. ** for situations where the memory might be held long-term. This
  23313. ** routine is intended to get memory to old large transient data
  23314. ** structures that would not normally fit on the stack of an
  23315. ** embedded processor.
  23316. */
  23317. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  23318. void *p;
  23319. assert( n>0 );
  23320. sqlite3_mutex_enter(mem0.mutex);
  23321. sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
  23322. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  23323. p = mem0.pScratchFree;
  23324. mem0.pScratchFree = mem0.pScratchFree->pNext;
  23325. mem0.nScratchFree--;
  23326. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
  23327. sqlite3_mutex_leave(mem0.mutex);
  23328. }else{
  23329. sqlite3_mutex_leave(mem0.mutex);
  23330. p = sqlite3Malloc(n);
  23331. if( sqlite3GlobalConfig.bMemstat && p ){
  23332. sqlite3_mutex_enter(mem0.mutex);
  23333. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
  23334. sqlite3_mutex_leave(mem0.mutex);
  23335. }
  23336. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  23337. }
  23338. assert( sqlite3_mutex_notheld(mem0.mutex) );
  23339. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  23340. /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
  23341. ** buffers per thread.
  23342. **
  23343. ** This can only be checked in single-threaded mode.
  23344. */
  23345. assert( scratchAllocOut==0 );
  23346. if( p ) scratchAllocOut++;
  23347. #endif
  23348. return p;
  23349. }
  23350. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  23351. if( p ){
  23352. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  23353. /* Verify that no more than two scratch allocation per thread
  23354. ** is outstanding at one time. (This is only checked in the
  23355. ** single-threaded case since checking in the multi-threaded case
  23356. ** would be much more complicated.) */
  23357. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  23358. scratchAllocOut--;
  23359. #endif
  23360. if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
  23361. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  23362. ScratchFreeslot *pSlot;
  23363. pSlot = (ScratchFreeslot*)p;
  23364. sqlite3_mutex_enter(mem0.mutex);
  23365. pSlot->pNext = mem0.pScratchFree;
  23366. mem0.pScratchFree = pSlot;
  23367. mem0.nScratchFree++;
  23368. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  23369. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
  23370. sqlite3_mutex_leave(mem0.mutex);
  23371. }else{
  23372. /* Release memory back to the heap */
  23373. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  23374. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
  23375. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  23376. if( sqlite3GlobalConfig.bMemstat ){
  23377. int iSize = sqlite3MallocSize(p);
  23378. sqlite3_mutex_enter(mem0.mutex);
  23379. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
  23380. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
  23381. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  23382. sqlite3GlobalConfig.m.xFree(p);
  23383. sqlite3_mutex_leave(mem0.mutex);
  23384. }else{
  23385. sqlite3GlobalConfig.m.xFree(p);
  23386. }
  23387. }
  23388. }
  23389. }
  23390. /*
  23391. ** TRUE if p is a lookaside memory allocation from db
  23392. */
  23393. #ifndef SQLITE_OMIT_LOOKASIDE
  23394. static int isLookaside(sqlite3 *db, void *p){
  23395. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  23396. }
  23397. #else
  23398. #define isLookaside(A,B) 0
  23399. #endif
  23400. /*
  23401. ** Return the size of a memory allocation previously obtained from
  23402. ** sqlite3Malloc() or sqlite3_malloc().
  23403. */
  23404. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  23405. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23406. return sqlite3GlobalConfig.m.xSize(p);
  23407. }
  23408. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  23409. assert( p!=0 );
  23410. if( db==0 || !isLookaside(db,p) ){
  23411. #ifdef SQLITE_DEBUG
  23412. if( db==0 ){
  23413. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  23414. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23415. }else{
  23416. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23417. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23418. }
  23419. #endif
  23420. return sqlite3GlobalConfig.m.xSize(p);
  23421. }else{
  23422. assert( sqlite3_mutex_held(db->mutex) );
  23423. return db->lookaside.sz;
  23424. }
  23425. }
  23426. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  23427. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  23428. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23429. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  23430. }
  23431. /*
  23432. ** Free memory previously obtained from sqlite3Malloc().
  23433. */
  23434. SQLITE_API void sqlite3_free(void *p){
  23435. if( p==0 ) return; /* IMP: R-49053-54554 */
  23436. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23437. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  23438. if( sqlite3GlobalConfig.bMemstat ){
  23439. sqlite3_mutex_enter(mem0.mutex);
  23440. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  23441. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  23442. sqlite3GlobalConfig.m.xFree(p);
  23443. sqlite3_mutex_leave(mem0.mutex);
  23444. }else{
  23445. sqlite3GlobalConfig.m.xFree(p);
  23446. }
  23447. }
  23448. /*
  23449. ** Add the size of memory allocation "p" to the count in
  23450. ** *db->pnBytesFreed.
  23451. */
  23452. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  23453. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  23454. }
  23455. /*
  23456. ** Free memory that might be associated with a particular database
  23457. ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
  23458. ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
  23459. */
  23460. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
  23461. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  23462. assert( p!=0 );
  23463. if( db ){
  23464. if( db->pnBytesFreed ){
  23465. measureAllocationSize(db, p);
  23466. return;
  23467. }
  23468. if( isLookaside(db, p) ){
  23469. LookasideSlot *pBuf = (LookasideSlot*)p;
  23470. #ifdef SQLITE_DEBUG
  23471. /* Trash all content in the buffer being freed */
  23472. memset(p, 0xaa, db->lookaside.sz);
  23473. #endif
  23474. pBuf->pNext = db->lookaside.pFree;
  23475. db->lookaside.pFree = pBuf;
  23476. db->lookaside.nOut--;
  23477. return;
  23478. }
  23479. }
  23480. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23481. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23482. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  23483. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  23484. sqlite3_free(p);
  23485. }
  23486. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  23487. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  23488. if( p ) sqlite3DbFreeNN(db, p);
  23489. }
  23490. /*
  23491. ** Change the size of an existing memory allocation
  23492. */
  23493. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  23494. int nOld, nNew, nDiff;
  23495. void *pNew;
  23496. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  23497. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  23498. if( pOld==0 ){
  23499. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  23500. }
  23501. if( nBytes==0 ){
  23502. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  23503. return 0;
  23504. }
  23505. if( nBytes>=0x7fffff00 ){
  23506. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  23507. return 0;
  23508. }
  23509. nOld = sqlite3MallocSize(pOld);
  23510. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  23511. ** argument to xRealloc is always a value returned by a prior call to
  23512. ** xRoundup. */
  23513. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  23514. if( nOld==nNew ){
  23515. pNew = pOld;
  23516. }else if( sqlite3GlobalConfig.bMemstat ){
  23517. sqlite3_mutex_enter(mem0.mutex);
  23518. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  23519. nDiff = nNew - nOld;
  23520. if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  23521. mem0.alarmThreshold-nDiff ){
  23522. sqlite3MallocAlarm(nDiff);
  23523. }
  23524. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  23525. if( pNew==0 && mem0.alarmThreshold>0 ){
  23526. sqlite3MallocAlarm((int)nBytes);
  23527. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  23528. }
  23529. if( pNew ){
  23530. nNew = sqlite3MallocSize(pNew);
  23531. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  23532. }
  23533. sqlite3_mutex_leave(mem0.mutex);
  23534. }else{
  23535. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  23536. }
  23537. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  23538. return pNew;
  23539. }
  23540. /*
  23541. ** The public interface to sqlite3Realloc. Make sure that the memory
  23542. ** subsystem is initialized prior to invoking sqliteRealloc.
  23543. */
  23544. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  23545. #ifndef SQLITE_OMIT_AUTOINIT
  23546. if( sqlite3_initialize() ) return 0;
  23547. #endif
  23548. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  23549. return sqlite3Realloc(pOld, n);
  23550. }
  23551. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  23552. #ifndef SQLITE_OMIT_AUTOINIT
  23553. if( sqlite3_initialize() ) return 0;
  23554. #endif
  23555. return sqlite3Realloc(pOld, n);
  23556. }
  23557. /*
  23558. ** Allocate and zero memory.
  23559. */
  23560. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  23561. void *p = sqlite3Malloc(n);
  23562. if( p ){
  23563. memset(p, 0, (size_t)n);
  23564. }
  23565. return p;
  23566. }
  23567. /*
  23568. ** Allocate and zero memory. If the allocation fails, make
  23569. ** the mallocFailed flag in the connection pointer.
  23570. */
  23571. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  23572. void *p;
  23573. testcase( db==0 );
  23574. p = sqlite3DbMallocRaw(db, n);
  23575. if( p ) memset(p, 0, (size_t)n);
  23576. return p;
  23577. }
  23578. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  23579. ** slower case when the allocation cannot be fulfilled using lookaside.
  23580. */
  23581. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  23582. void *p;
  23583. assert( db!=0 );
  23584. p = sqlite3Malloc(n);
  23585. if( !p ) sqlite3OomFault(db);
  23586. sqlite3MemdebugSetType(p,
  23587. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  23588. return p;
  23589. }
  23590. /*
  23591. ** Allocate memory, either lookaside (if possible) or heap.
  23592. ** If the allocation fails, set the mallocFailed flag in
  23593. ** the connection pointer.
  23594. **
  23595. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  23596. ** failure on the same database connection) then always return 0.
  23597. ** Hence for a particular database connection, once malloc starts
  23598. ** failing, it fails consistently until mallocFailed is reset.
  23599. ** This is an important assumption. There are many places in the
  23600. ** code that do things like this:
  23601. **
  23602. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  23603. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  23604. ** if( b ) a[10] = 9;
  23605. **
  23606. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  23607. ** that all prior mallocs (ex: "a") worked too.
  23608. **
  23609. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  23610. ** not a NULL pointer.
  23611. */
  23612. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  23613. void *p;
  23614. if( db ) return sqlite3DbMallocRawNN(db, n);
  23615. p = sqlite3Malloc(n);
  23616. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  23617. return p;
  23618. }
  23619. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  23620. #ifndef SQLITE_OMIT_LOOKASIDE
  23621. LookasideSlot *pBuf;
  23622. assert( db!=0 );
  23623. assert( sqlite3_mutex_held(db->mutex) );
  23624. assert( db->pnBytesFreed==0 );
  23625. if( db->lookaside.bDisable==0 ){
  23626. assert( db->mallocFailed==0 );
  23627. if( n>db->lookaside.sz ){
  23628. db->lookaside.anStat[1]++;
  23629. }else if( (pBuf = db->lookaside.pFree)==0 ){
  23630. db->lookaside.anStat[2]++;
  23631. }else{
  23632. db->lookaside.pFree = pBuf->pNext;
  23633. db->lookaside.nOut++;
  23634. db->lookaside.anStat[0]++;
  23635. if( db->lookaside.nOut>db->lookaside.mxOut ){
  23636. db->lookaside.mxOut = db->lookaside.nOut;
  23637. }
  23638. return (void*)pBuf;
  23639. }
  23640. }else if( db->mallocFailed ){
  23641. return 0;
  23642. }
  23643. #else
  23644. assert( db!=0 );
  23645. assert( sqlite3_mutex_held(db->mutex) );
  23646. assert( db->pnBytesFreed==0 );
  23647. if( db->mallocFailed ){
  23648. return 0;
  23649. }
  23650. #endif
  23651. return dbMallocRawFinish(db, n);
  23652. }
  23653. /* Forward declaration */
  23654. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  23655. /*
  23656. ** Resize the block of memory pointed to by p to n bytes. If the
  23657. ** resize fails, set the mallocFailed flag in the connection object.
  23658. */
  23659. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  23660. assert( db!=0 );
  23661. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  23662. assert( sqlite3_mutex_held(db->mutex) );
  23663. if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
  23664. return dbReallocFinish(db, p, n);
  23665. }
  23666. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  23667. void *pNew = 0;
  23668. assert( db!=0 );
  23669. assert( p!=0 );
  23670. if( db->mallocFailed==0 ){
  23671. if( isLookaside(db, p) ){
  23672. pNew = sqlite3DbMallocRawNN(db, n);
  23673. if( pNew ){
  23674. memcpy(pNew, p, db->lookaside.sz);
  23675. sqlite3DbFree(db, p);
  23676. }
  23677. }else{
  23678. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23679. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23680. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  23681. pNew = sqlite3_realloc64(p, n);
  23682. if( !pNew ){
  23683. sqlite3OomFault(db);
  23684. }
  23685. sqlite3MemdebugSetType(pNew,
  23686. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  23687. }
  23688. }
  23689. return pNew;
  23690. }
  23691. /*
  23692. ** Attempt to reallocate p. If the reallocation fails, then free p
  23693. ** and set the mallocFailed flag in the database connection.
  23694. */
  23695. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  23696. void *pNew;
  23697. pNew = sqlite3DbRealloc(db, p, n);
  23698. if( !pNew ){
  23699. sqlite3DbFree(db, p);
  23700. }
  23701. return pNew;
  23702. }
  23703. /*
  23704. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  23705. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  23706. ** is because when memory debugging is turned on, these two functions are
  23707. ** called via macros that record the current file and line number in the
  23708. ** ThreadData structure.
  23709. */
  23710. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  23711. char *zNew;
  23712. size_t n;
  23713. if( z==0 ){
  23714. return 0;
  23715. }
  23716. n = strlen(z) + 1;
  23717. zNew = sqlite3DbMallocRaw(db, n);
  23718. if( zNew ){
  23719. memcpy(zNew, z, n);
  23720. }
  23721. return zNew;
  23722. }
  23723. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  23724. char *zNew;
  23725. assert( db!=0 );
  23726. if( z==0 ){
  23727. return 0;
  23728. }
  23729. assert( (n&0x7fffffff)==n );
  23730. zNew = sqlite3DbMallocRawNN(db, n+1);
  23731. if( zNew ){
  23732. memcpy(zNew, z, (size_t)n);
  23733. zNew[n] = 0;
  23734. }
  23735. return zNew;
  23736. }
  23737. /*
  23738. ** Free any prior content in *pz and replace it with a copy of zNew.
  23739. */
  23740. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  23741. sqlite3DbFree(db, *pz);
  23742. *pz = sqlite3DbStrDup(db, zNew);
  23743. }
  23744. /*
  23745. ** Call this routine to record the fact that an OOM (out-of-memory) error
  23746. ** has happened. This routine will set db->mallocFailed, and also
  23747. ** temporarily disable the lookaside memory allocator and interrupt
  23748. ** any running VDBEs.
  23749. */
  23750. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  23751. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  23752. db->mallocFailed = 1;
  23753. if( db->nVdbeExec>0 ){
  23754. db->u1.isInterrupted = 1;
  23755. }
  23756. db->lookaside.bDisable++;
  23757. }
  23758. }
  23759. /*
  23760. ** This routine reactivates the memory allocator and clears the
  23761. ** db->mallocFailed flag as necessary.
  23762. **
  23763. ** The memory allocator is not restarted if there are running
  23764. ** VDBEs.
  23765. */
  23766. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  23767. if( db->mallocFailed && db->nVdbeExec==0 ){
  23768. db->mallocFailed = 0;
  23769. db->u1.isInterrupted = 0;
  23770. assert( db->lookaside.bDisable>0 );
  23771. db->lookaside.bDisable--;
  23772. }
  23773. }
  23774. /*
  23775. ** Take actions at the end of an API call to indicate an OOM error
  23776. */
  23777. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  23778. sqlite3OomClear(db);
  23779. sqlite3Error(db, SQLITE_NOMEM);
  23780. return SQLITE_NOMEM_BKPT;
  23781. }
  23782. /*
  23783. ** This function must be called before exiting any API function (i.e.
  23784. ** returning control to the user) that has called sqlite3_malloc or
  23785. ** sqlite3_realloc.
  23786. **
  23787. ** The returned value is normally a copy of the second argument to this
  23788. ** function. However, if a malloc() failure has occurred since the previous
  23789. ** invocation SQLITE_NOMEM is returned instead.
  23790. **
  23791. ** If an OOM as occurred, then the connection error-code (the value
  23792. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  23793. */
  23794. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  23795. /* If the db handle must hold the connection handle mutex here.
  23796. ** Otherwise the read (and possible write) of db->mallocFailed
  23797. ** is unsafe, as is the call to sqlite3Error().
  23798. */
  23799. assert( db!=0 );
  23800. assert( sqlite3_mutex_held(db->mutex) );
  23801. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  23802. return apiOomError(db);
  23803. }
  23804. return rc & db->errMask;
  23805. }
  23806. /************** End of malloc.c **********************************************/
  23807. /************** Begin file printf.c ******************************************/
  23808. /*
  23809. ** The "printf" code that follows dates from the 1980's. It is in
  23810. ** the public domain.
  23811. **
  23812. **************************************************************************
  23813. **
  23814. ** This file contains code for a set of "printf"-like routines. These
  23815. ** routines format strings much like the printf() from the standard C
  23816. ** library, though the implementation here has enhancements to support
  23817. ** SQLite.
  23818. */
  23819. /* #include "sqliteInt.h" */
  23820. /*
  23821. ** Conversion types fall into various categories as defined by the
  23822. ** following enumeration.
  23823. */
  23824. #define etRADIX 0 /* non-decimal integer types. %x %o */
  23825. #define etFLOAT 1 /* Floating point. %f */
  23826. #define etEXP 2 /* Exponentional notation. %e and %E */
  23827. #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
  23828. #define etSIZE 4 /* Return number of characters processed so far. %n */
  23829. #define etSTRING 5 /* Strings. %s */
  23830. #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
  23831. #define etPERCENT 7 /* Percent symbol. %% */
  23832. #define etCHARX 8 /* Characters. %c */
  23833. /* The rest are extensions, not normally found in printf() */
  23834. #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
  23835. #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
  23836. NULL pointers replaced by SQL NULL. %Q */
  23837. #define etTOKEN 11 /* a pointer to a Token structure */
  23838. #define etSRCLIST 12 /* a pointer to a SrcList */
  23839. #define etPOINTER 13 /* The %p conversion */
  23840. #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
  23841. #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  23842. #define etDECIMAL 16 /* %d or %u, but not %x, %o */
  23843. #define etINVALID 17 /* Any unrecognized conversion type */
  23844. /*
  23845. ** An "etByte" is an 8-bit unsigned value.
  23846. */
  23847. typedef unsigned char etByte;
  23848. /*
  23849. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  23850. ** by an instance of the following structure
  23851. */
  23852. typedef struct et_info { /* Information about each format field */
  23853. char fmttype; /* The format field code letter */
  23854. etByte base; /* The base for radix conversion */
  23855. etByte flags; /* One or more of FLAG_ constants below */
  23856. etByte type; /* Conversion paradigm */
  23857. etByte charset; /* Offset into aDigits[] of the digits string */
  23858. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  23859. } et_info;
  23860. /*
  23861. ** Allowed values for et_info.flags
  23862. */
  23863. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  23864. #define FLAG_STRING 4 /* Allow infinite precision */
  23865. /*
  23866. ** The following table is searched linearly, so it is good to put the
  23867. ** most frequently used conversion types first.
  23868. */
  23869. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  23870. static const char aPrefix[] = "-x0\000X0";
  23871. static const et_info fmtinfo[] = {
  23872. { 'd', 10, 1, etDECIMAL, 0, 0 },
  23873. { 's', 0, 4, etSTRING, 0, 0 },
  23874. { 'g', 0, 1, etGENERIC, 30, 0 },
  23875. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  23876. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  23877. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  23878. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  23879. { 'c', 0, 0, etCHARX, 0, 0 },
  23880. { 'o', 8, 0, etRADIX, 0, 2 },
  23881. { 'u', 10, 0, etDECIMAL, 0, 0 },
  23882. { 'x', 16, 0, etRADIX, 16, 1 },
  23883. { 'X', 16, 0, etRADIX, 0, 4 },
  23884. #ifndef SQLITE_OMIT_FLOATING_POINT
  23885. { 'f', 0, 1, etFLOAT, 0, 0 },
  23886. { 'e', 0, 1, etEXP, 30, 0 },
  23887. { 'E', 0, 1, etEXP, 14, 0 },
  23888. { 'G', 0, 1, etGENERIC, 14, 0 },
  23889. #endif
  23890. { 'i', 10, 1, etDECIMAL, 0, 0 },
  23891. { 'n', 0, 0, etSIZE, 0, 0 },
  23892. { '%', 0, 0, etPERCENT, 0, 0 },
  23893. { 'p', 16, 0, etPOINTER, 0, 1 },
  23894. /* All the rest are undocumented and are for internal use only */
  23895. { 'T', 0, 0, etTOKEN, 0, 0 },
  23896. { 'S', 0, 0, etSRCLIST, 0, 0 },
  23897. { 'r', 10, 1, etORDINAL, 0, 0 },
  23898. };
  23899. /*
  23900. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  23901. ** conversions will work.
  23902. */
  23903. #ifndef SQLITE_OMIT_FLOATING_POINT
  23904. /*
  23905. ** "*val" is a double such that 0.1 <= *val < 10.0
  23906. ** Return the ascii code for the leading digit of *val, then
  23907. ** multiply "*val" by 10.0 to renormalize.
  23908. **
  23909. ** Example:
  23910. ** input: *val = 3.14159
  23911. ** output: *val = 1.4159 function return = '3'
  23912. **
  23913. ** The counter *cnt is incremented each time. After counter exceeds
  23914. ** 16 (the number of significant digits in a 64-bit float) '0' is
  23915. ** always returned.
  23916. */
  23917. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  23918. int digit;
  23919. LONGDOUBLE_TYPE d;
  23920. if( (*cnt)<=0 ) return '0';
  23921. (*cnt)--;
  23922. digit = (int)*val;
  23923. d = digit;
  23924. digit += '0';
  23925. *val = (*val - d)*10.0;
  23926. return (char)digit;
  23927. }
  23928. #endif /* SQLITE_OMIT_FLOATING_POINT */
  23929. /*
  23930. ** Set the StrAccum object to an error mode.
  23931. */
  23932. static void setStrAccumError(StrAccum *p, u8 eError){
  23933. assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
  23934. p->accError = eError;
  23935. p->nAlloc = 0;
  23936. }
  23937. /*
  23938. ** Extra argument values from a PrintfArguments object
  23939. */
  23940. static sqlite3_int64 getIntArg(PrintfArguments *p){
  23941. if( p->nArg<=p->nUsed ) return 0;
  23942. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  23943. }
  23944. static double getDoubleArg(PrintfArguments *p){
  23945. if( p->nArg<=p->nUsed ) return 0.0;
  23946. return sqlite3_value_double(p->apArg[p->nUsed++]);
  23947. }
  23948. static char *getTextArg(PrintfArguments *p){
  23949. if( p->nArg<=p->nUsed ) return 0;
  23950. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  23951. }
  23952. /*
  23953. ** On machines with a small stack size, you can redefine the
  23954. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  23955. */
  23956. #ifndef SQLITE_PRINT_BUF_SIZE
  23957. # define SQLITE_PRINT_BUF_SIZE 70
  23958. #endif
  23959. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  23960. /*
  23961. ** Render a string given by "fmt" into the StrAccum object.
  23962. */
  23963. SQLITE_PRIVATE void sqlite3VXPrintf(
  23964. StrAccum *pAccum, /* Accumulate results here */
  23965. const char *fmt, /* Format string */
  23966. va_list ap /* arguments */
  23967. ){
  23968. int c; /* Next character in the format string */
  23969. char *bufpt; /* Pointer to the conversion buffer */
  23970. int precision; /* Precision of the current field */
  23971. int length; /* Length of the field */
  23972. int idx; /* A general purpose loop counter */
  23973. int width; /* Width of the current field */
  23974. etByte flag_leftjustify; /* True if "-" flag is present */
  23975. etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
  23976. etByte flag_alternateform; /* True if "#" flag is present */
  23977. etByte flag_altform2; /* True if "!" flag is present */
  23978. etByte flag_zeropad; /* True if field width constant starts with zero */
  23979. etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
  23980. etByte done; /* Loop termination flag */
  23981. etByte cThousand; /* Thousands separator for %d and %u */
  23982. etByte xtype = etINVALID; /* Conversion paradigm */
  23983. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  23984. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  23985. sqlite_uint64 longvalue; /* Value for integer types */
  23986. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  23987. const et_info *infop; /* Pointer to the appropriate info structure */
  23988. char *zOut; /* Rendering buffer */
  23989. int nOut; /* Size of the rendering buffer */
  23990. char *zExtra = 0; /* Malloced memory used by some conversion */
  23991. #ifndef SQLITE_OMIT_FLOATING_POINT
  23992. int exp, e2; /* exponent of real numbers */
  23993. int nsd; /* Number of significant digits returned */
  23994. double rounder; /* Used for rounding floating point values */
  23995. etByte flag_dp; /* True if decimal point should be shown */
  23996. etByte flag_rtz; /* True if trailing zeros should be removed */
  23997. #endif
  23998. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  23999. char buf[etBUFSIZE]; /* Conversion buffer */
  24000. bufpt = 0;
  24001. if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
  24002. pArgList = va_arg(ap, PrintfArguments*);
  24003. bArgList = 1;
  24004. }else{
  24005. bArgList = 0;
  24006. }
  24007. for(; (c=(*fmt))!=0; ++fmt){
  24008. if( c!='%' ){
  24009. bufpt = (char *)fmt;
  24010. #if HAVE_STRCHRNUL
  24011. fmt = strchrnul(fmt, '%');
  24012. #else
  24013. do{ fmt++; }while( *fmt && *fmt != '%' );
  24014. #endif
  24015. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  24016. if( *fmt==0 ) break;
  24017. }
  24018. if( (c=(*++fmt))==0 ){
  24019. sqlite3StrAccumAppend(pAccum, "%", 1);
  24020. break;
  24021. }
  24022. /* Find out what flags are present */
  24023. flag_leftjustify = flag_prefix = cThousand =
  24024. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  24025. done = 0;
  24026. do{
  24027. switch( c ){
  24028. case '-': flag_leftjustify = 1; break;
  24029. case '+': flag_prefix = '+'; break;
  24030. case ' ': flag_prefix = ' '; break;
  24031. case '#': flag_alternateform = 1; break;
  24032. case '!': flag_altform2 = 1; break;
  24033. case '0': flag_zeropad = 1; break;
  24034. case ',': cThousand = ','; break;
  24035. default: done = 1; break;
  24036. }
  24037. }while( !done && (c=(*++fmt))!=0 );
  24038. /* Get the field width */
  24039. if( c=='*' ){
  24040. if( bArgList ){
  24041. width = (int)getIntArg(pArgList);
  24042. }else{
  24043. width = va_arg(ap,int);
  24044. }
  24045. if( width<0 ){
  24046. flag_leftjustify = 1;
  24047. width = width >= -2147483647 ? -width : 0;
  24048. }
  24049. c = *++fmt;
  24050. }else{
  24051. unsigned wx = 0;
  24052. while( c>='0' && c<='9' ){
  24053. wx = wx*10 + c - '0';
  24054. c = *++fmt;
  24055. }
  24056. testcase( wx>0x7fffffff );
  24057. width = wx & 0x7fffffff;
  24058. }
  24059. assert( width>=0 );
  24060. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  24061. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  24062. width = SQLITE_PRINTF_PRECISION_LIMIT;
  24063. }
  24064. #endif
  24065. /* Get the precision */
  24066. if( c=='.' ){
  24067. c = *++fmt;
  24068. if( c=='*' ){
  24069. if( bArgList ){
  24070. precision = (int)getIntArg(pArgList);
  24071. }else{
  24072. precision = va_arg(ap,int);
  24073. }
  24074. c = *++fmt;
  24075. if( precision<0 ){
  24076. precision = precision >= -2147483647 ? -precision : -1;
  24077. }
  24078. }else{
  24079. unsigned px = 0;
  24080. while( c>='0' && c<='9' ){
  24081. px = px*10 + c - '0';
  24082. c = *++fmt;
  24083. }
  24084. testcase( px>0x7fffffff );
  24085. precision = px & 0x7fffffff;
  24086. }
  24087. }else{
  24088. precision = -1;
  24089. }
  24090. assert( precision>=(-1) );
  24091. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  24092. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  24093. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  24094. }
  24095. #endif
  24096. /* Get the conversion type modifier */
  24097. if( c=='l' ){
  24098. flag_long = 1;
  24099. c = *++fmt;
  24100. if( c=='l' ){
  24101. flag_long = 2;
  24102. c = *++fmt;
  24103. }
  24104. }else{
  24105. flag_long = 0;
  24106. }
  24107. /* Fetch the info entry for the field */
  24108. infop = &fmtinfo[0];
  24109. xtype = etINVALID;
  24110. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  24111. if( c==fmtinfo[idx].fmttype ){
  24112. infop = &fmtinfo[idx];
  24113. xtype = infop->type;
  24114. break;
  24115. }
  24116. }
  24117. /*
  24118. ** At this point, variables are initialized as follows:
  24119. **
  24120. ** flag_alternateform TRUE if a '#' is present.
  24121. ** flag_altform2 TRUE if a '!' is present.
  24122. ** flag_prefix '+' or ' ' or zero
  24123. ** flag_leftjustify TRUE if a '-' is present or if the
  24124. ** field width was negative.
  24125. ** flag_zeropad TRUE if the width began with 0.
  24126. ** flag_long 1 for "l", 2 for "ll"
  24127. ** width The specified field width. This is
  24128. ** always non-negative. Zero is the default.
  24129. ** precision The specified precision. The default
  24130. ** is -1.
  24131. ** xtype The class of the conversion.
  24132. ** infop Pointer to the appropriate info struct.
  24133. */
  24134. switch( xtype ){
  24135. case etPOINTER:
  24136. flag_long = sizeof(char*)==sizeof(i64) ? 2 :
  24137. sizeof(char*)==sizeof(long int) ? 1 : 0;
  24138. /* Fall through into the next case */
  24139. case etORDINAL:
  24140. case etRADIX:
  24141. cThousand = 0;
  24142. /* Fall through into the next case */
  24143. case etDECIMAL:
  24144. if( infop->flags & FLAG_SIGNED ){
  24145. i64 v;
  24146. if( bArgList ){
  24147. v = getIntArg(pArgList);
  24148. }else if( flag_long ){
  24149. if( flag_long==2 ){
  24150. v = va_arg(ap,i64) ;
  24151. }else{
  24152. v = va_arg(ap,long int);
  24153. }
  24154. }else{
  24155. v = va_arg(ap,int);
  24156. }
  24157. if( v<0 ){
  24158. if( v==SMALLEST_INT64 ){
  24159. longvalue = ((u64)1)<<63;
  24160. }else{
  24161. longvalue = -v;
  24162. }
  24163. prefix = '-';
  24164. }else{
  24165. longvalue = v;
  24166. prefix = flag_prefix;
  24167. }
  24168. }else{
  24169. if( bArgList ){
  24170. longvalue = (u64)getIntArg(pArgList);
  24171. }else if( flag_long ){
  24172. if( flag_long==2 ){
  24173. longvalue = va_arg(ap,u64);
  24174. }else{
  24175. longvalue = va_arg(ap,unsigned long int);
  24176. }
  24177. }else{
  24178. longvalue = va_arg(ap,unsigned int);
  24179. }
  24180. prefix = 0;
  24181. }
  24182. if( longvalue==0 ) flag_alternateform = 0;
  24183. if( flag_zeropad && precision<width-(prefix!=0) ){
  24184. precision = width-(prefix!=0);
  24185. }
  24186. if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
  24187. nOut = etBUFSIZE;
  24188. zOut = buf;
  24189. }else{
  24190. u64 n = (u64)precision + 10 + precision/3;
  24191. zOut = zExtra = sqlite3Malloc( n );
  24192. if( zOut==0 ){
  24193. setStrAccumError(pAccum, STRACCUM_NOMEM);
  24194. return;
  24195. }
  24196. nOut = (int)n;
  24197. }
  24198. bufpt = &zOut[nOut-1];
  24199. if( xtype==etORDINAL ){
  24200. static const char zOrd[] = "thstndrd";
  24201. int x = (int)(longvalue % 10);
  24202. if( x>=4 || (longvalue/10)%10==1 ){
  24203. x = 0;
  24204. }
  24205. *(--bufpt) = zOrd[x*2+1];
  24206. *(--bufpt) = zOrd[x*2];
  24207. }
  24208. {
  24209. const char *cset = &aDigits[infop->charset];
  24210. u8 base = infop->base;
  24211. do{ /* Convert to ascii */
  24212. *(--bufpt) = cset[longvalue%base];
  24213. longvalue = longvalue/base;
  24214. }while( longvalue>0 );
  24215. }
  24216. length = (int)(&zOut[nOut-1]-bufpt);
  24217. while( precision>length ){
  24218. *(--bufpt) = '0'; /* Zero pad */
  24219. length++;
  24220. }
  24221. if( cThousand ){
  24222. int nn = (length - 1)/3; /* Number of "," to insert */
  24223. int ix = (length - 1)%3 + 1;
  24224. bufpt -= nn;
  24225. for(idx=0; nn>0; idx++){
  24226. bufpt[idx] = bufpt[idx+nn];
  24227. ix--;
  24228. if( ix==0 ){
  24229. bufpt[++idx] = cThousand;
  24230. nn--;
  24231. ix = 3;
  24232. }
  24233. }
  24234. }
  24235. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  24236. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  24237. const char *pre;
  24238. char x;
  24239. pre = &aPrefix[infop->prefix];
  24240. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  24241. }
  24242. length = (int)(&zOut[nOut-1]-bufpt);
  24243. break;
  24244. case etFLOAT:
  24245. case etEXP:
  24246. case etGENERIC:
  24247. if( bArgList ){
  24248. realvalue = getDoubleArg(pArgList);
  24249. }else{
  24250. realvalue = va_arg(ap,double);
  24251. }
  24252. #ifdef SQLITE_OMIT_FLOATING_POINT
  24253. length = 0;
  24254. #else
  24255. if( precision<0 ) precision = 6; /* Set default precision */
  24256. if( realvalue<0.0 ){
  24257. realvalue = -realvalue;
  24258. prefix = '-';
  24259. }else{
  24260. prefix = flag_prefix;
  24261. }
  24262. if( xtype==etGENERIC && precision>0 ) precision--;
  24263. testcase( precision>0xfff );
  24264. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  24265. if( xtype==etFLOAT ) realvalue += rounder;
  24266. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  24267. exp = 0;
  24268. if( sqlite3IsNaN((double)realvalue) ){
  24269. bufpt = "NaN";
  24270. length = 3;
  24271. break;
  24272. }
  24273. if( realvalue>0.0 ){
  24274. LONGDOUBLE_TYPE scale = 1.0;
  24275. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  24276. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  24277. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  24278. realvalue /= scale;
  24279. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  24280. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  24281. if( exp>350 ){
  24282. bufpt = buf;
  24283. buf[0] = prefix;
  24284. memcpy(buf+(prefix!=0),"Inf",4);
  24285. length = 3+(prefix!=0);
  24286. break;
  24287. }
  24288. }
  24289. bufpt = buf;
  24290. /*
  24291. ** If the field type is etGENERIC, then convert to either etEXP
  24292. ** or etFLOAT, as appropriate.
  24293. */
  24294. if( xtype!=etFLOAT ){
  24295. realvalue += rounder;
  24296. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  24297. }
  24298. if( xtype==etGENERIC ){
  24299. flag_rtz = !flag_alternateform;
  24300. if( exp<-4 || exp>precision ){
  24301. xtype = etEXP;
  24302. }else{
  24303. precision = precision - exp;
  24304. xtype = etFLOAT;
  24305. }
  24306. }else{
  24307. flag_rtz = flag_altform2;
  24308. }
  24309. if( xtype==etEXP ){
  24310. e2 = 0;
  24311. }else{
  24312. e2 = exp;
  24313. }
  24314. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  24315. bufpt = zExtra
  24316. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  24317. if( bufpt==0 ){
  24318. setStrAccumError(pAccum, STRACCUM_NOMEM);
  24319. return;
  24320. }
  24321. }
  24322. zOut = bufpt;
  24323. nsd = 16 + flag_altform2*10;
  24324. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  24325. /* The sign in front of the number */
  24326. if( prefix ){
  24327. *(bufpt++) = prefix;
  24328. }
  24329. /* Digits prior to the decimal point */
  24330. if( e2<0 ){
  24331. *(bufpt++) = '0';
  24332. }else{
  24333. for(; e2>=0; e2--){
  24334. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  24335. }
  24336. }
  24337. /* The decimal point */
  24338. if( flag_dp ){
  24339. *(bufpt++) = '.';
  24340. }
  24341. /* "0" digits after the decimal point but before the first
  24342. ** significant digit of the number */
  24343. for(e2++; e2<0; precision--, e2++){
  24344. assert( precision>0 );
  24345. *(bufpt++) = '0';
  24346. }
  24347. /* Significant digits after the decimal point */
  24348. while( (precision--)>0 ){
  24349. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  24350. }
  24351. /* Remove trailing zeros and the "." if no digits follow the "." */
  24352. if( flag_rtz && flag_dp ){
  24353. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  24354. assert( bufpt>zOut );
  24355. if( bufpt[-1]=='.' ){
  24356. if( flag_altform2 ){
  24357. *(bufpt++) = '0';
  24358. }else{
  24359. *(--bufpt) = 0;
  24360. }
  24361. }
  24362. }
  24363. /* Add the "eNNN" suffix */
  24364. if( xtype==etEXP ){
  24365. *(bufpt++) = aDigits[infop->charset];
  24366. if( exp<0 ){
  24367. *(bufpt++) = '-'; exp = -exp;
  24368. }else{
  24369. *(bufpt++) = '+';
  24370. }
  24371. if( exp>=100 ){
  24372. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  24373. exp %= 100;
  24374. }
  24375. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  24376. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  24377. }
  24378. *bufpt = 0;
  24379. /* The converted number is in buf[] and zero terminated. Output it.
  24380. ** Note that the number is in the usual order, not reversed as with
  24381. ** integer conversions. */
  24382. length = (int)(bufpt-zOut);
  24383. bufpt = zOut;
  24384. /* Special case: Add leading zeros if the flag_zeropad flag is
  24385. ** set and we are not left justified */
  24386. if( flag_zeropad && !flag_leftjustify && length < width){
  24387. int i;
  24388. int nPad = width - length;
  24389. for(i=width; i>=nPad; i--){
  24390. bufpt[i] = bufpt[i-nPad];
  24391. }
  24392. i = prefix!=0;
  24393. while( nPad-- ) bufpt[i++] = '0';
  24394. length = width;
  24395. }
  24396. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  24397. break;
  24398. case etSIZE:
  24399. if( !bArgList ){
  24400. *(va_arg(ap,int*)) = pAccum->nChar;
  24401. }
  24402. length = width = 0;
  24403. break;
  24404. case etPERCENT:
  24405. buf[0] = '%';
  24406. bufpt = buf;
  24407. length = 1;
  24408. break;
  24409. case etCHARX:
  24410. if( bArgList ){
  24411. bufpt = getTextArg(pArgList);
  24412. c = bufpt ? bufpt[0] : 0;
  24413. }else{
  24414. c = va_arg(ap,int);
  24415. }
  24416. if( precision>1 ){
  24417. width -= precision-1;
  24418. if( width>1 && !flag_leftjustify ){
  24419. sqlite3AppendChar(pAccum, width-1, ' ');
  24420. width = 0;
  24421. }
  24422. sqlite3AppendChar(pAccum, precision-1, c);
  24423. }
  24424. length = 1;
  24425. buf[0] = c;
  24426. bufpt = buf;
  24427. break;
  24428. case etSTRING:
  24429. case etDYNSTRING:
  24430. if( bArgList ){
  24431. bufpt = getTextArg(pArgList);
  24432. xtype = etSTRING;
  24433. }else{
  24434. bufpt = va_arg(ap,char*);
  24435. }
  24436. if( bufpt==0 ){
  24437. bufpt = "";
  24438. }else if( xtype==etDYNSTRING ){
  24439. zExtra = bufpt;
  24440. }
  24441. if( precision>=0 ){
  24442. for(length=0; length<precision && bufpt[length]; length++){}
  24443. }else{
  24444. length = sqlite3Strlen30(bufpt);
  24445. }
  24446. break;
  24447. case etSQLESCAPE: /* Escape ' characters */
  24448. case etSQLESCAPE2: /* Escape ' and enclose in '...' */
  24449. case etSQLESCAPE3: { /* Escape " characters */
  24450. int i, j, k, n, isnull;
  24451. int needQuote;
  24452. char ch;
  24453. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  24454. char *escarg;
  24455. if( bArgList ){
  24456. escarg = getTextArg(pArgList);
  24457. }else{
  24458. escarg = va_arg(ap,char*);
  24459. }
  24460. isnull = escarg==0;
  24461. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  24462. k = precision;
  24463. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  24464. if( ch==q ) n++;
  24465. }
  24466. needQuote = !isnull && xtype==etSQLESCAPE2;
  24467. n += i + 3;
  24468. if( n>etBUFSIZE ){
  24469. bufpt = zExtra = sqlite3Malloc( n );
  24470. if( bufpt==0 ){
  24471. setStrAccumError(pAccum, STRACCUM_NOMEM);
  24472. return;
  24473. }
  24474. }else{
  24475. bufpt = buf;
  24476. }
  24477. j = 0;
  24478. if( needQuote ) bufpt[j++] = q;
  24479. k = i;
  24480. for(i=0; i<k; i++){
  24481. bufpt[j++] = ch = escarg[i];
  24482. if( ch==q ) bufpt[j++] = ch;
  24483. }
  24484. if( needQuote ) bufpt[j++] = q;
  24485. bufpt[j] = 0;
  24486. length = j;
  24487. /* The precision in %q and %Q means how many input characters to
  24488. ** consume, not the length of the output...
  24489. ** if( precision>=0 && precision<length ) length = precision; */
  24490. break;
  24491. }
  24492. case etTOKEN: {
  24493. Token *pToken;
  24494. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  24495. pToken = va_arg(ap, Token*);
  24496. assert( bArgList==0 );
  24497. if( pToken && pToken->n ){
  24498. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  24499. }
  24500. length = width = 0;
  24501. break;
  24502. }
  24503. case etSRCLIST: {
  24504. SrcList *pSrc;
  24505. int k;
  24506. struct SrcList_item *pItem;
  24507. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  24508. pSrc = va_arg(ap, SrcList*);
  24509. k = va_arg(ap, int);
  24510. pItem = &pSrc->a[k];
  24511. assert( bArgList==0 );
  24512. assert( k>=0 && k<pSrc->nSrc );
  24513. if( pItem->zDatabase ){
  24514. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  24515. sqlite3StrAccumAppend(pAccum, ".", 1);
  24516. }
  24517. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  24518. length = width = 0;
  24519. break;
  24520. }
  24521. default: {
  24522. assert( xtype==etINVALID );
  24523. return;
  24524. }
  24525. }/* End switch over the format type */
  24526. /*
  24527. ** The text of the conversion is pointed to by "bufpt" and is
  24528. ** "length" characters long. The field width is "width". Do
  24529. ** the output.
  24530. */
  24531. width -= length;
  24532. if( width>0 ){
  24533. if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  24534. sqlite3StrAccumAppend(pAccum, bufpt, length);
  24535. if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  24536. }else{
  24537. sqlite3StrAccumAppend(pAccum, bufpt, length);
  24538. }
  24539. if( zExtra ){
  24540. sqlite3DbFree(pAccum->db, zExtra);
  24541. zExtra = 0;
  24542. }
  24543. }/* End for loop over the format string */
  24544. } /* End of function */
  24545. /*
  24546. ** Enlarge the memory allocation on a StrAccum object so that it is
  24547. ** able to accept at least N more bytes of text.
  24548. **
  24549. ** Return the number of bytes of text that StrAccum is able to accept
  24550. ** after the attempted enlargement. The value returned might be zero.
  24551. */
  24552. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  24553. char *zNew;
  24554. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  24555. if( p->accError ){
  24556. testcase(p->accError==STRACCUM_TOOBIG);
  24557. testcase(p->accError==STRACCUM_NOMEM);
  24558. return 0;
  24559. }
  24560. if( p->mxAlloc==0 ){
  24561. N = p->nAlloc - p->nChar - 1;
  24562. setStrAccumError(p, STRACCUM_TOOBIG);
  24563. return N;
  24564. }else{
  24565. char *zOld = isMalloced(p) ? p->zText : 0;
  24566. i64 szNew = p->nChar;
  24567. assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
  24568. szNew += N + 1;
  24569. if( szNew+p->nChar<=p->mxAlloc ){
  24570. /* Force exponential buffer size growth as long as it does not overflow,
  24571. ** to avoid having to call this routine too often */
  24572. szNew += p->nChar;
  24573. }
  24574. if( szNew > p->mxAlloc ){
  24575. sqlite3StrAccumReset(p);
  24576. setStrAccumError(p, STRACCUM_TOOBIG);
  24577. return 0;
  24578. }else{
  24579. p->nAlloc = (int)szNew;
  24580. }
  24581. if( p->db ){
  24582. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  24583. }else{
  24584. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  24585. }
  24586. if( zNew ){
  24587. assert( p->zText!=0 || p->nChar==0 );
  24588. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  24589. p->zText = zNew;
  24590. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  24591. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  24592. }else{
  24593. sqlite3StrAccumReset(p);
  24594. setStrAccumError(p, STRACCUM_NOMEM);
  24595. return 0;
  24596. }
  24597. }
  24598. return N;
  24599. }
  24600. /*
  24601. ** Append N copies of character c to the given string buffer.
  24602. */
  24603. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  24604. testcase( p->nChar + (i64)N > 0x7fffffff );
  24605. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  24606. return;
  24607. }
  24608. assert( (p->zText==p->zBase)==!isMalloced(p) );
  24609. while( (N--)>0 ) p->zText[p->nChar++] = c;
  24610. }
  24611. /*
  24612. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  24613. ** So enlarge if first, then do the append.
  24614. **
  24615. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  24616. ** work (enlarging the buffer) using tail recursion, so that the
  24617. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  24618. */
  24619. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  24620. N = sqlite3StrAccumEnlarge(p, N);
  24621. if( N>0 ){
  24622. memcpy(&p->zText[p->nChar], z, N);
  24623. p->nChar += N;
  24624. }
  24625. assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
  24626. }
  24627. /*
  24628. ** Append N bytes of text from z to the StrAccum object. Increase the
  24629. ** size of the memory allocation for StrAccum if necessary.
  24630. */
  24631. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  24632. assert( z!=0 || N==0 );
  24633. assert( p->zText!=0 || p->nChar==0 || p->accError );
  24634. assert( N>=0 );
  24635. assert( p->accError==0 || p->nAlloc==0 );
  24636. if( p->nChar+N >= p->nAlloc ){
  24637. enlargeAndAppend(p,z,N);
  24638. }else if( N ){
  24639. assert( p->zText );
  24640. p->nChar += N;
  24641. memcpy(&p->zText[p->nChar-N], z, N);
  24642. }
  24643. }
  24644. /*
  24645. ** Append the complete text of zero-terminated string z[] to the p string.
  24646. */
  24647. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  24648. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  24649. }
  24650. /*
  24651. ** Finish off a string by making sure it is zero-terminated.
  24652. ** Return a pointer to the resulting string. Return a NULL
  24653. ** pointer if any kind of error was encountered.
  24654. */
  24655. static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
  24656. assert( p->mxAlloc>0 && !isMalloced(p) );
  24657. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  24658. if( p->zText ){
  24659. memcpy(p->zText, p->zBase, p->nChar+1);
  24660. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  24661. }else{
  24662. setStrAccumError(p, STRACCUM_NOMEM);
  24663. }
  24664. return p->zText;
  24665. }
  24666. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  24667. if( p->zText ){
  24668. assert( (p->zText==p->zBase)==!isMalloced(p) );
  24669. p->zText[p->nChar] = 0;
  24670. if( p->mxAlloc>0 && !isMalloced(p) ){
  24671. return strAccumFinishRealloc(p);
  24672. }
  24673. }
  24674. return p->zText;
  24675. }
  24676. /*
  24677. ** Reset an StrAccum string. Reclaim all malloced memory.
  24678. */
  24679. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  24680. assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
  24681. if( isMalloced(p) ){
  24682. sqlite3DbFree(p->db, p->zText);
  24683. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  24684. }
  24685. p->zText = 0;
  24686. }
  24687. /*
  24688. ** Initialize a string accumulator.
  24689. **
  24690. ** p: The accumulator to be initialized.
  24691. ** db: Pointer to a database connection. May be NULL. Lookaside
  24692. ** memory is used if not NULL. db->mallocFailed is set appropriately
  24693. ** when not NULL.
  24694. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  24695. ** is malloced.
  24696. ** n: Size of zBase in bytes. If total space requirements never exceed
  24697. ** n then no memory allocations ever occur.
  24698. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  24699. ** allocations will ever occur.
  24700. */
  24701. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  24702. p->zText = p->zBase = zBase;
  24703. p->db = db;
  24704. p->nChar = 0;
  24705. p->nAlloc = n;
  24706. p->mxAlloc = mx;
  24707. p->accError = 0;
  24708. p->printfFlags = 0;
  24709. }
  24710. /*
  24711. ** Print into memory obtained from sqliteMalloc(). Use the internal
  24712. ** %-conversion extensions.
  24713. */
  24714. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  24715. char *z;
  24716. char zBase[SQLITE_PRINT_BUF_SIZE];
  24717. StrAccum acc;
  24718. assert( db!=0 );
  24719. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  24720. db->aLimit[SQLITE_LIMIT_LENGTH]);
  24721. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  24722. sqlite3VXPrintf(&acc, zFormat, ap);
  24723. z = sqlite3StrAccumFinish(&acc);
  24724. if( acc.accError==STRACCUM_NOMEM ){
  24725. sqlite3OomFault(db);
  24726. }
  24727. return z;
  24728. }
  24729. /*
  24730. ** Print into memory obtained from sqliteMalloc(). Use the internal
  24731. ** %-conversion extensions.
  24732. */
  24733. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  24734. va_list ap;
  24735. char *z;
  24736. va_start(ap, zFormat);
  24737. z = sqlite3VMPrintf(db, zFormat, ap);
  24738. va_end(ap);
  24739. return z;
  24740. }
  24741. /*
  24742. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  24743. ** %-conversion extensions.
  24744. */
  24745. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  24746. char *z;
  24747. char zBase[SQLITE_PRINT_BUF_SIZE];
  24748. StrAccum acc;
  24749. #ifdef SQLITE_ENABLE_API_ARMOR
  24750. if( zFormat==0 ){
  24751. (void)SQLITE_MISUSE_BKPT;
  24752. return 0;
  24753. }
  24754. #endif
  24755. #ifndef SQLITE_OMIT_AUTOINIT
  24756. if( sqlite3_initialize() ) return 0;
  24757. #endif
  24758. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  24759. sqlite3VXPrintf(&acc, zFormat, ap);
  24760. z = sqlite3StrAccumFinish(&acc);
  24761. return z;
  24762. }
  24763. /*
  24764. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  24765. ** %-conversion extensions.
  24766. */
  24767. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  24768. va_list ap;
  24769. char *z;
  24770. #ifndef SQLITE_OMIT_AUTOINIT
  24771. if( sqlite3_initialize() ) return 0;
  24772. #endif
  24773. va_start(ap, zFormat);
  24774. z = sqlite3_vmprintf(zFormat, ap);
  24775. va_end(ap);
  24776. return z;
  24777. }
  24778. /*
  24779. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  24780. ** current locale settings. This is important for SQLite because we
  24781. ** are not able to use a "," as the decimal point in place of "." as
  24782. ** specified by some locales.
  24783. **
  24784. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  24785. ** from the snprintf() standard. Unfortunately, it is too late to change
  24786. ** this without breaking compatibility, so we just have to live with the
  24787. ** mistake.
  24788. **
  24789. ** sqlite3_vsnprintf() is the varargs version.
  24790. */
  24791. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  24792. StrAccum acc;
  24793. if( n<=0 ) return zBuf;
  24794. #ifdef SQLITE_ENABLE_API_ARMOR
  24795. if( zBuf==0 || zFormat==0 ) {
  24796. (void)SQLITE_MISUSE_BKPT;
  24797. if( zBuf ) zBuf[0] = 0;
  24798. return zBuf;
  24799. }
  24800. #endif
  24801. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  24802. sqlite3VXPrintf(&acc, zFormat, ap);
  24803. zBuf[acc.nChar] = 0;
  24804. return zBuf;
  24805. }
  24806. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  24807. char *z;
  24808. va_list ap;
  24809. va_start(ap,zFormat);
  24810. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  24811. va_end(ap);
  24812. return z;
  24813. }
  24814. /*
  24815. ** This is the routine that actually formats the sqlite3_log() message.
  24816. ** We house it in a separate routine from sqlite3_log() to avoid using
  24817. ** stack space on small-stack systems when logging is disabled.
  24818. **
  24819. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  24820. ** allocate memory because it might be called while the memory allocator
  24821. ** mutex is held.
  24822. **
  24823. ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
  24824. ** certain format characters (%q) or for very large precisions or widths.
  24825. ** Care must be taken that any sqlite3_log() calls that occur while the
  24826. ** memory mutex is held do not use these mechanisms.
  24827. */
  24828. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  24829. StrAccum acc; /* String accumulator */
  24830. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  24831. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  24832. sqlite3VXPrintf(&acc, zFormat, ap);
  24833. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  24834. sqlite3StrAccumFinish(&acc));
  24835. }
  24836. /*
  24837. ** Format and write a message to the log if logging is enabled.
  24838. */
  24839. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  24840. va_list ap; /* Vararg list */
  24841. if( sqlite3GlobalConfig.xLog ){
  24842. va_start(ap, zFormat);
  24843. renderLogMsg(iErrCode, zFormat, ap);
  24844. va_end(ap);
  24845. }
  24846. }
  24847. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  24848. /*
  24849. ** A version of printf() that understands %lld. Used for debugging.
  24850. ** The printf() built into some versions of windows does not understand %lld
  24851. ** and segfaults if you give it a long long int.
  24852. */
  24853. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  24854. va_list ap;
  24855. StrAccum acc;
  24856. char zBuf[500];
  24857. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  24858. va_start(ap,zFormat);
  24859. sqlite3VXPrintf(&acc, zFormat, ap);
  24860. va_end(ap);
  24861. sqlite3StrAccumFinish(&acc);
  24862. fprintf(stdout,"%s", zBuf);
  24863. fflush(stdout);
  24864. }
  24865. #endif
  24866. /*
  24867. ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
  24868. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  24869. */
  24870. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  24871. va_list ap;
  24872. va_start(ap,zFormat);
  24873. sqlite3VXPrintf(p, zFormat, ap);
  24874. va_end(ap);
  24875. }
  24876. /************** End of printf.c **********************************************/
  24877. /************** Begin file treeview.c ****************************************/
  24878. /*
  24879. ** 2015-06-08
  24880. **
  24881. ** The author disclaims copyright to this source code. In place of
  24882. ** a legal notice, here is a blessing:
  24883. **
  24884. ** May you do good and not evil.
  24885. ** May you find forgiveness for yourself and forgive others.
  24886. ** May you share freely, never taking more than you give.
  24887. **
  24888. *************************************************************************
  24889. **
  24890. ** This file contains C code to implement the TreeView debugging routines.
  24891. ** These routines print a parse tree to standard output for debugging and
  24892. ** analysis.
  24893. **
  24894. ** The interfaces in this file is only available when compiling
  24895. ** with SQLITE_DEBUG.
  24896. */
  24897. /* #include "sqliteInt.h" */
  24898. #ifdef SQLITE_DEBUG
  24899. /*
  24900. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  24901. ** is not the last item in the tree.
  24902. */
  24903. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  24904. if( p==0 ){
  24905. p = sqlite3_malloc64( sizeof(*p) );
  24906. if( p==0 ) return 0;
  24907. memset(p, 0, sizeof(*p));
  24908. }else{
  24909. p->iLevel++;
  24910. }
  24911. assert( moreToFollow==0 || moreToFollow==1 );
  24912. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  24913. return p;
  24914. }
  24915. /*
  24916. ** Finished with one layer of the tree
  24917. */
  24918. static void sqlite3TreeViewPop(TreeView *p){
  24919. if( p==0 ) return;
  24920. p->iLevel--;
  24921. if( p->iLevel<0 ) sqlite3_free(p);
  24922. }
  24923. /*
  24924. ** Generate a single line of output for the tree, with a prefix that contains
  24925. ** all the appropriate tree lines
  24926. */
  24927. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  24928. va_list ap;
  24929. int i;
  24930. StrAccum acc;
  24931. char zBuf[500];
  24932. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  24933. if( p ){
  24934. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  24935. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  24936. }
  24937. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  24938. }
  24939. va_start(ap, zFormat);
  24940. sqlite3VXPrintf(&acc, zFormat, ap);
  24941. va_end(ap);
  24942. assert( acc.nChar>0 );
  24943. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  24944. sqlite3StrAccumFinish(&acc);
  24945. fprintf(stdout,"%s", zBuf);
  24946. fflush(stdout);
  24947. }
  24948. /*
  24949. ** Shorthand for starting a new tree item that consists of a single label
  24950. */
  24951. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  24952. p = sqlite3TreeViewPush(p, moreFollows);
  24953. sqlite3TreeViewLine(p, "%s", zLabel);
  24954. }
  24955. /*
  24956. ** Generate a human-readable description of a WITH clause.
  24957. */
  24958. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  24959. int i;
  24960. if( pWith==0 ) return;
  24961. if( pWith->nCte==0 ) return;
  24962. if( pWith->pOuter ){
  24963. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  24964. }else{
  24965. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  24966. }
  24967. if( pWith->nCte>0 ){
  24968. pView = sqlite3TreeViewPush(pView, 1);
  24969. for(i=0; i<pWith->nCte; i++){
  24970. StrAccum x;
  24971. char zLine[1000];
  24972. const struct Cte *pCte = &pWith->a[i];
  24973. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  24974. sqlite3XPrintf(&x, "%s", pCte->zName);
  24975. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  24976. char cSep = '(';
  24977. int j;
  24978. for(j=0; j<pCte->pCols->nExpr; j++){
  24979. sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
  24980. cSep = ',';
  24981. }
  24982. sqlite3XPrintf(&x, ")");
  24983. }
  24984. sqlite3XPrintf(&x, " AS");
  24985. sqlite3StrAccumFinish(&x);
  24986. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  24987. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  24988. sqlite3TreeViewPop(pView);
  24989. }
  24990. sqlite3TreeViewPop(pView);
  24991. }
  24992. }
  24993. /*
  24994. ** Generate a human-readable description of a Select object.
  24995. */
  24996. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  24997. int n = 0;
  24998. int cnt = 0;
  24999. if( p==0 ){
  25000. sqlite3TreeViewLine(pView, "nil-SELECT");
  25001. return;
  25002. }
  25003. pView = sqlite3TreeViewPush(pView, moreToFollow);
  25004. if( p->pWith ){
  25005. sqlite3TreeViewWith(pView, p->pWith, 1);
  25006. cnt = 1;
  25007. sqlite3TreeViewPush(pView, 1);
  25008. }
  25009. do{
  25010. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
  25011. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  25012. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
  25013. (int)p->nSelectRow
  25014. );
  25015. if( cnt++ ) sqlite3TreeViewPop(pView);
  25016. if( p->pPrior ){
  25017. n = 1000;
  25018. }else{
  25019. n = 0;
  25020. if( p->pSrc && p->pSrc->nSrc ) n++;
  25021. if( p->pWhere ) n++;
  25022. if( p->pGroupBy ) n++;
  25023. if( p->pHaving ) n++;
  25024. if( p->pOrderBy ) n++;
  25025. if( p->pLimit ) n++;
  25026. if( p->pOffset ) n++;
  25027. }
  25028. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  25029. if( p->pSrc && p->pSrc->nSrc ){
  25030. int i;
  25031. pView = sqlite3TreeViewPush(pView, (n--)>0);
  25032. sqlite3TreeViewLine(pView, "FROM");
  25033. for(i=0; i<p->pSrc->nSrc; i++){
  25034. struct SrcList_item *pItem = &p->pSrc->a[i];
  25035. StrAccum x;
  25036. char zLine[100];
  25037. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  25038. sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
  25039. if( pItem->zDatabase ){
  25040. sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  25041. }else if( pItem->zName ){
  25042. sqlite3XPrintf(&x, " %s", pItem->zName);
  25043. }
  25044. if( pItem->pTab ){
  25045. sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
  25046. }
  25047. if( pItem->zAlias ){
  25048. sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
  25049. }
  25050. if( pItem->fg.jointype & JT_LEFT ){
  25051. sqlite3XPrintf(&x, " LEFT-JOIN");
  25052. }
  25053. sqlite3StrAccumFinish(&x);
  25054. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  25055. if( pItem->pSelect ){
  25056. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  25057. }
  25058. if( pItem->fg.isTabFunc ){
  25059. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  25060. }
  25061. sqlite3TreeViewPop(pView);
  25062. }
  25063. sqlite3TreeViewPop(pView);
  25064. }
  25065. if( p->pWhere ){
  25066. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  25067. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  25068. sqlite3TreeViewPop(pView);
  25069. }
  25070. if( p->pGroupBy ){
  25071. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  25072. }
  25073. if( p->pHaving ){
  25074. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  25075. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  25076. sqlite3TreeViewPop(pView);
  25077. }
  25078. if( p->pOrderBy ){
  25079. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  25080. }
  25081. if( p->pLimit ){
  25082. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  25083. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  25084. sqlite3TreeViewPop(pView);
  25085. }
  25086. if( p->pOffset ){
  25087. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  25088. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  25089. sqlite3TreeViewPop(pView);
  25090. }
  25091. if( p->pPrior ){
  25092. const char *zOp = "UNION";
  25093. switch( p->op ){
  25094. case TK_ALL: zOp = "UNION ALL"; break;
  25095. case TK_INTERSECT: zOp = "INTERSECT"; break;
  25096. case TK_EXCEPT: zOp = "EXCEPT"; break;
  25097. }
  25098. sqlite3TreeViewItem(pView, zOp, 1);
  25099. }
  25100. p = p->pPrior;
  25101. }while( p!=0 );
  25102. sqlite3TreeViewPop(pView);
  25103. }
  25104. /*
  25105. ** Generate a human-readable explanation of an expression tree.
  25106. */
  25107. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  25108. const char *zBinOp = 0; /* Binary operator */
  25109. const char *zUniOp = 0; /* Unary operator */
  25110. char zFlgs[60];
  25111. pView = sqlite3TreeViewPush(pView, moreToFollow);
  25112. if( pExpr==0 ){
  25113. sqlite3TreeViewLine(pView, "nil");
  25114. sqlite3TreeViewPop(pView);
  25115. return;
  25116. }
  25117. if( pExpr->flags ){
  25118. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  25119. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
  25120. pExpr->flags, pExpr->iRightJoinTable);
  25121. }else{
  25122. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  25123. }
  25124. }else{
  25125. zFlgs[0] = 0;
  25126. }
  25127. switch( pExpr->op ){
  25128. case TK_AGG_COLUMN: {
  25129. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  25130. pExpr->iTable, pExpr->iColumn, zFlgs);
  25131. break;
  25132. }
  25133. case TK_COLUMN: {
  25134. if( pExpr->iTable<0 ){
  25135. /* This only happens when coding check constraints */
  25136. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  25137. }else{
  25138. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  25139. pExpr->iTable, pExpr->iColumn, zFlgs);
  25140. }
  25141. break;
  25142. }
  25143. case TK_INTEGER: {
  25144. if( pExpr->flags & EP_IntValue ){
  25145. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  25146. }else{
  25147. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  25148. }
  25149. break;
  25150. }
  25151. #ifndef SQLITE_OMIT_FLOATING_POINT
  25152. case TK_FLOAT: {
  25153. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  25154. break;
  25155. }
  25156. #endif
  25157. case TK_STRING: {
  25158. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  25159. break;
  25160. }
  25161. case TK_NULL: {
  25162. sqlite3TreeViewLine(pView,"NULL");
  25163. break;
  25164. }
  25165. #ifndef SQLITE_OMIT_BLOB_LITERAL
  25166. case TK_BLOB: {
  25167. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  25168. break;
  25169. }
  25170. #endif
  25171. case TK_VARIABLE: {
  25172. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  25173. pExpr->u.zToken, pExpr->iColumn);
  25174. break;
  25175. }
  25176. case TK_REGISTER: {
  25177. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  25178. break;
  25179. }
  25180. case TK_ID: {
  25181. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  25182. break;
  25183. }
  25184. #ifndef SQLITE_OMIT_CAST
  25185. case TK_CAST: {
  25186. /* Expressions of the form: CAST(pLeft AS token) */
  25187. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  25188. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25189. break;
  25190. }
  25191. #endif /* SQLITE_OMIT_CAST */
  25192. case TK_LT: zBinOp = "LT"; break;
  25193. case TK_LE: zBinOp = "LE"; break;
  25194. case TK_GT: zBinOp = "GT"; break;
  25195. case TK_GE: zBinOp = "GE"; break;
  25196. case TK_NE: zBinOp = "NE"; break;
  25197. case TK_EQ: zBinOp = "EQ"; break;
  25198. case TK_IS: zBinOp = "IS"; break;
  25199. case TK_ISNOT: zBinOp = "ISNOT"; break;
  25200. case TK_AND: zBinOp = "AND"; break;
  25201. case TK_OR: zBinOp = "OR"; break;
  25202. case TK_PLUS: zBinOp = "ADD"; break;
  25203. case TK_STAR: zBinOp = "MUL"; break;
  25204. case TK_MINUS: zBinOp = "SUB"; break;
  25205. case TK_REM: zBinOp = "REM"; break;
  25206. case TK_BITAND: zBinOp = "BITAND"; break;
  25207. case TK_BITOR: zBinOp = "BITOR"; break;
  25208. case TK_SLASH: zBinOp = "DIV"; break;
  25209. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  25210. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  25211. case TK_CONCAT: zBinOp = "CONCAT"; break;
  25212. case TK_DOT: zBinOp = "DOT"; break;
  25213. case TK_UMINUS: zUniOp = "UMINUS"; break;
  25214. case TK_UPLUS: zUniOp = "UPLUS"; break;
  25215. case TK_BITNOT: zUniOp = "BITNOT"; break;
  25216. case TK_NOT: zUniOp = "NOT"; break;
  25217. case TK_ISNULL: zUniOp = "ISNULL"; break;
  25218. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  25219. case TK_SPAN: {
  25220. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  25221. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25222. break;
  25223. }
  25224. case TK_COLLATE: {
  25225. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  25226. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25227. break;
  25228. }
  25229. case TK_AGG_FUNCTION:
  25230. case TK_FUNCTION: {
  25231. ExprList *pFarg; /* List of function arguments */
  25232. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  25233. pFarg = 0;
  25234. }else{
  25235. pFarg = pExpr->x.pList;
  25236. }
  25237. if( pExpr->op==TK_AGG_FUNCTION ){
  25238. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  25239. pExpr->op2, pExpr->u.zToken);
  25240. }else{
  25241. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  25242. }
  25243. if( pFarg ){
  25244. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  25245. }
  25246. break;
  25247. }
  25248. #ifndef SQLITE_OMIT_SUBQUERY
  25249. case TK_EXISTS: {
  25250. sqlite3TreeViewLine(pView, "EXISTS-expr");
  25251. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  25252. break;
  25253. }
  25254. case TK_SELECT: {
  25255. sqlite3TreeViewLine(pView, "SELECT-expr");
  25256. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  25257. break;
  25258. }
  25259. case TK_IN: {
  25260. sqlite3TreeViewLine(pView, "IN");
  25261. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  25262. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  25263. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  25264. }else{
  25265. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  25266. }
  25267. break;
  25268. }
  25269. #endif /* SQLITE_OMIT_SUBQUERY */
  25270. /*
  25271. ** x BETWEEN y AND z
  25272. **
  25273. ** This is equivalent to
  25274. **
  25275. ** x>=y AND x<=z
  25276. **
  25277. ** X is stored in pExpr->pLeft.
  25278. ** Y is stored in pExpr->pList->a[0].pExpr.
  25279. ** Z is stored in pExpr->pList->a[1].pExpr.
  25280. */
  25281. case TK_BETWEEN: {
  25282. Expr *pX = pExpr->pLeft;
  25283. Expr *pY = pExpr->x.pList->a[0].pExpr;
  25284. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  25285. sqlite3TreeViewLine(pView, "BETWEEN");
  25286. sqlite3TreeViewExpr(pView, pX, 1);
  25287. sqlite3TreeViewExpr(pView, pY, 1);
  25288. sqlite3TreeViewExpr(pView, pZ, 0);
  25289. break;
  25290. }
  25291. case TK_TRIGGER: {
  25292. /* If the opcode is TK_TRIGGER, then the expression is a reference
  25293. ** to a column in the new.* or old.* pseudo-tables available to
  25294. ** trigger programs. In this case Expr.iTable is set to 1 for the
  25295. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  25296. ** is set to the column of the pseudo-table to read, or to -1 to
  25297. ** read the rowid field.
  25298. */
  25299. sqlite3TreeViewLine(pView, "%s(%d)",
  25300. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  25301. break;
  25302. }
  25303. case TK_CASE: {
  25304. sqlite3TreeViewLine(pView, "CASE");
  25305. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  25306. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  25307. break;
  25308. }
  25309. #ifndef SQLITE_OMIT_TRIGGER
  25310. case TK_RAISE: {
  25311. const char *zType = "unk";
  25312. switch( pExpr->affinity ){
  25313. case OE_Rollback: zType = "rollback"; break;
  25314. case OE_Abort: zType = "abort"; break;
  25315. case OE_Fail: zType = "fail"; break;
  25316. case OE_Ignore: zType = "ignore"; break;
  25317. }
  25318. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  25319. break;
  25320. }
  25321. #endif
  25322. case TK_MATCH: {
  25323. sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
  25324. pExpr->iTable, pExpr->iColumn, zFlgs);
  25325. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  25326. break;
  25327. }
  25328. case TK_VECTOR: {
  25329. sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
  25330. break;
  25331. }
  25332. case TK_SELECT_COLUMN: {
  25333. sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
  25334. sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
  25335. break;
  25336. }
  25337. case TK_IF_NULL_ROW: {
  25338. sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
  25339. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25340. break;
  25341. }
  25342. default: {
  25343. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  25344. break;
  25345. }
  25346. }
  25347. if( zBinOp ){
  25348. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  25349. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  25350. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  25351. }else if( zUniOp ){
  25352. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  25353. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25354. }
  25355. sqlite3TreeViewPop(pView);
  25356. }
  25357. /*
  25358. ** Generate a human-readable explanation of an expression list.
  25359. */
  25360. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
  25361. TreeView *pView,
  25362. const ExprList *pList,
  25363. const char *zLabel
  25364. ){
  25365. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  25366. if( pList==0 ){
  25367. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  25368. }else{
  25369. int i;
  25370. sqlite3TreeViewLine(pView, "%s", zLabel);
  25371. for(i=0; i<pList->nExpr; i++){
  25372. int j = pList->a[i].u.x.iOrderByCol;
  25373. if( j ){
  25374. sqlite3TreeViewPush(pView, 0);
  25375. sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
  25376. }
  25377. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  25378. if( j ) sqlite3TreeViewPop(pView);
  25379. }
  25380. }
  25381. }
  25382. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  25383. TreeView *pView,
  25384. const ExprList *pList,
  25385. u8 moreToFollow,
  25386. const char *zLabel
  25387. ){
  25388. pView = sqlite3TreeViewPush(pView, moreToFollow);
  25389. sqlite3TreeViewBareExprList(pView, pList, zLabel);
  25390. sqlite3TreeViewPop(pView);
  25391. }
  25392. #endif /* SQLITE_DEBUG */
  25393. /************** End of treeview.c ********************************************/
  25394. /************** Begin file random.c ******************************************/
  25395. /*
  25396. ** 2001 September 15
  25397. **
  25398. ** The author disclaims copyright to this source code. In place of
  25399. ** a legal notice, here is a blessing:
  25400. **
  25401. ** May you do good and not evil.
  25402. ** May you find forgiveness for yourself and forgive others.
  25403. ** May you share freely, never taking more than you give.
  25404. **
  25405. *************************************************************************
  25406. ** This file contains code to implement a pseudo-random number
  25407. ** generator (PRNG) for SQLite.
  25408. **
  25409. ** Random numbers are used by some of the database backends in order
  25410. ** to generate random integer keys for tables or random filenames.
  25411. */
  25412. /* #include "sqliteInt.h" */
  25413. /* All threads share a single random number generator.
  25414. ** This structure is the current state of the generator.
  25415. */
  25416. static SQLITE_WSD struct sqlite3PrngType {
  25417. unsigned char isInit; /* True if initialized */
  25418. unsigned char i, j; /* State variables */
  25419. unsigned char s[256]; /* State variables */
  25420. } sqlite3Prng;
  25421. /*
  25422. ** Return N random bytes.
  25423. */
  25424. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  25425. unsigned char t;
  25426. unsigned char *zBuf = pBuf;
  25427. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  25428. ** state vector. If writable static data is unsupported on the target,
  25429. ** we have to locate the state vector at run-time. In the more common
  25430. ** case where writable static data is supported, wsdPrng can refer directly
  25431. ** to the "sqlite3Prng" state vector declared above.
  25432. */
  25433. #ifdef SQLITE_OMIT_WSD
  25434. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  25435. # define wsdPrng p[0]
  25436. #else
  25437. # define wsdPrng sqlite3Prng
  25438. #endif
  25439. #if SQLITE_THREADSAFE
  25440. sqlite3_mutex *mutex;
  25441. #endif
  25442. #ifndef SQLITE_OMIT_AUTOINIT
  25443. if( sqlite3_initialize() ) return;
  25444. #endif
  25445. #if SQLITE_THREADSAFE
  25446. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  25447. #endif
  25448. sqlite3_mutex_enter(mutex);
  25449. if( N<=0 || pBuf==0 ){
  25450. wsdPrng.isInit = 0;
  25451. sqlite3_mutex_leave(mutex);
  25452. return;
  25453. }
  25454. /* Initialize the state of the random number generator once,
  25455. ** the first time this routine is called. The seed value does
  25456. ** not need to contain a lot of randomness since we are not
  25457. ** trying to do secure encryption or anything like that...
  25458. **
  25459. ** Nothing in this file or anywhere else in SQLite does any kind of
  25460. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  25461. ** number generator) not as an encryption device.
  25462. */
  25463. if( !wsdPrng.isInit ){
  25464. int i;
  25465. char k[256];
  25466. wsdPrng.j = 0;
  25467. wsdPrng.i = 0;
  25468. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  25469. for(i=0; i<256; i++){
  25470. wsdPrng.s[i] = (u8)i;
  25471. }
  25472. for(i=0; i<256; i++){
  25473. wsdPrng.j += wsdPrng.s[i] + k[i];
  25474. t = wsdPrng.s[wsdPrng.j];
  25475. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  25476. wsdPrng.s[i] = t;
  25477. }
  25478. wsdPrng.isInit = 1;
  25479. }
  25480. assert( N>0 );
  25481. do{
  25482. wsdPrng.i++;
  25483. t = wsdPrng.s[wsdPrng.i];
  25484. wsdPrng.j += t;
  25485. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  25486. wsdPrng.s[wsdPrng.j] = t;
  25487. t += wsdPrng.s[wsdPrng.i];
  25488. *(zBuf++) = wsdPrng.s[t];
  25489. }while( --N );
  25490. sqlite3_mutex_leave(mutex);
  25491. }
  25492. #ifndef SQLITE_UNTESTABLE
  25493. /*
  25494. ** For testing purposes, we sometimes want to preserve the state of
  25495. ** PRNG and restore the PRNG to its saved state at a later time, or
  25496. ** to reset the PRNG to its initial state. These routines accomplish
  25497. ** those tasks.
  25498. **
  25499. ** The sqlite3_test_control() interface calls these routines to
  25500. ** control the PRNG.
  25501. */
  25502. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  25503. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  25504. memcpy(
  25505. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  25506. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  25507. sizeof(sqlite3Prng)
  25508. );
  25509. }
  25510. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  25511. memcpy(
  25512. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  25513. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  25514. sizeof(sqlite3Prng)
  25515. );
  25516. }
  25517. #endif /* SQLITE_UNTESTABLE */
  25518. /************** End of random.c **********************************************/
  25519. /************** Begin file threads.c *****************************************/
  25520. /*
  25521. ** 2012 July 21
  25522. **
  25523. ** The author disclaims copyright to this source code. In place of
  25524. ** a legal notice, here is a blessing:
  25525. **
  25526. ** May you do good and not evil.
  25527. ** May you find forgiveness for yourself and forgive others.
  25528. ** May you share freely, never taking more than you give.
  25529. **
  25530. ******************************************************************************
  25531. **
  25532. ** This file presents a simple cross-platform threading interface for
  25533. ** use internally by SQLite.
  25534. **
  25535. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  25536. ** runs independently of its creator until it is joined using
  25537. ** sqlite3ThreadJoin(), at which point it terminates.
  25538. **
  25539. ** Threads do not have to be real. It could be that the work of the
  25540. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  25541. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  25542. ** single threaded systems. Nothing in SQLite requires multiple threads.
  25543. ** This interface exists so that applications that want to take advantage
  25544. ** of multiple cores can do so, while also allowing applications to stay
  25545. ** single-threaded if desired.
  25546. */
  25547. /* #include "sqliteInt.h" */
  25548. #if SQLITE_OS_WIN
  25549. /* # include "os_win.h" */
  25550. #endif
  25551. #if SQLITE_MAX_WORKER_THREADS>0
  25552. /********************************* Unix Pthreads ****************************/
  25553. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  25554. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  25555. /* #include <pthread.h> */
  25556. /* A running thread */
  25557. struct SQLiteThread {
  25558. pthread_t tid; /* Thread ID */
  25559. int done; /* Set to true when thread finishes */
  25560. void *pOut; /* Result returned by the thread */
  25561. void *(*xTask)(void*); /* The thread routine */
  25562. void *pIn; /* Argument to the thread */
  25563. };
  25564. /* Create a new thread */
  25565. SQLITE_PRIVATE int sqlite3ThreadCreate(
  25566. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  25567. void *(*xTask)(void*), /* Routine to run in a separate thread */
  25568. void *pIn /* Argument passed into xTask() */
  25569. ){
  25570. SQLiteThread *p;
  25571. int rc;
  25572. assert( ppThread!=0 );
  25573. assert( xTask!=0 );
  25574. /* This routine is never used in single-threaded mode */
  25575. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  25576. *ppThread = 0;
  25577. p = sqlite3Malloc(sizeof(*p));
  25578. if( p==0 ) return SQLITE_NOMEM_BKPT;
  25579. memset(p, 0, sizeof(*p));
  25580. p->xTask = xTask;
  25581. p->pIn = pIn;
  25582. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  25583. ** function that returns SQLITE_ERROR when passed the argument 200, that
  25584. ** forces worker threads to run sequentially and deterministically
  25585. ** for testing purposes. */
  25586. if( sqlite3FaultSim(200) ){
  25587. rc = 1;
  25588. }else{
  25589. rc = pthread_create(&p->tid, 0, xTask, pIn);
  25590. }
  25591. if( rc ){
  25592. p->done = 1;
  25593. p->pOut = xTask(pIn);
  25594. }
  25595. *ppThread = p;
  25596. return SQLITE_OK;
  25597. }
  25598. /* Get the results of the thread */
  25599. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  25600. int rc;
  25601. assert( ppOut!=0 );
  25602. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  25603. if( p->done ){
  25604. *ppOut = p->pOut;
  25605. rc = SQLITE_OK;
  25606. }else{
  25607. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  25608. }
  25609. sqlite3_free(p);
  25610. return rc;
  25611. }
  25612. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  25613. /******************************** End Unix Pthreads *************************/
  25614. /********************************* Win32 Threads ****************************/
  25615. #if SQLITE_OS_WIN_THREADS
  25616. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  25617. #include <process.h>
  25618. /* A running thread */
  25619. struct SQLiteThread {
  25620. void *tid; /* The thread handle */
  25621. unsigned id; /* The thread identifier */
  25622. void *(*xTask)(void*); /* The routine to run as a thread */
  25623. void *pIn; /* Argument to xTask */
  25624. void *pResult; /* Result of xTask */
  25625. };
  25626. /* Thread procedure Win32 compatibility shim */
  25627. static unsigned __stdcall sqlite3ThreadProc(
  25628. void *pArg /* IN: Pointer to the SQLiteThread structure */
  25629. ){
  25630. SQLiteThread *p = (SQLiteThread *)pArg;
  25631. assert( p!=0 );
  25632. #if 0
  25633. /*
  25634. ** This assert appears to trigger spuriously on certain
  25635. ** versions of Windows, possibly due to _beginthreadex()
  25636. ** and/or CreateThread() not fully setting their thread
  25637. ** ID parameter before starting the thread.
  25638. */
  25639. assert( p->id==GetCurrentThreadId() );
  25640. #endif
  25641. assert( p->xTask!=0 );
  25642. p->pResult = p->xTask(p->pIn);
  25643. _endthreadex(0);
  25644. return 0; /* NOT REACHED */
  25645. }
  25646. /* Create a new thread */
  25647. SQLITE_PRIVATE int sqlite3ThreadCreate(
  25648. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  25649. void *(*xTask)(void*), /* Routine to run in a separate thread */
  25650. void *pIn /* Argument passed into xTask() */
  25651. ){
  25652. SQLiteThread *p;
  25653. assert( ppThread!=0 );
  25654. assert( xTask!=0 );
  25655. *ppThread = 0;
  25656. p = sqlite3Malloc(sizeof(*p));
  25657. if( p==0 ) return SQLITE_NOMEM_BKPT;
  25658. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  25659. ** function that returns SQLITE_ERROR when passed the argument 200, that
  25660. ** forces worker threads to run sequentially and deterministically
  25661. ** (via the sqlite3FaultSim() term of the conditional) for testing
  25662. ** purposes. */
  25663. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  25664. memset(p, 0, sizeof(*p));
  25665. }else{
  25666. p->xTask = xTask;
  25667. p->pIn = pIn;
  25668. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  25669. if( p->tid==0 ){
  25670. memset(p, 0, sizeof(*p));
  25671. }
  25672. }
  25673. if( p->xTask==0 ){
  25674. p->id = GetCurrentThreadId();
  25675. p->pResult = xTask(pIn);
  25676. }
  25677. *ppThread = p;
  25678. return SQLITE_OK;
  25679. }
  25680. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  25681. /* Get the results of the thread */
  25682. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  25683. DWORD rc;
  25684. BOOL bRc;
  25685. assert( ppOut!=0 );
  25686. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  25687. if( p->xTask==0 ){
  25688. /* assert( p->id==GetCurrentThreadId() ); */
  25689. rc = WAIT_OBJECT_0;
  25690. assert( p->tid==0 );
  25691. }else{
  25692. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  25693. rc = sqlite3Win32Wait((HANDLE)p->tid);
  25694. assert( rc!=WAIT_IO_COMPLETION );
  25695. bRc = CloseHandle((HANDLE)p->tid);
  25696. assert( bRc );
  25697. }
  25698. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  25699. sqlite3_free(p);
  25700. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  25701. }
  25702. #endif /* SQLITE_OS_WIN_THREADS */
  25703. /******************************** End Win32 Threads *************************/
  25704. /********************************* Single-Threaded **************************/
  25705. #ifndef SQLITE_THREADS_IMPLEMENTED
  25706. /*
  25707. ** This implementation does not actually create a new thread. It does the
  25708. ** work of the thread in the main thread, when either the thread is created
  25709. ** or when it is joined
  25710. */
  25711. /* A running thread */
  25712. struct SQLiteThread {
  25713. void *(*xTask)(void*); /* The routine to run as a thread */
  25714. void *pIn; /* Argument to xTask */
  25715. void *pResult; /* Result of xTask */
  25716. };
  25717. /* Create a new thread */
  25718. SQLITE_PRIVATE int sqlite3ThreadCreate(
  25719. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  25720. void *(*xTask)(void*), /* Routine to run in a separate thread */
  25721. void *pIn /* Argument passed into xTask() */
  25722. ){
  25723. SQLiteThread *p;
  25724. assert( ppThread!=0 );
  25725. assert( xTask!=0 );
  25726. *ppThread = 0;
  25727. p = sqlite3Malloc(sizeof(*p));
  25728. if( p==0 ) return SQLITE_NOMEM_BKPT;
  25729. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  25730. p->xTask = xTask;
  25731. p->pIn = pIn;
  25732. }else{
  25733. p->xTask = 0;
  25734. p->pResult = xTask(pIn);
  25735. }
  25736. *ppThread = p;
  25737. return SQLITE_OK;
  25738. }
  25739. /* Get the results of the thread */
  25740. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  25741. assert( ppOut!=0 );
  25742. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  25743. if( p->xTask ){
  25744. *ppOut = p->xTask(p->pIn);
  25745. }else{
  25746. *ppOut = p->pResult;
  25747. }
  25748. sqlite3_free(p);
  25749. #if defined(SQLITE_TEST)
  25750. {
  25751. void *pTstAlloc = sqlite3Malloc(10);
  25752. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  25753. sqlite3_free(pTstAlloc);
  25754. }
  25755. #endif
  25756. return SQLITE_OK;
  25757. }
  25758. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  25759. /****************************** End Single-Threaded *************************/
  25760. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  25761. /************** End of threads.c *********************************************/
  25762. /************** Begin file utf.c *********************************************/
  25763. /*
  25764. ** 2004 April 13
  25765. **
  25766. ** The author disclaims copyright to this source code. In place of
  25767. ** a legal notice, here is a blessing:
  25768. **
  25769. ** May you do good and not evil.
  25770. ** May you find forgiveness for yourself and forgive others.
  25771. ** May you share freely, never taking more than you give.
  25772. **
  25773. *************************************************************************
  25774. ** This file contains routines used to translate between UTF-8,
  25775. ** UTF-16, UTF-16BE, and UTF-16LE.
  25776. **
  25777. ** Notes on UTF-8:
  25778. **
  25779. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  25780. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  25781. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  25782. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  25783. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  25784. **
  25785. **
  25786. ** Notes on UTF-16: (with wwww+1==uuuuu)
  25787. **
  25788. ** Word-0 Word-1 Value
  25789. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  25790. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  25791. **
  25792. **
  25793. ** BOM or Byte Order Mark:
  25794. ** 0xff 0xfe little-endian utf-16 follows
  25795. ** 0xfe 0xff big-endian utf-16 follows
  25796. **
  25797. */
  25798. /* #include "sqliteInt.h" */
  25799. /* #include <assert.h> */
  25800. /* #include "vdbeInt.h" */
  25801. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  25802. /*
  25803. ** The following constant value is used by the SQLITE_BIGENDIAN and
  25804. ** SQLITE_LITTLEENDIAN macros.
  25805. */
  25806. SQLITE_PRIVATE const int sqlite3one = 1;
  25807. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  25808. /*
  25809. ** This lookup table is used to help decode the first byte of
  25810. ** a multi-byte UTF8 character.
  25811. */
  25812. static const unsigned char sqlite3Utf8Trans1[] = {
  25813. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  25814. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  25815. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  25816. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  25817. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  25818. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  25819. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  25820. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  25821. };
  25822. #define WRITE_UTF8(zOut, c) { \
  25823. if( c<0x00080 ){ \
  25824. *zOut++ = (u8)(c&0xFF); \
  25825. } \
  25826. else if( c<0x00800 ){ \
  25827. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  25828. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  25829. } \
  25830. else if( c<0x10000 ){ \
  25831. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  25832. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  25833. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  25834. }else{ \
  25835. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  25836. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  25837. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  25838. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  25839. } \
  25840. }
  25841. #define WRITE_UTF16LE(zOut, c) { \
  25842. if( c<=0xFFFF ){ \
  25843. *zOut++ = (u8)(c&0x00FF); \
  25844. *zOut++ = (u8)((c>>8)&0x00FF); \
  25845. }else{ \
  25846. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  25847. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  25848. *zOut++ = (u8)(c&0x00FF); \
  25849. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  25850. } \
  25851. }
  25852. #define WRITE_UTF16BE(zOut, c) { \
  25853. if( c<=0xFFFF ){ \
  25854. *zOut++ = (u8)((c>>8)&0x00FF); \
  25855. *zOut++ = (u8)(c&0x00FF); \
  25856. }else{ \
  25857. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  25858. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  25859. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  25860. *zOut++ = (u8)(c&0x00FF); \
  25861. } \
  25862. }
  25863. #define READ_UTF16LE(zIn, TERM, c){ \
  25864. c = (*zIn++); \
  25865. c += ((*zIn++)<<8); \
  25866. if( c>=0xD800 && c<0xE000 && TERM ){ \
  25867. int c2 = (*zIn++); \
  25868. c2 += ((*zIn++)<<8); \
  25869. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  25870. } \
  25871. }
  25872. #define READ_UTF16BE(zIn, TERM, c){ \
  25873. c = ((*zIn++)<<8); \
  25874. c += (*zIn++); \
  25875. if( c>=0xD800 && c<0xE000 && TERM ){ \
  25876. int c2 = ((*zIn++)<<8); \
  25877. c2 += (*zIn++); \
  25878. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  25879. } \
  25880. }
  25881. /*
  25882. ** Translate a single UTF-8 character. Return the unicode value.
  25883. **
  25884. ** During translation, assume that the byte that zTerm points
  25885. ** is a 0x00.
  25886. **
  25887. ** Write a pointer to the next unread byte back into *pzNext.
  25888. **
  25889. ** Notes On Invalid UTF-8:
  25890. **
  25891. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  25892. ** be encoded as a multi-byte character. Any multi-byte character that
  25893. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  25894. **
  25895. ** * This routine never allows a UTF16 surrogate value to be encoded.
  25896. ** If a multi-byte character attempts to encode a value between
  25897. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  25898. **
  25899. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  25900. ** byte of a character are interpreted as single-byte characters
  25901. ** and rendered as themselves even though they are technically
  25902. ** invalid characters.
  25903. **
  25904. ** * This routine accepts over-length UTF8 encodings
  25905. ** for unicode values 0x80 and greater. It does not change over-length
  25906. ** encodings to 0xfffd as some systems recommend.
  25907. */
  25908. #define READ_UTF8(zIn, zTerm, c) \
  25909. c = *(zIn++); \
  25910. if( c>=0xc0 ){ \
  25911. c = sqlite3Utf8Trans1[c-0xc0]; \
  25912. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  25913. c = (c<<6) + (0x3f & *(zIn++)); \
  25914. } \
  25915. if( c<0x80 \
  25916. || (c&0xFFFFF800)==0xD800 \
  25917. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  25918. }
  25919. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  25920. const unsigned char **pz /* Pointer to string from which to read char */
  25921. ){
  25922. unsigned int c;
  25923. /* Same as READ_UTF8() above but without the zTerm parameter.
  25924. ** For this routine, we assume the UTF8 string is always zero-terminated.
  25925. */
  25926. c = *((*pz)++);
  25927. if( c>=0xc0 ){
  25928. c = sqlite3Utf8Trans1[c-0xc0];
  25929. while( (*(*pz) & 0xc0)==0x80 ){
  25930. c = (c<<6) + (0x3f & *((*pz)++));
  25931. }
  25932. if( c<0x80
  25933. || (c&0xFFFFF800)==0xD800
  25934. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  25935. }
  25936. return c;
  25937. }
  25938. /*
  25939. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  25940. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  25941. */
  25942. /* #define TRANSLATE_TRACE 1 */
  25943. #ifndef SQLITE_OMIT_UTF16
  25944. /*
  25945. ** This routine transforms the internal text encoding used by pMem to
  25946. ** desiredEnc. It is an error if the string is already of the desired
  25947. ** encoding, or if *pMem does not contain a string value.
  25948. */
  25949. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  25950. int len; /* Maximum length of output string in bytes */
  25951. unsigned char *zOut; /* Output buffer */
  25952. unsigned char *zIn; /* Input iterator */
  25953. unsigned char *zTerm; /* End of input */
  25954. unsigned char *z; /* Output iterator */
  25955. unsigned int c;
  25956. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  25957. assert( pMem->flags&MEM_Str );
  25958. assert( pMem->enc!=desiredEnc );
  25959. assert( pMem->enc!=0 );
  25960. assert( pMem->n>=0 );
  25961. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  25962. {
  25963. char zBuf[100];
  25964. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  25965. fprintf(stderr, "INPUT: %s\n", zBuf);
  25966. }
  25967. #endif
  25968. /* If the translation is between UTF-16 little and big endian, then
  25969. ** all that is required is to swap the byte order. This case is handled
  25970. ** differently from the others.
  25971. */
  25972. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  25973. u8 temp;
  25974. int rc;
  25975. rc = sqlite3VdbeMemMakeWriteable(pMem);
  25976. if( rc!=SQLITE_OK ){
  25977. assert( rc==SQLITE_NOMEM );
  25978. return SQLITE_NOMEM_BKPT;
  25979. }
  25980. zIn = (u8*)pMem->z;
  25981. zTerm = &zIn[pMem->n&~1];
  25982. while( zIn<zTerm ){
  25983. temp = *zIn;
  25984. *zIn = *(zIn+1);
  25985. zIn++;
  25986. *zIn++ = temp;
  25987. }
  25988. pMem->enc = desiredEnc;
  25989. goto translate_out;
  25990. }
  25991. /* Set len to the maximum number of bytes required in the output buffer. */
  25992. if( desiredEnc==SQLITE_UTF8 ){
  25993. /* When converting from UTF-16, the maximum growth results from
  25994. ** translating a 2-byte character to a 4-byte UTF-8 character.
  25995. ** A single byte is required for the output string
  25996. ** nul-terminator.
  25997. */
  25998. pMem->n &= ~1;
  25999. len = pMem->n * 2 + 1;
  26000. }else{
  26001. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  26002. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  26003. ** character. Two bytes are required in the output buffer for the
  26004. ** nul-terminator.
  26005. */
  26006. len = pMem->n * 2 + 2;
  26007. }
  26008. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  26009. ** byte past the end.
  26010. **
  26011. ** Variable zOut is set to point at the output buffer, space obtained
  26012. ** from sqlite3_malloc().
  26013. */
  26014. zIn = (u8*)pMem->z;
  26015. zTerm = &zIn[pMem->n];
  26016. zOut = sqlite3DbMallocRaw(pMem->db, len);
  26017. if( !zOut ){
  26018. return SQLITE_NOMEM_BKPT;
  26019. }
  26020. z = zOut;
  26021. if( pMem->enc==SQLITE_UTF8 ){
  26022. if( desiredEnc==SQLITE_UTF16LE ){
  26023. /* UTF-8 -> UTF-16 Little-endian */
  26024. while( zIn<zTerm ){
  26025. READ_UTF8(zIn, zTerm, c);
  26026. WRITE_UTF16LE(z, c);
  26027. }
  26028. }else{
  26029. assert( desiredEnc==SQLITE_UTF16BE );
  26030. /* UTF-8 -> UTF-16 Big-endian */
  26031. while( zIn<zTerm ){
  26032. READ_UTF8(zIn, zTerm, c);
  26033. WRITE_UTF16BE(z, c);
  26034. }
  26035. }
  26036. pMem->n = (int)(z - zOut);
  26037. *z++ = 0;
  26038. }else{
  26039. assert( desiredEnc==SQLITE_UTF8 );
  26040. if( pMem->enc==SQLITE_UTF16LE ){
  26041. /* UTF-16 Little-endian -> UTF-8 */
  26042. while( zIn<zTerm ){
  26043. READ_UTF16LE(zIn, zIn<zTerm, c);
  26044. WRITE_UTF8(z, c);
  26045. }
  26046. }else{
  26047. /* UTF-16 Big-endian -> UTF-8 */
  26048. while( zIn<zTerm ){
  26049. READ_UTF16BE(zIn, zIn<zTerm, c);
  26050. WRITE_UTF8(z, c);
  26051. }
  26052. }
  26053. pMem->n = (int)(z - zOut);
  26054. }
  26055. *z = 0;
  26056. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  26057. c = pMem->flags;
  26058. sqlite3VdbeMemRelease(pMem);
  26059. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  26060. pMem->enc = desiredEnc;
  26061. pMem->z = (char*)zOut;
  26062. pMem->zMalloc = pMem->z;
  26063. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  26064. translate_out:
  26065. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  26066. {
  26067. char zBuf[100];
  26068. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  26069. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  26070. }
  26071. #endif
  26072. return SQLITE_OK;
  26073. }
  26074. /*
  26075. ** This routine checks for a byte-order mark at the beginning of the
  26076. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  26077. ** the encoding of the Mem adjusted. This routine does not do any
  26078. ** byte-swapping, it just sets Mem.enc appropriately.
  26079. **
  26080. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  26081. ** changed by this function.
  26082. */
  26083. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  26084. int rc = SQLITE_OK;
  26085. u8 bom = 0;
  26086. assert( pMem->n>=0 );
  26087. if( pMem->n>1 ){
  26088. u8 b1 = *(u8 *)pMem->z;
  26089. u8 b2 = *(((u8 *)pMem->z) + 1);
  26090. if( b1==0xFE && b2==0xFF ){
  26091. bom = SQLITE_UTF16BE;
  26092. }
  26093. if( b1==0xFF && b2==0xFE ){
  26094. bom = SQLITE_UTF16LE;
  26095. }
  26096. }
  26097. if( bom ){
  26098. rc = sqlite3VdbeMemMakeWriteable(pMem);
  26099. if( rc==SQLITE_OK ){
  26100. pMem->n -= 2;
  26101. memmove(pMem->z, &pMem->z[2], pMem->n);
  26102. pMem->z[pMem->n] = '\0';
  26103. pMem->z[pMem->n+1] = '\0';
  26104. pMem->flags |= MEM_Term;
  26105. pMem->enc = bom;
  26106. }
  26107. }
  26108. return rc;
  26109. }
  26110. #endif /* SQLITE_OMIT_UTF16 */
  26111. /*
  26112. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  26113. ** return the number of unicode characters in pZ up to (but not including)
  26114. ** the first 0x00 byte. If nByte is not less than zero, return the
  26115. ** number of unicode characters in the first nByte of pZ (or up to
  26116. ** the first 0x00, whichever comes first).
  26117. */
  26118. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  26119. int r = 0;
  26120. const u8 *z = (const u8*)zIn;
  26121. const u8 *zTerm;
  26122. if( nByte>=0 ){
  26123. zTerm = &z[nByte];
  26124. }else{
  26125. zTerm = (const u8*)(-1);
  26126. }
  26127. assert( z<=zTerm );
  26128. while( *z!=0 && z<zTerm ){
  26129. SQLITE_SKIP_UTF8(z);
  26130. r++;
  26131. }
  26132. return r;
  26133. }
  26134. /* This test function is not currently used by the automated test-suite.
  26135. ** Hence it is only available in debug builds.
  26136. */
  26137. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  26138. /*
  26139. ** Translate UTF-8 to UTF-8.
  26140. **
  26141. ** This has the effect of making sure that the string is well-formed
  26142. ** UTF-8. Miscoded characters are removed.
  26143. **
  26144. ** The translation is done in-place and aborted if the output
  26145. ** overruns the input.
  26146. */
  26147. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  26148. unsigned char *zOut = zIn;
  26149. unsigned char *zStart = zIn;
  26150. u32 c;
  26151. while( zIn[0] && zOut<=zIn ){
  26152. c = sqlite3Utf8Read((const u8**)&zIn);
  26153. if( c!=0xfffd ){
  26154. WRITE_UTF8(zOut, c);
  26155. }
  26156. }
  26157. *zOut = 0;
  26158. return (int)(zOut - zStart);
  26159. }
  26160. #endif
  26161. #ifndef SQLITE_OMIT_UTF16
  26162. /*
  26163. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  26164. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  26165. ** be freed by the calling function.
  26166. **
  26167. ** NULL is returned if there is an allocation error.
  26168. */
  26169. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  26170. Mem m;
  26171. memset(&m, 0, sizeof(m));
  26172. m.db = db;
  26173. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  26174. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  26175. if( db->mallocFailed ){
  26176. sqlite3VdbeMemRelease(&m);
  26177. m.z = 0;
  26178. }
  26179. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  26180. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  26181. assert( m.z || db->mallocFailed );
  26182. return m.z;
  26183. }
  26184. /*
  26185. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  26186. ** Return the number of bytes in the first nChar unicode characters
  26187. ** in pZ. nChar must be non-negative.
  26188. */
  26189. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  26190. int c;
  26191. unsigned char const *z = zIn;
  26192. int n = 0;
  26193. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  26194. while( n<nChar ){
  26195. READ_UTF16BE(z, 1, c);
  26196. n++;
  26197. }
  26198. }else{
  26199. while( n<nChar ){
  26200. READ_UTF16LE(z, 1, c);
  26201. n++;
  26202. }
  26203. }
  26204. return (int)(z-(unsigned char const *)zIn);
  26205. }
  26206. #if defined(SQLITE_TEST)
  26207. /*
  26208. ** This routine is called from the TCL test function "translate_selftest".
  26209. ** It checks that the primitives for serializing and deserializing
  26210. ** characters in each encoding are inverses of each other.
  26211. */
  26212. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  26213. unsigned int i, t;
  26214. unsigned char zBuf[20];
  26215. unsigned char *z;
  26216. int n;
  26217. unsigned int c;
  26218. for(i=0; i<0x00110000; i++){
  26219. z = zBuf;
  26220. WRITE_UTF8(z, i);
  26221. n = (int)(z-zBuf);
  26222. assert( n>0 && n<=4 );
  26223. z[0] = 0;
  26224. z = zBuf;
  26225. c = sqlite3Utf8Read((const u8**)&z);
  26226. t = i;
  26227. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  26228. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  26229. assert( c==t );
  26230. assert( (z-zBuf)==n );
  26231. }
  26232. for(i=0; i<0x00110000; i++){
  26233. if( i>=0xD800 && i<0xE000 ) continue;
  26234. z = zBuf;
  26235. WRITE_UTF16LE(z, i);
  26236. n = (int)(z-zBuf);
  26237. assert( n>0 && n<=4 );
  26238. z[0] = 0;
  26239. z = zBuf;
  26240. READ_UTF16LE(z, 1, c);
  26241. assert( c==i );
  26242. assert( (z-zBuf)==n );
  26243. }
  26244. for(i=0; i<0x00110000; i++){
  26245. if( i>=0xD800 && i<0xE000 ) continue;
  26246. z = zBuf;
  26247. WRITE_UTF16BE(z, i);
  26248. n = (int)(z-zBuf);
  26249. assert( n>0 && n<=4 );
  26250. z[0] = 0;
  26251. z = zBuf;
  26252. READ_UTF16BE(z, 1, c);
  26253. assert( c==i );
  26254. assert( (z-zBuf)==n );
  26255. }
  26256. }
  26257. #endif /* SQLITE_TEST */
  26258. #endif /* SQLITE_OMIT_UTF16 */
  26259. /************** End of utf.c *************************************************/
  26260. /************** Begin file util.c ********************************************/
  26261. /*
  26262. ** 2001 September 15
  26263. **
  26264. ** The author disclaims copyright to this source code. In place of
  26265. ** a legal notice, here is a blessing:
  26266. **
  26267. ** May you do good and not evil.
  26268. ** May you find forgiveness for yourself and forgive others.
  26269. ** May you share freely, never taking more than you give.
  26270. **
  26271. *************************************************************************
  26272. ** Utility functions used throughout sqlite.
  26273. **
  26274. ** This file contains functions for allocating memory, comparing
  26275. ** strings, and stuff like that.
  26276. **
  26277. */
  26278. /* #include "sqliteInt.h" */
  26279. /* #include <stdarg.h> */
  26280. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  26281. # include <math.h>
  26282. #endif
  26283. /*
  26284. ** Routine needed to support the testcase() macro.
  26285. */
  26286. #ifdef SQLITE_COVERAGE_TEST
  26287. SQLITE_PRIVATE void sqlite3Coverage(int x){
  26288. static unsigned dummy = 0;
  26289. dummy += (unsigned)x;
  26290. }
  26291. #endif
  26292. /*
  26293. ** Give a callback to the test harness that can be used to simulate faults
  26294. ** in places where it is difficult or expensive to do so purely by means
  26295. ** of inputs.
  26296. **
  26297. ** The intent of the integer argument is to let the fault simulator know
  26298. ** which of multiple sqlite3FaultSim() calls has been hit.
  26299. **
  26300. ** Return whatever integer value the test callback returns, or return
  26301. ** SQLITE_OK if no test callback is installed.
  26302. */
  26303. #ifndef SQLITE_UNTESTABLE
  26304. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  26305. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  26306. return xCallback ? xCallback(iTest) : SQLITE_OK;
  26307. }
  26308. #endif
  26309. #ifndef SQLITE_OMIT_FLOATING_POINT
  26310. /*
  26311. ** Return true if the floating point value is Not a Number (NaN).
  26312. **
  26313. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  26314. ** Otherwise, we have our own implementation that works on most systems.
  26315. */
  26316. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  26317. int rc; /* The value return */
  26318. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  26319. /*
  26320. ** Systems that support the isnan() library function should probably
  26321. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  26322. ** found that many systems do not have a working isnan() function so
  26323. ** this implementation is provided as an alternative.
  26324. **
  26325. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  26326. ** On the other hand, the use of -ffast-math comes with the following
  26327. ** warning:
  26328. **
  26329. ** This option [-ffast-math] should never be turned on by any
  26330. ** -O option since it can result in incorrect output for programs
  26331. ** which depend on an exact implementation of IEEE or ISO
  26332. ** rules/specifications for math functions.
  26333. **
  26334. ** Under MSVC, this NaN test may fail if compiled with a floating-
  26335. ** point precision mode other than /fp:precise. From the MSDN
  26336. ** documentation:
  26337. **
  26338. ** The compiler [with /fp:precise] will properly handle comparisons
  26339. ** involving NaN. For example, x != x evaluates to true if x is NaN
  26340. ** ...
  26341. */
  26342. #ifdef __FAST_MATH__
  26343. # error SQLite will not work correctly with the -ffast-math option of GCC.
  26344. #endif
  26345. volatile double y = x;
  26346. volatile double z = y;
  26347. rc = (y!=z);
  26348. #else /* if HAVE_ISNAN */
  26349. rc = isnan(x);
  26350. #endif /* HAVE_ISNAN */
  26351. testcase( rc );
  26352. return rc;
  26353. }
  26354. #endif /* SQLITE_OMIT_FLOATING_POINT */
  26355. /*
  26356. ** Compute a string length that is limited to what can be stored in
  26357. ** lower 30 bits of a 32-bit signed integer.
  26358. **
  26359. ** The value returned will never be negative. Nor will it ever be greater
  26360. ** than the actual length of the string. For very long strings (greater
  26361. ** than 1GiB) the value returned might be less than the true string length.
  26362. */
  26363. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  26364. if( z==0 ) return 0;
  26365. return 0x3fffffff & (int)strlen(z);
  26366. }
  26367. /*
  26368. ** Return the declared type of a column. Or return zDflt if the column
  26369. ** has no declared type.
  26370. **
  26371. ** The column type is an extra string stored after the zero-terminator on
  26372. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  26373. */
  26374. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  26375. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  26376. return pCol->zName + strlen(pCol->zName) + 1;
  26377. }
  26378. /*
  26379. ** Helper function for sqlite3Error() - called rarely. Broken out into
  26380. ** a separate routine to avoid unnecessary register saves on entry to
  26381. ** sqlite3Error().
  26382. */
  26383. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  26384. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  26385. sqlite3SystemError(db, err_code);
  26386. }
  26387. /*
  26388. ** Set the current error code to err_code and clear any prior error message.
  26389. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  26390. ** that would be appropriate.
  26391. */
  26392. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  26393. assert( db!=0 );
  26394. db->errCode = err_code;
  26395. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  26396. }
  26397. /*
  26398. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  26399. ** to do based on the SQLite error code in rc.
  26400. */
  26401. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  26402. if( rc==SQLITE_IOERR_NOMEM ) return;
  26403. rc &= 0xff;
  26404. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  26405. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  26406. }
  26407. }
  26408. /*
  26409. ** Set the most recent error code and error string for the sqlite
  26410. ** handle "db". The error code is set to "err_code".
  26411. **
  26412. ** If it is not NULL, string zFormat specifies the format of the
  26413. ** error string in the style of the printf functions: The following
  26414. ** format characters are allowed:
  26415. **
  26416. ** %s Insert a string
  26417. ** %z A string that should be freed after use
  26418. ** %d Insert an integer
  26419. ** %T Insert a token
  26420. ** %S Insert the first element of a SrcList
  26421. **
  26422. ** zFormat and any string tokens that follow it are assumed to be
  26423. ** encoded in UTF-8.
  26424. **
  26425. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  26426. ** should be called with err_code set to SQLITE_OK and zFormat set
  26427. ** to NULL.
  26428. */
  26429. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  26430. assert( db!=0 );
  26431. db->errCode = err_code;
  26432. sqlite3SystemError(db, err_code);
  26433. if( zFormat==0 ){
  26434. sqlite3Error(db, err_code);
  26435. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  26436. char *z;
  26437. va_list ap;
  26438. va_start(ap, zFormat);
  26439. z = sqlite3VMPrintf(db, zFormat, ap);
  26440. va_end(ap);
  26441. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  26442. }
  26443. }
  26444. /*
  26445. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  26446. ** The following formatting characters are allowed:
  26447. **
  26448. ** %s Insert a string
  26449. ** %z A string that should be freed after use
  26450. ** %d Insert an integer
  26451. ** %T Insert a token
  26452. ** %S Insert the first element of a SrcList
  26453. **
  26454. ** This function should be used to report any error that occurs while
  26455. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  26456. ** last thing the sqlite3_prepare() function does is copy the error
  26457. ** stored by this function into the database handle using sqlite3Error().
  26458. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  26459. ** during statement execution (sqlite3_step() etc.).
  26460. */
  26461. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  26462. char *zMsg;
  26463. va_list ap;
  26464. sqlite3 *db = pParse->db;
  26465. va_start(ap, zFormat);
  26466. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  26467. va_end(ap);
  26468. if( db->suppressErr ){
  26469. sqlite3DbFree(db, zMsg);
  26470. }else{
  26471. pParse->nErr++;
  26472. sqlite3DbFree(db, pParse->zErrMsg);
  26473. pParse->zErrMsg = zMsg;
  26474. pParse->rc = SQLITE_ERROR;
  26475. }
  26476. }
  26477. /*
  26478. ** Convert an SQL-style quoted string into a normal string by removing
  26479. ** the quote characters. The conversion is done in-place. If the
  26480. ** input does not begin with a quote character, then this routine
  26481. ** is a no-op.
  26482. **
  26483. ** The input string must be zero-terminated. A new zero-terminator
  26484. ** is added to the dequoted string.
  26485. **
  26486. ** The return value is -1 if no dequoting occurs or the length of the
  26487. ** dequoted string, exclusive of the zero terminator, if dequoting does
  26488. ** occur.
  26489. **
  26490. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  26491. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  26492. ** "a-b-c".
  26493. */
  26494. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  26495. char quote;
  26496. int i, j;
  26497. if( z==0 ) return;
  26498. quote = z[0];
  26499. if( !sqlite3Isquote(quote) ) return;
  26500. if( quote=='[' ) quote = ']';
  26501. for(i=1, j=0;; i++){
  26502. assert( z[i] );
  26503. if( z[i]==quote ){
  26504. if( z[i+1]==quote ){
  26505. z[j++] = quote;
  26506. i++;
  26507. }else{
  26508. break;
  26509. }
  26510. }else{
  26511. z[j++] = z[i];
  26512. }
  26513. }
  26514. z[j] = 0;
  26515. }
  26516. /*
  26517. ** Generate a Token object from a string
  26518. */
  26519. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  26520. p->z = z;
  26521. p->n = sqlite3Strlen30(z);
  26522. }
  26523. /* Convenient short-hand */
  26524. #define UpperToLower sqlite3UpperToLower
  26525. /*
  26526. ** Some systems have stricmp(). Others have strcasecmp(). Because
  26527. ** there is no consistency, we will define our own.
  26528. **
  26529. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  26530. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  26531. ** the contents of two buffers containing UTF-8 strings in a
  26532. ** case-independent fashion, using the same definition of "case
  26533. ** independence" that SQLite uses internally when comparing identifiers.
  26534. */
  26535. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  26536. if( zLeft==0 ){
  26537. return zRight ? -1 : 0;
  26538. }else if( zRight==0 ){
  26539. return 1;
  26540. }
  26541. return sqlite3StrICmp(zLeft, zRight);
  26542. }
  26543. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  26544. unsigned char *a, *b;
  26545. int c;
  26546. a = (unsigned char *)zLeft;
  26547. b = (unsigned char *)zRight;
  26548. for(;;){
  26549. c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
  26550. if( c || *a==0 ) break;
  26551. a++;
  26552. b++;
  26553. }
  26554. return c;
  26555. }
  26556. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  26557. register unsigned char *a, *b;
  26558. if( zLeft==0 ){
  26559. return zRight ? -1 : 0;
  26560. }else if( zRight==0 ){
  26561. return 1;
  26562. }
  26563. a = (unsigned char *)zLeft;
  26564. b = (unsigned char *)zRight;
  26565. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  26566. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  26567. }
  26568. /*
  26569. ** The string z[] is an text representation of a real number.
  26570. ** Convert this string to a double and write it into *pResult.
  26571. **
  26572. ** The string z[] is length bytes in length (bytes, not characters) and
  26573. ** uses the encoding enc. The string is not necessarily zero-terminated.
  26574. **
  26575. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  26576. ** if the string is empty or contains extraneous text. Valid numbers
  26577. ** are in one of these formats:
  26578. **
  26579. ** [+-]digits[E[+-]digits]
  26580. ** [+-]digits.[digits][E[+-]digits]
  26581. ** [+-].digits[E[+-]digits]
  26582. **
  26583. ** Leading and trailing whitespace is ignored for the purpose of determining
  26584. ** validity.
  26585. **
  26586. ** If some prefix of the input string is a valid number, this routine
  26587. ** returns FALSE but it still converts the prefix and writes the result
  26588. ** into *pResult.
  26589. */
  26590. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  26591. #ifndef SQLITE_OMIT_FLOATING_POINT
  26592. int incr;
  26593. const char *zEnd = z + length;
  26594. /* sign * significand * (10 ^ (esign * exponent)) */
  26595. int sign = 1; /* sign of significand */
  26596. i64 s = 0; /* significand */
  26597. int d = 0; /* adjust exponent for shifting decimal point */
  26598. int esign = 1; /* sign of exponent */
  26599. int e = 0; /* exponent */
  26600. int eValid = 1; /* True exponent is either not used or is well-formed */
  26601. double result;
  26602. int nDigits = 0;
  26603. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  26604. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  26605. *pResult = 0.0; /* Default return value, in case of an error */
  26606. if( enc==SQLITE_UTF8 ){
  26607. incr = 1;
  26608. }else{
  26609. int i;
  26610. incr = 2;
  26611. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  26612. for(i=3-enc; i<length && z[i]==0; i+=2){}
  26613. nonNum = i<length;
  26614. zEnd = &z[i^1];
  26615. z += (enc&1);
  26616. }
  26617. /* skip leading spaces */
  26618. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  26619. if( z>=zEnd ) return 0;
  26620. /* get sign of significand */
  26621. if( *z=='-' ){
  26622. sign = -1;
  26623. z+=incr;
  26624. }else if( *z=='+' ){
  26625. z+=incr;
  26626. }
  26627. /* copy max significant digits to significand */
  26628. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  26629. s = s*10 + (*z - '0');
  26630. z+=incr, nDigits++;
  26631. }
  26632. /* skip non-significant significand digits
  26633. ** (increase exponent by d to shift decimal left) */
  26634. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  26635. if( z>=zEnd ) goto do_atof_calc;
  26636. /* if decimal point is present */
  26637. if( *z=='.' ){
  26638. z+=incr;
  26639. /* copy digits from after decimal to significand
  26640. ** (decrease exponent by d to shift decimal right) */
  26641. while( z<zEnd && sqlite3Isdigit(*z) ){
  26642. if( s<((LARGEST_INT64-9)/10) ){
  26643. s = s*10 + (*z - '0');
  26644. d--;
  26645. }
  26646. z+=incr, nDigits++;
  26647. }
  26648. }
  26649. if( z>=zEnd ) goto do_atof_calc;
  26650. /* if exponent is present */
  26651. if( *z=='e' || *z=='E' ){
  26652. z+=incr;
  26653. eValid = 0;
  26654. /* This branch is needed to avoid a (harmless) buffer overread. The
  26655. ** special comment alerts the mutation tester that the correct answer
  26656. ** is obtained even if the branch is omitted */
  26657. if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
  26658. /* get sign of exponent */
  26659. if( *z=='-' ){
  26660. esign = -1;
  26661. z+=incr;
  26662. }else if( *z=='+' ){
  26663. z+=incr;
  26664. }
  26665. /* copy digits to exponent */
  26666. while( z<zEnd && sqlite3Isdigit(*z) ){
  26667. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  26668. z+=incr;
  26669. eValid = 1;
  26670. }
  26671. }
  26672. /* skip trailing spaces */
  26673. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  26674. do_atof_calc:
  26675. /* adjust exponent by d, and update sign */
  26676. e = (e*esign) + d;
  26677. if( e<0 ) {
  26678. esign = -1;
  26679. e *= -1;
  26680. } else {
  26681. esign = 1;
  26682. }
  26683. if( s==0 ) {
  26684. /* In the IEEE 754 standard, zero is signed. */
  26685. result = sign<0 ? -(double)0 : (double)0;
  26686. } else {
  26687. /* Attempt to reduce exponent.
  26688. **
  26689. ** Branches that are not required for the correct answer but which only
  26690. ** help to obtain the correct answer faster are marked with special
  26691. ** comments, as a hint to the mutation tester.
  26692. */
  26693. while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
  26694. if( esign>0 ){
  26695. if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
  26696. s *= 10;
  26697. }else{
  26698. if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
  26699. s /= 10;
  26700. }
  26701. e--;
  26702. }
  26703. /* adjust the sign of significand */
  26704. s = sign<0 ? -s : s;
  26705. if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
  26706. result = (double)s;
  26707. }else{
  26708. LONGDOUBLE_TYPE scale = 1.0;
  26709. /* attempt to handle extremely small/large numbers better */
  26710. if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
  26711. if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
  26712. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  26713. if( esign<0 ){
  26714. result = s / scale;
  26715. result /= 1.0e+308;
  26716. }else{
  26717. result = s * scale;
  26718. result *= 1.0e+308;
  26719. }
  26720. }else{ assert( e>=342 );
  26721. if( esign<0 ){
  26722. result = 0.0*s;
  26723. }else{
  26724. result = 1e308*1e308*s; /* Infinity */
  26725. }
  26726. }
  26727. }else{
  26728. /* 1.0e+22 is the largest power of 10 than can be
  26729. ** represented exactly. */
  26730. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  26731. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  26732. if( esign<0 ){
  26733. result = s / scale;
  26734. }else{
  26735. result = s * scale;
  26736. }
  26737. }
  26738. }
  26739. }
  26740. /* store the result */
  26741. *pResult = result;
  26742. /* return true if number and no extra non-whitespace chracters after */
  26743. return z==zEnd && nDigits>0 && eValid && nonNum==0;
  26744. #else
  26745. return !sqlite3Atoi64(z, pResult, length, enc);
  26746. #endif /* SQLITE_OMIT_FLOATING_POINT */
  26747. }
  26748. /*
  26749. ** Compare the 19-character string zNum against the text representation
  26750. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  26751. ** if zNum is less than, equal to, or greater than the string.
  26752. ** Note that zNum must contain exactly 19 characters.
  26753. **
  26754. ** Unlike memcmp() this routine is guaranteed to return the difference
  26755. ** in the values of the last digit if the only difference is in the
  26756. ** last digit. So, for example,
  26757. **
  26758. ** compare2pow63("9223372036854775800", 1)
  26759. **
  26760. ** will return -8.
  26761. */
  26762. static int compare2pow63(const char *zNum, int incr){
  26763. int c = 0;
  26764. int i;
  26765. /* 012345678901234567 */
  26766. const char *pow63 = "922337203685477580";
  26767. for(i=0; c==0 && i<18; i++){
  26768. c = (zNum[i*incr]-pow63[i])*10;
  26769. }
  26770. if( c==0 ){
  26771. c = zNum[18*incr] - '8';
  26772. testcase( c==(-1) );
  26773. testcase( c==0 );
  26774. testcase( c==(+1) );
  26775. }
  26776. return c;
  26777. }
  26778. /*
  26779. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  26780. ** routine does *not* accept hexadecimal notation.
  26781. **
  26782. ** If the zNum value is representable as a 64-bit twos-complement
  26783. ** integer, then write that value into *pNum and return 0.
  26784. **
  26785. ** If zNum is exactly 9223372036854775808, return 2. This special
  26786. ** case is broken out because while 9223372036854775808 cannot be a
  26787. ** signed 64-bit integer, its negative -9223372036854775808 can be.
  26788. **
  26789. ** If zNum is too big for a 64-bit integer and is not
  26790. ** 9223372036854775808 or if zNum contains any non-numeric text,
  26791. ** then return 1.
  26792. **
  26793. ** length is the number of bytes in the string (bytes, not characters).
  26794. ** The string is not necessarily zero-terminated. The encoding is
  26795. ** given by enc.
  26796. */
  26797. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  26798. int incr;
  26799. u64 u = 0;
  26800. int neg = 0; /* assume positive */
  26801. int i;
  26802. int c = 0;
  26803. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  26804. const char *zStart;
  26805. const char *zEnd = zNum + length;
  26806. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  26807. if( enc==SQLITE_UTF8 ){
  26808. incr = 1;
  26809. }else{
  26810. incr = 2;
  26811. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  26812. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  26813. nonNum = i<length;
  26814. zEnd = &zNum[i^1];
  26815. zNum += (enc&1);
  26816. }
  26817. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  26818. if( zNum<zEnd ){
  26819. if( *zNum=='-' ){
  26820. neg = 1;
  26821. zNum+=incr;
  26822. }else if( *zNum=='+' ){
  26823. zNum+=incr;
  26824. }
  26825. }
  26826. zStart = zNum;
  26827. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  26828. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  26829. u = u*10 + c - '0';
  26830. }
  26831. if( u>LARGEST_INT64 ){
  26832. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  26833. }else if( neg ){
  26834. *pNum = -(i64)u;
  26835. }else{
  26836. *pNum = (i64)u;
  26837. }
  26838. testcase( i==18 );
  26839. testcase( i==19 );
  26840. testcase( i==20 );
  26841. if( &zNum[i]<zEnd /* Extra bytes at the end */
  26842. || (i==0 && zStart==zNum) /* No digits */
  26843. || i>19*incr /* Too many digits */
  26844. || nonNum /* UTF16 with high-order bytes non-zero */
  26845. ){
  26846. /* zNum is empty or contains non-numeric text or is longer
  26847. ** than 19 digits (thus guaranteeing that it is too large) */
  26848. return 1;
  26849. }else if( i<19*incr ){
  26850. /* Less than 19 digits, so we know that it fits in 64 bits */
  26851. assert( u<=LARGEST_INT64 );
  26852. return 0;
  26853. }else{
  26854. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  26855. c = compare2pow63(zNum, incr);
  26856. if( c<0 ){
  26857. /* zNum is less than 9223372036854775808 so it fits */
  26858. assert( u<=LARGEST_INT64 );
  26859. return 0;
  26860. }else if( c>0 ){
  26861. /* zNum is greater than 9223372036854775808 so it overflows */
  26862. return 1;
  26863. }else{
  26864. /* zNum is exactly 9223372036854775808. Fits if negative. The
  26865. ** special case 2 overflow if positive */
  26866. assert( u-1==LARGEST_INT64 );
  26867. return neg ? 0 : 2;
  26868. }
  26869. }
  26870. }
  26871. /*
  26872. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  26873. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  26874. ** whereas sqlite3Atoi64() does not.
  26875. **
  26876. ** Returns:
  26877. **
  26878. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  26879. ** 1 Integer too large for a 64-bit signed integer or is malformed
  26880. ** 2 Special case of 9223372036854775808
  26881. */
  26882. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  26883. #ifndef SQLITE_OMIT_HEX_INTEGER
  26884. if( z[0]=='0'
  26885. && (z[1]=='x' || z[1]=='X')
  26886. ){
  26887. u64 u = 0;
  26888. int i, k;
  26889. for(i=2; z[i]=='0'; i++){}
  26890. for(k=i; sqlite3Isxdigit(z[k]); k++){
  26891. u = u*16 + sqlite3HexToInt(z[k]);
  26892. }
  26893. memcpy(pOut, &u, 8);
  26894. return (z[k]==0 && k-i<=16) ? 0 : 1;
  26895. }else
  26896. #endif /* SQLITE_OMIT_HEX_INTEGER */
  26897. {
  26898. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  26899. }
  26900. }
  26901. /*
  26902. ** If zNum represents an integer that will fit in 32-bits, then set
  26903. ** *pValue to that integer and return true. Otherwise return false.
  26904. **
  26905. ** This routine accepts both decimal and hexadecimal notation for integers.
  26906. **
  26907. ** Any non-numeric characters that following zNum are ignored.
  26908. ** This is different from sqlite3Atoi64() which requires the
  26909. ** input number to be zero-terminated.
  26910. */
  26911. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  26912. sqlite_int64 v = 0;
  26913. int i, c;
  26914. int neg = 0;
  26915. if( zNum[0]=='-' ){
  26916. neg = 1;
  26917. zNum++;
  26918. }else if( zNum[0]=='+' ){
  26919. zNum++;
  26920. }
  26921. #ifndef SQLITE_OMIT_HEX_INTEGER
  26922. else if( zNum[0]=='0'
  26923. && (zNum[1]=='x' || zNum[1]=='X')
  26924. && sqlite3Isxdigit(zNum[2])
  26925. ){
  26926. u32 u = 0;
  26927. zNum += 2;
  26928. while( zNum[0]=='0' ) zNum++;
  26929. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  26930. u = u*16 + sqlite3HexToInt(zNum[i]);
  26931. }
  26932. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  26933. memcpy(pValue, &u, 4);
  26934. return 1;
  26935. }else{
  26936. return 0;
  26937. }
  26938. }
  26939. #endif
  26940. if( !sqlite3Isdigit(zNum[0]) ) return 0;
  26941. while( zNum[0]=='0' ) zNum++;
  26942. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  26943. v = v*10 + c;
  26944. }
  26945. /* The longest decimal representation of a 32 bit integer is 10 digits:
  26946. **
  26947. ** 1234567890
  26948. ** 2^31 -> 2147483648
  26949. */
  26950. testcase( i==10 );
  26951. if( i>10 ){
  26952. return 0;
  26953. }
  26954. testcase( v-neg==2147483647 );
  26955. if( v-neg>2147483647 ){
  26956. return 0;
  26957. }
  26958. if( neg ){
  26959. v = -v;
  26960. }
  26961. *pValue = (int)v;
  26962. return 1;
  26963. }
  26964. /*
  26965. ** Return a 32-bit integer value extracted from a string. If the
  26966. ** string is not an integer, just return 0.
  26967. */
  26968. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  26969. int x = 0;
  26970. if( z ) sqlite3GetInt32(z, &x);
  26971. return x;
  26972. }
  26973. /*
  26974. ** The variable-length integer encoding is as follows:
  26975. **
  26976. ** KEY:
  26977. ** A = 0xxxxxxx 7 bits of data and one flag bit
  26978. ** B = 1xxxxxxx 7 bits of data and one flag bit
  26979. ** C = xxxxxxxx 8 bits of data
  26980. **
  26981. ** 7 bits - A
  26982. ** 14 bits - BA
  26983. ** 21 bits - BBA
  26984. ** 28 bits - BBBA
  26985. ** 35 bits - BBBBA
  26986. ** 42 bits - BBBBBA
  26987. ** 49 bits - BBBBBBA
  26988. ** 56 bits - BBBBBBBA
  26989. ** 64 bits - BBBBBBBBC
  26990. */
  26991. /*
  26992. ** Write a 64-bit variable-length integer to memory starting at p[0].
  26993. ** The length of data write will be between 1 and 9 bytes. The number
  26994. ** of bytes written is returned.
  26995. **
  26996. ** A variable-length integer consists of the lower 7 bits of each byte
  26997. ** for all bytes that have the 8th bit set and one byte with the 8th
  26998. ** bit clear. Except, if we get to the 9th byte, it stores the full
  26999. ** 8 bits and is the last byte.
  27000. */
  27001. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  27002. int i, j, n;
  27003. u8 buf[10];
  27004. if( v & (((u64)0xff000000)<<32) ){
  27005. p[8] = (u8)v;
  27006. v >>= 8;
  27007. for(i=7; i>=0; i--){
  27008. p[i] = (u8)((v & 0x7f) | 0x80);
  27009. v >>= 7;
  27010. }
  27011. return 9;
  27012. }
  27013. n = 0;
  27014. do{
  27015. buf[n++] = (u8)((v & 0x7f) | 0x80);
  27016. v >>= 7;
  27017. }while( v!=0 );
  27018. buf[0] &= 0x7f;
  27019. assert( n<=9 );
  27020. for(i=0, j=n-1; j>=0; j--, i++){
  27021. p[i] = buf[j];
  27022. }
  27023. return n;
  27024. }
  27025. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  27026. if( v<=0x7f ){
  27027. p[0] = v&0x7f;
  27028. return 1;
  27029. }
  27030. if( v<=0x3fff ){
  27031. p[0] = ((v>>7)&0x7f)|0x80;
  27032. p[1] = v&0x7f;
  27033. return 2;
  27034. }
  27035. return putVarint64(p,v);
  27036. }
  27037. /*
  27038. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  27039. ** are defined here rather than simply putting the constant expressions
  27040. ** inline in order to work around bugs in the RVT compiler.
  27041. **
  27042. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  27043. **
  27044. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  27045. */
  27046. #define SLOT_2_0 0x001fc07f
  27047. #define SLOT_4_2_0 0xf01fc07f
  27048. /*
  27049. ** Read a 64-bit variable-length integer from memory starting at p[0].
  27050. ** Return the number of bytes read. The value is stored in *v.
  27051. */
  27052. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  27053. u32 a,b,s;
  27054. a = *p;
  27055. /* a: p0 (unmasked) */
  27056. if (!(a&0x80))
  27057. {
  27058. *v = a;
  27059. return 1;
  27060. }
  27061. p++;
  27062. b = *p;
  27063. /* b: p1 (unmasked) */
  27064. if (!(b&0x80))
  27065. {
  27066. a &= 0x7f;
  27067. a = a<<7;
  27068. a |= b;
  27069. *v = a;
  27070. return 2;
  27071. }
  27072. /* Verify that constants are precomputed correctly */
  27073. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  27074. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  27075. p++;
  27076. a = a<<14;
  27077. a |= *p;
  27078. /* a: p0<<14 | p2 (unmasked) */
  27079. if (!(a&0x80))
  27080. {
  27081. a &= SLOT_2_0;
  27082. b &= 0x7f;
  27083. b = b<<7;
  27084. a |= b;
  27085. *v = a;
  27086. return 3;
  27087. }
  27088. /* CSE1 from below */
  27089. a &= SLOT_2_0;
  27090. p++;
  27091. b = b<<14;
  27092. b |= *p;
  27093. /* b: p1<<14 | p3 (unmasked) */
  27094. if (!(b&0x80))
  27095. {
  27096. b &= SLOT_2_0;
  27097. /* moved CSE1 up */
  27098. /* a &= (0x7f<<14)|(0x7f); */
  27099. a = a<<7;
  27100. a |= b;
  27101. *v = a;
  27102. return 4;
  27103. }
  27104. /* a: p0<<14 | p2 (masked) */
  27105. /* b: p1<<14 | p3 (unmasked) */
  27106. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  27107. /* moved CSE1 up */
  27108. /* a &= (0x7f<<14)|(0x7f); */
  27109. b &= SLOT_2_0;
  27110. s = a;
  27111. /* s: p0<<14 | p2 (masked) */
  27112. p++;
  27113. a = a<<14;
  27114. a |= *p;
  27115. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  27116. if (!(a&0x80))
  27117. {
  27118. /* we can skip these cause they were (effectively) done above
  27119. ** while calculating s */
  27120. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  27121. /* b &= (0x7f<<14)|(0x7f); */
  27122. b = b<<7;
  27123. a |= b;
  27124. s = s>>18;
  27125. *v = ((u64)s)<<32 | a;
  27126. return 5;
  27127. }
  27128. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  27129. s = s<<7;
  27130. s |= b;
  27131. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  27132. p++;
  27133. b = b<<14;
  27134. b |= *p;
  27135. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  27136. if (!(b&0x80))
  27137. {
  27138. /* we can skip this cause it was (effectively) done above in calc'ing s */
  27139. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  27140. a &= SLOT_2_0;
  27141. a = a<<7;
  27142. a |= b;
  27143. s = s>>18;
  27144. *v = ((u64)s)<<32 | a;
  27145. return 6;
  27146. }
  27147. p++;
  27148. a = a<<14;
  27149. a |= *p;
  27150. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  27151. if (!(a&0x80))
  27152. {
  27153. a &= SLOT_4_2_0;
  27154. b &= SLOT_2_0;
  27155. b = b<<7;
  27156. a |= b;
  27157. s = s>>11;
  27158. *v = ((u64)s)<<32 | a;
  27159. return 7;
  27160. }
  27161. /* CSE2 from below */
  27162. a &= SLOT_2_0;
  27163. p++;
  27164. b = b<<14;
  27165. b |= *p;
  27166. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  27167. if (!(b&0x80))
  27168. {
  27169. b &= SLOT_4_2_0;
  27170. /* moved CSE2 up */
  27171. /* a &= (0x7f<<14)|(0x7f); */
  27172. a = a<<7;
  27173. a |= b;
  27174. s = s>>4;
  27175. *v = ((u64)s)<<32 | a;
  27176. return 8;
  27177. }
  27178. p++;
  27179. a = a<<15;
  27180. a |= *p;
  27181. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  27182. /* moved CSE2 up */
  27183. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  27184. b &= SLOT_2_0;
  27185. b = b<<8;
  27186. a |= b;
  27187. s = s<<4;
  27188. b = p[-4];
  27189. b &= 0x7f;
  27190. b = b>>3;
  27191. s |= b;
  27192. *v = ((u64)s)<<32 | a;
  27193. return 9;
  27194. }
  27195. /*
  27196. ** Read a 32-bit variable-length integer from memory starting at p[0].
  27197. ** Return the number of bytes read. The value is stored in *v.
  27198. **
  27199. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  27200. ** integer, then set *v to 0xffffffff.
  27201. **
  27202. ** A MACRO version, getVarint32, is provided which inlines the
  27203. ** single-byte case. All code should use the MACRO version as
  27204. ** this function assumes the single-byte case has already been handled.
  27205. */
  27206. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  27207. u32 a,b;
  27208. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  27209. ** by the getVarin32() macro */
  27210. a = *p;
  27211. /* a: p0 (unmasked) */
  27212. #ifndef getVarint32
  27213. if (!(a&0x80))
  27214. {
  27215. /* Values between 0 and 127 */
  27216. *v = a;
  27217. return 1;
  27218. }
  27219. #endif
  27220. /* The 2-byte case */
  27221. p++;
  27222. b = *p;
  27223. /* b: p1 (unmasked) */
  27224. if (!(b&0x80))
  27225. {
  27226. /* Values between 128 and 16383 */
  27227. a &= 0x7f;
  27228. a = a<<7;
  27229. *v = a | b;
  27230. return 2;
  27231. }
  27232. /* The 3-byte case */
  27233. p++;
  27234. a = a<<14;
  27235. a |= *p;
  27236. /* a: p0<<14 | p2 (unmasked) */
  27237. if (!(a&0x80))
  27238. {
  27239. /* Values between 16384 and 2097151 */
  27240. a &= (0x7f<<14)|(0x7f);
  27241. b &= 0x7f;
  27242. b = b<<7;
  27243. *v = a | b;
  27244. return 3;
  27245. }
  27246. /* A 32-bit varint is used to store size information in btrees.
  27247. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  27248. ** A 3-byte varint is sufficient, for example, to record the size
  27249. ** of a 1048569-byte BLOB or string.
  27250. **
  27251. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  27252. ** rare larger cases can be handled by the slower 64-bit varint
  27253. ** routine.
  27254. */
  27255. #if 1
  27256. {
  27257. u64 v64;
  27258. u8 n;
  27259. p -= 2;
  27260. n = sqlite3GetVarint(p, &v64);
  27261. assert( n>3 && n<=9 );
  27262. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  27263. *v = 0xffffffff;
  27264. }else{
  27265. *v = (u32)v64;
  27266. }
  27267. return n;
  27268. }
  27269. #else
  27270. /* For following code (kept for historical record only) shows an
  27271. ** unrolling for the 3- and 4-byte varint cases. This code is
  27272. ** slightly faster, but it is also larger and much harder to test.
  27273. */
  27274. p++;
  27275. b = b<<14;
  27276. b |= *p;
  27277. /* b: p1<<14 | p3 (unmasked) */
  27278. if (!(b&0x80))
  27279. {
  27280. /* Values between 2097152 and 268435455 */
  27281. b &= (0x7f<<14)|(0x7f);
  27282. a &= (0x7f<<14)|(0x7f);
  27283. a = a<<7;
  27284. *v = a | b;
  27285. return 4;
  27286. }
  27287. p++;
  27288. a = a<<14;
  27289. a |= *p;
  27290. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  27291. if (!(a&0x80))
  27292. {
  27293. /* Values between 268435456 and 34359738367 */
  27294. a &= SLOT_4_2_0;
  27295. b &= SLOT_4_2_0;
  27296. b = b<<7;
  27297. *v = a | b;
  27298. return 5;
  27299. }
  27300. /* We can only reach this point when reading a corrupt database
  27301. ** file. In that case we are not in any hurry. Use the (relatively
  27302. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  27303. ** value. */
  27304. {
  27305. u64 v64;
  27306. u8 n;
  27307. p -= 4;
  27308. n = sqlite3GetVarint(p, &v64);
  27309. assert( n>5 && n<=9 );
  27310. *v = (u32)v64;
  27311. return n;
  27312. }
  27313. #endif
  27314. }
  27315. /*
  27316. ** Return the number of bytes that will be needed to store the given
  27317. ** 64-bit integer.
  27318. */
  27319. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  27320. int i;
  27321. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  27322. return i;
  27323. }
  27324. /*
  27325. ** Read or write a four-byte big-endian integer value.
  27326. */
  27327. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  27328. #if SQLITE_BYTEORDER==4321
  27329. u32 x;
  27330. memcpy(&x,p,4);
  27331. return x;
  27332. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  27333. u32 x;
  27334. memcpy(&x,p,4);
  27335. return __builtin_bswap32(x);
  27336. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  27337. u32 x;
  27338. memcpy(&x,p,4);
  27339. return _byteswap_ulong(x);
  27340. #else
  27341. testcase( p[0]&0x80 );
  27342. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  27343. #endif
  27344. }
  27345. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  27346. #if SQLITE_BYTEORDER==4321
  27347. memcpy(p,&v,4);
  27348. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  27349. u32 x = __builtin_bswap32(v);
  27350. memcpy(p,&x,4);
  27351. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  27352. u32 x = _byteswap_ulong(v);
  27353. memcpy(p,&x,4);
  27354. #else
  27355. p[0] = (u8)(v>>24);
  27356. p[1] = (u8)(v>>16);
  27357. p[2] = (u8)(v>>8);
  27358. p[3] = (u8)v;
  27359. #endif
  27360. }
  27361. /*
  27362. ** Translate a single byte of Hex into an integer.
  27363. ** This routine only works if h really is a valid hexadecimal
  27364. ** character: 0..9a..fA..F
  27365. */
  27366. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  27367. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  27368. #ifdef SQLITE_ASCII
  27369. h += 9*(1&(h>>6));
  27370. #endif
  27371. #ifdef SQLITE_EBCDIC
  27372. h += 9*(1&~(h>>4));
  27373. #endif
  27374. return (u8)(h & 0xf);
  27375. }
  27376. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  27377. /*
  27378. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  27379. ** value. Return a pointer to its binary value. Space to hold the
  27380. ** binary value has been obtained from malloc and must be freed by
  27381. ** the calling routine.
  27382. */
  27383. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  27384. char *zBlob;
  27385. int i;
  27386. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  27387. n--;
  27388. if( zBlob ){
  27389. for(i=0; i<n; i+=2){
  27390. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  27391. }
  27392. zBlob[i/2] = 0;
  27393. }
  27394. return zBlob;
  27395. }
  27396. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  27397. /*
  27398. ** Log an error that is an API call on a connection pointer that should
  27399. ** not have been used. The "type" of connection pointer is given as the
  27400. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  27401. */
  27402. static void logBadConnection(const char *zType){
  27403. sqlite3_log(SQLITE_MISUSE,
  27404. "API call with %s database connection pointer",
  27405. zType
  27406. );
  27407. }
  27408. /*
  27409. ** Check to make sure we have a valid db pointer. This test is not
  27410. ** foolproof but it does provide some measure of protection against
  27411. ** misuse of the interface such as passing in db pointers that are
  27412. ** NULL or which have been previously closed. If this routine returns
  27413. ** 1 it means that the db pointer is valid and 0 if it should not be
  27414. ** dereferenced for any reason. The calling function should invoke
  27415. ** SQLITE_MISUSE immediately.
  27416. **
  27417. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  27418. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  27419. ** open properly and is not fit for general use but which can be
  27420. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  27421. */
  27422. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  27423. u32 magic;
  27424. if( db==0 ){
  27425. logBadConnection("NULL");
  27426. return 0;
  27427. }
  27428. magic = db->magic;
  27429. if( magic!=SQLITE_MAGIC_OPEN ){
  27430. if( sqlite3SafetyCheckSickOrOk(db) ){
  27431. testcase( sqlite3GlobalConfig.xLog!=0 );
  27432. logBadConnection("unopened");
  27433. }
  27434. return 0;
  27435. }else{
  27436. return 1;
  27437. }
  27438. }
  27439. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  27440. u32 magic;
  27441. magic = db->magic;
  27442. if( magic!=SQLITE_MAGIC_SICK &&
  27443. magic!=SQLITE_MAGIC_OPEN &&
  27444. magic!=SQLITE_MAGIC_BUSY ){
  27445. testcase( sqlite3GlobalConfig.xLog!=0 );
  27446. logBadConnection("invalid");
  27447. return 0;
  27448. }else{
  27449. return 1;
  27450. }
  27451. }
  27452. /*
  27453. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  27454. ** the other 64-bit signed integer at *pA and store the result in *pA.
  27455. ** Return 0 on success. Or if the operation would have resulted in an
  27456. ** overflow, leave *pA unchanged and return 1.
  27457. */
  27458. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  27459. #if GCC_VERSION>=5004000
  27460. return __builtin_add_overflow(*pA, iB, pA);
  27461. #else
  27462. i64 iA = *pA;
  27463. testcase( iA==0 ); testcase( iA==1 );
  27464. testcase( iB==-1 ); testcase( iB==0 );
  27465. if( iB>=0 ){
  27466. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  27467. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  27468. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  27469. }else{
  27470. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  27471. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  27472. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  27473. }
  27474. *pA += iB;
  27475. return 0;
  27476. #endif
  27477. }
  27478. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  27479. #if GCC_VERSION>=5004000
  27480. return __builtin_sub_overflow(*pA, iB, pA);
  27481. #else
  27482. testcase( iB==SMALLEST_INT64+1 );
  27483. if( iB==SMALLEST_INT64 ){
  27484. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  27485. if( (*pA)>=0 ) return 1;
  27486. *pA -= iB;
  27487. return 0;
  27488. }else{
  27489. return sqlite3AddInt64(pA, -iB);
  27490. }
  27491. #endif
  27492. }
  27493. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  27494. #if GCC_VERSION>=5004000
  27495. return __builtin_mul_overflow(*pA, iB, pA);
  27496. #else
  27497. i64 iA = *pA;
  27498. if( iB>0 ){
  27499. if( iA>LARGEST_INT64/iB ) return 1;
  27500. if( iA<SMALLEST_INT64/iB ) return 1;
  27501. }else if( iB<0 ){
  27502. if( iA>0 ){
  27503. if( iB<SMALLEST_INT64/iA ) return 1;
  27504. }else if( iA<0 ){
  27505. if( iB==SMALLEST_INT64 ) return 1;
  27506. if( iA==SMALLEST_INT64 ) return 1;
  27507. if( -iA>LARGEST_INT64/-iB ) return 1;
  27508. }
  27509. }
  27510. *pA = iA*iB;
  27511. return 0;
  27512. #endif
  27513. }
  27514. /*
  27515. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  27516. ** if the integer has a value of -2147483648, return +2147483647
  27517. */
  27518. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  27519. if( x>=0 ) return x;
  27520. if( x==(int)0x80000000 ) return 0x7fffffff;
  27521. return -x;
  27522. }
  27523. #ifdef SQLITE_ENABLE_8_3_NAMES
  27524. /*
  27525. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  27526. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  27527. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  27528. ** three characters, then shorten the suffix on z[] to be the last three
  27529. ** characters of the original suffix.
  27530. **
  27531. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  27532. ** do the suffix shortening regardless of URI parameter.
  27533. **
  27534. ** Examples:
  27535. **
  27536. ** test.db-journal => test.nal
  27537. ** test.db-wal => test.wal
  27538. ** test.db-shm => test.shm
  27539. ** test.db-mj7f3319fa => test.9fa
  27540. */
  27541. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  27542. #if SQLITE_ENABLE_8_3_NAMES<2
  27543. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  27544. #endif
  27545. {
  27546. int i, sz;
  27547. sz = sqlite3Strlen30(z);
  27548. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  27549. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  27550. }
  27551. }
  27552. #endif
  27553. /*
  27554. ** Find (an approximate) sum of two LogEst values. This computation is
  27555. ** not a simple "+" operator because LogEst is stored as a logarithmic
  27556. ** value.
  27557. **
  27558. */
  27559. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  27560. static const unsigned char x[] = {
  27561. 10, 10, /* 0,1 */
  27562. 9, 9, /* 2,3 */
  27563. 8, 8, /* 4,5 */
  27564. 7, 7, 7, /* 6,7,8 */
  27565. 6, 6, 6, /* 9,10,11 */
  27566. 5, 5, 5, /* 12-14 */
  27567. 4, 4, 4, 4, /* 15-18 */
  27568. 3, 3, 3, 3, 3, 3, /* 19-24 */
  27569. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  27570. };
  27571. if( a>=b ){
  27572. if( a>b+49 ) return a;
  27573. if( a>b+31 ) return a+1;
  27574. return a+x[a-b];
  27575. }else{
  27576. if( b>a+49 ) return b;
  27577. if( b>a+31 ) return b+1;
  27578. return b+x[b-a];
  27579. }
  27580. }
  27581. /*
  27582. ** Convert an integer into a LogEst. In other words, compute an
  27583. ** approximation for 10*log2(x).
  27584. */
  27585. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  27586. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  27587. LogEst y = 40;
  27588. if( x<8 ){
  27589. if( x<2 ) return 0;
  27590. while( x<8 ){ y -= 10; x <<= 1; }
  27591. }else{
  27592. while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
  27593. while( x>15 ){ y += 10; x >>= 1; }
  27594. }
  27595. return a[x&7] + y - 10;
  27596. }
  27597. #ifndef SQLITE_OMIT_VIRTUALTABLE
  27598. /*
  27599. ** Convert a double into a LogEst
  27600. ** In other words, compute an approximation for 10*log2(x).
  27601. */
  27602. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  27603. u64 a;
  27604. LogEst e;
  27605. assert( sizeof(x)==8 && sizeof(a)==8 );
  27606. if( x<=1 ) return 0;
  27607. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  27608. memcpy(&a, &x, 8);
  27609. e = (a>>52) - 1022;
  27610. return e*10;
  27611. }
  27612. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  27613. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  27614. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  27615. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  27616. /*
  27617. ** Convert a LogEst into an integer.
  27618. **
  27619. ** Note that this routine is only used when one or more of various
  27620. ** non-standard compile-time options is enabled.
  27621. */
  27622. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  27623. u64 n;
  27624. n = x%10;
  27625. x /= 10;
  27626. if( n>=5 ) n -= 2;
  27627. else if( n>=1 ) n -= 1;
  27628. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  27629. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  27630. if( x>60 ) return (u64)LARGEST_INT64;
  27631. #else
  27632. /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
  27633. ** possible to this routine is 310, resulting in a maximum x of 31 */
  27634. assert( x<=60 );
  27635. #endif
  27636. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  27637. }
  27638. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  27639. /*
  27640. ** Add a new name/number pair to a VList. This might require that the
  27641. ** VList object be reallocated, so return the new VList. If an OOM
  27642. ** error occurs, the original VList returned and the
  27643. ** db->mallocFailed flag is set.
  27644. **
  27645. ** A VList is really just an array of integers. To destroy a VList,
  27646. ** simply pass it to sqlite3DbFree().
  27647. **
  27648. ** The first integer is the number of integers allocated for the whole
  27649. ** VList. The second integer is the number of integers actually used.
  27650. ** Each name/number pair is encoded by subsequent groups of 3 or more
  27651. ** integers.
  27652. **
  27653. ** Each name/number pair starts with two integers which are the numeric
  27654. ** value for the pair and the size of the name/number pair, respectively.
  27655. ** The text name overlays one or more following integers. The text name
  27656. ** is always zero-terminated.
  27657. **
  27658. ** Conceptually:
  27659. **
  27660. ** struct VList {
  27661. ** int nAlloc; // Number of allocated slots
  27662. ** int nUsed; // Number of used slots
  27663. ** struct VListEntry {
  27664. ** int iValue; // Value for this entry
  27665. ** int nSlot; // Slots used by this entry
  27666. ** // ... variable name goes here
  27667. ** } a[0];
  27668. ** }
  27669. **
  27670. ** During code generation, pointers to the variable names within the
  27671. ** VList are taken. When that happens, nAlloc is set to zero as an
  27672. ** indication that the VList may never again be enlarged, since the
  27673. ** accompanying realloc() would invalidate the pointers.
  27674. */
  27675. SQLITE_PRIVATE VList *sqlite3VListAdd(
  27676. sqlite3 *db, /* The database connection used for malloc() */
  27677. VList *pIn, /* The input VList. Might be NULL */
  27678. const char *zName, /* Name of symbol to add */
  27679. int nName, /* Bytes of text in zName */
  27680. int iVal /* Value to associate with zName */
  27681. ){
  27682. int nInt; /* number of sizeof(int) objects needed for zName */
  27683. char *z; /* Pointer to where zName will be stored */
  27684. int i; /* Index in pIn[] where zName is stored */
  27685. nInt = nName/4 + 3;
  27686. assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
  27687. if( pIn==0 || pIn[1]+nInt > pIn[0] ){
  27688. /* Enlarge the allocation */
  27689. int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
  27690. VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
  27691. if( pOut==0 ) return pIn;
  27692. if( pIn==0 ) pOut[1] = 2;
  27693. pIn = pOut;
  27694. pIn[0] = nAlloc;
  27695. }
  27696. i = pIn[1];
  27697. pIn[i] = iVal;
  27698. pIn[i+1] = nInt;
  27699. z = (char*)&pIn[i+2];
  27700. pIn[1] = i+nInt;
  27701. assert( pIn[1]<=pIn[0] );
  27702. memcpy(z, zName, nName);
  27703. z[nName] = 0;
  27704. return pIn;
  27705. }
  27706. /*
  27707. ** Return a pointer to the name of a variable in the given VList that
  27708. ** has the value iVal. Or return a NULL if there is no such variable in
  27709. ** the list
  27710. */
  27711. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
  27712. int i, mx;
  27713. if( pIn==0 ) return 0;
  27714. mx = pIn[1];
  27715. i = 2;
  27716. do{
  27717. if( pIn[i]==iVal ) return (char*)&pIn[i+2];
  27718. i += pIn[i+1];
  27719. }while( i<mx );
  27720. return 0;
  27721. }
  27722. /*
  27723. ** Return the number of the variable named zName, if it is in VList.
  27724. ** or return 0 if there is no such variable.
  27725. */
  27726. SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
  27727. int i, mx;
  27728. if( pIn==0 ) return 0;
  27729. mx = pIn[1];
  27730. i = 2;
  27731. do{
  27732. const char *z = (const char*)&pIn[i+2];
  27733. if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
  27734. i += pIn[i+1];
  27735. }while( i<mx );
  27736. return 0;
  27737. }
  27738. /************** End of util.c ************************************************/
  27739. /************** Begin file hash.c ********************************************/
  27740. /*
  27741. ** 2001 September 22
  27742. **
  27743. ** The author disclaims copyright to this source code. In place of
  27744. ** a legal notice, here is a blessing:
  27745. **
  27746. ** May you do good and not evil.
  27747. ** May you find forgiveness for yourself and forgive others.
  27748. ** May you share freely, never taking more than you give.
  27749. **
  27750. *************************************************************************
  27751. ** This is the implementation of generic hash-tables
  27752. ** used in SQLite.
  27753. */
  27754. /* #include "sqliteInt.h" */
  27755. /* #include <assert.h> */
  27756. /* Turn bulk memory into a hash table object by initializing the
  27757. ** fields of the Hash structure.
  27758. **
  27759. ** "pNew" is a pointer to the hash table that is to be initialized.
  27760. */
  27761. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  27762. assert( pNew!=0 );
  27763. pNew->first = 0;
  27764. pNew->count = 0;
  27765. pNew->htsize = 0;
  27766. pNew->ht = 0;
  27767. }
  27768. /* Remove all entries from a hash table. Reclaim all memory.
  27769. ** Call this routine to delete a hash table or to reset a hash table
  27770. ** to the empty state.
  27771. */
  27772. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  27773. HashElem *elem; /* For looping over all elements of the table */
  27774. assert( pH!=0 );
  27775. elem = pH->first;
  27776. pH->first = 0;
  27777. sqlite3_free(pH->ht);
  27778. pH->ht = 0;
  27779. pH->htsize = 0;
  27780. while( elem ){
  27781. HashElem *next_elem = elem->next;
  27782. sqlite3_free(elem);
  27783. elem = next_elem;
  27784. }
  27785. pH->count = 0;
  27786. }
  27787. /*
  27788. ** The hashing function.
  27789. */
  27790. static unsigned int strHash(const char *z){
  27791. unsigned int h = 0;
  27792. unsigned char c;
  27793. while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
  27794. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  27795. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  27796. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  27797. h += sqlite3UpperToLower[c];
  27798. h *= 0x9e3779b1;
  27799. }
  27800. return h;
  27801. }
  27802. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  27803. ** insert pNew into the pEntry hash bucket.
  27804. */
  27805. static void insertElement(
  27806. Hash *pH, /* The complete hash table */
  27807. struct _ht *pEntry, /* The entry into which pNew is inserted */
  27808. HashElem *pNew /* The element to be inserted */
  27809. ){
  27810. HashElem *pHead; /* First element already in pEntry */
  27811. if( pEntry ){
  27812. pHead = pEntry->count ? pEntry->chain : 0;
  27813. pEntry->count++;
  27814. pEntry->chain = pNew;
  27815. }else{
  27816. pHead = 0;
  27817. }
  27818. if( pHead ){
  27819. pNew->next = pHead;
  27820. pNew->prev = pHead->prev;
  27821. if( pHead->prev ){ pHead->prev->next = pNew; }
  27822. else { pH->first = pNew; }
  27823. pHead->prev = pNew;
  27824. }else{
  27825. pNew->next = pH->first;
  27826. if( pH->first ){ pH->first->prev = pNew; }
  27827. pNew->prev = 0;
  27828. pH->first = pNew;
  27829. }
  27830. }
  27831. /* Resize the hash table so that it cantains "new_size" buckets.
  27832. **
  27833. ** The hash table might fail to resize if sqlite3_malloc() fails or
  27834. ** if the new size is the same as the prior size.
  27835. ** Return TRUE if the resize occurs and false if not.
  27836. */
  27837. static int rehash(Hash *pH, unsigned int new_size){
  27838. struct _ht *new_ht; /* The new hash table */
  27839. HashElem *elem, *next_elem; /* For looping over existing elements */
  27840. #if SQLITE_MALLOC_SOFT_LIMIT>0
  27841. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  27842. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  27843. }
  27844. if( new_size==pH->htsize ) return 0;
  27845. #endif
  27846. /* The inability to allocates space for a larger hash table is
  27847. ** a performance hit but it is not a fatal error. So mark the
  27848. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  27849. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  27850. ** only zeroes the requested number of bytes whereas this module will
  27851. ** use the actual amount of space allocated for the hash table (which
  27852. ** may be larger than the requested amount).
  27853. */
  27854. sqlite3BeginBenignMalloc();
  27855. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  27856. sqlite3EndBenignMalloc();
  27857. if( new_ht==0 ) return 0;
  27858. sqlite3_free(pH->ht);
  27859. pH->ht = new_ht;
  27860. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  27861. memset(new_ht, 0, new_size*sizeof(struct _ht));
  27862. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  27863. unsigned int h = strHash(elem->pKey) % new_size;
  27864. next_elem = elem->next;
  27865. insertElement(pH, &new_ht[h], elem);
  27866. }
  27867. return 1;
  27868. }
  27869. /* This function (for internal use only) locates an element in an
  27870. ** hash table that matches the given key. The hash for this key is
  27871. ** also computed and returned in the *pH parameter.
  27872. */
  27873. static HashElem *findElementWithHash(
  27874. const Hash *pH, /* The pH to be searched */
  27875. const char *pKey, /* The key we are searching for */
  27876. unsigned int *pHash /* Write the hash value here */
  27877. ){
  27878. HashElem *elem; /* Used to loop thru the element list */
  27879. int count; /* Number of elements left to test */
  27880. unsigned int h; /* The computed hash */
  27881. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  27882. struct _ht *pEntry;
  27883. h = strHash(pKey) % pH->htsize;
  27884. pEntry = &pH->ht[h];
  27885. elem = pEntry->chain;
  27886. count = pEntry->count;
  27887. }else{
  27888. h = 0;
  27889. elem = pH->first;
  27890. count = pH->count;
  27891. }
  27892. *pHash = h;
  27893. while( count-- ){
  27894. assert( elem!=0 );
  27895. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  27896. return elem;
  27897. }
  27898. elem = elem->next;
  27899. }
  27900. return 0;
  27901. }
  27902. /* Remove a single entry from the hash table given a pointer to that
  27903. ** element and a hash on the element's key.
  27904. */
  27905. static void removeElementGivenHash(
  27906. Hash *pH, /* The pH containing "elem" */
  27907. HashElem* elem, /* The element to be removed from the pH */
  27908. unsigned int h /* Hash value for the element */
  27909. ){
  27910. struct _ht *pEntry;
  27911. if( elem->prev ){
  27912. elem->prev->next = elem->next;
  27913. }else{
  27914. pH->first = elem->next;
  27915. }
  27916. if( elem->next ){
  27917. elem->next->prev = elem->prev;
  27918. }
  27919. if( pH->ht ){
  27920. pEntry = &pH->ht[h];
  27921. if( pEntry->chain==elem ){
  27922. pEntry->chain = elem->next;
  27923. }
  27924. pEntry->count--;
  27925. assert( pEntry->count>=0 );
  27926. }
  27927. sqlite3_free( elem );
  27928. pH->count--;
  27929. if( pH->count==0 ){
  27930. assert( pH->first==0 );
  27931. assert( pH->count==0 );
  27932. sqlite3HashClear(pH);
  27933. }
  27934. }
  27935. /* Attempt to locate an element of the hash table pH with a key
  27936. ** that matches pKey. Return the data for this element if it is
  27937. ** found, or NULL if there is no match.
  27938. */
  27939. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  27940. HashElem *elem; /* The element that matches key */
  27941. unsigned int h; /* A hash on key */
  27942. assert( pH!=0 );
  27943. assert( pKey!=0 );
  27944. elem = findElementWithHash(pH, pKey, &h);
  27945. return elem ? elem->data : 0;
  27946. }
  27947. /* Insert an element into the hash table pH. The key is pKey
  27948. ** and the data is "data".
  27949. **
  27950. ** If no element exists with a matching key, then a new
  27951. ** element is created and NULL is returned.
  27952. **
  27953. ** If another element already exists with the same key, then the
  27954. ** new data replaces the old data and the old data is returned.
  27955. ** The key is not copied in this instance. If a malloc fails, then
  27956. ** the new data is returned and the hash table is unchanged.
  27957. **
  27958. ** If the "data" parameter to this function is NULL, then the
  27959. ** element corresponding to "key" is removed from the hash table.
  27960. */
  27961. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  27962. unsigned int h; /* the hash of the key modulo hash table size */
  27963. HashElem *elem; /* Used to loop thru the element list */
  27964. HashElem *new_elem; /* New element added to the pH */
  27965. assert( pH!=0 );
  27966. assert( pKey!=0 );
  27967. elem = findElementWithHash(pH,pKey,&h);
  27968. if( elem ){
  27969. void *old_data = elem->data;
  27970. if( data==0 ){
  27971. removeElementGivenHash(pH,elem,h);
  27972. }else{
  27973. elem->data = data;
  27974. elem->pKey = pKey;
  27975. }
  27976. return old_data;
  27977. }
  27978. if( data==0 ) return 0;
  27979. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  27980. if( new_elem==0 ) return data;
  27981. new_elem->pKey = pKey;
  27982. new_elem->data = data;
  27983. pH->count++;
  27984. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  27985. if( rehash(pH, pH->count*2) ){
  27986. assert( pH->htsize>0 );
  27987. h = strHash(pKey) % pH->htsize;
  27988. }
  27989. }
  27990. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  27991. return 0;
  27992. }
  27993. /************** End of hash.c ************************************************/
  27994. /************** Begin file opcodes.c *****************************************/
  27995. /* Automatically generated. Do not edit */
  27996. /* See the tool/mkopcodec.tcl script for details. */
  27997. #if !defined(SQLITE_OMIT_EXPLAIN) \
  27998. || defined(VDBE_PROFILE) \
  27999. || defined(SQLITE_DEBUG)
  28000. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  28001. # define OpHelp(X) "\0" X
  28002. #else
  28003. # define OpHelp(X)
  28004. #endif
  28005. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  28006. static const char *const azName[] = {
  28007. /* 0 */ "Savepoint" OpHelp(""),
  28008. /* 1 */ "AutoCommit" OpHelp(""),
  28009. /* 2 */ "Transaction" OpHelp(""),
  28010. /* 3 */ "SorterNext" OpHelp(""),
  28011. /* 4 */ "PrevIfOpen" OpHelp(""),
  28012. /* 5 */ "NextIfOpen" OpHelp(""),
  28013. /* 6 */ "Prev" OpHelp(""),
  28014. /* 7 */ "Next" OpHelp(""),
  28015. /* 8 */ "Checkpoint" OpHelp(""),
  28016. /* 9 */ "JournalMode" OpHelp(""),
  28017. /* 10 */ "Vacuum" OpHelp(""),
  28018. /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  28019. /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  28020. /* 13 */ "Goto" OpHelp(""),
  28021. /* 14 */ "Gosub" OpHelp(""),
  28022. /* 15 */ "InitCoroutine" OpHelp(""),
  28023. /* 16 */ "Yield" OpHelp(""),
  28024. /* 17 */ "MustBeInt" OpHelp(""),
  28025. /* 18 */ "Jump" OpHelp(""),
  28026. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  28027. /* 20 */ "Once" OpHelp(""),
  28028. /* 21 */ "If" OpHelp(""),
  28029. /* 22 */ "IfNot" OpHelp(""),
  28030. /* 23 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
  28031. /* 24 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  28032. /* 25 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  28033. /* 26 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  28034. /* 27 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  28035. /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  28036. /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"),
  28037. /* 30 */ "Found" OpHelp("key=r[P3@P4]"),
  28038. /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"),
  28039. /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
  28040. /* 33 */ "Last" OpHelp(""),
  28041. /* 34 */ "IfSmaller" OpHelp(""),
  28042. /* 35 */ "SorterSort" OpHelp(""),
  28043. /* 36 */ "Sort" OpHelp(""),
  28044. /* 37 */ "Rewind" OpHelp(""),
  28045. /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  28046. /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  28047. /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  28048. /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  28049. /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  28050. /* 43 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  28051. /* 44 */ "Program" OpHelp(""),
  28052. /* 45 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  28053. /* 46 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  28054. /* 47 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
  28055. /* 48 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  28056. /* 49 */ "IncrVacuum" OpHelp(""),
  28057. /* 50 */ "VNext" OpHelp(""),
  28058. /* 51 */ "Init" OpHelp("Start at P2"),
  28059. /* 52 */ "Return" OpHelp(""),
  28060. /* 53 */ "EndCoroutine" OpHelp(""),
  28061. /* 54 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  28062. /* 55 */ "Halt" OpHelp(""),
  28063. /* 56 */ "Integer" OpHelp("r[P2]=P1"),
  28064. /* 57 */ "Int64" OpHelp("r[P2]=P4"),
  28065. /* 58 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  28066. /* 59 */ "Null" OpHelp("r[P2..P3]=NULL"),
  28067. /* 60 */ "SoftNull" OpHelp("r[P1]=NULL"),
  28068. /* 61 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  28069. /* 62 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  28070. /* 63 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  28071. /* 64 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  28072. /* 65 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  28073. /* 66 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  28074. /* 67 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  28075. /* 68 */ "CollSeq" OpHelp(""),
  28076. /* 69 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  28077. /* 70 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  28078. /* 71 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  28079. /* 72 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  28080. /* 73 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  28081. /* 74 */ "RealAffinity" OpHelp(""),
  28082. /* 75 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  28083. /* 76 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  28084. /* 77 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
  28085. /* 78 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
  28086. /* 79 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
  28087. /* 80 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
  28088. /* 81 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
  28089. /* 82 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
  28090. /* 83 */ "ElseNotEq" OpHelp(""),
  28091. /* 84 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  28092. /* 85 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  28093. /* 86 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  28094. /* 87 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  28095. /* 88 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  28096. /* 89 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  28097. /* 90 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  28098. /* 91 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  28099. /* 92 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  28100. /* 93 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  28101. /* 94 */ "Cast" OpHelp("affinity(r[P1])"),
  28102. /* 95 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  28103. /* 96 */ "Permutation" OpHelp(""),
  28104. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  28105. /* 98 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  28106. /* 99 */ "Column" OpHelp("r[P3]=PX"),
  28107. /* 100 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  28108. /* 101 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  28109. /* 102 */ "Count" OpHelp("r[P2]=count()"),
  28110. /* 103 */ "ReadCookie" OpHelp(""),
  28111. /* 104 */ "SetCookie" OpHelp(""),
  28112. /* 105 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  28113. /* 106 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  28114. /* 107 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  28115. /* 108 */ "OpenDup" OpHelp(""),
  28116. /* 109 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  28117. /* 110 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  28118. /* 111 */ "SorterOpen" OpHelp(""),
  28119. /* 112 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  28120. /* 113 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  28121. /* 114 */ "Close" OpHelp(""),
  28122. /* 115 */ "ColumnsUsed" OpHelp(""),
  28123. /* 116 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  28124. /* 117 */ "NewRowid" OpHelp("r[P2]=rowid"),
  28125. /* 118 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  28126. /* 119 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  28127. /* 120 */ "Delete" OpHelp(""),
  28128. /* 121 */ "ResetCount" OpHelp(""),
  28129. /* 122 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  28130. /* 123 */ "SorterData" OpHelp("r[P2]=data"),
  28131. /* 124 */ "RowData" OpHelp("r[P2]=data"),
  28132. /* 125 */ "Rowid" OpHelp("r[P2]=rowid"),
  28133. /* 126 */ "NullRow" OpHelp(""),
  28134. /* 127 */ "SorterInsert" OpHelp("key=r[P2]"),
  28135. /* 128 */ "IdxInsert" OpHelp("key=r[P2]"),
  28136. /* 129 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  28137. /* 130 */ "Seek" OpHelp("Move P3 to P1.rowid"),
  28138. /* 131 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  28139. /* 132 */ "Real" OpHelp("r[P2]=P4"),
  28140. /* 133 */ "Destroy" OpHelp(""),
  28141. /* 134 */ "Clear" OpHelp(""),
  28142. /* 135 */ "ResetSorter" OpHelp(""),
  28143. /* 136 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
  28144. /* 137 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
  28145. /* 138 */ "SqlExec" OpHelp(""),
  28146. /* 139 */ "ParseSchema" OpHelp(""),
  28147. /* 140 */ "LoadAnalysis" OpHelp(""),
  28148. /* 141 */ "DropTable" OpHelp(""),
  28149. /* 142 */ "DropIndex" OpHelp(""),
  28150. /* 143 */ "DropTrigger" OpHelp(""),
  28151. /* 144 */ "IntegrityCk" OpHelp(""),
  28152. /* 145 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  28153. /* 146 */ "Param" OpHelp(""),
  28154. /* 147 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  28155. /* 148 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  28156. /* 149 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  28157. /* 150 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
  28158. /* 151 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  28159. /* 152 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  28160. /* 153 */ "Expire" OpHelp(""),
  28161. /* 154 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  28162. /* 155 */ "VBegin" OpHelp(""),
  28163. /* 156 */ "VCreate" OpHelp(""),
  28164. /* 157 */ "VDestroy" OpHelp(""),
  28165. /* 158 */ "VOpen" OpHelp(""),
  28166. /* 159 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  28167. /* 160 */ "VRename" OpHelp(""),
  28168. /* 161 */ "Pagecount" OpHelp(""),
  28169. /* 162 */ "MaxPgcnt" OpHelp(""),
  28170. /* 163 */ "CursorHint" OpHelp(""),
  28171. /* 164 */ "Noop" OpHelp(""),
  28172. /* 165 */ "Explain" OpHelp(""),
  28173. };
  28174. return azName[i];
  28175. }
  28176. #endif
  28177. /************** End of opcodes.c *********************************************/
  28178. /************** Begin file os_unix.c *****************************************/
  28179. /*
  28180. ** 2004 May 22
  28181. **
  28182. ** The author disclaims copyright to this source code. In place of
  28183. ** a legal notice, here is a blessing:
  28184. **
  28185. ** May you do good and not evil.
  28186. ** May you find forgiveness for yourself and forgive others.
  28187. ** May you share freely, never taking more than you give.
  28188. **
  28189. ******************************************************************************
  28190. **
  28191. ** This file contains the VFS implementation for unix-like operating systems
  28192. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  28193. **
  28194. ** There are actually several different VFS implementations in this file.
  28195. ** The differences are in the way that file locking is done. The default
  28196. ** implementation uses Posix Advisory Locks. Alternative implementations
  28197. ** use flock(), dot-files, various proprietary locking schemas, or simply
  28198. ** skip locking all together.
  28199. **
  28200. ** This source file is organized into divisions where the logic for various
  28201. ** subfunctions is contained within the appropriate division. PLEASE
  28202. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  28203. ** in the correct division and should be clearly labeled.
  28204. **
  28205. ** The layout of divisions is as follows:
  28206. **
  28207. ** * General-purpose declarations and utility functions.
  28208. ** * Unique file ID logic used by VxWorks.
  28209. ** * Various locking primitive implementations (all except proxy locking):
  28210. ** + for Posix Advisory Locks
  28211. ** + for no-op locks
  28212. ** + for dot-file locks
  28213. ** + for flock() locking
  28214. ** + for named semaphore locks (VxWorks only)
  28215. ** + for AFP filesystem locks (MacOSX only)
  28216. ** * sqlite3_file methods not associated with locking.
  28217. ** * Definitions of sqlite3_io_methods objects for all locking
  28218. ** methods plus "finder" functions for each locking method.
  28219. ** * sqlite3_vfs method implementations.
  28220. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  28221. ** * Definitions of sqlite3_vfs objects for all locking methods
  28222. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  28223. */
  28224. /* #include "sqliteInt.h" */
  28225. #if SQLITE_OS_UNIX /* This file is used on unix only */
  28226. /*
  28227. ** There are various methods for file locking used for concurrency
  28228. ** control:
  28229. **
  28230. ** 1. POSIX locking (the default),
  28231. ** 2. No locking,
  28232. ** 3. Dot-file locking,
  28233. ** 4. flock() locking,
  28234. ** 5. AFP locking (OSX only),
  28235. ** 6. Named POSIX semaphores (VXWorks only),
  28236. ** 7. proxy locking. (OSX only)
  28237. **
  28238. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  28239. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  28240. ** selection of the appropriate locking style based on the filesystem
  28241. ** where the database is located.
  28242. */
  28243. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  28244. # if defined(__APPLE__)
  28245. # define SQLITE_ENABLE_LOCKING_STYLE 1
  28246. # else
  28247. # define SQLITE_ENABLE_LOCKING_STYLE 0
  28248. # endif
  28249. #endif
  28250. /* Use pread() and pwrite() if they are available */
  28251. #if defined(__APPLE__)
  28252. # define HAVE_PREAD 1
  28253. # define HAVE_PWRITE 1
  28254. #endif
  28255. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  28256. # undef USE_PREAD
  28257. # define USE_PREAD64 1
  28258. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  28259. # undef USE_PREAD64
  28260. # define USE_PREAD 1
  28261. #endif
  28262. /*
  28263. ** standard include files.
  28264. */
  28265. #include <sys/types.h>
  28266. #include <sys/stat.h>
  28267. #include <fcntl.h>
  28268. #include <unistd.h>
  28269. /* #include <time.h> */
  28270. #include <sys/time.h>
  28271. #include <errno.h>
  28272. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28273. # include <sys/mman.h>
  28274. #endif
  28275. #if SQLITE_ENABLE_LOCKING_STYLE
  28276. # include <sys/ioctl.h>
  28277. # include <sys/file.h>
  28278. # include <sys/param.h>
  28279. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  28280. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  28281. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  28282. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  28283. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  28284. # define HAVE_GETHOSTUUID 1
  28285. # else
  28286. # warning "gethostuuid() is disabled."
  28287. # endif
  28288. #endif
  28289. #if OS_VXWORKS
  28290. /* # include <sys/ioctl.h> */
  28291. # include <semaphore.h>
  28292. # include <limits.h>
  28293. #endif /* OS_VXWORKS */
  28294. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  28295. # include <sys/mount.h>
  28296. #endif
  28297. #ifdef HAVE_UTIME
  28298. # include <utime.h>
  28299. #endif
  28300. /*
  28301. ** Allowed values of unixFile.fsFlags
  28302. */
  28303. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  28304. /*
  28305. ** If we are to be thread-safe, include the pthreads header and define
  28306. ** the SQLITE_UNIX_THREADS macro.
  28307. */
  28308. #if SQLITE_THREADSAFE
  28309. /* # include <pthread.h> */
  28310. # define SQLITE_UNIX_THREADS 1
  28311. #endif
  28312. /*
  28313. ** Default permissions when creating a new file
  28314. */
  28315. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  28316. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  28317. #endif
  28318. /*
  28319. ** Default permissions when creating auto proxy dir
  28320. */
  28321. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  28322. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  28323. #endif
  28324. /*
  28325. ** Maximum supported path-length.
  28326. */
  28327. #define MAX_PATHNAME 512
  28328. /*
  28329. ** Maximum supported symbolic links
  28330. */
  28331. #define SQLITE_MAX_SYMLINKS 100
  28332. /* Always cast the getpid() return type for compatibility with
  28333. ** kernel modules in VxWorks. */
  28334. #define osGetpid(X) (pid_t)getpid()
  28335. /*
  28336. ** Only set the lastErrno if the error code is a real error and not
  28337. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  28338. */
  28339. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  28340. /* Forward references */
  28341. typedef struct unixShm unixShm; /* Connection shared memory */
  28342. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  28343. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  28344. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  28345. /*
  28346. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  28347. ** cannot be closed immediately. In these cases, instances of the following
  28348. ** structure are used to store the file descriptor while waiting for an
  28349. ** opportunity to either close or reuse it.
  28350. */
  28351. struct UnixUnusedFd {
  28352. int fd; /* File descriptor to close */
  28353. int flags; /* Flags this file descriptor was opened with */
  28354. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  28355. };
  28356. /*
  28357. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  28358. ** VFS implementations.
  28359. */
  28360. typedef struct unixFile unixFile;
  28361. struct unixFile {
  28362. sqlite3_io_methods const *pMethod; /* Always the first entry */
  28363. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  28364. unixInodeInfo *pInode; /* Info about locks on this inode */
  28365. int h; /* The file descriptor */
  28366. unsigned char eFileLock; /* The type of lock held on this fd */
  28367. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  28368. int lastErrno; /* The unix errno from last I/O error */
  28369. void *lockingContext; /* Locking style specific state */
  28370. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  28371. const char *zPath; /* Name of the file */
  28372. unixShm *pShm; /* Shared memory segment information */
  28373. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  28374. #if SQLITE_MAX_MMAP_SIZE>0
  28375. int nFetchOut; /* Number of outstanding xFetch refs */
  28376. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  28377. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  28378. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  28379. void *pMapRegion; /* Memory mapped region */
  28380. #endif
  28381. #ifdef __QNXNTO__
  28382. int sectorSize; /* Device sector size */
  28383. int deviceCharacteristics; /* Precomputed device characteristics */
  28384. #endif
  28385. #if SQLITE_ENABLE_LOCKING_STYLE
  28386. int openFlags; /* The flags specified at open() */
  28387. #endif
  28388. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  28389. unsigned fsFlags; /* cached details from statfs() */
  28390. #endif
  28391. #if OS_VXWORKS
  28392. struct vxworksFileId *pId; /* Unique file ID */
  28393. #endif
  28394. #ifdef SQLITE_DEBUG
  28395. /* The next group of variables are used to track whether or not the
  28396. ** transaction counter in bytes 24-27 of database files are updated
  28397. ** whenever any part of the database changes. An assertion fault will
  28398. ** occur if a file is updated without also updating the transaction
  28399. ** counter. This test is made to avoid new problems similar to the
  28400. ** one described by ticket #3584.
  28401. */
  28402. unsigned char transCntrChng; /* True if the transaction counter changed */
  28403. unsigned char dbUpdate; /* True if any part of database file changed */
  28404. unsigned char inNormalWrite; /* True if in a normal write operation */
  28405. #endif
  28406. #ifdef SQLITE_TEST
  28407. /* In test mode, increase the size of this structure a bit so that
  28408. ** it is larger than the struct CrashFile defined in test6.c.
  28409. */
  28410. char aPadding[32];
  28411. #endif
  28412. };
  28413. /* This variable holds the process id (pid) from when the xRandomness()
  28414. ** method was called. If xOpen() is called from a different process id,
  28415. ** indicating that a fork() has occurred, the PRNG will be reset.
  28416. */
  28417. static pid_t randomnessPid = 0;
  28418. /*
  28419. ** Allowed values for the unixFile.ctrlFlags bitmask:
  28420. */
  28421. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  28422. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  28423. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  28424. #ifndef SQLITE_DISABLE_DIRSYNC
  28425. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  28426. #else
  28427. # define UNIXFILE_DIRSYNC 0x00
  28428. #endif
  28429. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  28430. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  28431. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  28432. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  28433. /*
  28434. ** Include code that is common to all os_*.c files
  28435. */
  28436. /************** Include os_common.h in the middle of os_unix.c ***************/
  28437. /************** Begin file os_common.h ***************************************/
  28438. /*
  28439. ** 2004 May 22
  28440. **
  28441. ** The author disclaims copyright to this source code. In place of
  28442. ** a legal notice, here is a blessing:
  28443. **
  28444. ** May you do good and not evil.
  28445. ** May you find forgiveness for yourself and forgive others.
  28446. ** May you share freely, never taking more than you give.
  28447. **
  28448. ******************************************************************************
  28449. **
  28450. ** This file contains macros and a little bit of code that is common to
  28451. ** all of the platform-specific files (os_*.c) and is #included into those
  28452. ** files.
  28453. **
  28454. ** This file should be #included by the os_*.c files only. It is not a
  28455. ** general purpose header file.
  28456. */
  28457. #ifndef _OS_COMMON_H_
  28458. #define _OS_COMMON_H_
  28459. /*
  28460. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  28461. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  28462. ** switch. The following code should catch this problem at compile-time.
  28463. */
  28464. #ifdef MEMORY_DEBUG
  28465. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  28466. #endif
  28467. /*
  28468. ** Macros for performance tracing. Normally turned off. Only works
  28469. ** on i486 hardware.
  28470. */
  28471. #ifdef SQLITE_PERFORMANCE_TRACE
  28472. /*
  28473. ** hwtime.h contains inline assembler code for implementing
  28474. ** high-performance timing routines.
  28475. */
  28476. /************** Include hwtime.h in the middle of os_common.h ****************/
  28477. /************** Begin file hwtime.h ******************************************/
  28478. /*
  28479. ** 2008 May 27
  28480. **
  28481. ** The author disclaims copyright to this source code. In place of
  28482. ** a legal notice, here is a blessing:
  28483. **
  28484. ** May you do good and not evil.
  28485. ** May you find forgiveness for yourself and forgive others.
  28486. ** May you share freely, never taking more than you give.
  28487. **
  28488. ******************************************************************************
  28489. **
  28490. ** This file contains inline asm code for retrieving "high-performance"
  28491. ** counters for x86 class CPUs.
  28492. */
  28493. #ifndef SQLITE_HWTIME_H
  28494. #define SQLITE_HWTIME_H
  28495. /*
  28496. ** The following routine only works on pentium-class (or newer) processors.
  28497. ** It uses the RDTSC opcode to read the cycle count value out of the
  28498. ** processor and returns that value. This can be used for high-res
  28499. ** profiling.
  28500. */
  28501. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  28502. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  28503. #if defined(__GNUC__)
  28504. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28505. unsigned int lo, hi;
  28506. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  28507. return (sqlite_uint64)hi << 32 | lo;
  28508. }
  28509. #elif defined(_MSC_VER)
  28510. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  28511. __asm {
  28512. rdtsc
  28513. ret ; return value at EDX:EAX
  28514. }
  28515. }
  28516. #endif
  28517. #elif (defined(__GNUC__) && defined(__x86_64__))
  28518. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28519. unsigned long val;
  28520. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  28521. return val;
  28522. }
  28523. #elif (defined(__GNUC__) && defined(__ppc__))
  28524. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28525. unsigned long long retval;
  28526. unsigned long junk;
  28527. __asm__ __volatile__ ("\n\
  28528. 1: mftbu %1\n\
  28529. mftb %L0\n\
  28530. mftbu %0\n\
  28531. cmpw %0,%1\n\
  28532. bne 1b"
  28533. : "=r" (retval), "=r" (junk));
  28534. return retval;
  28535. }
  28536. #else
  28537. #error Need implementation of sqlite3Hwtime() for your platform.
  28538. /*
  28539. ** To compile without implementing sqlite3Hwtime() for your platform,
  28540. ** you can remove the above #error and use the following
  28541. ** stub function. You will lose timing support for many
  28542. ** of the debugging and testing utilities, but it should at
  28543. ** least compile and run.
  28544. */
  28545. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  28546. #endif
  28547. #endif /* !defined(SQLITE_HWTIME_H) */
  28548. /************** End of hwtime.h **********************************************/
  28549. /************** Continuing where we left off in os_common.h ******************/
  28550. static sqlite_uint64 g_start;
  28551. static sqlite_uint64 g_elapsed;
  28552. #define TIMER_START g_start=sqlite3Hwtime()
  28553. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  28554. #define TIMER_ELAPSED g_elapsed
  28555. #else
  28556. #define TIMER_START
  28557. #define TIMER_END
  28558. #define TIMER_ELAPSED ((sqlite_uint64)0)
  28559. #endif
  28560. /*
  28561. ** If we compile with the SQLITE_TEST macro set, then the following block
  28562. ** of code will give us the ability to simulate a disk I/O error. This
  28563. ** is used for testing the I/O recovery logic.
  28564. */
  28565. #if defined(SQLITE_TEST)
  28566. SQLITE_API extern int sqlite3_io_error_hit;
  28567. SQLITE_API extern int sqlite3_io_error_hardhit;
  28568. SQLITE_API extern int sqlite3_io_error_pending;
  28569. SQLITE_API extern int sqlite3_io_error_persist;
  28570. SQLITE_API extern int sqlite3_io_error_benign;
  28571. SQLITE_API extern int sqlite3_diskfull_pending;
  28572. SQLITE_API extern int sqlite3_diskfull;
  28573. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  28574. #define SimulateIOError(CODE) \
  28575. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  28576. || sqlite3_io_error_pending-- == 1 ) \
  28577. { local_ioerr(); CODE; }
  28578. static void local_ioerr(){
  28579. IOTRACE(("IOERR\n"));
  28580. sqlite3_io_error_hit++;
  28581. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  28582. }
  28583. #define SimulateDiskfullError(CODE) \
  28584. if( sqlite3_diskfull_pending ){ \
  28585. if( sqlite3_diskfull_pending == 1 ){ \
  28586. local_ioerr(); \
  28587. sqlite3_diskfull = 1; \
  28588. sqlite3_io_error_hit = 1; \
  28589. CODE; \
  28590. }else{ \
  28591. sqlite3_diskfull_pending--; \
  28592. } \
  28593. }
  28594. #else
  28595. #define SimulateIOErrorBenign(X)
  28596. #define SimulateIOError(A)
  28597. #define SimulateDiskfullError(A)
  28598. #endif /* defined(SQLITE_TEST) */
  28599. /*
  28600. ** When testing, keep a count of the number of open files.
  28601. */
  28602. #if defined(SQLITE_TEST)
  28603. SQLITE_API extern int sqlite3_open_file_count;
  28604. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  28605. #else
  28606. #define OpenCounter(X)
  28607. #endif /* defined(SQLITE_TEST) */
  28608. #endif /* !defined(_OS_COMMON_H_) */
  28609. /************** End of os_common.h *******************************************/
  28610. /************** Continuing where we left off in os_unix.c ********************/
  28611. /*
  28612. ** Define various macros that are missing from some systems.
  28613. */
  28614. #ifndef O_LARGEFILE
  28615. # define O_LARGEFILE 0
  28616. #endif
  28617. #ifdef SQLITE_DISABLE_LFS
  28618. # undef O_LARGEFILE
  28619. # define O_LARGEFILE 0
  28620. #endif
  28621. #ifndef O_NOFOLLOW
  28622. # define O_NOFOLLOW 0
  28623. #endif
  28624. #ifndef O_BINARY
  28625. # define O_BINARY 0
  28626. #endif
  28627. /*
  28628. ** The threadid macro resolves to the thread-id or to 0. Used for
  28629. ** testing and debugging only.
  28630. */
  28631. #if SQLITE_THREADSAFE
  28632. #define threadid pthread_self()
  28633. #else
  28634. #define threadid 0
  28635. #endif
  28636. /*
  28637. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  28638. */
  28639. #if !defined(HAVE_MREMAP)
  28640. # if defined(__linux__) && defined(_GNU_SOURCE)
  28641. # define HAVE_MREMAP 1
  28642. # else
  28643. # define HAVE_MREMAP 0
  28644. # endif
  28645. #endif
  28646. /*
  28647. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  28648. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  28649. */
  28650. #ifdef __ANDROID__
  28651. # define lseek lseek64
  28652. #endif
  28653. /*
  28654. ** Different Unix systems declare open() in different ways. Same use
  28655. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  28656. ** The difference is important when using a pointer to the function.
  28657. **
  28658. ** The safest way to deal with the problem is to always use this wrapper
  28659. ** which always has the same well-defined interface.
  28660. */
  28661. static int posixOpen(const char *zFile, int flags, int mode){
  28662. return open(zFile, flags, mode);
  28663. }
  28664. /* Forward reference */
  28665. static int openDirectory(const char*, int*);
  28666. static int unixGetpagesize(void);
  28667. /*
  28668. ** Many system calls are accessed through pointer-to-functions so that
  28669. ** they may be overridden at runtime to facilitate fault injection during
  28670. ** testing and sandboxing. The following array holds the names and pointers
  28671. ** to all overrideable system calls.
  28672. */
  28673. static struct unix_syscall {
  28674. const char *zName; /* Name of the system call */
  28675. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  28676. sqlite3_syscall_ptr pDefault; /* Default value */
  28677. } aSyscall[] = {
  28678. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  28679. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  28680. { "close", (sqlite3_syscall_ptr)close, 0 },
  28681. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  28682. { "access", (sqlite3_syscall_ptr)access, 0 },
  28683. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  28684. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  28685. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  28686. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  28687. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  28688. /*
  28689. ** The DJGPP compiler environment looks mostly like Unix, but it
  28690. ** lacks the fcntl() system call. So redefine fcntl() to be something
  28691. ** that always succeeds. This means that locking does not occur under
  28692. ** DJGPP. But it is DOS - what did you expect?
  28693. */
  28694. #ifdef __DJGPP__
  28695. { "fstat", 0, 0 },
  28696. #define osFstat(a,b,c) 0
  28697. #else
  28698. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  28699. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  28700. #endif
  28701. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  28702. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  28703. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  28704. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  28705. { "read", (sqlite3_syscall_ptr)read, 0 },
  28706. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  28707. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  28708. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  28709. #else
  28710. { "pread", (sqlite3_syscall_ptr)0, 0 },
  28711. #endif
  28712. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  28713. #if defined(USE_PREAD64)
  28714. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  28715. #else
  28716. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  28717. #endif
  28718. #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
  28719. { "write", (sqlite3_syscall_ptr)write, 0 },
  28720. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  28721. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  28722. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  28723. #else
  28724. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  28725. #endif
  28726. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  28727. aSyscall[12].pCurrent)
  28728. #if defined(USE_PREAD64)
  28729. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  28730. #else
  28731. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  28732. #endif
  28733. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
  28734. aSyscall[13].pCurrent)
  28735. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  28736. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  28737. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  28738. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  28739. #else
  28740. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  28741. #endif
  28742. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  28743. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  28744. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  28745. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  28746. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  28747. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  28748. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  28749. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  28750. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  28751. #if defined(HAVE_FCHOWN)
  28752. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  28753. #else
  28754. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  28755. #endif
  28756. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  28757. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  28758. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  28759. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28760. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  28761. #else
  28762. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  28763. #endif
  28764. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  28765. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28766. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  28767. #else
  28768. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  28769. #endif
  28770. #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
  28771. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  28772. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  28773. #else
  28774. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  28775. #endif
  28776. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  28777. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28778. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  28779. #else
  28780. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  28781. #endif
  28782. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  28783. #if defined(HAVE_READLINK)
  28784. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  28785. #else
  28786. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  28787. #endif
  28788. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  28789. #if defined(HAVE_LSTAT)
  28790. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  28791. #else
  28792. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  28793. #endif
  28794. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  28795. }; /* End of the overrideable system calls */
  28796. /*
  28797. ** On some systems, calls to fchown() will trigger a message in a security
  28798. ** log if they come from non-root processes. So avoid calling fchown() if
  28799. ** we are not running as root.
  28800. */
  28801. static int robustFchown(int fd, uid_t uid, gid_t gid){
  28802. #if defined(HAVE_FCHOWN)
  28803. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  28804. #else
  28805. return 0;
  28806. #endif
  28807. }
  28808. /*
  28809. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  28810. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  28811. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  28812. ** system call named zName.
  28813. */
  28814. static int unixSetSystemCall(
  28815. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  28816. const char *zName, /* Name of system call to override */
  28817. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  28818. ){
  28819. unsigned int i;
  28820. int rc = SQLITE_NOTFOUND;
  28821. UNUSED_PARAMETER(pNotUsed);
  28822. if( zName==0 ){
  28823. /* If no zName is given, restore all system calls to their default
  28824. ** settings and return NULL
  28825. */
  28826. rc = SQLITE_OK;
  28827. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  28828. if( aSyscall[i].pDefault ){
  28829. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  28830. }
  28831. }
  28832. }else{
  28833. /* If zName is specified, operate on only the one system call
  28834. ** specified.
  28835. */
  28836. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  28837. if( strcmp(zName, aSyscall[i].zName)==0 ){
  28838. if( aSyscall[i].pDefault==0 ){
  28839. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  28840. }
  28841. rc = SQLITE_OK;
  28842. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  28843. aSyscall[i].pCurrent = pNewFunc;
  28844. break;
  28845. }
  28846. }
  28847. }
  28848. return rc;
  28849. }
  28850. /*
  28851. ** Return the value of a system call. Return NULL if zName is not a
  28852. ** recognized system call name. NULL is also returned if the system call
  28853. ** is currently undefined.
  28854. */
  28855. static sqlite3_syscall_ptr unixGetSystemCall(
  28856. sqlite3_vfs *pNotUsed,
  28857. const char *zName
  28858. ){
  28859. unsigned int i;
  28860. UNUSED_PARAMETER(pNotUsed);
  28861. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  28862. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  28863. }
  28864. return 0;
  28865. }
  28866. /*
  28867. ** Return the name of the first system call after zName. If zName==NULL
  28868. ** then return the name of the first system call. Return NULL if zName
  28869. ** is the last system call or if zName is not the name of a valid
  28870. ** system call.
  28871. */
  28872. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  28873. int i = -1;
  28874. UNUSED_PARAMETER(p);
  28875. if( zName ){
  28876. for(i=0; i<ArraySize(aSyscall)-1; i++){
  28877. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  28878. }
  28879. }
  28880. for(i++; i<ArraySize(aSyscall); i++){
  28881. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  28882. }
  28883. return 0;
  28884. }
  28885. /*
  28886. ** Do not accept any file descriptor less than this value, in order to avoid
  28887. ** opening database file using file descriptors that are commonly used for
  28888. ** standard input, output, and error.
  28889. */
  28890. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  28891. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  28892. #endif
  28893. /*
  28894. ** Invoke open(). Do so multiple times, until it either succeeds or
  28895. ** fails for some reason other than EINTR.
  28896. **
  28897. ** If the file creation mode "m" is 0 then set it to the default for
  28898. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  28899. ** 0644) as modified by the system umask. If m is not 0, then
  28900. ** make the file creation mode be exactly m ignoring the umask.
  28901. **
  28902. ** The m parameter will be non-zero only when creating -wal, -journal,
  28903. ** and -shm files. We want those files to have *exactly* the same
  28904. ** permissions as their original database, unadulterated by the umask.
  28905. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  28906. ** transaction crashes and leaves behind hot journals, then any
  28907. ** process that is able to write to the database will also be able to
  28908. ** recover the hot journals.
  28909. */
  28910. static int robust_open(const char *z, int f, mode_t m){
  28911. int fd;
  28912. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  28913. while(1){
  28914. #if defined(O_CLOEXEC)
  28915. fd = osOpen(z,f|O_CLOEXEC,m2);
  28916. #else
  28917. fd = osOpen(z,f,m2);
  28918. #endif
  28919. if( fd<0 ){
  28920. if( errno==EINTR ) continue;
  28921. break;
  28922. }
  28923. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  28924. osClose(fd);
  28925. sqlite3_log(SQLITE_WARNING,
  28926. "attempt to open \"%s\" as file descriptor %d", z, fd);
  28927. fd = -1;
  28928. if( osOpen("/dev/null", f, m)<0 ) break;
  28929. }
  28930. if( fd>=0 ){
  28931. if( m!=0 ){
  28932. struct stat statbuf;
  28933. if( osFstat(fd, &statbuf)==0
  28934. && statbuf.st_size==0
  28935. && (statbuf.st_mode&0777)!=m
  28936. ){
  28937. osFchmod(fd, m);
  28938. }
  28939. }
  28940. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  28941. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  28942. #endif
  28943. }
  28944. return fd;
  28945. }
  28946. /*
  28947. ** Helper functions to obtain and relinquish the global mutex. The
  28948. ** global mutex is used to protect the unixInodeInfo and
  28949. ** vxworksFileId objects used by this file, all of which may be
  28950. ** shared by multiple threads.
  28951. **
  28952. ** Function unixMutexHeld() is used to assert() that the global mutex
  28953. ** is held when required. This function is only used as part of assert()
  28954. ** statements. e.g.
  28955. **
  28956. ** unixEnterMutex()
  28957. ** assert( unixMutexHeld() );
  28958. ** unixEnterLeave()
  28959. */
  28960. static void unixEnterMutex(void){
  28961. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  28962. }
  28963. static void unixLeaveMutex(void){
  28964. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  28965. }
  28966. #ifdef SQLITE_DEBUG
  28967. static int unixMutexHeld(void) {
  28968. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  28969. }
  28970. #endif
  28971. #ifdef SQLITE_HAVE_OS_TRACE
  28972. /*
  28973. ** Helper function for printing out trace information from debugging
  28974. ** binaries. This returns the string representation of the supplied
  28975. ** integer lock-type.
  28976. */
  28977. static const char *azFileLock(int eFileLock){
  28978. switch( eFileLock ){
  28979. case NO_LOCK: return "NONE";
  28980. case SHARED_LOCK: return "SHARED";
  28981. case RESERVED_LOCK: return "RESERVED";
  28982. case PENDING_LOCK: return "PENDING";
  28983. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  28984. }
  28985. return "ERROR";
  28986. }
  28987. #endif
  28988. #ifdef SQLITE_LOCK_TRACE
  28989. /*
  28990. ** Print out information about all locking operations.
  28991. **
  28992. ** This routine is used for troubleshooting locks on multithreaded
  28993. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  28994. ** command-line option on the compiler. This code is normally
  28995. ** turned off.
  28996. */
  28997. static int lockTrace(int fd, int op, struct flock *p){
  28998. char *zOpName, *zType;
  28999. int s;
  29000. int savedErrno;
  29001. if( op==F_GETLK ){
  29002. zOpName = "GETLK";
  29003. }else if( op==F_SETLK ){
  29004. zOpName = "SETLK";
  29005. }else{
  29006. s = osFcntl(fd, op, p);
  29007. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  29008. return s;
  29009. }
  29010. if( p->l_type==F_RDLCK ){
  29011. zType = "RDLCK";
  29012. }else if( p->l_type==F_WRLCK ){
  29013. zType = "WRLCK";
  29014. }else if( p->l_type==F_UNLCK ){
  29015. zType = "UNLCK";
  29016. }else{
  29017. assert( 0 );
  29018. }
  29019. assert( p->l_whence==SEEK_SET );
  29020. s = osFcntl(fd, op, p);
  29021. savedErrno = errno;
  29022. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  29023. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  29024. (int)p->l_pid, s);
  29025. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  29026. struct flock l2;
  29027. l2 = *p;
  29028. osFcntl(fd, F_GETLK, &l2);
  29029. if( l2.l_type==F_RDLCK ){
  29030. zType = "RDLCK";
  29031. }else if( l2.l_type==F_WRLCK ){
  29032. zType = "WRLCK";
  29033. }else if( l2.l_type==F_UNLCK ){
  29034. zType = "UNLCK";
  29035. }else{
  29036. assert( 0 );
  29037. }
  29038. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  29039. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  29040. }
  29041. errno = savedErrno;
  29042. return s;
  29043. }
  29044. #undef osFcntl
  29045. #define osFcntl lockTrace
  29046. #endif /* SQLITE_LOCK_TRACE */
  29047. /*
  29048. ** Retry ftruncate() calls that fail due to EINTR
  29049. **
  29050. ** All calls to ftruncate() within this file should be made through
  29051. ** this wrapper. On the Android platform, bypassing the logic below
  29052. ** could lead to a corrupt database.
  29053. */
  29054. static int robust_ftruncate(int h, sqlite3_int64 sz){
  29055. int rc;
  29056. #ifdef __ANDROID__
  29057. /* On Android, ftruncate() always uses 32-bit offsets, even if
  29058. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  29059. ** truncate a file to any size larger than 2GiB. Silently ignore any
  29060. ** such attempts. */
  29061. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  29062. rc = SQLITE_OK;
  29063. }else
  29064. #endif
  29065. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  29066. return rc;
  29067. }
  29068. /*
  29069. ** This routine translates a standard POSIX errno code into something
  29070. ** useful to the clients of the sqlite3 functions. Specifically, it is
  29071. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  29072. ** and a variety of "please close the file descriptor NOW" errors into
  29073. ** SQLITE_IOERR
  29074. **
  29075. ** Errors during initialization of locks, or file system support for locks,
  29076. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  29077. */
  29078. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  29079. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  29080. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  29081. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  29082. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  29083. switch (posixError) {
  29084. case EACCES:
  29085. case EAGAIN:
  29086. case ETIMEDOUT:
  29087. case EBUSY:
  29088. case EINTR:
  29089. case ENOLCK:
  29090. /* random NFS retry error, unless during file system support
  29091. * introspection, in which it actually means what it says */
  29092. return SQLITE_BUSY;
  29093. case EPERM:
  29094. return SQLITE_PERM;
  29095. default:
  29096. return sqliteIOErr;
  29097. }
  29098. }
  29099. /******************************************************************************
  29100. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  29101. **
  29102. ** On most versions of unix, we can get a unique ID for a file by concatenating
  29103. ** the device number and the inode number. But this does not work on VxWorks.
  29104. ** On VxWorks, a unique file id must be based on the canonical filename.
  29105. **
  29106. ** A pointer to an instance of the following structure can be used as a
  29107. ** unique file ID in VxWorks. Each instance of this structure contains
  29108. ** a copy of the canonical filename. There is also a reference count.
  29109. ** The structure is reclaimed when the number of pointers to it drops to
  29110. ** zero.
  29111. **
  29112. ** There are never very many files open at one time and lookups are not
  29113. ** a performance-critical path, so it is sufficient to put these
  29114. ** structures on a linked list.
  29115. */
  29116. struct vxworksFileId {
  29117. struct vxworksFileId *pNext; /* Next in a list of them all */
  29118. int nRef; /* Number of references to this one */
  29119. int nName; /* Length of the zCanonicalName[] string */
  29120. char *zCanonicalName; /* Canonical filename */
  29121. };
  29122. #if OS_VXWORKS
  29123. /*
  29124. ** All unique filenames are held on a linked list headed by this
  29125. ** variable:
  29126. */
  29127. static struct vxworksFileId *vxworksFileList = 0;
  29128. /*
  29129. ** Simplify a filename into its canonical form
  29130. ** by making the following changes:
  29131. **
  29132. ** * removing any trailing and duplicate /
  29133. ** * convert /./ into just /
  29134. ** * convert /A/../ where A is any simple name into just /
  29135. **
  29136. ** Changes are made in-place. Return the new name length.
  29137. **
  29138. ** The original filename is in z[0..n-1]. Return the number of
  29139. ** characters in the simplified name.
  29140. */
  29141. static int vxworksSimplifyName(char *z, int n){
  29142. int i, j;
  29143. while( n>1 && z[n-1]=='/' ){ n--; }
  29144. for(i=j=0; i<n; i++){
  29145. if( z[i]=='/' ){
  29146. if( z[i+1]=='/' ) continue;
  29147. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  29148. i += 1;
  29149. continue;
  29150. }
  29151. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  29152. while( j>0 && z[j-1]!='/' ){ j--; }
  29153. if( j>0 ){ j--; }
  29154. i += 2;
  29155. continue;
  29156. }
  29157. }
  29158. z[j++] = z[i];
  29159. }
  29160. z[j] = 0;
  29161. return j;
  29162. }
  29163. /*
  29164. ** Find a unique file ID for the given absolute pathname. Return
  29165. ** a pointer to the vxworksFileId object. This pointer is the unique
  29166. ** file ID.
  29167. **
  29168. ** The nRef field of the vxworksFileId object is incremented before
  29169. ** the object is returned. A new vxworksFileId object is created
  29170. ** and added to the global list if necessary.
  29171. **
  29172. ** If a memory allocation error occurs, return NULL.
  29173. */
  29174. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  29175. struct vxworksFileId *pNew; /* search key and new file ID */
  29176. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  29177. int n; /* Length of zAbsoluteName string */
  29178. assert( zAbsoluteName[0]=='/' );
  29179. n = (int)strlen(zAbsoluteName);
  29180. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  29181. if( pNew==0 ) return 0;
  29182. pNew->zCanonicalName = (char*)&pNew[1];
  29183. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  29184. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  29185. /* Search for an existing entry that matching the canonical name.
  29186. ** If found, increment the reference count and return a pointer to
  29187. ** the existing file ID.
  29188. */
  29189. unixEnterMutex();
  29190. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  29191. if( pCandidate->nName==n
  29192. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  29193. ){
  29194. sqlite3_free(pNew);
  29195. pCandidate->nRef++;
  29196. unixLeaveMutex();
  29197. return pCandidate;
  29198. }
  29199. }
  29200. /* No match was found. We will make a new file ID */
  29201. pNew->nRef = 1;
  29202. pNew->nName = n;
  29203. pNew->pNext = vxworksFileList;
  29204. vxworksFileList = pNew;
  29205. unixLeaveMutex();
  29206. return pNew;
  29207. }
  29208. /*
  29209. ** Decrement the reference count on a vxworksFileId object. Free
  29210. ** the object when the reference count reaches zero.
  29211. */
  29212. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  29213. unixEnterMutex();
  29214. assert( pId->nRef>0 );
  29215. pId->nRef--;
  29216. if( pId->nRef==0 ){
  29217. struct vxworksFileId **pp;
  29218. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  29219. assert( *pp==pId );
  29220. *pp = pId->pNext;
  29221. sqlite3_free(pId);
  29222. }
  29223. unixLeaveMutex();
  29224. }
  29225. #endif /* OS_VXWORKS */
  29226. /*************** End of Unique File ID Utility Used By VxWorks ****************
  29227. ******************************************************************************/
  29228. /******************************************************************************
  29229. *************************** Posix Advisory Locking ****************************
  29230. **
  29231. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  29232. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  29233. ** sets or clears a lock, that operation overrides any prior locks set
  29234. ** by the same process. It does not explicitly say so, but this implies
  29235. ** that it overrides locks set by the same process using a different
  29236. ** file descriptor. Consider this test case:
  29237. **
  29238. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  29239. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  29240. **
  29241. ** Suppose ./file1 and ./file2 are really the same file (because
  29242. ** one is a hard or symbolic link to the other) then if you set
  29243. ** an exclusive lock on fd1, then try to get an exclusive lock
  29244. ** on fd2, it works. I would have expected the second lock to
  29245. ** fail since there was already a lock on the file due to fd1.
  29246. ** But not so. Since both locks came from the same process, the
  29247. ** second overrides the first, even though they were on different
  29248. ** file descriptors opened on different file names.
  29249. **
  29250. ** This means that we cannot use POSIX locks to synchronize file access
  29251. ** among competing threads of the same process. POSIX locks will work fine
  29252. ** to synchronize access for threads in separate processes, but not
  29253. ** threads within the same process.
  29254. **
  29255. ** To work around the problem, SQLite has to manage file locks internally
  29256. ** on its own. Whenever a new database is opened, we have to find the
  29257. ** specific inode of the database file (the inode is determined by the
  29258. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  29259. ** and check for locks already existing on that inode. When locks are
  29260. ** created or removed, we have to look at our own internal record of the
  29261. ** locks to see if another thread has previously set a lock on that same
  29262. ** inode.
  29263. **
  29264. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  29265. ** For VxWorks, we have to use the alternative unique ID system based on
  29266. ** canonical filename and implemented in the previous division.)
  29267. **
  29268. ** The sqlite3_file structure for POSIX is no longer just an integer file
  29269. ** descriptor. It is now a structure that holds the integer file
  29270. ** descriptor and a pointer to a structure that describes the internal
  29271. ** locks on the corresponding inode. There is one locking structure
  29272. ** per inode, so if the same inode is opened twice, both unixFile structures
  29273. ** point to the same locking structure. The locking structure keeps
  29274. ** a reference count (so we will know when to delete it) and a "cnt"
  29275. ** field that tells us its internal lock status. cnt==0 means the
  29276. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  29277. ** cnt>0 means there are cnt shared locks on the file.
  29278. **
  29279. ** Any attempt to lock or unlock a file first checks the locking
  29280. ** structure. The fcntl() system call is only invoked to set a
  29281. ** POSIX lock if the internal lock structure transitions between
  29282. ** a locked and an unlocked state.
  29283. **
  29284. ** But wait: there are yet more problems with POSIX advisory locks.
  29285. **
  29286. ** If you close a file descriptor that points to a file that has locks,
  29287. ** all locks on that file that are owned by the current process are
  29288. ** released. To work around this problem, each unixInodeInfo object
  29289. ** maintains a count of the number of pending locks on tha inode.
  29290. ** When an attempt is made to close an unixFile, if there are
  29291. ** other unixFile open on the same inode that are holding locks, the call
  29292. ** to close() the file descriptor is deferred until all of the locks clear.
  29293. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  29294. ** be closed and that list is walked (and cleared) when the last lock
  29295. ** clears.
  29296. **
  29297. ** Yet another problem: LinuxThreads do not play well with posix locks.
  29298. **
  29299. ** Many older versions of linux use the LinuxThreads library which is
  29300. ** not posix compliant. Under LinuxThreads, a lock created by thread
  29301. ** A cannot be modified or overridden by a different thread B.
  29302. ** Only thread A can modify the lock. Locking behavior is correct
  29303. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  29304. ** on linux - with NPTL a lock created by thread A can override locks
  29305. ** in thread B. But there is no way to know at compile-time which
  29306. ** threading library is being used. So there is no way to know at
  29307. ** compile-time whether or not thread A can override locks on thread B.
  29308. ** One has to do a run-time check to discover the behavior of the
  29309. ** current process.
  29310. **
  29311. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  29312. ** was dropped beginning with version 3.7.0. SQLite will still work with
  29313. ** LinuxThreads provided that (1) there is no more than one connection
  29314. ** per database file in the same process and (2) database connections
  29315. ** do not move across threads.
  29316. */
  29317. /*
  29318. ** An instance of the following structure serves as the key used
  29319. ** to locate a particular unixInodeInfo object.
  29320. */
  29321. struct unixFileId {
  29322. dev_t dev; /* Device number */
  29323. #if OS_VXWORKS
  29324. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  29325. #else
  29326. /* We are told that some versions of Android contain a bug that
  29327. ** sizes ino_t at only 32-bits instead of 64-bits. (See
  29328. ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
  29329. ** To work around this, always allocate 64-bits for the inode number.
  29330. ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
  29331. ** but that should not be a big deal. */
  29332. /* WAS: ino_t ino; */
  29333. u64 ino; /* Inode number */
  29334. #endif
  29335. };
  29336. /*
  29337. ** An instance of the following structure is allocated for each open
  29338. ** inode. Or, on LinuxThreads, there is one of these structures for
  29339. ** each inode opened by each thread.
  29340. **
  29341. ** A single inode can have multiple file descriptors, so each unixFile
  29342. ** structure contains a pointer to an instance of this object and this
  29343. ** object keeps a count of the number of unixFile pointing to it.
  29344. */
  29345. struct unixInodeInfo {
  29346. struct unixFileId fileId; /* The lookup key */
  29347. int nShared; /* Number of SHARED locks held */
  29348. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  29349. unsigned char bProcessLock; /* An exclusive process lock is held */
  29350. int nRef; /* Number of pointers to this structure */
  29351. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  29352. int nLock; /* Number of outstanding file locks */
  29353. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  29354. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  29355. unixInodeInfo *pPrev; /* .... doubly linked */
  29356. #if SQLITE_ENABLE_LOCKING_STYLE
  29357. unsigned long long sharedByte; /* for AFP simulated shared lock */
  29358. #endif
  29359. #if OS_VXWORKS
  29360. sem_t *pSem; /* Named POSIX semaphore */
  29361. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  29362. #endif
  29363. };
  29364. /*
  29365. ** A lists of all unixInodeInfo objects.
  29366. */
  29367. static unixInodeInfo *inodeList = 0;
  29368. /*
  29369. **
  29370. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  29371. ** unixLogError().
  29372. **
  29373. ** It is invoked after an error occurs in an OS function and errno has been
  29374. ** set. It logs a message using sqlite3_log() containing the current value of
  29375. ** errno and, if possible, the human-readable equivalent from strerror() or
  29376. ** strerror_r().
  29377. **
  29378. ** The first argument passed to the macro should be the error code that
  29379. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  29380. ** The two subsequent arguments should be the name of the OS function that
  29381. ** failed (e.g. "unlink", "open") and the associated file-system path,
  29382. ** if any.
  29383. */
  29384. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  29385. static int unixLogErrorAtLine(
  29386. int errcode, /* SQLite error code */
  29387. const char *zFunc, /* Name of OS function that failed */
  29388. const char *zPath, /* File path associated with error */
  29389. int iLine /* Source line number where error occurred */
  29390. ){
  29391. char *zErr; /* Message from strerror() or equivalent */
  29392. int iErrno = errno; /* Saved syscall error number */
  29393. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  29394. ** the strerror() function to obtain the human-readable error message
  29395. ** equivalent to errno. Otherwise, use strerror_r().
  29396. */
  29397. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  29398. char aErr[80];
  29399. memset(aErr, 0, sizeof(aErr));
  29400. zErr = aErr;
  29401. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  29402. ** assume that the system provides the GNU version of strerror_r() that
  29403. ** returns a pointer to a buffer containing the error message. That pointer
  29404. ** may point to aErr[], or it may point to some static storage somewhere.
  29405. ** Otherwise, assume that the system provides the POSIX version of
  29406. ** strerror_r(), which always writes an error message into aErr[].
  29407. **
  29408. ** If the code incorrectly assumes that it is the POSIX version that is
  29409. ** available, the error message will often be an empty string. Not a
  29410. ** huge problem. Incorrectly concluding that the GNU version is available
  29411. ** could lead to a segfault though.
  29412. */
  29413. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  29414. zErr =
  29415. # endif
  29416. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  29417. #elif SQLITE_THREADSAFE
  29418. /* This is a threadsafe build, but strerror_r() is not available. */
  29419. zErr = "";
  29420. #else
  29421. /* Non-threadsafe build, use strerror(). */
  29422. zErr = strerror(iErrno);
  29423. #endif
  29424. if( zPath==0 ) zPath = "";
  29425. sqlite3_log(errcode,
  29426. "os_unix.c:%d: (%d) %s(%s) - %s",
  29427. iLine, iErrno, zFunc, zPath, zErr
  29428. );
  29429. return errcode;
  29430. }
  29431. /*
  29432. ** Close a file descriptor.
  29433. **
  29434. ** We assume that close() almost always works, since it is only in a
  29435. ** very sick application or on a very sick platform that it might fail.
  29436. ** If it does fail, simply leak the file descriptor, but do log the
  29437. ** error.
  29438. **
  29439. ** Note that it is not safe to retry close() after EINTR since the
  29440. ** file descriptor might have already been reused by another thread.
  29441. ** So we don't even try to recover from an EINTR. Just log the error
  29442. ** and move on.
  29443. */
  29444. static void robust_close(unixFile *pFile, int h, int lineno){
  29445. if( osClose(h) ){
  29446. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  29447. pFile ? pFile->zPath : 0, lineno);
  29448. }
  29449. }
  29450. /*
  29451. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  29452. ** a convenient place to set a breakpoint.
  29453. */
  29454. static void storeLastErrno(unixFile *pFile, int error){
  29455. pFile->lastErrno = error;
  29456. }
  29457. /*
  29458. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  29459. */
  29460. static void closePendingFds(unixFile *pFile){
  29461. unixInodeInfo *pInode = pFile->pInode;
  29462. UnixUnusedFd *p;
  29463. UnixUnusedFd *pNext;
  29464. for(p=pInode->pUnused; p; p=pNext){
  29465. pNext = p->pNext;
  29466. robust_close(pFile, p->fd, __LINE__);
  29467. sqlite3_free(p);
  29468. }
  29469. pInode->pUnused = 0;
  29470. }
  29471. /*
  29472. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  29473. **
  29474. ** The mutex entered using the unixEnterMutex() function must be held
  29475. ** when this function is called.
  29476. */
  29477. static void releaseInodeInfo(unixFile *pFile){
  29478. unixInodeInfo *pInode = pFile->pInode;
  29479. assert( unixMutexHeld() );
  29480. if( ALWAYS(pInode) ){
  29481. pInode->nRef--;
  29482. if( pInode->nRef==0 ){
  29483. assert( pInode->pShmNode==0 );
  29484. closePendingFds(pFile);
  29485. if( pInode->pPrev ){
  29486. assert( pInode->pPrev->pNext==pInode );
  29487. pInode->pPrev->pNext = pInode->pNext;
  29488. }else{
  29489. assert( inodeList==pInode );
  29490. inodeList = pInode->pNext;
  29491. }
  29492. if( pInode->pNext ){
  29493. assert( pInode->pNext->pPrev==pInode );
  29494. pInode->pNext->pPrev = pInode->pPrev;
  29495. }
  29496. sqlite3_free(pInode);
  29497. }
  29498. }
  29499. }
  29500. /*
  29501. ** Given a file descriptor, locate the unixInodeInfo object that
  29502. ** describes that file descriptor. Create a new one if necessary. The
  29503. ** return value might be uninitialized if an error occurs.
  29504. **
  29505. ** The mutex entered using the unixEnterMutex() function must be held
  29506. ** when this function is called.
  29507. **
  29508. ** Return an appropriate error code.
  29509. */
  29510. static int findInodeInfo(
  29511. unixFile *pFile, /* Unix file with file desc used in the key */
  29512. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  29513. ){
  29514. int rc; /* System call return code */
  29515. int fd; /* The file descriptor for pFile */
  29516. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  29517. struct stat statbuf; /* Low-level file information */
  29518. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  29519. assert( unixMutexHeld() );
  29520. /* Get low-level information about the file that we can used to
  29521. ** create a unique name for the file.
  29522. */
  29523. fd = pFile->h;
  29524. rc = osFstat(fd, &statbuf);
  29525. if( rc!=0 ){
  29526. storeLastErrno(pFile, errno);
  29527. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  29528. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  29529. #endif
  29530. return SQLITE_IOERR;
  29531. }
  29532. #ifdef __APPLE__
  29533. /* On OS X on an msdos filesystem, the inode number is reported
  29534. ** incorrectly for zero-size files. See ticket #3260. To work
  29535. ** around this problem (we consider it a bug in OS X, not SQLite)
  29536. ** we always increase the file size to 1 by writing a single byte
  29537. ** prior to accessing the inode number. The one byte written is
  29538. ** an ASCII 'S' character which also happens to be the first byte
  29539. ** in the header of every SQLite database. In this way, if there
  29540. ** is a race condition such that another thread has already populated
  29541. ** the first page of the database, no damage is done.
  29542. */
  29543. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  29544. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  29545. if( rc!=1 ){
  29546. storeLastErrno(pFile, errno);
  29547. return SQLITE_IOERR;
  29548. }
  29549. rc = osFstat(fd, &statbuf);
  29550. if( rc!=0 ){
  29551. storeLastErrno(pFile, errno);
  29552. return SQLITE_IOERR;
  29553. }
  29554. }
  29555. #endif
  29556. memset(&fileId, 0, sizeof(fileId));
  29557. fileId.dev = statbuf.st_dev;
  29558. #if OS_VXWORKS
  29559. fileId.pId = pFile->pId;
  29560. #else
  29561. fileId.ino = (u64)statbuf.st_ino;
  29562. #endif
  29563. pInode = inodeList;
  29564. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  29565. pInode = pInode->pNext;
  29566. }
  29567. if( pInode==0 ){
  29568. pInode = sqlite3_malloc64( sizeof(*pInode) );
  29569. if( pInode==0 ){
  29570. return SQLITE_NOMEM_BKPT;
  29571. }
  29572. memset(pInode, 0, sizeof(*pInode));
  29573. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  29574. pInode->nRef = 1;
  29575. pInode->pNext = inodeList;
  29576. pInode->pPrev = 0;
  29577. if( inodeList ) inodeList->pPrev = pInode;
  29578. inodeList = pInode;
  29579. }else{
  29580. pInode->nRef++;
  29581. }
  29582. *ppInode = pInode;
  29583. return SQLITE_OK;
  29584. }
  29585. /*
  29586. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  29587. */
  29588. static int fileHasMoved(unixFile *pFile){
  29589. #if OS_VXWORKS
  29590. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  29591. #else
  29592. struct stat buf;
  29593. return pFile->pInode!=0 &&
  29594. (osStat(pFile->zPath, &buf)!=0
  29595. || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
  29596. #endif
  29597. }
  29598. /*
  29599. ** Check a unixFile that is a database. Verify the following:
  29600. **
  29601. ** (1) There is exactly one hard link on the file
  29602. ** (2) The file is not a symbolic link
  29603. ** (3) The file has not been renamed or unlinked
  29604. **
  29605. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  29606. */
  29607. static void verifyDbFile(unixFile *pFile){
  29608. struct stat buf;
  29609. int rc;
  29610. /* These verifications occurs for the main database only */
  29611. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  29612. rc = osFstat(pFile->h, &buf);
  29613. if( rc!=0 ){
  29614. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  29615. return;
  29616. }
  29617. if( buf.st_nlink==0 ){
  29618. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  29619. return;
  29620. }
  29621. if( buf.st_nlink>1 ){
  29622. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  29623. return;
  29624. }
  29625. if( fileHasMoved(pFile) ){
  29626. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  29627. return;
  29628. }
  29629. }
  29630. /*
  29631. ** This routine checks if there is a RESERVED lock held on the specified
  29632. ** file by this or any other process. If such a lock is held, set *pResOut
  29633. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  29634. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  29635. */
  29636. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  29637. int rc = SQLITE_OK;
  29638. int reserved = 0;
  29639. unixFile *pFile = (unixFile*)id;
  29640. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  29641. assert( pFile );
  29642. assert( pFile->eFileLock<=SHARED_LOCK );
  29643. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  29644. /* Check if a thread in this process holds such a lock */
  29645. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  29646. reserved = 1;
  29647. }
  29648. /* Otherwise see if some other process holds it.
  29649. */
  29650. #ifndef __DJGPP__
  29651. if( !reserved && !pFile->pInode->bProcessLock ){
  29652. struct flock lock;
  29653. lock.l_whence = SEEK_SET;
  29654. lock.l_start = RESERVED_BYTE;
  29655. lock.l_len = 1;
  29656. lock.l_type = F_WRLCK;
  29657. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  29658. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  29659. storeLastErrno(pFile, errno);
  29660. } else if( lock.l_type!=F_UNLCK ){
  29661. reserved = 1;
  29662. }
  29663. }
  29664. #endif
  29665. unixLeaveMutex();
  29666. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  29667. *pResOut = reserved;
  29668. return rc;
  29669. }
  29670. /*
  29671. ** Attempt to set a system-lock on the file pFile. The lock is
  29672. ** described by pLock.
  29673. **
  29674. ** If the pFile was opened read/write from unix-excl, then the only lock
  29675. ** ever obtained is an exclusive lock, and it is obtained exactly once
  29676. ** the first time any lock is attempted. All subsequent system locking
  29677. ** operations become no-ops. Locking operations still happen internally,
  29678. ** in order to coordinate access between separate database connections
  29679. ** within this process, but all of that is handled in memory and the
  29680. ** operating system does not participate.
  29681. **
  29682. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  29683. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  29684. ** and is read-only.
  29685. **
  29686. ** Zero is returned if the call completes successfully, or -1 if a call
  29687. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  29688. */
  29689. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  29690. int rc;
  29691. unixInodeInfo *pInode = pFile->pInode;
  29692. assert( unixMutexHeld() );
  29693. assert( pInode!=0 );
  29694. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  29695. if( pInode->bProcessLock==0 ){
  29696. struct flock lock;
  29697. assert( pInode->nLock==0 );
  29698. lock.l_whence = SEEK_SET;
  29699. lock.l_start = SHARED_FIRST;
  29700. lock.l_len = SHARED_SIZE;
  29701. lock.l_type = F_WRLCK;
  29702. rc = osFcntl(pFile->h, F_SETLK, &lock);
  29703. if( rc<0 ) return rc;
  29704. pInode->bProcessLock = 1;
  29705. pInode->nLock++;
  29706. }else{
  29707. rc = 0;
  29708. }
  29709. }else{
  29710. rc = osFcntl(pFile->h, F_SETLK, pLock);
  29711. }
  29712. return rc;
  29713. }
  29714. /*
  29715. ** Lock the file with the lock specified by parameter eFileLock - one
  29716. ** of the following:
  29717. **
  29718. ** (1) SHARED_LOCK
  29719. ** (2) RESERVED_LOCK
  29720. ** (3) PENDING_LOCK
  29721. ** (4) EXCLUSIVE_LOCK
  29722. **
  29723. ** Sometimes when requesting one lock state, additional lock states
  29724. ** are inserted in between. The locking might fail on one of the later
  29725. ** transitions leaving the lock state different from what it started but
  29726. ** still short of its goal. The following chart shows the allowed
  29727. ** transitions and the inserted intermediate states:
  29728. **
  29729. ** UNLOCKED -> SHARED
  29730. ** SHARED -> RESERVED
  29731. ** SHARED -> (PENDING) -> EXCLUSIVE
  29732. ** RESERVED -> (PENDING) -> EXCLUSIVE
  29733. ** PENDING -> EXCLUSIVE
  29734. **
  29735. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  29736. ** routine to lower a locking level.
  29737. */
  29738. static int unixLock(sqlite3_file *id, int eFileLock){
  29739. /* The following describes the implementation of the various locks and
  29740. ** lock transitions in terms of the POSIX advisory shared and exclusive
  29741. ** lock primitives (called read-locks and write-locks below, to avoid
  29742. ** confusion with SQLite lock names). The algorithms are complicated
  29743. ** slightly in order to be compatible with Windows95 systems simultaneously
  29744. ** accessing the same database file, in case that is ever required.
  29745. **
  29746. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  29747. ** byte', each single bytes at well known offsets, and the 'shared byte
  29748. ** range', a range of 510 bytes at a well known offset.
  29749. **
  29750. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  29751. ** byte'. If this is successful, 'shared byte range' is read-locked
  29752. ** and the lock on the 'pending byte' released. (Legacy note: When
  29753. ** SQLite was first developed, Windows95 systems were still very common,
  29754. ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
  29755. ** single randomly selected by from the 'shared byte range' is locked.
  29756. ** Windows95 is now pretty much extinct, but this work-around for the
  29757. ** lack of shared-locks on Windows95 lives on, for backwards
  29758. ** compatibility.)
  29759. **
  29760. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  29761. ** A RESERVED lock is implemented by grabbing a write-lock on the
  29762. ** 'reserved byte'.
  29763. **
  29764. ** A process may only obtain a PENDING lock after it has obtained a
  29765. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  29766. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  29767. ** obtained, but existing SHARED locks are allowed to persist. A process
  29768. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  29769. ** This property is used by the algorithm for rolling back a journal file
  29770. ** after a crash.
  29771. **
  29772. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  29773. ** implemented by obtaining a write-lock on the entire 'shared byte
  29774. ** range'. Since all other locks require a read-lock on one of the bytes
  29775. ** within this range, this ensures that no other locks are held on the
  29776. ** database.
  29777. */
  29778. int rc = SQLITE_OK;
  29779. unixFile *pFile = (unixFile*)id;
  29780. unixInodeInfo *pInode;
  29781. struct flock lock;
  29782. int tErrno = 0;
  29783. assert( pFile );
  29784. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  29785. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  29786. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  29787. osGetpid(0)));
  29788. /* If there is already a lock of this type or more restrictive on the
  29789. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  29790. ** unixEnterMutex() hasn't been called yet.
  29791. */
  29792. if( pFile->eFileLock>=eFileLock ){
  29793. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  29794. azFileLock(eFileLock)));
  29795. return SQLITE_OK;
  29796. }
  29797. /* Make sure the locking sequence is correct.
  29798. ** (1) We never move from unlocked to anything higher than shared lock.
  29799. ** (2) SQLite never explicitly requests a pendig lock.
  29800. ** (3) A shared lock is always held when a reserve lock is requested.
  29801. */
  29802. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  29803. assert( eFileLock!=PENDING_LOCK );
  29804. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  29805. /* This mutex is needed because pFile->pInode is shared across threads
  29806. */
  29807. unixEnterMutex();
  29808. pInode = pFile->pInode;
  29809. /* If some thread using this PID has a lock via a different unixFile*
  29810. ** handle that precludes the requested lock, return BUSY.
  29811. */
  29812. if( (pFile->eFileLock!=pInode->eFileLock &&
  29813. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  29814. ){
  29815. rc = SQLITE_BUSY;
  29816. goto end_lock;
  29817. }
  29818. /* If a SHARED lock is requested, and some thread using this PID already
  29819. ** has a SHARED or RESERVED lock, then increment reference counts and
  29820. ** return SQLITE_OK.
  29821. */
  29822. if( eFileLock==SHARED_LOCK &&
  29823. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  29824. assert( eFileLock==SHARED_LOCK );
  29825. assert( pFile->eFileLock==0 );
  29826. assert( pInode->nShared>0 );
  29827. pFile->eFileLock = SHARED_LOCK;
  29828. pInode->nShared++;
  29829. pInode->nLock++;
  29830. goto end_lock;
  29831. }
  29832. /* A PENDING lock is needed before acquiring a SHARED lock and before
  29833. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  29834. ** be released.
  29835. */
  29836. lock.l_len = 1L;
  29837. lock.l_whence = SEEK_SET;
  29838. if( eFileLock==SHARED_LOCK
  29839. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  29840. ){
  29841. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  29842. lock.l_start = PENDING_BYTE;
  29843. if( unixFileLock(pFile, &lock) ){
  29844. tErrno = errno;
  29845. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  29846. if( rc!=SQLITE_BUSY ){
  29847. storeLastErrno(pFile, tErrno);
  29848. }
  29849. goto end_lock;
  29850. }
  29851. }
  29852. /* If control gets to this point, then actually go ahead and make
  29853. ** operating system calls for the specified lock.
  29854. */
  29855. if( eFileLock==SHARED_LOCK ){
  29856. assert( pInode->nShared==0 );
  29857. assert( pInode->eFileLock==0 );
  29858. assert( rc==SQLITE_OK );
  29859. /* Now get the read-lock */
  29860. lock.l_start = SHARED_FIRST;
  29861. lock.l_len = SHARED_SIZE;
  29862. if( unixFileLock(pFile, &lock) ){
  29863. tErrno = errno;
  29864. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  29865. }
  29866. /* Drop the temporary PENDING lock */
  29867. lock.l_start = PENDING_BYTE;
  29868. lock.l_len = 1L;
  29869. lock.l_type = F_UNLCK;
  29870. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  29871. /* This could happen with a network mount */
  29872. tErrno = errno;
  29873. rc = SQLITE_IOERR_UNLOCK;
  29874. }
  29875. if( rc ){
  29876. if( rc!=SQLITE_BUSY ){
  29877. storeLastErrno(pFile, tErrno);
  29878. }
  29879. goto end_lock;
  29880. }else{
  29881. pFile->eFileLock = SHARED_LOCK;
  29882. pInode->nLock++;
  29883. pInode->nShared = 1;
  29884. }
  29885. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  29886. /* We are trying for an exclusive lock but another thread in this
  29887. ** same process is still holding a shared lock. */
  29888. rc = SQLITE_BUSY;
  29889. }else{
  29890. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  29891. ** assumed that there is a SHARED or greater lock on the file
  29892. ** already.
  29893. */
  29894. assert( 0!=pFile->eFileLock );
  29895. lock.l_type = F_WRLCK;
  29896. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  29897. if( eFileLock==RESERVED_LOCK ){
  29898. lock.l_start = RESERVED_BYTE;
  29899. lock.l_len = 1L;
  29900. }else{
  29901. lock.l_start = SHARED_FIRST;
  29902. lock.l_len = SHARED_SIZE;
  29903. }
  29904. if( unixFileLock(pFile, &lock) ){
  29905. tErrno = errno;
  29906. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  29907. if( rc!=SQLITE_BUSY ){
  29908. storeLastErrno(pFile, tErrno);
  29909. }
  29910. }
  29911. }
  29912. #ifdef SQLITE_DEBUG
  29913. /* Set up the transaction-counter change checking flags when
  29914. ** transitioning from a SHARED to a RESERVED lock. The change
  29915. ** from SHARED to RESERVED marks the beginning of a normal
  29916. ** write operation (not a hot journal rollback).
  29917. */
  29918. if( rc==SQLITE_OK
  29919. && pFile->eFileLock<=SHARED_LOCK
  29920. && eFileLock==RESERVED_LOCK
  29921. ){
  29922. pFile->transCntrChng = 0;
  29923. pFile->dbUpdate = 0;
  29924. pFile->inNormalWrite = 1;
  29925. }
  29926. #endif
  29927. if( rc==SQLITE_OK ){
  29928. pFile->eFileLock = eFileLock;
  29929. pInode->eFileLock = eFileLock;
  29930. }else if( eFileLock==EXCLUSIVE_LOCK ){
  29931. pFile->eFileLock = PENDING_LOCK;
  29932. pInode->eFileLock = PENDING_LOCK;
  29933. }
  29934. end_lock:
  29935. unixLeaveMutex();
  29936. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  29937. rc==SQLITE_OK ? "ok" : "failed"));
  29938. return rc;
  29939. }
  29940. /*
  29941. ** Add the file descriptor used by file handle pFile to the corresponding
  29942. ** pUnused list.
  29943. */
  29944. static void setPendingFd(unixFile *pFile){
  29945. unixInodeInfo *pInode = pFile->pInode;
  29946. UnixUnusedFd *p = pFile->pUnused;
  29947. p->pNext = pInode->pUnused;
  29948. pInode->pUnused = p;
  29949. pFile->h = -1;
  29950. pFile->pUnused = 0;
  29951. }
  29952. /*
  29953. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  29954. ** must be either NO_LOCK or SHARED_LOCK.
  29955. **
  29956. ** If the locking level of the file descriptor is already at or below
  29957. ** the requested locking level, this routine is a no-op.
  29958. **
  29959. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  29960. ** the byte range is divided into 2 parts and the first part is unlocked then
  29961. ** set to a read lock, then the other part is simply unlocked. This works
  29962. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  29963. ** remove the write lock on a region when a read lock is set.
  29964. */
  29965. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  29966. unixFile *pFile = (unixFile*)id;
  29967. unixInodeInfo *pInode;
  29968. struct flock lock;
  29969. int rc = SQLITE_OK;
  29970. assert( pFile );
  29971. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  29972. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  29973. osGetpid(0)));
  29974. assert( eFileLock<=SHARED_LOCK );
  29975. if( pFile->eFileLock<=eFileLock ){
  29976. return SQLITE_OK;
  29977. }
  29978. unixEnterMutex();
  29979. pInode = pFile->pInode;
  29980. assert( pInode->nShared!=0 );
  29981. if( pFile->eFileLock>SHARED_LOCK ){
  29982. assert( pInode->eFileLock==pFile->eFileLock );
  29983. #ifdef SQLITE_DEBUG
  29984. /* When reducing a lock such that other processes can start
  29985. ** reading the database file again, make sure that the
  29986. ** transaction counter was updated if any part of the database
  29987. ** file changed. If the transaction counter is not updated,
  29988. ** other connections to the same file might not realize that
  29989. ** the file has changed and hence might not know to flush their
  29990. ** cache. The use of a stale cache can lead to database corruption.
  29991. */
  29992. pFile->inNormalWrite = 0;
  29993. #endif
  29994. /* downgrading to a shared lock on NFS involves clearing the write lock
  29995. ** before establishing the readlock - to avoid a race condition we downgrade
  29996. ** the lock in 2 blocks, so that part of the range will be covered by a
  29997. ** write lock until the rest is covered by a read lock:
  29998. ** 1: [WWWWW]
  29999. ** 2: [....W]
  30000. ** 3: [RRRRW]
  30001. ** 4: [RRRR.]
  30002. */
  30003. if( eFileLock==SHARED_LOCK ){
  30004. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  30005. (void)handleNFSUnlock;
  30006. assert( handleNFSUnlock==0 );
  30007. #endif
  30008. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30009. if( handleNFSUnlock ){
  30010. int tErrno; /* Error code from system call errors */
  30011. off_t divSize = SHARED_SIZE - 1;
  30012. lock.l_type = F_UNLCK;
  30013. lock.l_whence = SEEK_SET;
  30014. lock.l_start = SHARED_FIRST;
  30015. lock.l_len = divSize;
  30016. if( unixFileLock(pFile, &lock)==(-1) ){
  30017. tErrno = errno;
  30018. rc = SQLITE_IOERR_UNLOCK;
  30019. storeLastErrno(pFile, tErrno);
  30020. goto end_unlock;
  30021. }
  30022. lock.l_type = F_RDLCK;
  30023. lock.l_whence = SEEK_SET;
  30024. lock.l_start = SHARED_FIRST;
  30025. lock.l_len = divSize;
  30026. if( unixFileLock(pFile, &lock)==(-1) ){
  30027. tErrno = errno;
  30028. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  30029. if( IS_LOCK_ERROR(rc) ){
  30030. storeLastErrno(pFile, tErrno);
  30031. }
  30032. goto end_unlock;
  30033. }
  30034. lock.l_type = F_UNLCK;
  30035. lock.l_whence = SEEK_SET;
  30036. lock.l_start = SHARED_FIRST+divSize;
  30037. lock.l_len = SHARED_SIZE-divSize;
  30038. if( unixFileLock(pFile, &lock)==(-1) ){
  30039. tErrno = errno;
  30040. rc = SQLITE_IOERR_UNLOCK;
  30041. storeLastErrno(pFile, tErrno);
  30042. goto end_unlock;
  30043. }
  30044. }else
  30045. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  30046. {
  30047. lock.l_type = F_RDLCK;
  30048. lock.l_whence = SEEK_SET;
  30049. lock.l_start = SHARED_FIRST;
  30050. lock.l_len = SHARED_SIZE;
  30051. if( unixFileLock(pFile, &lock) ){
  30052. /* In theory, the call to unixFileLock() cannot fail because another
  30053. ** process is holding an incompatible lock. If it does, this
  30054. ** indicates that the other process is not following the locking
  30055. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  30056. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  30057. ** an assert to fail). */
  30058. rc = SQLITE_IOERR_RDLOCK;
  30059. storeLastErrno(pFile, errno);
  30060. goto end_unlock;
  30061. }
  30062. }
  30063. }
  30064. lock.l_type = F_UNLCK;
  30065. lock.l_whence = SEEK_SET;
  30066. lock.l_start = PENDING_BYTE;
  30067. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  30068. if( unixFileLock(pFile, &lock)==0 ){
  30069. pInode->eFileLock = SHARED_LOCK;
  30070. }else{
  30071. rc = SQLITE_IOERR_UNLOCK;
  30072. storeLastErrno(pFile, errno);
  30073. goto end_unlock;
  30074. }
  30075. }
  30076. if( eFileLock==NO_LOCK ){
  30077. /* Decrement the shared lock counter. Release the lock using an
  30078. ** OS call only when all threads in this same process have released
  30079. ** the lock.
  30080. */
  30081. pInode->nShared--;
  30082. if( pInode->nShared==0 ){
  30083. lock.l_type = F_UNLCK;
  30084. lock.l_whence = SEEK_SET;
  30085. lock.l_start = lock.l_len = 0L;
  30086. if( unixFileLock(pFile, &lock)==0 ){
  30087. pInode->eFileLock = NO_LOCK;
  30088. }else{
  30089. rc = SQLITE_IOERR_UNLOCK;
  30090. storeLastErrno(pFile, errno);
  30091. pInode->eFileLock = NO_LOCK;
  30092. pFile->eFileLock = NO_LOCK;
  30093. }
  30094. }
  30095. /* Decrement the count of locks against this same file. When the
  30096. ** count reaches zero, close any other file descriptors whose close
  30097. ** was deferred because of outstanding locks.
  30098. */
  30099. pInode->nLock--;
  30100. assert( pInode->nLock>=0 );
  30101. if( pInode->nLock==0 ){
  30102. closePendingFds(pFile);
  30103. }
  30104. }
  30105. end_unlock:
  30106. unixLeaveMutex();
  30107. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  30108. return rc;
  30109. }
  30110. /*
  30111. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30112. ** must be either NO_LOCK or SHARED_LOCK.
  30113. **
  30114. ** If the locking level of the file descriptor is already at or below
  30115. ** the requested locking level, this routine is a no-op.
  30116. */
  30117. static int unixUnlock(sqlite3_file *id, int eFileLock){
  30118. #if SQLITE_MAX_MMAP_SIZE>0
  30119. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  30120. #endif
  30121. return posixUnlock(id, eFileLock, 0);
  30122. }
  30123. #if SQLITE_MAX_MMAP_SIZE>0
  30124. static int unixMapfile(unixFile *pFd, i64 nByte);
  30125. static void unixUnmapfile(unixFile *pFd);
  30126. #endif
  30127. /*
  30128. ** This function performs the parts of the "close file" operation
  30129. ** common to all locking schemes. It closes the directory and file
  30130. ** handles, if they are valid, and sets all fields of the unixFile
  30131. ** structure to 0.
  30132. **
  30133. ** It is *not* necessary to hold the mutex when this routine is called,
  30134. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  30135. ** vxworksReleaseFileId() routine.
  30136. */
  30137. static int closeUnixFile(sqlite3_file *id){
  30138. unixFile *pFile = (unixFile*)id;
  30139. #if SQLITE_MAX_MMAP_SIZE>0
  30140. unixUnmapfile(pFile);
  30141. #endif
  30142. if( pFile->h>=0 ){
  30143. robust_close(pFile, pFile->h, __LINE__);
  30144. pFile->h = -1;
  30145. }
  30146. #if OS_VXWORKS
  30147. if( pFile->pId ){
  30148. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  30149. osUnlink(pFile->pId->zCanonicalName);
  30150. }
  30151. vxworksReleaseFileId(pFile->pId);
  30152. pFile->pId = 0;
  30153. }
  30154. #endif
  30155. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  30156. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  30157. osUnlink(pFile->zPath);
  30158. sqlite3_free(*(char**)&pFile->zPath);
  30159. pFile->zPath = 0;
  30160. }
  30161. #endif
  30162. OSTRACE(("CLOSE %-3d\n", pFile->h));
  30163. OpenCounter(-1);
  30164. sqlite3_free(pFile->pUnused);
  30165. memset(pFile, 0, sizeof(unixFile));
  30166. return SQLITE_OK;
  30167. }
  30168. /*
  30169. ** Close a file.
  30170. */
  30171. static int unixClose(sqlite3_file *id){
  30172. int rc = SQLITE_OK;
  30173. unixFile *pFile = (unixFile *)id;
  30174. verifyDbFile(pFile);
  30175. unixUnlock(id, NO_LOCK);
  30176. unixEnterMutex();
  30177. /* unixFile.pInode is always valid here. Otherwise, a different close
  30178. ** routine (e.g. nolockClose()) would be called instead.
  30179. */
  30180. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  30181. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  30182. /* If there are outstanding locks, do not actually close the file just
  30183. ** yet because that would clear those locks. Instead, add the file
  30184. ** descriptor to pInode->pUnused list. It will be automatically closed
  30185. ** when the last lock is cleared.
  30186. */
  30187. setPendingFd(pFile);
  30188. }
  30189. releaseInodeInfo(pFile);
  30190. rc = closeUnixFile(id);
  30191. unixLeaveMutex();
  30192. return rc;
  30193. }
  30194. /************** End of the posix advisory lock implementation *****************
  30195. ******************************************************************************/
  30196. /******************************************************************************
  30197. ****************************** No-op Locking **********************************
  30198. **
  30199. ** Of the various locking implementations available, this is by far the
  30200. ** simplest: locking is ignored. No attempt is made to lock the database
  30201. ** file for reading or writing.
  30202. **
  30203. ** This locking mode is appropriate for use on read-only databases
  30204. ** (ex: databases that are burned into CD-ROM, for example.) It can
  30205. ** also be used if the application employs some external mechanism to
  30206. ** prevent simultaneous access of the same database by two or more
  30207. ** database connections. But there is a serious risk of database
  30208. ** corruption if this locking mode is used in situations where multiple
  30209. ** database connections are accessing the same database file at the same
  30210. ** time and one or more of those connections are writing.
  30211. */
  30212. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  30213. UNUSED_PARAMETER(NotUsed);
  30214. *pResOut = 0;
  30215. return SQLITE_OK;
  30216. }
  30217. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  30218. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  30219. return SQLITE_OK;
  30220. }
  30221. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  30222. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  30223. return SQLITE_OK;
  30224. }
  30225. /*
  30226. ** Close the file.
  30227. */
  30228. static int nolockClose(sqlite3_file *id) {
  30229. return closeUnixFile(id);
  30230. }
  30231. /******************* End of the no-op lock implementation *********************
  30232. ******************************************************************************/
  30233. /******************************************************************************
  30234. ************************* Begin dot-file Locking ******************************
  30235. **
  30236. ** The dotfile locking implementation uses the existence of separate lock
  30237. ** files (really a directory) to control access to the database. This works
  30238. ** on just about every filesystem imaginable. But there are serious downsides:
  30239. **
  30240. ** (1) There is zero concurrency. A single reader blocks all other
  30241. ** connections from reading or writing the database.
  30242. **
  30243. ** (2) An application crash or power loss can leave stale lock files
  30244. ** sitting around that need to be cleared manually.
  30245. **
  30246. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  30247. ** other locking strategy is available.
  30248. **
  30249. ** Dotfile locking works by creating a subdirectory in the same directory as
  30250. ** the database and with the same name but with a ".lock" extension added.
  30251. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  30252. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  30253. */
  30254. /*
  30255. ** The file suffix added to the data base filename in order to create the
  30256. ** lock directory.
  30257. */
  30258. #define DOTLOCK_SUFFIX ".lock"
  30259. /*
  30260. ** This routine checks if there is a RESERVED lock held on the specified
  30261. ** file by this or any other process. If such a lock is held, set *pResOut
  30262. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30263. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30264. **
  30265. ** In dotfile locking, either a lock exists or it does not. So in this
  30266. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  30267. ** is held on the file and false if the file is unlocked.
  30268. */
  30269. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  30270. int rc = SQLITE_OK;
  30271. int reserved = 0;
  30272. unixFile *pFile = (unixFile*)id;
  30273. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30274. assert( pFile );
  30275. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  30276. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  30277. *pResOut = reserved;
  30278. return rc;
  30279. }
  30280. /*
  30281. ** Lock the file with the lock specified by parameter eFileLock - one
  30282. ** of the following:
  30283. **
  30284. ** (1) SHARED_LOCK
  30285. ** (2) RESERVED_LOCK
  30286. ** (3) PENDING_LOCK
  30287. ** (4) EXCLUSIVE_LOCK
  30288. **
  30289. ** Sometimes when requesting one lock state, additional lock states
  30290. ** are inserted in between. The locking might fail on one of the later
  30291. ** transitions leaving the lock state different from what it started but
  30292. ** still short of its goal. The following chart shows the allowed
  30293. ** transitions and the inserted intermediate states:
  30294. **
  30295. ** UNLOCKED -> SHARED
  30296. ** SHARED -> RESERVED
  30297. ** SHARED -> (PENDING) -> EXCLUSIVE
  30298. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30299. ** PENDING -> EXCLUSIVE
  30300. **
  30301. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30302. ** routine to lower a locking level.
  30303. **
  30304. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  30305. ** But we track the other locking levels internally.
  30306. */
  30307. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  30308. unixFile *pFile = (unixFile*)id;
  30309. char *zLockFile = (char *)pFile->lockingContext;
  30310. int rc = SQLITE_OK;
  30311. /* If we have any lock, then the lock file already exists. All we have
  30312. ** to do is adjust our internal record of the lock level.
  30313. */
  30314. if( pFile->eFileLock > NO_LOCK ){
  30315. pFile->eFileLock = eFileLock;
  30316. /* Always update the timestamp on the old file */
  30317. #ifdef HAVE_UTIME
  30318. utime(zLockFile, NULL);
  30319. #else
  30320. utimes(zLockFile, NULL);
  30321. #endif
  30322. return SQLITE_OK;
  30323. }
  30324. /* grab an exclusive lock */
  30325. rc = osMkdir(zLockFile, 0777);
  30326. if( rc<0 ){
  30327. /* failed to open/create the lock directory */
  30328. int tErrno = errno;
  30329. if( EEXIST == tErrno ){
  30330. rc = SQLITE_BUSY;
  30331. } else {
  30332. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30333. if( rc!=SQLITE_BUSY ){
  30334. storeLastErrno(pFile, tErrno);
  30335. }
  30336. }
  30337. return rc;
  30338. }
  30339. /* got it, set the type and return ok */
  30340. pFile->eFileLock = eFileLock;
  30341. return rc;
  30342. }
  30343. /*
  30344. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30345. ** must be either NO_LOCK or SHARED_LOCK.
  30346. **
  30347. ** If the locking level of the file descriptor is already at or below
  30348. ** the requested locking level, this routine is a no-op.
  30349. **
  30350. ** When the locking level reaches NO_LOCK, delete the lock file.
  30351. */
  30352. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  30353. unixFile *pFile = (unixFile*)id;
  30354. char *zLockFile = (char *)pFile->lockingContext;
  30355. int rc;
  30356. assert( pFile );
  30357. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  30358. pFile->eFileLock, osGetpid(0)));
  30359. assert( eFileLock<=SHARED_LOCK );
  30360. /* no-op if possible */
  30361. if( pFile->eFileLock==eFileLock ){
  30362. return SQLITE_OK;
  30363. }
  30364. /* To downgrade to shared, simply update our internal notion of the
  30365. ** lock state. No need to mess with the file on disk.
  30366. */
  30367. if( eFileLock==SHARED_LOCK ){
  30368. pFile->eFileLock = SHARED_LOCK;
  30369. return SQLITE_OK;
  30370. }
  30371. /* To fully unlock the database, delete the lock file */
  30372. assert( eFileLock==NO_LOCK );
  30373. rc = osRmdir(zLockFile);
  30374. if( rc<0 ){
  30375. int tErrno = errno;
  30376. if( tErrno==ENOENT ){
  30377. rc = SQLITE_OK;
  30378. }else{
  30379. rc = SQLITE_IOERR_UNLOCK;
  30380. storeLastErrno(pFile, tErrno);
  30381. }
  30382. return rc;
  30383. }
  30384. pFile->eFileLock = NO_LOCK;
  30385. return SQLITE_OK;
  30386. }
  30387. /*
  30388. ** Close a file. Make sure the lock has been released before closing.
  30389. */
  30390. static int dotlockClose(sqlite3_file *id) {
  30391. unixFile *pFile = (unixFile*)id;
  30392. assert( id!=0 );
  30393. dotlockUnlock(id, NO_LOCK);
  30394. sqlite3_free(pFile->lockingContext);
  30395. return closeUnixFile(id);
  30396. }
  30397. /****************** End of the dot-file lock implementation *******************
  30398. ******************************************************************************/
  30399. /******************************************************************************
  30400. ************************** Begin flock Locking ********************************
  30401. **
  30402. ** Use the flock() system call to do file locking.
  30403. **
  30404. ** flock() locking is like dot-file locking in that the various
  30405. ** fine-grain locking levels supported by SQLite are collapsed into
  30406. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  30407. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  30408. ** still works when you do this, but concurrency is reduced since
  30409. ** only a single process can be reading the database at a time.
  30410. **
  30411. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  30412. */
  30413. #if SQLITE_ENABLE_LOCKING_STYLE
  30414. /*
  30415. ** Retry flock() calls that fail with EINTR
  30416. */
  30417. #ifdef EINTR
  30418. static int robust_flock(int fd, int op){
  30419. int rc;
  30420. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  30421. return rc;
  30422. }
  30423. #else
  30424. # define robust_flock(a,b) flock(a,b)
  30425. #endif
  30426. /*
  30427. ** This routine checks if there is a RESERVED lock held on the specified
  30428. ** file by this or any other process. If such a lock is held, set *pResOut
  30429. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30430. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30431. */
  30432. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  30433. int rc = SQLITE_OK;
  30434. int reserved = 0;
  30435. unixFile *pFile = (unixFile*)id;
  30436. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30437. assert( pFile );
  30438. /* Check if a thread in this process holds such a lock */
  30439. if( pFile->eFileLock>SHARED_LOCK ){
  30440. reserved = 1;
  30441. }
  30442. /* Otherwise see if some other process holds it. */
  30443. if( !reserved ){
  30444. /* attempt to get the lock */
  30445. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  30446. if( !lrc ){
  30447. /* got the lock, unlock it */
  30448. lrc = robust_flock(pFile->h, LOCK_UN);
  30449. if ( lrc ) {
  30450. int tErrno = errno;
  30451. /* unlock failed with an error */
  30452. lrc = SQLITE_IOERR_UNLOCK;
  30453. storeLastErrno(pFile, tErrno);
  30454. rc = lrc;
  30455. }
  30456. } else {
  30457. int tErrno = errno;
  30458. reserved = 1;
  30459. /* someone else might have it reserved */
  30460. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30461. if( IS_LOCK_ERROR(lrc) ){
  30462. storeLastErrno(pFile, tErrno);
  30463. rc = lrc;
  30464. }
  30465. }
  30466. }
  30467. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  30468. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  30469. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  30470. rc = SQLITE_OK;
  30471. reserved=1;
  30472. }
  30473. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  30474. *pResOut = reserved;
  30475. return rc;
  30476. }
  30477. /*
  30478. ** Lock the file with the lock specified by parameter eFileLock - one
  30479. ** of the following:
  30480. **
  30481. ** (1) SHARED_LOCK
  30482. ** (2) RESERVED_LOCK
  30483. ** (3) PENDING_LOCK
  30484. ** (4) EXCLUSIVE_LOCK
  30485. **
  30486. ** Sometimes when requesting one lock state, additional lock states
  30487. ** are inserted in between. The locking might fail on one of the later
  30488. ** transitions leaving the lock state different from what it started but
  30489. ** still short of its goal. The following chart shows the allowed
  30490. ** transitions and the inserted intermediate states:
  30491. **
  30492. ** UNLOCKED -> SHARED
  30493. ** SHARED -> RESERVED
  30494. ** SHARED -> (PENDING) -> EXCLUSIVE
  30495. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30496. ** PENDING -> EXCLUSIVE
  30497. **
  30498. ** flock() only really support EXCLUSIVE locks. We track intermediate
  30499. ** lock states in the sqlite3_file structure, but all locks SHARED or
  30500. ** above are really EXCLUSIVE locks and exclude all other processes from
  30501. ** access the file.
  30502. **
  30503. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30504. ** routine to lower a locking level.
  30505. */
  30506. static int flockLock(sqlite3_file *id, int eFileLock) {
  30507. int rc = SQLITE_OK;
  30508. unixFile *pFile = (unixFile*)id;
  30509. assert( pFile );
  30510. /* if we already have a lock, it is exclusive.
  30511. ** Just adjust level and punt on outta here. */
  30512. if (pFile->eFileLock > NO_LOCK) {
  30513. pFile->eFileLock = eFileLock;
  30514. return SQLITE_OK;
  30515. }
  30516. /* grab an exclusive lock */
  30517. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  30518. int tErrno = errno;
  30519. /* didn't get, must be busy */
  30520. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30521. if( IS_LOCK_ERROR(rc) ){
  30522. storeLastErrno(pFile, tErrno);
  30523. }
  30524. } else {
  30525. /* got it, set the type and return ok */
  30526. pFile->eFileLock = eFileLock;
  30527. }
  30528. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  30529. rc==SQLITE_OK ? "ok" : "failed"));
  30530. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  30531. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  30532. rc = SQLITE_BUSY;
  30533. }
  30534. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  30535. return rc;
  30536. }
  30537. /*
  30538. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30539. ** must be either NO_LOCK or SHARED_LOCK.
  30540. **
  30541. ** If the locking level of the file descriptor is already at or below
  30542. ** the requested locking level, this routine is a no-op.
  30543. */
  30544. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  30545. unixFile *pFile = (unixFile*)id;
  30546. assert( pFile );
  30547. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  30548. pFile->eFileLock, osGetpid(0)));
  30549. assert( eFileLock<=SHARED_LOCK );
  30550. /* no-op if possible */
  30551. if( pFile->eFileLock==eFileLock ){
  30552. return SQLITE_OK;
  30553. }
  30554. /* shared can just be set because we always have an exclusive */
  30555. if (eFileLock==SHARED_LOCK) {
  30556. pFile->eFileLock = eFileLock;
  30557. return SQLITE_OK;
  30558. }
  30559. /* no, really, unlock. */
  30560. if( robust_flock(pFile->h, LOCK_UN) ){
  30561. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  30562. return SQLITE_OK;
  30563. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  30564. return SQLITE_IOERR_UNLOCK;
  30565. }else{
  30566. pFile->eFileLock = NO_LOCK;
  30567. return SQLITE_OK;
  30568. }
  30569. }
  30570. /*
  30571. ** Close a file.
  30572. */
  30573. static int flockClose(sqlite3_file *id) {
  30574. assert( id!=0 );
  30575. flockUnlock(id, NO_LOCK);
  30576. return closeUnixFile(id);
  30577. }
  30578. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  30579. /******************* End of the flock lock implementation *********************
  30580. ******************************************************************************/
  30581. /******************************************************************************
  30582. ************************ Begin Named Semaphore Locking ************************
  30583. **
  30584. ** Named semaphore locking is only supported on VxWorks.
  30585. **
  30586. ** Semaphore locking is like dot-lock and flock in that it really only
  30587. ** supports EXCLUSIVE locking. Only a single process can read or write
  30588. ** the database file at a time. This reduces potential concurrency, but
  30589. ** makes the lock implementation much easier.
  30590. */
  30591. #if OS_VXWORKS
  30592. /*
  30593. ** This routine checks if there is a RESERVED lock held on the specified
  30594. ** file by this or any other process. If such a lock is held, set *pResOut
  30595. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30596. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30597. */
  30598. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  30599. int rc = SQLITE_OK;
  30600. int reserved = 0;
  30601. unixFile *pFile = (unixFile*)id;
  30602. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30603. assert( pFile );
  30604. /* Check if a thread in this process holds such a lock */
  30605. if( pFile->eFileLock>SHARED_LOCK ){
  30606. reserved = 1;
  30607. }
  30608. /* Otherwise see if some other process holds it. */
  30609. if( !reserved ){
  30610. sem_t *pSem = pFile->pInode->pSem;
  30611. if( sem_trywait(pSem)==-1 ){
  30612. int tErrno = errno;
  30613. if( EAGAIN != tErrno ){
  30614. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  30615. storeLastErrno(pFile, tErrno);
  30616. } else {
  30617. /* someone else has the lock when we are in NO_LOCK */
  30618. reserved = (pFile->eFileLock < SHARED_LOCK);
  30619. }
  30620. }else{
  30621. /* we could have it if we want it */
  30622. sem_post(pSem);
  30623. }
  30624. }
  30625. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  30626. *pResOut = reserved;
  30627. return rc;
  30628. }
  30629. /*
  30630. ** Lock the file with the lock specified by parameter eFileLock - one
  30631. ** of the following:
  30632. **
  30633. ** (1) SHARED_LOCK
  30634. ** (2) RESERVED_LOCK
  30635. ** (3) PENDING_LOCK
  30636. ** (4) EXCLUSIVE_LOCK
  30637. **
  30638. ** Sometimes when requesting one lock state, additional lock states
  30639. ** are inserted in between. The locking might fail on one of the later
  30640. ** transitions leaving the lock state different from what it started but
  30641. ** still short of its goal. The following chart shows the allowed
  30642. ** transitions and the inserted intermediate states:
  30643. **
  30644. ** UNLOCKED -> SHARED
  30645. ** SHARED -> RESERVED
  30646. ** SHARED -> (PENDING) -> EXCLUSIVE
  30647. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30648. ** PENDING -> EXCLUSIVE
  30649. **
  30650. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  30651. ** lock states in the sqlite3_file structure, but all locks SHARED or
  30652. ** above are really EXCLUSIVE locks and exclude all other processes from
  30653. ** access the file.
  30654. **
  30655. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30656. ** routine to lower a locking level.
  30657. */
  30658. static int semXLock(sqlite3_file *id, int eFileLock) {
  30659. unixFile *pFile = (unixFile*)id;
  30660. sem_t *pSem = pFile->pInode->pSem;
  30661. int rc = SQLITE_OK;
  30662. /* if we already have a lock, it is exclusive.
  30663. ** Just adjust level and punt on outta here. */
  30664. if (pFile->eFileLock > NO_LOCK) {
  30665. pFile->eFileLock = eFileLock;
  30666. rc = SQLITE_OK;
  30667. goto sem_end_lock;
  30668. }
  30669. /* lock semaphore now but bail out when already locked. */
  30670. if( sem_trywait(pSem)==-1 ){
  30671. rc = SQLITE_BUSY;
  30672. goto sem_end_lock;
  30673. }
  30674. /* got it, set the type and return ok */
  30675. pFile->eFileLock = eFileLock;
  30676. sem_end_lock:
  30677. return rc;
  30678. }
  30679. /*
  30680. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30681. ** must be either NO_LOCK or SHARED_LOCK.
  30682. **
  30683. ** If the locking level of the file descriptor is already at or below
  30684. ** the requested locking level, this routine is a no-op.
  30685. */
  30686. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  30687. unixFile *pFile = (unixFile*)id;
  30688. sem_t *pSem = pFile->pInode->pSem;
  30689. assert( pFile );
  30690. assert( pSem );
  30691. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  30692. pFile->eFileLock, osGetpid(0)));
  30693. assert( eFileLock<=SHARED_LOCK );
  30694. /* no-op if possible */
  30695. if( pFile->eFileLock==eFileLock ){
  30696. return SQLITE_OK;
  30697. }
  30698. /* shared can just be set because we always have an exclusive */
  30699. if (eFileLock==SHARED_LOCK) {
  30700. pFile->eFileLock = eFileLock;
  30701. return SQLITE_OK;
  30702. }
  30703. /* no, really unlock. */
  30704. if ( sem_post(pSem)==-1 ) {
  30705. int rc, tErrno = errno;
  30706. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  30707. if( IS_LOCK_ERROR(rc) ){
  30708. storeLastErrno(pFile, tErrno);
  30709. }
  30710. return rc;
  30711. }
  30712. pFile->eFileLock = NO_LOCK;
  30713. return SQLITE_OK;
  30714. }
  30715. /*
  30716. ** Close a file.
  30717. */
  30718. static int semXClose(sqlite3_file *id) {
  30719. if( id ){
  30720. unixFile *pFile = (unixFile*)id;
  30721. semXUnlock(id, NO_LOCK);
  30722. assert( pFile );
  30723. unixEnterMutex();
  30724. releaseInodeInfo(pFile);
  30725. unixLeaveMutex();
  30726. closeUnixFile(id);
  30727. }
  30728. return SQLITE_OK;
  30729. }
  30730. #endif /* OS_VXWORKS */
  30731. /*
  30732. ** Named semaphore locking is only available on VxWorks.
  30733. **
  30734. *************** End of the named semaphore lock implementation ****************
  30735. ******************************************************************************/
  30736. /******************************************************************************
  30737. *************************** Begin AFP Locking *********************************
  30738. **
  30739. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  30740. ** on Apple Macintosh computers - both OS9 and OSX.
  30741. **
  30742. ** Third-party implementations of AFP are available. But this code here
  30743. ** only works on OSX.
  30744. */
  30745. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30746. /*
  30747. ** The afpLockingContext structure contains all afp lock specific state
  30748. */
  30749. typedef struct afpLockingContext afpLockingContext;
  30750. struct afpLockingContext {
  30751. int reserved;
  30752. const char *dbPath; /* Name of the open file */
  30753. };
  30754. struct ByteRangeLockPB2
  30755. {
  30756. unsigned long long offset; /* offset to first byte to lock */
  30757. unsigned long long length; /* nbr of bytes to lock */
  30758. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  30759. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  30760. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  30761. int fd; /* file desc to assoc this lock with */
  30762. };
  30763. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  30764. /*
  30765. ** This is a utility for setting or clearing a bit-range lock on an
  30766. ** AFP filesystem.
  30767. **
  30768. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  30769. */
  30770. static int afpSetLock(
  30771. const char *path, /* Name of the file to be locked or unlocked */
  30772. unixFile *pFile, /* Open file descriptor on path */
  30773. unsigned long long offset, /* First byte to be locked */
  30774. unsigned long long length, /* Number of bytes to lock */
  30775. int setLockFlag /* True to set lock. False to clear lock */
  30776. ){
  30777. struct ByteRangeLockPB2 pb;
  30778. int err;
  30779. pb.unLockFlag = setLockFlag ? 0 : 1;
  30780. pb.startEndFlag = 0;
  30781. pb.offset = offset;
  30782. pb.length = length;
  30783. pb.fd = pFile->h;
  30784. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  30785. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  30786. offset, length));
  30787. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  30788. if ( err==-1 ) {
  30789. int rc;
  30790. int tErrno = errno;
  30791. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  30792. path, tErrno, strerror(tErrno)));
  30793. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  30794. rc = SQLITE_BUSY;
  30795. #else
  30796. rc = sqliteErrorFromPosixError(tErrno,
  30797. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  30798. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  30799. if( IS_LOCK_ERROR(rc) ){
  30800. storeLastErrno(pFile, tErrno);
  30801. }
  30802. return rc;
  30803. } else {
  30804. return SQLITE_OK;
  30805. }
  30806. }
  30807. /*
  30808. ** This routine checks if there is a RESERVED lock held on the specified
  30809. ** file by this or any other process. If such a lock is held, set *pResOut
  30810. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30811. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30812. */
  30813. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  30814. int rc = SQLITE_OK;
  30815. int reserved = 0;
  30816. unixFile *pFile = (unixFile*)id;
  30817. afpLockingContext *context;
  30818. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30819. assert( pFile );
  30820. context = (afpLockingContext *) pFile->lockingContext;
  30821. if( context->reserved ){
  30822. *pResOut = 1;
  30823. return SQLITE_OK;
  30824. }
  30825. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  30826. /* Check if a thread in this process holds such a lock */
  30827. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  30828. reserved = 1;
  30829. }
  30830. /* Otherwise see if some other process holds it.
  30831. */
  30832. if( !reserved ){
  30833. /* lock the RESERVED byte */
  30834. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  30835. if( SQLITE_OK==lrc ){
  30836. /* if we succeeded in taking the reserved lock, unlock it to restore
  30837. ** the original state */
  30838. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  30839. } else {
  30840. /* if we failed to get the lock then someone else must have it */
  30841. reserved = 1;
  30842. }
  30843. if( IS_LOCK_ERROR(lrc) ){
  30844. rc=lrc;
  30845. }
  30846. }
  30847. unixLeaveMutex();
  30848. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  30849. *pResOut = reserved;
  30850. return rc;
  30851. }
  30852. /*
  30853. ** Lock the file with the lock specified by parameter eFileLock - one
  30854. ** of the following:
  30855. **
  30856. ** (1) SHARED_LOCK
  30857. ** (2) RESERVED_LOCK
  30858. ** (3) PENDING_LOCK
  30859. ** (4) EXCLUSIVE_LOCK
  30860. **
  30861. ** Sometimes when requesting one lock state, additional lock states
  30862. ** are inserted in between. The locking might fail on one of the later
  30863. ** transitions leaving the lock state different from what it started but
  30864. ** still short of its goal. The following chart shows the allowed
  30865. ** transitions and the inserted intermediate states:
  30866. **
  30867. ** UNLOCKED -> SHARED
  30868. ** SHARED -> RESERVED
  30869. ** SHARED -> (PENDING) -> EXCLUSIVE
  30870. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30871. ** PENDING -> EXCLUSIVE
  30872. **
  30873. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30874. ** routine to lower a locking level.
  30875. */
  30876. static int afpLock(sqlite3_file *id, int eFileLock){
  30877. int rc = SQLITE_OK;
  30878. unixFile *pFile = (unixFile*)id;
  30879. unixInodeInfo *pInode = pFile->pInode;
  30880. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  30881. assert( pFile );
  30882. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  30883. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  30884. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  30885. /* If there is already a lock of this type or more restrictive on the
  30886. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  30887. ** unixEnterMutex() hasn't been called yet.
  30888. */
  30889. if( pFile->eFileLock>=eFileLock ){
  30890. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  30891. azFileLock(eFileLock)));
  30892. return SQLITE_OK;
  30893. }
  30894. /* Make sure the locking sequence is correct
  30895. ** (1) We never move from unlocked to anything higher than shared lock.
  30896. ** (2) SQLite never explicitly requests a pendig lock.
  30897. ** (3) A shared lock is always held when a reserve lock is requested.
  30898. */
  30899. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  30900. assert( eFileLock!=PENDING_LOCK );
  30901. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  30902. /* This mutex is needed because pFile->pInode is shared across threads
  30903. */
  30904. unixEnterMutex();
  30905. pInode = pFile->pInode;
  30906. /* If some thread using this PID has a lock via a different unixFile*
  30907. ** handle that precludes the requested lock, return BUSY.
  30908. */
  30909. if( (pFile->eFileLock!=pInode->eFileLock &&
  30910. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  30911. ){
  30912. rc = SQLITE_BUSY;
  30913. goto afp_end_lock;
  30914. }
  30915. /* If a SHARED lock is requested, and some thread using this PID already
  30916. ** has a SHARED or RESERVED lock, then increment reference counts and
  30917. ** return SQLITE_OK.
  30918. */
  30919. if( eFileLock==SHARED_LOCK &&
  30920. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  30921. assert( eFileLock==SHARED_LOCK );
  30922. assert( pFile->eFileLock==0 );
  30923. assert( pInode->nShared>0 );
  30924. pFile->eFileLock = SHARED_LOCK;
  30925. pInode->nShared++;
  30926. pInode->nLock++;
  30927. goto afp_end_lock;
  30928. }
  30929. /* A PENDING lock is needed before acquiring a SHARED lock and before
  30930. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  30931. ** be released.
  30932. */
  30933. if( eFileLock==SHARED_LOCK
  30934. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  30935. ){
  30936. int failed;
  30937. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  30938. if (failed) {
  30939. rc = failed;
  30940. goto afp_end_lock;
  30941. }
  30942. }
  30943. /* If control gets to this point, then actually go ahead and make
  30944. ** operating system calls for the specified lock.
  30945. */
  30946. if( eFileLock==SHARED_LOCK ){
  30947. int lrc1, lrc2, lrc1Errno = 0;
  30948. long lk, mask;
  30949. assert( pInode->nShared==0 );
  30950. assert( pInode->eFileLock==0 );
  30951. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  30952. /* Now get the read-lock SHARED_LOCK */
  30953. /* note that the quality of the randomness doesn't matter that much */
  30954. lk = random();
  30955. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  30956. lrc1 = afpSetLock(context->dbPath, pFile,
  30957. SHARED_FIRST+pInode->sharedByte, 1, 1);
  30958. if( IS_LOCK_ERROR(lrc1) ){
  30959. lrc1Errno = pFile->lastErrno;
  30960. }
  30961. /* Drop the temporary PENDING lock */
  30962. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  30963. if( IS_LOCK_ERROR(lrc1) ) {
  30964. storeLastErrno(pFile, lrc1Errno);
  30965. rc = lrc1;
  30966. goto afp_end_lock;
  30967. } else if( IS_LOCK_ERROR(lrc2) ){
  30968. rc = lrc2;
  30969. goto afp_end_lock;
  30970. } else if( lrc1 != SQLITE_OK ) {
  30971. rc = lrc1;
  30972. } else {
  30973. pFile->eFileLock = SHARED_LOCK;
  30974. pInode->nLock++;
  30975. pInode->nShared = 1;
  30976. }
  30977. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  30978. /* We are trying for an exclusive lock but another thread in this
  30979. ** same process is still holding a shared lock. */
  30980. rc = SQLITE_BUSY;
  30981. }else{
  30982. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  30983. ** assumed that there is a SHARED or greater lock on the file
  30984. ** already.
  30985. */
  30986. int failed = 0;
  30987. assert( 0!=pFile->eFileLock );
  30988. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  30989. /* Acquire a RESERVED lock */
  30990. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  30991. if( !failed ){
  30992. context->reserved = 1;
  30993. }
  30994. }
  30995. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  30996. /* Acquire an EXCLUSIVE lock */
  30997. /* Remove the shared lock before trying the range. we'll need to
  30998. ** reestablish the shared lock if we can't get the afpUnlock
  30999. */
  31000. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  31001. pInode->sharedByte, 1, 0)) ){
  31002. int failed2 = SQLITE_OK;
  31003. /* now attemmpt to get the exclusive lock range */
  31004. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  31005. SHARED_SIZE, 1);
  31006. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  31007. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  31008. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  31009. ** a critical I/O error
  31010. */
  31011. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  31012. SQLITE_IOERR_LOCK;
  31013. goto afp_end_lock;
  31014. }
  31015. }else{
  31016. rc = failed;
  31017. }
  31018. }
  31019. if( failed ){
  31020. rc = failed;
  31021. }
  31022. }
  31023. if( rc==SQLITE_OK ){
  31024. pFile->eFileLock = eFileLock;
  31025. pInode->eFileLock = eFileLock;
  31026. }else if( eFileLock==EXCLUSIVE_LOCK ){
  31027. pFile->eFileLock = PENDING_LOCK;
  31028. pInode->eFileLock = PENDING_LOCK;
  31029. }
  31030. afp_end_lock:
  31031. unixLeaveMutex();
  31032. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  31033. rc==SQLITE_OK ? "ok" : "failed"));
  31034. return rc;
  31035. }
  31036. /*
  31037. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31038. ** must be either NO_LOCK or SHARED_LOCK.
  31039. **
  31040. ** If the locking level of the file descriptor is already at or below
  31041. ** the requested locking level, this routine is a no-op.
  31042. */
  31043. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  31044. int rc = SQLITE_OK;
  31045. unixFile *pFile = (unixFile*)id;
  31046. unixInodeInfo *pInode;
  31047. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  31048. int skipShared = 0;
  31049. #ifdef SQLITE_TEST
  31050. int h = pFile->h;
  31051. #endif
  31052. assert( pFile );
  31053. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  31054. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  31055. osGetpid(0)));
  31056. assert( eFileLock<=SHARED_LOCK );
  31057. if( pFile->eFileLock<=eFileLock ){
  31058. return SQLITE_OK;
  31059. }
  31060. unixEnterMutex();
  31061. pInode = pFile->pInode;
  31062. assert( pInode->nShared!=0 );
  31063. if( pFile->eFileLock>SHARED_LOCK ){
  31064. assert( pInode->eFileLock==pFile->eFileLock );
  31065. SimulateIOErrorBenign(1);
  31066. SimulateIOError( h=(-1) )
  31067. SimulateIOErrorBenign(0);
  31068. #ifdef SQLITE_DEBUG
  31069. /* When reducing a lock such that other processes can start
  31070. ** reading the database file again, make sure that the
  31071. ** transaction counter was updated if any part of the database
  31072. ** file changed. If the transaction counter is not updated,
  31073. ** other connections to the same file might not realize that
  31074. ** the file has changed and hence might not know to flush their
  31075. ** cache. The use of a stale cache can lead to database corruption.
  31076. */
  31077. assert( pFile->inNormalWrite==0
  31078. || pFile->dbUpdate==0
  31079. || pFile->transCntrChng==1 );
  31080. pFile->inNormalWrite = 0;
  31081. #endif
  31082. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  31083. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  31084. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  31085. /* only re-establish the shared lock if necessary */
  31086. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  31087. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  31088. } else {
  31089. skipShared = 1;
  31090. }
  31091. }
  31092. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  31093. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  31094. }
  31095. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  31096. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  31097. if( !rc ){
  31098. context->reserved = 0;
  31099. }
  31100. }
  31101. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  31102. pInode->eFileLock = SHARED_LOCK;
  31103. }
  31104. }
  31105. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  31106. /* Decrement the shared lock counter. Release the lock using an
  31107. ** OS call only when all threads in this same process have released
  31108. ** the lock.
  31109. */
  31110. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  31111. pInode->nShared--;
  31112. if( pInode->nShared==0 ){
  31113. SimulateIOErrorBenign(1);
  31114. SimulateIOError( h=(-1) )
  31115. SimulateIOErrorBenign(0);
  31116. if( !skipShared ){
  31117. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  31118. }
  31119. if( !rc ){
  31120. pInode->eFileLock = NO_LOCK;
  31121. pFile->eFileLock = NO_LOCK;
  31122. }
  31123. }
  31124. if( rc==SQLITE_OK ){
  31125. pInode->nLock--;
  31126. assert( pInode->nLock>=0 );
  31127. if( pInode->nLock==0 ){
  31128. closePendingFds(pFile);
  31129. }
  31130. }
  31131. }
  31132. unixLeaveMutex();
  31133. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  31134. return rc;
  31135. }
  31136. /*
  31137. ** Close a file & cleanup AFP specific locking context
  31138. */
  31139. static int afpClose(sqlite3_file *id) {
  31140. int rc = SQLITE_OK;
  31141. unixFile *pFile = (unixFile*)id;
  31142. assert( id!=0 );
  31143. afpUnlock(id, NO_LOCK);
  31144. unixEnterMutex();
  31145. if( pFile->pInode && pFile->pInode->nLock ){
  31146. /* If there are outstanding locks, do not actually close the file just
  31147. ** yet because that would clear those locks. Instead, add the file
  31148. ** descriptor to pInode->aPending. It will be automatically closed when
  31149. ** the last lock is cleared.
  31150. */
  31151. setPendingFd(pFile);
  31152. }
  31153. releaseInodeInfo(pFile);
  31154. sqlite3_free(pFile->lockingContext);
  31155. rc = closeUnixFile(id);
  31156. unixLeaveMutex();
  31157. return rc;
  31158. }
  31159. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  31160. /*
  31161. ** The code above is the AFP lock implementation. The code is specific
  31162. ** to MacOSX and does not work on other unix platforms. No alternative
  31163. ** is available. If you don't compile for a mac, then the "unix-afp"
  31164. ** VFS is not available.
  31165. **
  31166. ********************* End of the AFP lock implementation **********************
  31167. ******************************************************************************/
  31168. /******************************************************************************
  31169. *************************** Begin NFS Locking ********************************/
  31170. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  31171. /*
  31172. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31173. ** must be either NO_LOCK or SHARED_LOCK.
  31174. **
  31175. ** If the locking level of the file descriptor is already at or below
  31176. ** the requested locking level, this routine is a no-op.
  31177. */
  31178. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  31179. return posixUnlock(id, eFileLock, 1);
  31180. }
  31181. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  31182. /*
  31183. ** The code above is the NFS lock implementation. The code is specific
  31184. ** to MacOSX and does not work on other unix platforms. No alternative
  31185. ** is available.
  31186. **
  31187. ********************* End of the NFS lock implementation **********************
  31188. ******************************************************************************/
  31189. /******************************************************************************
  31190. **************** Non-locking sqlite3_file methods *****************************
  31191. **
  31192. ** The next division contains implementations for all methods of the
  31193. ** sqlite3_file object other than the locking methods. The locking
  31194. ** methods were defined in divisions above (one locking method per
  31195. ** division). Those methods that are common to all locking modes
  31196. ** are gather together into this division.
  31197. */
  31198. /*
  31199. ** Seek to the offset passed as the second argument, then read cnt
  31200. ** bytes into pBuf. Return the number of bytes actually read.
  31201. **
  31202. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  31203. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  31204. ** one system to another. Since SQLite does not define USE_PREAD
  31205. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  31206. ** See tickets #2741 and #2681.
  31207. **
  31208. ** To avoid stomping the errno value on a failed read the lastErrno value
  31209. ** is set before returning.
  31210. */
  31211. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  31212. int got;
  31213. int prior = 0;
  31214. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  31215. i64 newOffset;
  31216. #endif
  31217. TIMER_START;
  31218. assert( cnt==(cnt&0x1ffff) );
  31219. assert( id->h>2 );
  31220. do{
  31221. #if defined(USE_PREAD)
  31222. got = osPread(id->h, pBuf, cnt, offset);
  31223. SimulateIOError( got = -1 );
  31224. #elif defined(USE_PREAD64)
  31225. got = osPread64(id->h, pBuf, cnt, offset);
  31226. SimulateIOError( got = -1 );
  31227. #else
  31228. newOffset = lseek(id->h, offset, SEEK_SET);
  31229. SimulateIOError( newOffset = -1 );
  31230. if( newOffset<0 ){
  31231. storeLastErrno((unixFile*)id, errno);
  31232. return -1;
  31233. }
  31234. got = osRead(id->h, pBuf, cnt);
  31235. #endif
  31236. if( got==cnt ) break;
  31237. if( got<0 ){
  31238. if( errno==EINTR ){ got = 1; continue; }
  31239. prior = 0;
  31240. storeLastErrno((unixFile*)id, errno);
  31241. break;
  31242. }else if( got>0 ){
  31243. cnt -= got;
  31244. offset += got;
  31245. prior += got;
  31246. pBuf = (void*)(got + (char*)pBuf);
  31247. }
  31248. }while( got>0 );
  31249. TIMER_END;
  31250. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  31251. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  31252. return got+prior;
  31253. }
  31254. /*
  31255. ** Read data from a file into a buffer. Return SQLITE_OK if all
  31256. ** bytes were read successfully and SQLITE_IOERR if anything goes
  31257. ** wrong.
  31258. */
  31259. static int unixRead(
  31260. sqlite3_file *id,
  31261. void *pBuf,
  31262. int amt,
  31263. sqlite3_int64 offset
  31264. ){
  31265. unixFile *pFile = (unixFile *)id;
  31266. int got;
  31267. assert( id );
  31268. assert( offset>=0 );
  31269. assert( amt>0 );
  31270. /* If this is a database file (not a journal, master-journal or temp
  31271. ** file), the bytes in the locking range should never be read or written. */
  31272. #if 0
  31273. assert( pFile->pUnused==0
  31274. || offset>=PENDING_BYTE+512
  31275. || offset+amt<=PENDING_BYTE
  31276. );
  31277. #endif
  31278. #if SQLITE_MAX_MMAP_SIZE>0
  31279. /* Deal with as much of this read request as possible by transfering
  31280. ** data from the memory mapping using memcpy(). */
  31281. if( offset<pFile->mmapSize ){
  31282. if( offset+amt <= pFile->mmapSize ){
  31283. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  31284. return SQLITE_OK;
  31285. }else{
  31286. int nCopy = pFile->mmapSize - offset;
  31287. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  31288. pBuf = &((u8 *)pBuf)[nCopy];
  31289. amt -= nCopy;
  31290. offset += nCopy;
  31291. }
  31292. }
  31293. #endif
  31294. got = seekAndRead(pFile, offset, pBuf, amt);
  31295. if( got==amt ){
  31296. return SQLITE_OK;
  31297. }else if( got<0 ){
  31298. /* lastErrno set by seekAndRead */
  31299. return SQLITE_IOERR_READ;
  31300. }else{
  31301. storeLastErrno(pFile, 0); /* not a system error */
  31302. /* Unread parts of the buffer must be zero-filled */
  31303. memset(&((char*)pBuf)[got], 0, amt-got);
  31304. return SQLITE_IOERR_SHORT_READ;
  31305. }
  31306. }
  31307. /*
  31308. ** Attempt to seek the file-descriptor passed as the first argument to
  31309. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  31310. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  31311. ** return the actual number of bytes written (which may be less than
  31312. ** nBuf).
  31313. */
  31314. static int seekAndWriteFd(
  31315. int fd, /* File descriptor to write to */
  31316. i64 iOff, /* File offset to begin writing at */
  31317. const void *pBuf, /* Copy data from this buffer to the file */
  31318. int nBuf, /* Size of buffer pBuf in bytes */
  31319. int *piErrno /* OUT: Error number if error occurs */
  31320. ){
  31321. int rc = 0; /* Value returned by system call */
  31322. assert( nBuf==(nBuf&0x1ffff) );
  31323. assert( fd>2 );
  31324. assert( piErrno!=0 );
  31325. nBuf &= 0x1ffff;
  31326. TIMER_START;
  31327. #if defined(USE_PREAD)
  31328. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  31329. #elif defined(USE_PREAD64)
  31330. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  31331. #else
  31332. do{
  31333. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  31334. SimulateIOError( iSeek = -1 );
  31335. if( iSeek<0 ){
  31336. rc = -1;
  31337. break;
  31338. }
  31339. rc = osWrite(fd, pBuf, nBuf);
  31340. }while( rc<0 && errno==EINTR );
  31341. #endif
  31342. TIMER_END;
  31343. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  31344. if( rc<0 ) *piErrno = errno;
  31345. return rc;
  31346. }
  31347. /*
  31348. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  31349. ** Return the number of bytes actually read. Update the offset.
  31350. **
  31351. ** To avoid stomping the errno value on a failed write the lastErrno value
  31352. ** is set before returning.
  31353. */
  31354. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  31355. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  31356. }
  31357. /*
  31358. ** Write data from a buffer into a file. Return SQLITE_OK on success
  31359. ** or some other error code on failure.
  31360. */
  31361. static int unixWrite(
  31362. sqlite3_file *id,
  31363. const void *pBuf,
  31364. int amt,
  31365. sqlite3_int64 offset
  31366. ){
  31367. unixFile *pFile = (unixFile*)id;
  31368. int wrote = 0;
  31369. assert( id );
  31370. assert( amt>0 );
  31371. /* If this is a database file (not a journal, master-journal or temp
  31372. ** file), the bytes in the locking range should never be read or written. */
  31373. #if 0
  31374. assert( pFile->pUnused==0
  31375. || offset>=PENDING_BYTE+512
  31376. || offset+amt<=PENDING_BYTE
  31377. );
  31378. #endif
  31379. #ifdef SQLITE_DEBUG
  31380. /* If we are doing a normal write to a database file (as opposed to
  31381. ** doing a hot-journal rollback or a write to some file other than a
  31382. ** normal database file) then record the fact that the database
  31383. ** has changed. If the transaction counter is modified, record that
  31384. ** fact too.
  31385. */
  31386. if( pFile->inNormalWrite ){
  31387. pFile->dbUpdate = 1; /* The database has been modified */
  31388. if( offset<=24 && offset+amt>=27 ){
  31389. int rc;
  31390. char oldCntr[4];
  31391. SimulateIOErrorBenign(1);
  31392. rc = seekAndRead(pFile, 24, oldCntr, 4);
  31393. SimulateIOErrorBenign(0);
  31394. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  31395. pFile->transCntrChng = 1; /* The transaction counter has changed */
  31396. }
  31397. }
  31398. }
  31399. #endif
  31400. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  31401. /* Deal with as much of this write request as possible by transfering
  31402. ** data from the memory mapping using memcpy(). */
  31403. if( offset<pFile->mmapSize ){
  31404. if( offset+amt <= pFile->mmapSize ){
  31405. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  31406. return SQLITE_OK;
  31407. }else{
  31408. int nCopy = pFile->mmapSize - offset;
  31409. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  31410. pBuf = &((u8 *)pBuf)[nCopy];
  31411. amt -= nCopy;
  31412. offset += nCopy;
  31413. }
  31414. }
  31415. #endif
  31416. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  31417. amt -= wrote;
  31418. offset += wrote;
  31419. pBuf = &((char*)pBuf)[wrote];
  31420. }
  31421. SimulateIOError(( wrote=(-1), amt=1 ));
  31422. SimulateDiskfullError(( wrote=0, amt=1 ));
  31423. if( amt>wrote ){
  31424. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  31425. /* lastErrno set by seekAndWrite */
  31426. return SQLITE_IOERR_WRITE;
  31427. }else{
  31428. storeLastErrno(pFile, 0); /* not a system error */
  31429. return SQLITE_FULL;
  31430. }
  31431. }
  31432. return SQLITE_OK;
  31433. }
  31434. #ifdef SQLITE_TEST
  31435. /*
  31436. ** Count the number of fullsyncs and normal syncs. This is used to test
  31437. ** that syncs and fullsyncs are occurring at the right times.
  31438. */
  31439. SQLITE_API int sqlite3_sync_count = 0;
  31440. SQLITE_API int sqlite3_fullsync_count = 0;
  31441. #endif
  31442. /*
  31443. ** We do not trust systems to provide a working fdatasync(). Some do.
  31444. ** Others do no. To be safe, we will stick with the (slightly slower)
  31445. ** fsync(). If you know that your system does support fdatasync() correctly,
  31446. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  31447. */
  31448. #if !defined(fdatasync) && !HAVE_FDATASYNC
  31449. # define fdatasync fsync
  31450. #endif
  31451. /*
  31452. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  31453. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  31454. ** only available on Mac OS X. But that could change.
  31455. */
  31456. #ifdef F_FULLFSYNC
  31457. # define HAVE_FULLFSYNC 1
  31458. #else
  31459. # define HAVE_FULLFSYNC 0
  31460. #endif
  31461. /*
  31462. ** The fsync() system call does not work as advertised on many
  31463. ** unix systems. The following procedure is an attempt to make
  31464. ** it work better.
  31465. **
  31466. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  31467. ** for testing when we want to run through the test suite quickly.
  31468. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  31469. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  31470. ** or power failure will likely corrupt the database file.
  31471. **
  31472. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  31473. ** The idea behind dataOnly is that it should only write the file content
  31474. ** to disk, not the inode. We only set dataOnly if the file size is
  31475. ** unchanged since the file size is part of the inode. However,
  31476. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  31477. ** file size has changed. The only real difference between fdatasync()
  31478. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  31479. ** inode if the mtime or owner or other inode attributes have changed.
  31480. ** We only care about the file size, not the other file attributes, so
  31481. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  31482. ** So, we always use fdatasync() if it is available, regardless of
  31483. ** the value of the dataOnly flag.
  31484. */
  31485. static int full_fsync(int fd, int fullSync, int dataOnly){
  31486. int rc;
  31487. /* The following "ifdef/elif/else/" block has the same structure as
  31488. ** the one below. It is replicated here solely to avoid cluttering
  31489. ** up the real code with the UNUSED_PARAMETER() macros.
  31490. */
  31491. #ifdef SQLITE_NO_SYNC
  31492. UNUSED_PARAMETER(fd);
  31493. UNUSED_PARAMETER(fullSync);
  31494. UNUSED_PARAMETER(dataOnly);
  31495. #elif HAVE_FULLFSYNC
  31496. UNUSED_PARAMETER(dataOnly);
  31497. #else
  31498. UNUSED_PARAMETER(fullSync);
  31499. UNUSED_PARAMETER(dataOnly);
  31500. #endif
  31501. /* Record the number of times that we do a normal fsync() and
  31502. ** FULLSYNC. This is used during testing to verify that this procedure
  31503. ** gets called with the correct arguments.
  31504. */
  31505. #ifdef SQLITE_TEST
  31506. if( fullSync ) sqlite3_fullsync_count++;
  31507. sqlite3_sync_count++;
  31508. #endif
  31509. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  31510. ** no-op. But go ahead and call fstat() to validate the file
  31511. ** descriptor as we need a method to provoke a failure during
  31512. ** coverate testing.
  31513. */
  31514. #ifdef SQLITE_NO_SYNC
  31515. {
  31516. struct stat buf;
  31517. rc = osFstat(fd, &buf);
  31518. }
  31519. #elif HAVE_FULLFSYNC
  31520. if( fullSync ){
  31521. rc = osFcntl(fd, F_FULLFSYNC, 0);
  31522. }else{
  31523. rc = 1;
  31524. }
  31525. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  31526. ** It shouldn't be possible for fullfsync to fail on the local
  31527. ** file system (on OSX), so failure indicates that FULLFSYNC
  31528. ** isn't supported for this file system. So, attempt an fsync
  31529. ** and (for now) ignore the overhead of a superfluous fcntl call.
  31530. ** It'd be better to detect fullfsync support once and avoid
  31531. ** the fcntl call every time sync is called.
  31532. */
  31533. if( rc ) rc = fsync(fd);
  31534. #elif defined(__APPLE__)
  31535. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  31536. ** so currently we default to the macro that redefines fdatasync to fsync
  31537. */
  31538. rc = fsync(fd);
  31539. #else
  31540. rc = fdatasync(fd);
  31541. #if OS_VXWORKS
  31542. if( rc==-1 && errno==ENOTSUP ){
  31543. rc = fsync(fd);
  31544. }
  31545. #endif /* OS_VXWORKS */
  31546. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  31547. if( OS_VXWORKS && rc!= -1 ){
  31548. rc = 0;
  31549. }
  31550. return rc;
  31551. }
  31552. /*
  31553. ** Open a file descriptor to the directory containing file zFilename.
  31554. ** If successful, *pFd is set to the opened file descriptor and
  31555. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  31556. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  31557. ** value.
  31558. **
  31559. ** The directory file descriptor is used for only one thing - to
  31560. ** fsync() a directory to make sure file creation and deletion events
  31561. ** are flushed to disk. Such fsyncs are not needed on newer
  31562. ** journaling filesystems, but are required on older filesystems.
  31563. **
  31564. ** This routine can be overridden using the xSetSysCall interface.
  31565. ** The ability to override this routine was added in support of the
  31566. ** chromium sandbox. Opening a directory is a security risk (we are
  31567. ** told) so making it overrideable allows the chromium sandbox to
  31568. ** replace this routine with a harmless no-op. To make this routine
  31569. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  31570. ** *pFd set to a negative number.
  31571. **
  31572. ** If SQLITE_OK is returned, the caller is responsible for closing
  31573. ** the file descriptor *pFd using close().
  31574. */
  31575. static int openDirectory(const char *zFilename, int *pFd){
  31576. int ii;
  31577. int fd = -1;
  31578. char zDirname[MAX_PATHNAME+1];
  31579. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  31580. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  31581. if( ii>0 ){
  31582. zDirname[ii] = '\0';
  31583. }else{
  31584. if( zDirname[0]!='/' ) zDirname[0] = '.';
  31585. zDirname[1] = 0;
  31586. }
  31587. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  31588. if( fd>=0 ){
  31589. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  31590. }
  31591. *pFd = fd;
  31592. if( fd>=0 ) return SQLITE_OK;
  31593. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  31594. }
  31595. /*
  31596. ** Make sure all writes to a particular file are committed to disk.
  31597. **
  31598. ** If dataOnly==0 then both the file itself and its metadata (file
  31599. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  31600. ** file data is synced.
  31601. **
  31602. ** Under Unix, also make sure that the directory entry for the file
  31603. ** has been created by fsync-ing the directory that contains the file.
  31604. ** If we do not do this and we encounter a power failure, the directory
  31605. ** entry for the journal might not exist after we reboot. The next
  31606. ** SQLite to access the file will not know that the journal exists (because
  31607. ** the directory entry for the journal was never created) and the transaction
  31608. ** will not roll back - possibly leading to database corruption.
  31609. */
  31610. static int unixSync(sqlite3_file *id, int flags){
  31611. int rc;
  31612. unixFile *pFile = (unixFile*)id;
  31613. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  31614. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  31615. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  31616. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  31617. || (flags&0x0F)==SQLITE_SYNC_FULL
  31618. );
  31619. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  31620. ** line is to test that doing so does not cause any problems.
  31621. */
  31622. SimulateDiskfullError( return SQLITE_FULL );
  31623. assert( pFile );
  31624. OSTRACE(("SYNC %-3d\n", pFile->h));
  31625. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  31626. SimulateIOError( rc=1 );
  31627. if( rc ){
  31628. storeLastErrno(pFile, errno);
  31629. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  31630. }
  31631. /* Also fsync the directory containing the file if the DIRSYNC flag
  31632. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  31633. ** are unable to fsync a directory, so ignore errors on the fsync.
  31634. */
  31635. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  31636. int dirfd;
  31637. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  31638. HAVE_FULLFSYNC, isFullsync));
  31639. rc = osOpenDirectory(pFile->zPath, &dirfd);
  31640. if( rc==SQLITE_OK ){
  31641. full_fsync(dirfd, 0, 0);
  31642. robust_close(pFile, dirfd, __LINE__);
  31643. }else{
  31644. assert( rc==SQLITE_CANTOPEN );
  31645. rc = SQLITE_OK;
  31646. }
  31647. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  31648. }
  31649. return rc;
  31650. }
  31651. /*
  31652. ** Truncate an open file to a specified size
  31653. */
  31654. static int unixTruncate(sqlite3_file *id, i64 nByte){
  31655. unixFile *pFile = (unixFile *)id;
  31656. int rc;
  31657. assert( pFile );
  31658. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  31659. /* If the user has configured a chunk-size for this file, truncate the
  31660. ** file so that it consists of an integer number of chunks (i.e. the
  31661. ** actual file size after the operation may be larger than the requested
  31662. ** size).
  31663. */
  31664. if( pFile->szChunk>0 ){
  31665. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  31666. }
  31667. rc = robust_ftruncate(pFile->h, nByte);
  31668. if( rc ){
  31669. storeLastErrno(pFile, errno);
  31670. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  31671. }else{
  31672. #ifdef SQLITE_DEBUG
  31673. /* If we are doing a normal write to a database file (as opposed to
  31674. ** doing a hot-journal rollback or a write to some file other than a
  31675. ** normal database file) and we truncate the file to zero length,
  31676. ** that effectively updates the change counter. This might happen
  31677. ** when restoring a database using the backup API from a zero-length
  31678. ** source.
  31679. */
  31680. if( pFile->inNormalWrite && nByte==0 ){
  31681. pFile->transCntrChng = 1;
  31682. }
  31683. #endif
  31684. #if SQLITE_MAX_MMAP_SIZE>0
  31685. /* If the file was just truncated to a size smaller than the currently
  31686. ** mapped region, reduce the effective mapping size as well. SQLite will
  31687. ** use read() and write() to access data beyond this point from now on.
  31688. */
  31689. if( nByte<pFile->mmapSize ){
  31690. pFile->mmapSize = nByte;
  31691. }
  31692. #endif
  31693. return SQLITE_OK;
  31694. }
  31695. }
  31696. /*
  31697. ** Determine the current size of a file in bytes
  31698. */
  31699. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  31700. int rc;
  31701. struct stat buf;
  31702. assert( id );
  31703. rc = osFstat(((unixFile*)id)->h, &buf);
  31704. SimulateIOError( rc=1 );
  31705. if( rc!=0 ){
  31706. storeLastErrno((unixFile*)id, errno);
  31707. return SQLITE_IOERR_FSTAT;
  31708. }
  31709. *pSize = buf.st_size;
  31710. /* When opening a zero-size database, the findInodeInfo() procedure
  31711. ** writes a single byte into that file in order to work around a bug
  31712. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  31713. ** layers, we need to report this file size as zero even though it is
  31714. ** really 1. Ticket #3260.
  31715. */
  31716. if( *pSize==1 ) *pSize = 0;
  31717. return SQLITE_OK;
  31718. }
  31719. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  31720. /*
  31721. ** Handler for proxy-locking file-control verbs. Defined below in the
  31722. ** proxying locking division.
  31723. */
  31724. static int proxyFileControl(sqlite3_file*,int,void*);
  31725. #endif
  31726. /*
  31727. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  31728. ** file-control operation. Enlarge the database to nBytes in size
  31729. ** (rounded up to the next chunk-size). If the database is already
  31730. ** nBytes or larger, this routine is a no-op.
  31731. */
  31732. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  31733. if( pFile->szChunk>0 ){
  31734. i64 nSize; /* Required file size */
  31735. struct stat buf; /* Used to hold return values of fstat() */
  31736. if( osFstat(pFile->h, &buf) ){
  31737. return SQLITE_IOERR_FSTAT;
  31738. }
  31739. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  31740. if( nSize>(i64)buf.st_size ){
  31741. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  31742. /* The code below is handling the return value of osFallocate()
  31743. ** correctly. posix_fallocate() is defined to "returns zero on success,
  31744. ** or an error number on failure". See the manpage for details. */
  31745. int err;
  31746. do{
  31747. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  31748. }while( err==EINTR );
  31749. if( err ) return SQLITE_IOERR_WRITE;
  31750. #else
  31751. /* If the OS does not have posix_fallocate(), fake it. Write a
  31752. ** single byte to the last byte in each block that falls entirely
  31753. ** within the extended region. Then, if required, a single byte
  31754. ** at offset (nSize-1), to set the size of the file correctly.
  31755. ** This is a similar technique to that used by glibc on systems
  31756. ** that do not have a real fallocate() call.
  31757. */
  31758. int nBlk = buf.st_blksize; /* File-system block size */
  31759. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  31760. i64 iWrite; /* Next offset to write to */
  31761. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  31762. assert( iWrite>=buf.st_size );
  31763. assert( ((iWrite+1)%nBlk)==0 );
  31764. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  31765. if( iWrite>=nSize ) iWrite = nSize - 1;
  31766. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  31767. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  31768. }
  31769. #endif
  31770. }
  31771. }
  31772. #if SQLITE_MAX_MMAP_SIZE>0
  31773. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  31774. int rc;
  31775. if( pFile->szChunk<=0 ){
  31776. if( robust_ftruncate(pFile->h, nByte) ){
  31777. storeLastErrno(pFile, errno);
  31778. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  31779. }
  31780. }
  31781. rc = unixMapfile(pFile, nByte);
  31782. return rc;
  31783. }
  31784. #endif
  31785. return SQLITE_OK;
  31786. }
  31787. /*
  31788. ** If *pArg is initially negative then this is a query. Set *pArg to
  31789. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  31790. **
  31791. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  31792. */
  31793. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  31794. if( *pArg<0 ){
  31795. *pArg = (pFile->ctrlFlags & mask)!=0;
  31796. }else if( (*pArg)==0 ){
  31797. pFile->ctrlFlags &= ~mask;
  31798. }else{
  31799. pFile->ctrlFlags |= mask;
  31800. }
  31801. }
  31802. /* Forward declaration */
  31803. static int unixGetTempname(int nBuf, char *zBuf);
  31804. /*
  31805. ** Information and control of an open file handle.
  31806. */
  31807. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  31808. unixFile *pFile = (unixFile*)id;
  31809. switch( op ){
  31810. case SQLITE_FCNTL_LOCKSTATE: {
  31811. *(int*)pArg = pFile->eFileLock;
  31812. return SQLITE_OK;
  31813. }
  31814. case SQLITE_FCNTL_LAST_ERRNO: {
  31815. *(int*)pArg = pFile->lastErrno;
  31816. return SQLITE_OK;
  31817. }
  31818. case SQLITE_FCNTL_CHUNK_SIZE: {
  31819. pFile->szChunk = *(int *)pArg;
  31820. return SQLITE_OK;
  31821. }
  31822. case SQLITE_FCNTL_SIZE_HINT: {
  31823. int rc;
  31824. SimulateIOErrorBenign(1);
  31825. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  31826. SimulateIOErrorBenign(0);
  31827. return rc;
  31828. }
  31829. case SQLITE_FCNTL_PERSIST_WAL: {
  31830. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  31831. return SQLITE_OK;
  31832. }
  31833. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  31834. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  31835. return SQLITE_OK;
  31836. }
  31837. case SQLITE_FCNTL_VFSNAME: {
  31838. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  31839. return SQLITE_OK;
  31840. }
  31841. case SQLITE_FCNTL_TEMPFILENAME: {
  31842. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  31843. if( zTFile ){
  31844. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  31845. *(char**)pArg = zTFile;
  31846. }
  31847. return SQLITE_OK;
  31848. }
  31849. case SQLITE_FCNTL_HAS_MOVED: {
  31850. *(int*)pArg = fileHasMoved(pFile);
  31851. return SQLITE_OK;
  31852. }
  31853. #if SQLITE_MAX_MMAP_SIZE>0
  31854. case SQLITE_FCNTL_MMAP_SIZE: {
  31855. i64 newLimit = *(i64*)pArg;
  31856. int rc = SQLITE_OK;
  31857. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  31858. newLimit = sqlite3GlobalConfig.mxMmap;
  31859. }
  31860. *(i64*)pArg = pFile->mmapSizeMax;
  31861. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  31862. pFile->mmapSizeMax = newLimit;
  31863. if( pFile->mmapSize>0 ){
  31864. unixUnmapfile(pFile);
  31865. rc = unixMapfile(pFile, -1);
  31866. }
  31867. }
  31868. return rc;
  31869. }
  31870. #endif
  31871. #ifdef SQLITE_DEBUG
  31872. /* The pager calls this method to signal that it has done
  31873. ** a rollback and that the database is therefore unchanged and
  31874. ** it hence it is OK for the transaction change counter to be
  31875. ** unchanged.
  31876. */
  31877. case SQLITE_FCNTL_DB_UNCHANGED: {
  31878. ((unixFile*)id)->dbUpdate = 0;
  31879. return SQLITE_OK;
  31880. }
  31881. #endif
  31882. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  31883. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  31884. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  31885. return proxyFileControl(id,op,pArg);
  31886. }
  31887. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  31888. }
  31889. return SQLITE_NOTFOUND;
  31890. }
  31891. /*
  31892. ** Return the sector size in bytes of the underlying block device for
  31893. ** the specified file. This is almost always 512 bytes, but may be
  31894. ** larger for some devices.
  31895. **
  31896. ** SQLite code assumes this function cannot fail. It also assumes that
  31897. ** if two files are created in the same file-system directory (i.e.
  31898. ** a database and its journal file) that the sector size will be the
  31899. ** same for both.
  31900. */
  31901. #ifndef __QNXNTO__
  31902. static int unixSectorSize(sqlite3_file *NotUsed){
  31903. UNUSED_PARAMETER(NotUsed);
  31904. return SQLITE_DEFAULT_SECTOR_SIZE;
  31905. }
  31906. #endif
  31907. /*
  31908. ** The following version of unixSectorSize() is optimized for QNX.
  31909. */
  31910. #ifdef __QNXNTO__
  31911. #include <sys/dcmd_blk.h>
  31912. #include <sys/statvfs.h>
  31913. static int unixSectorSize(sqlite3_file *id){
  31914. unixFile *pFile = (unixFile*)id;
  31915. if( pFile->sectorSize == 0 ){
  31916. struct statvfs fsInfo;
  31917. /* Set defaults for non-supported filesystems */
  31918. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  31919. pFile->deviceCharacteristics = 0;
  31920. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  31921. return pFile->sectorSize;
  31922. }
  31923. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  31924. pFile->sectorSize = fsInfo.f_bsize;
  31925. pFile->deviceCharacteristics =
  31926. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  31927. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  31928. ** the write succeeds */
  31929. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31930. ** so it is ordered */
  31931. 0;
  31932. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  31933. pFile->sectorSize = fsInfo.f_bsize;
  31934. pFile->deviceCharacteristics =
  31935. /* etfs cluster size writes are atomic */
  31936. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  31937. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  31938. ** the write succeeds */
  31939. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31940. ** so it is ordered */
  31941. 0;
  31942. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  31943. pFile->sectorSize = fsInfo.f_bsize;
  31944. pFile->deviceCharacteristics =
  31945. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  31946. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  31947. ** the write succeeds */
  31948. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31949. ** so it is ordered */
  31950. 0;
  31951. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  31952. pFile->sectorSize = fsInfo.f_bsize;
  31953. pFile->deviceCharacteristics =
  31954. /* full bitset of atomics from max sector size and smaller */
  31955. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  31956. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31957. ** so it is ordered */
  31958. 0;
  31959. }else if( strstr(fsInfo.f_basetype, "dos") ){
  31960. pFile->sectorSize = fsInfo.f_bsize;
  31961. pFile->deviceCharacteristics =
  31962. /* full bitset of atomics from max sector size and smaller */
  31963. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  31964. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31965. ** so it is ordered */
  31966. 0;
  31967. }else{
  31968. pFile->deviceCharacteristics =
  31969. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  31970. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  31971. ** the write succeeds */
  31972. 0;
  31973. }
  31974. }
  31975. /* Last chance verification. If the sector size isn't a multiple of 512
  31976. ** then it isn't valid.*/
  31977. if( pFile->sectorSize % 512 != 0 ){
  31978. pFile->deviceCharacteristics = 0;
  31979. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  31980. }
  31981. return pFile->sectorSize;
  31982. }
  31983. #endif /* __QNXNTO__ */
  31984. /*
  31985. ** Return the device characteristics for the file.
  31986. **
  31987. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  31988. ** However, that choice is controversial since technically the underlying
  31989. ** file system does not always provide powersafe overwrites. (In other
  31990. ** words, after a power-loss event, parts of the file that were never
  31991. ** written might end up being altered.) However, non-PSOW behavior is very,
  31992. ** very rare. And asserting PSOW makes a large reduction in the amount
  31993. ** of required I/O for journaling, since a lot of padding is eliminated.
  31994. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  31995. ** available to turn it off and URI query parameter available to turn it off.
  31996. */
  31997. static int unixDeviceCharacteristics(sqlite3_file *id){
  31998. unixFile *p = (unixFile*)id;
  31999. int rc = 0;
  32000. #ifdef __QNXNTO__
  32001. if( p->sectorSize==0 ) unixSectorSize(id);
  32002. rc = p->deviceCharacteristics;
  32003. #endif
  32004. if( p->ctrlFlags & UNIXFILE_PSOW ){
  32005. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  32006. }
  32007. return rc;
  32008. }
  32009. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  32010. /*
  32011. ** Return the system page size.
  32012. **
  32013. ** This function should not be called directly by other code in this file.
  32014. ** Instead, it should be called via macro osGetpagesize().
  32015. */
  32016. static int unixGetpagesize(void){
  32017. #if OS_VXWORKS
  32018. return 1024;
  32019. #elif defined(_BSD_SOURCE)
  32020. return getpagesize();
  32021. #else
  32022. return (int)sysconf(_SC_PAGESIZE);
  32023. #endif
  32024. }
  32025. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  32026. #ifndef SQLITE_OMIT_WAL
  32027. /*
  32028. ** Object used to represent an shared memory buffer.
  32029. **
  32030. ** When multiple threads all reference the same wal-index, each thread
  32031. ** has its own unixShm object, but they all point to a single instance
  32032. ** of this unixShmNode object. In other words, each wal-index is opened
  32033. ** only once per process.
  32034. **
  32035. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  32036. ** We could coalesce this object into unixInodeInfo, but that would mean
  32037. ** every open file that does not use shared memory (in other words, most
  32038. ** open files) would have to carry around this extra information. So
  32039. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  32040. ** and the unixShmNode object is created only when needed.
  32041. **
  32042. ** unixMutexHeld() must be true when creating or destroying
  32043. ** this object or while reading or writing the following fields:
  32044. **
  32045. ** nRef
  32046. **
  32047. ** The following fields are read-only after the object is created:
  32048. **
  32049. ** fid
  32050. ** zFilename
  32051. **
  32052. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  32053. ** unixMutexHeld() is true when reading or writing any other field
  32054. ** in this structure.
  32055. */
  32056. struct unixShmNode {
  32057. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  32058. sqlite3_mutex *mutex; /* Mutex to access this object */
  32059. char *zFilename; /* Name of the mmapped file */
  32060. int h; /* Open file descriptor */
  32061. int szRegion; /* Size of shared-memory regions */
  32062. u16 nRegion; /* Size of array apRegion */
  32063. u8 isReadonly; /* True if read-only */
  32064. char **apRegion; /* Array of mapped shared-memory regions */
  32065. int nRef; /* Number of unixShm objects pointing to this */
  32066. unixShm *pFirst; /* All unixShm objects pointing to this */
  32067. #ifdef SQLITE_DEBUG
  32068. u8 exclMask; /* Mask of exclusive locks held */
  32069. u8 sharedMask; /* Mask of shared locks held */
  32070. u8 nextShmId; /* Next available unixShm.id value */
  32071. #endif
  32072. };
  32073. /*
  32074. ** Structure used internally by this VFS to record the state of an
  32075. ** open shared memory connection.
  32076. **
  32077. ** The following fields are initialized when this object is created and
  32078. ** are read-only thereafter:
  32079. **
  32080. ** unixShm.pFile
  32081. ** unixShm.id
  32082. **
  32083. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  32084. ** while accessing any read/write fields.
  32085. */
  32086. struct unixShm {
  32087. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  32088. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  32089. u8 hasMutex; /* True if holding the unixShmNode mutex */
  32090. u8 id; /* Id of this connection within its unixShmNode */
  32091. u16 sharedMask; /* Mask of shared locks held */
  32092. u16 exclMask; /* Mask of exclusive locks held */
  32093. };
  32094. /*
  32095. ** Constants used for locking
  32096. */
  32097. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  32098. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  32099. /*
  32100. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  32101. **
  32102. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  32103. ** otherwise.
  32104. */
  32105. static int unixShmSystemLock(
  32106. unixFile *pFile, /* Open connection to the WAL file */
  32107. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  32108. int ofst, /* First byte of the locking range */
  32109. int n /* Number of bytes to lock */
  32110. ){
  32111. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  32112. struct flock f; /* The posix advisory locking structure */
  32113. int rc = SQLITE_OK; /* Result code form fcntl() */
  32114. /* Access to the unixShmNode object is serialized by the caller */
  32115. pShmNode = pFile->pInode->pShmNode;
  32116. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  32117. /* Shared locks never span more than one byte */
  32118. assert( n==1 || lockType!=F_RDLCK );
  32119. /* Locks are within range */
  32120. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  32121. if( pShmNode->h>=0 ){
  32122. /* Initialize the locking parameters */
  32123. memset(&f, 0, sizeof(f));
  32124. f.l_type = lockType;
  32125. f.l_whence = SEEK_SET;
  32126. f.l_start = ofst;
  32127. f.l_len = n;
  32128. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  32129. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  32130. }
  32131. /* Update the global lock state and do debug tracing */
  32132. #ifdef SQLITE_DEBUG
  32133. { u16 mask;
  32134. OSTRACE(("SHM-LOCK "));
  32135. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  32136. if( rc==SQLITE_OK ){
  32137. if( lockType==F_UNLCK ){
  32138. OSTRACE(("unlock %d ok", ofst));
  32139. pShmNode->exclMask &= ~mask;
  32140. pShmNode->sharedMask &= ~mask;
  32141. }else if( lockType==F_RDLCK ){
  32142. OSTRACE(("read-lock %d ok", ofst));
  32143. pShmNode->exclMask &= ~mask;
  32144. pShmNode->sharedMask |= mask;
  32145. }else{
  32146. assert( lockType==F_WRLCK );
  32147. OSTRACE(("write-lock %d ok", ofst));
  32148. pShmNode->exclMask |= mask;
  32149. pShmNode->sharedMask &= ~mask;
  32150. }
  32151. }else{
  32152. if( lockType==F_UNLCK ){
  32153. OSTRACE(("unlock %d failed", ofst));
  32154. }else if( lockType==F_RDLCK ){
  32155. OSTRACE(("read-lock failed"));
  32156. }else{
  32157. assert( lockType==F_WRLCK );
  32158. OSTRACE(("write-lock %d failed", ofst));
  32159. }
  32160. }
  32161. OSTRACE((" - afterwards %03x,%03x\n",
  32162. pShmNode->sharedMask, pShmNode->exclMask));
  32163. }
  32164. #endif
  32165. return rc;
  32166. }
  32167. /*
  32168. ** Return the minimum number of 32KB shm regions that should be mapped at
  32169. ** a time, assuming that each mapping must be an integer multiple of the
  32170. ** current system page-size.
  32171. **
  32172. ** Usually, this is 1. The exception seems to be systems that are configured
  32173. ** to use 64KB pages - in this case each mapping must cover at least two
  32174. ** shm regions.
  32175. */
  32176. static int unixShmRegionPerMap(void){
  32177. int shmsz = 32*1024; /* SHM region size */
  32178. int pgsz = osGetpagesize(); /* System page size */
  32179. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  32180. if( pgsz<shmsz ) return 1;
  32181. return pgsz/shmsz;
  32182. }
  32183. /*
  32184. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  32185. **
  32186. ** This is not a VFS shared-memory method; it is a utility function called
  32187. ** by VFS shared-memory methods.
  32188. */
  32189. static void unixShmPurge(unixFile *pFd){
  32190. unixShmNode *p = pFd->pInode->pShmNode;
  32191. assert( unixMutexHeld() );
  32192. if( p && ALWAYS(p->nRef==0) ){
  32193. int nShmPerMap = unixShmRegionPerMap();
  32194. int i;
  32195. assert( p->pInode==pFd->pInode );
  32196. sqlite3_mutex_free(p->mutex);
  32197. for(i=0; i<p->nRegion; i+=nShmPerMap){
  32198. if( p->h>=0 ){
  32199. osMunmap(p->apRegion[i], p->szRegion);
  32200. }else{
  32201. sqlite3_free(p->apRegion[i]);
  32202. }
  32203. }
  32204. sqlite3_free(p->apRegion);
  32205. if( p->h>=0 ){
  32206. robust_close(pFd, p->h, __LINE__);
  32207. p->h = -1;
  32208. }
  32209. p->pInode->pShmNode = 0;
  32210. sqlite3_free(p);
  32211. }
  32212. }
  32213. /*
  32214. ** Open a shared-memory area associated with open database file pDbFd.
  32215. ** This particular implementation uses mmapped files.
  32216. **
  32217. ** The file used to implement shared-memory is in the same directory
  32218. ** as the open database file and has the same name as the open database
  32219. ** file with the "-shm" suffix added. For example, if the database file
  32220. ** is "/home/user1/config.db" then the file that is created and mmapped
  32221. ** for shared memory will be called "/home/user1/config.db-shm".
  32222. **
  32223. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  32224. ** some other tmpfs mount. But if a file in a different directory
  32225. ** from the database file is used, then differing access permissions
  32226. ** or a chroot() might cause two different processes on the same
  32227. ** database to end up using different files for shared memory -
  32228. ** meaning that their memory would not really be shared - resulting
  32229. ** in database corruption. Nevertheless, this tmpfs file usage
  32230. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  32231. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  32232. ** option results in an incompatible build of SQLite; builds of SQLite
  32233. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  32234. ** same database file at the same time, database corruption will likely
  32235. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  32236. ** "unsupported" and may go away in a future SQLite release.
  32237. **
  32238. ** When opening a new shared-memory file, if no other instances of that
  32239. ** file are currently open, in this process or in other processes, then
  32240. ** the file must be truncated to zero length or have its header cleared.
  32241. **
  32242. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  32243. ** that means that an exclusive lock is held on the database file and
  32244. ** that no other processes are able to read or write the database. In
  32245. ** that case, we do not really need shared memory. No shared memory
  32246. ** file is created. The shared memory will be simulated with heap memory.
  32247. */
  32248. static int unixOpenSharedMemory(unixFile *pDbFd){
  32249. struct unixShm *p = 0; /* The connection to be opened */
  32250. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  32251. int rc; /* Result code */
  32252. unixInodeInfo *pInode; /* The inode of fd */
  32253. char *zShmFilename; /* Name of the file used for SHM */
  32254. int nShmFilename; /* Size of the SHM filename in bytes */
  32255. /* Allocate space for the new unixShm object. */
  32256. p = sqlite3_malloc64( sizeof(*p) );
  32257. if( p==0 ) return SQLITE_NOMEM_BKPT;
  32258. memset(p, 0, sizeof(*p));
  32259. assert( pDbFd->pShm==0 );
  32260. /* Check to see if a unixShmNode object already exists. Reuse an existing
  32261. ** one if present. Create a new one if necessary.
  32262. */
  32263. unixEnterMutex();
  32264. pInode = pDbFd->pInode;
  32265. pShmNode = pInode->pShmNode;
  32266. if( pShmNode==0 ){
  32267. struct stat sStat; /* fstat() info for database file */
  32268. #ifndef SQLITE_SHM_DIRECTORY
  32269. const char *zBasePath = pDbFd->zPath;
  32270. #endif
  32271. /* Call fstat() to figure out the permissions on the database file. If
  32272. ** a new *-shm file is created, an attempt will be made to create it
  32273. ** with the same permissions.
  32274. */
  32275. if( osFstat(pDbFd->h, &sStat) ){
  32276. rc = SQLITE_IOERR_FSTAT;
  32277. goto shm_open_err;
  32278. }
  32279. #ifdef SQLITE_SHM_DIRECTORY
  32280. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  32281. #else
  32282. nShmFilename = 6 + (int)strlen(zBasePath);
  32283. #endif
  32284. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  32285. if( pShmNode==0 ){
  32286. rc = SQLITE_NOMEM_BKPT;
  32287. goto shm_open_err;
  32288. }
  32289. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  32290. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  32291. #ifdef SQLITE_SHM_DIRECTORY
  32292. sqlite3_snprintf(nShmFilename, zShmFilename,
  32293. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  32294. (u32)sStat.st_ino, (u32)sStat.st_dev);
  32295. #else
  32296. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
  32297. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  32298. #endif
  32299. pShmNode->h = -1;
  32300. pDbFd->pInode->pShmNode = pShmNode;
  32301. pShmNode->pInode = pDbFd->pInode;
  32302. if( sqlite3GlobalConfig.bCoreMutex ){
  32303. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  32304. if( pShmNode->mutex==0 ){
  32305. rc = SQLITE_NOMEM_BKPT;
  32306. goto shm_open_err;
  32307. }
  32308. }
  32309. if( pInode->bProcessLock==0 ){
  32310. int openFlags = O_RDWR | O_CREAT;
  32311. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  32312. openFlags = O_RDONLY;
  32313. pShmNode->isReadonly = 1;
  32314. }
  32315. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  32316. if( pShmNode->h<0 ){
  32317. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  32318. goto shm_open_err;
  32319. }
  32320. /* If this process is running as root, make sure that the SHM file
  32321. ** is owned by the same user that owns the original database. Otherwise,
  32322. ** the original owner will not be able to connect.
  32323. */
  32324. robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  32325. /* Check to see if another process is holding the dead-man switch.
  32326. ** If not, truncate the file to zero length.
  32327. */
  32328. rc = SQLITE_OK;
  32329. if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  32330. if( robust_ftruncate(pShmNode->h, 0) ){
  32331. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  32332. }
  32333. }
  32334. if( rc==SQLITE_OK ){
  32335. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  32336. }
  32337. if( rc ) goto shm_open_err;
  32338. }
  32339. }
  32340. /* Make the new connection a child of the unixShmNode */
  32341. p->pShmNode = pShmNode;
  32342. #ifdef SQLITE_DEBUG
  32343. p->id = pShmNode->nextShmId++;
  32344. #endif
  32345. pShmNode->nRef++;
  32346. pDbFd->pShm = p;
  32347. unixLeaveMutex();
  32348. /* The reference count on pShmNode has already been incremented under
  32349. ** the cover of the unixEnterMutex() mutex and the pointer from the
  32350. ** new (struct unixShm) object to the pShmNode has been set. All that is
  32351. ** left to do is to link the new object into the linked list starting
  32352. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  32353. ** mutex.
  32354. */
  32355. sqlite3_mutex_enter(pShmNode->mutex);
  32356. p->pNext = pShmNode->pFirst;
  32357. pShmNode->pFirst = p;
  32358. sqlite3_mutex_leave(pShmNode->mutex);
  32359. return SQLITE_OK;
  32360. /* Jump here on any error */
  32361. shm_open_err:
  32362. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  32363. sqlite3_free(p);
  32364. unixLeaveMutex();
  32365. return rc;
  32366. }
  32367. /*
  32368. ** This function is called to obtain a pointer to region iRegion of the
  32369. ** shared-memory associated with the database file fd. Shared-memory regions
  32370. ** are numbered starting from zero. Each shared-memory region is szRegion
  32371. ** bytes in size.
  32372. **
  32373. ** If an error occurs, an error code is returned and *pp is set to NULL.
  32374. **
  32375. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  32376. ** region has not been allocated (by any client, including one running in a
  32377. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  32378. ** bExtend is non-zero and the requested shared-memory region has not yet
  32379. ** been allocated, it is allocated by this function.
  32380. **
  32381. ** If the shared-memory region has already been allocated or is allocated by
  32382. ** this call as described above, then it is mapped into this processes
  32383. ** address space (if it is not already), *pp is set to point to the mapped
  32384. ** memory and SQLITE_OK returned.
  32385. */
  32386. static int unixShmMap(
  32387. sqlite3_file *fd, /* Handle open on database file */
  32388. int iRegion, /* Region to retrieve */
  32389. int szRegion, /* Size of regions */
  32390. int bExtend, /* True to extend file if necessary */
  32391. void volatile **pp /* OUT: Mapped memory */
  32392. ){
  32393. unixFile *pDbFd = (unixFile*)fd;
  32394. unixShm *p;
  32395. unixShmNode *pShmNode;
  32396. int rc = SQLITE_OK;
  32397. int nShmPerMap = unixShmRegionPerMap();
  32398. int nReqRegion;
  32399. /* If the shared-memory file has not yet been opened, open it now. */
  32400. if( pDbFd->pShm==0 ){
  32401. rc = unixOpenSharedMemory(pDbFd);
  32402. if( rc!=SQLITE_OK ) return rc;
  32403. }
  32404. p = pDbFd->pShm;
  32405. pShmNode = p->pShmNode;
  32406. sqlite3_mutex_enter(pShmNode->mutex);
  32407. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  32408. assert( pShmNode->pInode==pDbFd->pInode );
  32409. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  32410. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  32411. /* Minimum number of regions required to be mapped. */
  32412. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  32413. if( pShmNode->nRegion<nReqRegion ){
  32414. char **apNew; /* New apRegion[] array */
  32415. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  32416. struct stat sStat; /* Used by fstat() */
  32417. pShmNode->szRegion = szRegion;
  32418. if( pShmNode->h>=0 ){
  32419. /* The requested region is not mapped into this processes address space.
  32420. ** Check to see if it has been allocated (i.e. if the wal-index file is
  32421. ** large enough to contain the requested region).
  32422. */
  32423. if( osFstat(pShmNode->h, &sStat) ){
  32424. rc = SQLITE_IOERR_SHMSIZE;
  32425. goto shmpage_out;
  32426. }
  32427. if( sStat.st_size<nByte ){
  32428. /* The requested memory region does not exist. If bExtend is set to
  32429. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  32430. */
  32431. if( !bExtend ){
  32432. goto shmpage_out;
  32433. }
  32434. /* Alternatively, if bExtend is true, extend the file. Do this by
  32435. ** writing a single byte to the end of each (OS) page being
  32436. ** allocated or extended. Technically, we need only write to the
  32437. ** last page in order to extend the file. But writing to all new
  32438. ** pages forces the OS to allocate them immediately, which reduces
  32439. ** the chances of SIGBUS while accessing the mapped region later on.
  32440. */
  32441. else{
  32442. static const int pgsz = 4096;
  32443. int iPg;
  32444. /* Write to the last byte of each newly allocated or extended page */
  32445. assert( (nByte % pgsz)==0 );
  32446. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  32447. int x = 0;
  32448. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
  32449. const char *zFile = pShmNode->zFilename;
  32450. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  32451. goto shmpage_out;
  32452. }
  32453. }
  32454. }
  32455. }
  32456. }
  32457. /* Map the requested memory region into this processes address space. */
  32458. apNew = (char **)sqlite3_realloc(
  32459. pShmNode->apRegion, nReqRegion*sizeof(char *)
  32460. );
  32461. if( !apNew ){
  32462. rc = SQLITE_IOERR_NOMEM_BKPT;
  32463. goto shmpage_out;
  32464. }
  32465. pShmNode->apRegion = apNew;
  32466. while( pShmNode->nRegion<nReqRegion ){
  32467. int nMap = szRegion*nShmPerMap;
  32468. int i;
  32469. void *pMem;
  32470. if( pShmNode->h>=0 ){
  32471. pMem = osMmap(0, nMap,
  32472. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  32473. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  32474. );
  32475. if( pMem==MAP_FAILED ){
  32476. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  32477. goto shmpage_out;
  32478. }
  32479. }else{
  32480. pMem = sqlite3_malloc64(szRegion);
  32481. if( pMem==0 ){
  32482. rc = SQLITE_NOMEM_BKPT;
  32483. goto shmpage_out;
  32484. }
  32485. memset(pMem, 0, szRegion);
  32486. }
  32487. for(i=0; i<nShmPerMap; i++){
  32488. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  32489. }
  32490. pShmNode->nRegion += nShmPerMap;
  32491. }
  32492. }
  32493. shmpage_out:
  32494. if( pShmNode->nRegion>iRegion ){
  32495. *pp = pShmNode->apRegion[iRegion];
  32496. }else{
  32497. *pp = 0;
  32498. }
  32499. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  32500. sqlite3_mutex_leave(pShmNode->mutex);
  32501. return rc;
  32502. }
  32503. /*
  32504. ** Change the lock state for a shared-memory segment.
  32505. **
  32506. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  32507. ** different here than in posix. In xShmLock(), one can go from unlocked
  32508. ** to shared and back or from unlocked to exclusive and back. But one may
  32509. ** not go from shared to exclusive or from exclusive to shared.
  32510. */
  32511. static int unixShmLock(
  32512. sqlite3_file *fd, /* Database file holding the shared memory */
  32513. int ofst, /* First lock to acquire or release */
  32514. int n, /* Number of locks to acquire or release */
  32515. int flags /* What to do with the lock */
  32516. ){
  32517. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  32518. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  32519. unixShm *pX; /* For looping over all siblings */
  32520. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  32521. int rc = SQLITE_OK; /* Result code */
  32522. u16 mask; /* Mask of locks to take or release */
  32523. assert( pShmNode==pDbFd->pInode->pShmNode );
  32524. assert( pShmNode->pInode==pDbFd->pInode );
  32525. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  32526. assert( n>=1 );
  32527. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  32528. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  32529. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  32530. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  32531. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  32532. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  32533. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  32534. mask = (1<<(ofst+n)) - (1<<ofst);
  32535. assert( n>1 || mask==(1<<ofst) );
  32536. sqlite3_mutex_enter(pShmNode->mutex);
  32537. if( flags & SQLITE_SHM_UNLOCK ){
  32538. u16 allMask = 0; /* Mask of locks held by siblings */
  32539. /* See if any siblings hold this same lock */
  32540. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32541. if( pX==p ) continue;
  32542. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  32543. allMask |= pX->sharedMask;
  32544. }
  32545. /* Unlock the system-level locks */
  32546. if( (mask & allMask)==0 ){
  32547. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  32548. }else{
  32549. rc = SQLITE_OK;
  32550. }
  32551. /* Undo the local locks */
  32552. if( rc==SQLITE_OK ){
  32553. p->exclMask &= ~mask;
  32554. p->sharedMask &= ~mask;
  32555. }
  32556. }else if( flags & SQLITE_SHM_SHARED ){
  32557. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  32558. /* Find out which shared locks are already held by sibling connections.
  32559. ** If any sibling already holds an exclusive lock, go ahead and return
  32560. ** SQLITE_BUSY.
  32561. */
  32562. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32563. if( (pX->exclMask & mask)!=0 ){
  32564. rc = SQLITE_BUSY;
  32565. break;
  32566. }
  32567. allShared |= pX->sharedMask;
  32568. }
  32569. /* Get shared locks at the system level, if necessary */
  32570. if( rc==SQLITE_OK ){
  32571. if( (allShared & mask)==0 ){
  32572. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  32573. }else{
  32574. rc = SQLITE_OK;
  32575. }
  32576. }
  32577. /* Get the local shared locks */
  32578. if( rc==SQLITE_OK ){
  32579. p->sharedMask |= mask;
  32580. }
  32581. }else{
  32582. /* Make sure no sibling connections hold locks that will block this
  32583. ** lock. If any do, return SQLITE_BUSY right away.
  32584. */
  32585. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32586. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  32587. rc = SQLITE_BUSY;
  32588. break;
  32589. }
  32590. }
  32591. /* Get the exclusive locks at the system level. Then if successful
  32592. ** also mark the local connection as being locked.
  32593. */
  32594. if( rc==SQLITE_OK ){
  32595. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  32596. if( rc==SQLITE_OK ){
  32597. assert( (p->sharedMask & mask)==0 );
  32598. p->exclMask |= mask;
  32599. }
  32600. }
  32601. }
  32602. sqlite3_mutex_leave(pShmNode->mutex);
  32603. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  32604. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  32605. return rc;
  32606. }
  32607. /*
  32608. ** Implement a memory barrier or memory fence on shared memory.
  32609. **
  32610. ** All loads and stores begun before the barrier must complete before
  32611. ** any load or store begun after the barrier.
  32612. */
  32613. static void unixShmBarrier(
  32614. sqlite3_file *fd /* Database file holding the shared memory */
  32615. ){
  32616. UNUSED_PARAMETER(fd);
  32617. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  32618. unixEnterMutex(); /* Also mutex, for redundancy */
  32619. unixLeaveMutex();
  32620. }
  32621. /*
  32622. ** Close a connection to shared-memory. Delete the underlying
  32623. ** storage if deleteFlag is true.
  32624. **
  32625. ** If there is no shared memory associated with the connection then this
  32626. ** routine is a harmless no-op.
  32627. */
  32628. static int unixShmUnmap(
  32629. sqlite3_file *fd, /* The underlying database file */
  32630. int deleteFlag /* Delete shared-memory if true */
  32631. ){
  32632. unixShm *p; /* The connection to be closed */
  32633. unixShmNode *pShmNode; /* The underlying shared-memory file */
  32634. unixShm **pp; /* For looping over sibling connections */
  32635. unixFile *pDbFd; /* The underlying database file */
  32636. pDbFd = (unixFile*)fd;
  32637. p = pDbFd->pShm;
  32638. if( p==0 ) return SQLITE_OK;
  32639. pShmNode = p->pShmNode;
  32640. assert( pShmNode==pDbFd->pInode->pShmNode );
  32641. assert( pShmNode->pInode==pDbFd->pInode );
  32642. /* Remove connection p from the set of connections associated
  32643. ** with pShmNode */
  32644. sqlite3_mutex_enter(pShmNode->mutex);
  32645. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  32646. *pp = p->pNext;
  32647. /* Free the connection p */
  32648. sqlite3_free(p);
  32649. pDbFd->pShm = 0;
  32650. sqlite3_mutex_leave(pShmNode->mutex);
  32651. /* If pShmNode->nRef has reached 0, then close the underlying
  32652. ** shared-memory file, too */
  32653. unixEnterMutex();
  32654. assert( pShmNode->nRef>0 );
  32655. pShmNode->nRef--;
  32656. if( pShmNode->nRef==0 ){
  32657. if( deleteFlag && pShmNode->h>=0 ){
  32658. osUnlink(pShmNode->zFilename);
  32659. }
  32660. unixShmPurge(pDbFd);
  32661. }
  32662. unixLeaveMutex();
  32663. return SQLITE_OK;
  32664. }
  32665. #else
  32666. # define unixShmMap 0
  32667. # define unixShmLock 0
  32668. # define unixShmBarrier 0
  32669. # define unixShmUnmap 0
  32670. #endif /* #ifndef SQLITE_OMIT_WAL */
  32671. #if SQLITE_MAX_MMAP_SIZE>0
  32672. /*
  32673. ** If it is currently memory mapped, unmap file pFd.
  32674. */
  32675. static void unixUnmapfile(unixFile *pFd){
  32676. assert( pFd->nFetchOut==0 );
  32677. if( pFd->pMapRegion ){
  32678. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  32679. pFd->pMapRegion = 0;
  32680. pFd->mmapSize = 0;
  32681. pFd->mmapSizeActual = 0;
  32682. }
  32683. }
  32684. /*
  32685. ** Attempt to set the size of the memory mapping maintained by file
  32686. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  32687. **
  32688. ** If successful, this function sets the following variables:
  32689. **
  32690. ** unixFile.pMapRegion
  32691. ** unixFile.mmapSize
  32692. ** unixFile.mmapSizeActual
  32693. **
  32694. ** If unsuccessful, an error message is logged via sqlite3_log() and
  32695. ** the three variables above are zeroed. In this case SQLite should
  32696. ** continue accessing the database using the xRead() and xWrite()
  32697. ** methods.
  32698. */
  32699. static void unixRemapfile(
  32700. unixFile *pFd, /* File descriptor object */
  32701. i64 nNew /* Required mapping size */
  32702. ){
  32703. const char *zErr = "mmap";
  32704. int h = pFd->h; /* File descriptor open on db file */
  32705. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  32706. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  32707. u8 *pNew = 0; /* Location of new mapping */
  32708. int flags = PROT_READ; /* Flags to pass to mmap() */
  32709. assert( pFd->nFetchOut==0 );
  32710. assert( nNew>pFd->mmapSize );
  32711. assert( nNew<=pFd->mmapSizeMax );
  32712. assert( nNew>0 );
  32713. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  32714. assert( MAP_FAILED!=0 );
  32715. #ifdef SQLITE_MMAP_READWRITE
  32716. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  32717. #endif
  32718. if( pOrig ){
  32719. #if HAVE_MREMAP
  32720. i64 nReuse = pFd->mmapSize;
  32721. #else
  32722. const int szSyspage = osGetpagesize();
  32723. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  32724. #endif
  32725. u8 *pReq = &pOrig[nReuse];
  32726. /* Unmap any pages of the existing mapping that cannot be reused. */
  32727. if( nReuse!=nOrig ){
  32728. osMunmap(pReq, nOrig-nReuse);
  32729. }
  32730. #if HAVE_MREMAP
  32731. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  32732. zErr = "mremap";
  32733. #else
  32734. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  32735. if( pNew!=MAP_FAILED ){
  32736. if( pNew!=pReq ){
  32737. osMunmap(pNew, nNew - nReuse);
  32738. pNew = 0;
  32739. }else{
  32740. pNew = pOrig;
  32741. }
  32742. }
  32743. #endif
  32744. /* The attempt to extend the existing mapping failed. Free it. */
  32745. if( pNew==MAP_FAILED || pNew==0 ){
  32746. osMunmap(pOrig, nReuse);
  32747. }
  32748. }
  32749. /* If pNew is still NULL, try to create an entirely new mapping. */
  32750. if( pNew==0 ){
  32751. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  32752. }
  32753. if( pNew==MAP_FAILED ){
  32754. pNew = 0;
  32755. nNew = 0;
  32756. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  32757. /* If the mmap() above failed, assume that all subsequent mmap() calls
  32758. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  32759. ** in this case. */
  32760. pFd->mmapSizeMax = 0;
  32761. }
  32762. pFd->pMapRegion = (void *)pNew;
  32763. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  32764. }
  32765. /*
  32766. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  32767. ** is already mapped, the existing mapping is replaced by the new). Or, if
  32768. ** there already exists a mapping for this file, and there are still
  32769. ** outstanding xFetch() references to it, this function is a no-op.
  32770. **
  32771. ** If parameter nByte is non-negative, then it is the requested size of
  32772. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  32773. ** requested size is the size of the file on disk. The actual size of the
  32774. ** created mapping is either the requested size or the value configured
  32775. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  32776. **
  32777. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  32778. ** recreated as a result of outstanding references) or an SQLite error
  32779. ** code otherwise.
  32780. */
  32781. static int unixMapfile(unixFile *pFd, i64 nMap){
  32782. assert( nMap>=0 || pFd->nFetchOut==0 );
  32783. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  32784. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  32785. if( nMap<0 ){
  32786. struct stat statbuf; /* Low-level file information */
  32787. if( osFstat(pFd->h, &statbuf) ){
  32788. return SQLITE_IOERR_FSTAT;
  32789. }
  32790. nMap = statbuf.st_size;
  32791. }
  32792. if( nMap>pFd->mmapSizeMax ){
  32793. nMap = pFd->mmapSizeMax;
  32794. }
  32795. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  32796. if( nMap!=pFd->mmapSize ){
  32797. unixRemapfile(pFd, nMap);
  32798. }
  32799. return SQLITE_OK;
  32800. }
  32801. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  32802. /*
  32803. ** If possible, return a pointer to a mapping of file fd starting at offset
  32804. ** iOff. The mapping must be valid for at least nAmt bytes.
  32805. **
  32806. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  32807. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  32808. ** Finally, if an error does occur, return an SQLite error code. The final
  32809. ** value of *pp is undefined in this case.
  32810. **
  32811. ** If this function does return a pointer, the caller must eventually
  32812. ** release the reference by calling unixUnfetch().
  32813. */
  32814. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  32815. #if SQLITE_MAX_MMAP_SIZE>0
  32816. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  32817. #endif
  32818. *pp = 0;
  32819. #if SQLITE_MAX_MMAP_SIZE>0
  32820. if( pFd->mmapSizeMax>0 ){
  32821. if( pFd->pMapRegion==0 ){
  32822. int rc = unixMapfile(pFd, -1);
  32823. if( rc!=SQLITE_OK ) return rc;
  32824. }
  32825. if( pFd->mmapSize >= iOff+nAmt ){
  32826. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  32827. pFd->nFetchOut++;
  32828. }
  32829. }
  32830. #endif
  32831. return SQLITE_OK;
  32832. }
  32833. /*
  32834. ** If the third argument is non-NULL, then this function releases a
  32835. ** reference obtained by an earlier call to unixFetch(). The second
  32836. ** argument passed to this function must be the same as the corresponding
  32837. ** argument that was passed to the unixFetch() invocation.
  32838. **
  32839. ** Or, if the third argument is NULL, then this function is being called
  32840. ** to inform the VFS layer that, according to POSIX, any existing mapping
  32841. ** may now be invalid and should be unmapped.
  32842. */
  32843. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  32844. #if SQLITE_MAX_MMAP_SIZE>0
  32845. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  32846. UNUSED_PARAMETER(iOff);
  32847. /* If p==0 (unmap the entire file) then there must be no outstanding
  32848. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  32849. ** then there must be at least one outstanding. */
  32850. assert( (p==0)==(pFd->nFetchOut==0) );
  32851. /* If p!=0, it must match the iOff value. */
  32852. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  32853. if( p ){
  32854. pFd->nFetchOut--;
  32855. }else{
  32856. unixUnmapfile(pFd);
  32857. }
  32858. assert( pFd->nFetchOut>=0 );
  32859. #else
  32860. UNUSED_PARAMETER(fd);
  32861. UNUSED_PARAMETER(p);
  32862. UNUSED_PARAMETER(iOff);
  32863. #endif
  32864. return SQLITE_OK;
  32865. }
  32866. /*
  32867. ** Here ends the implementation of all sqlite3_file methods.
  32868. **
  32869. ********************** End sqlite3_file Methods *******************************
  32870. ******************************************************************************/
  32871. /*
  32872. ** This division contains definitions of sqlite3_io_methods objects that
  32873. ** implement various file locking strategies. It also contains definitions
  32874. ** of "finder" functions. A finder-function is used to locate the appropriate
  32875. ** sqlite3_io_methods object for a particular database file. The pAppData
  32876. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  32877. ** the correct finder-function for that VFS.
  32878. **
  32879. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  32880. ** object. The only interesting finder-function is autolockIoFinder, which
  32881. ** looks at the filesystem type and tries to guess the best locking
  32882. ** strategy from that.
  32883. **
  32884. ** For finder-function F, two objects are created:
  32885. **
  32886. ** (1) The real finder-function named "FImpt()".
  32887. **
  32888. ** (2) A constant pointer to this function named just "F".
  32889. **
  32890. **
  32891. ** A pointer to the F pointer is used as the pAppData value for VFS
  32892. ** objects. We have to do this instead of letting pAppData point
  32893. ** directly at the finder-function since C90 rules prevent a void*
  32894. ** from be cast into a function pointer.
  32895. **
  32896. **
  32897. ** Each instance of this macro generates two objects:
  32898. **
  32899. ** * A constant sqlite3_io_methods object call METHOD that has locking
  32900. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  32901. **
  32902. ** * An I/O method finder function called FINDER that returns a pointer
  32903. ** to the METHOD object in the previous bullet.
  32904. */
  32905. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  32906. static const sqlite3_io_methods METHOD = { \
  32907. VERSION, /* iVersion */ \
  32908. CLOSE, /* xClose */ \
  32909. unixRead, /* xRead */ \
  32910. unixWrite, /* xWrite */ \
  32911. unixTruncate, /* xTruncate */ \
  32912. unixSync, /* xSync */ \
  32913. unixFileSize, /* xFileSize */ \
  32914. LOCK, /* xLock */ \
  32915. UNLOCK, /* xUnlock */ \
  32916. CKLOCK, /* xCheckReservedLock */ \
  32917. unixFileControl, /* xFileControl */ \
  32918. unixSectorSize, /* xSectorSize */ \
  32919. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  32920. SHMMAP, /* xShmMap */ \
  32921. unixShmLock, /* xShmLock */ \
  32922. unixShmBarrier, /* xShmBarrier */ \
  32923. unixShmUnmap, /* xShmUnmap */ \
  32924. unixFetch, /* xFetch */ \
  32925. unixUnfetch, /* xUnfetch */ \
  32926. }; \
  32927. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  32928. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  32929. return &METHOD; \
  32930. } \
  32931. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  32932. = FINDER##Impl;
  32933. /*
  32934. ** Here are all of the sqlite3_io_methods objects for each of the
  32935. ** locking strategies. Functions that return pointers to these methods
  32936. ** are also created.
  32937. */
  32938. IOMETHODS(
  32939. posixIoFinder, /* Finder function name */
  32940. posixIoMethods, /* sqlite3_io_methods object name */
  32941. 3, /* shared memory and mmap are enabled */
  32942. unixClose, /* xClose method */
  32943. unixLock, /* xLock method */
  32944. unixUnlock, /* xUnlock method */
  32945. unixCheckReservedLock, /* xCheckReservedLock method */
  32946. unixShmMap /* xShmMap method */
  32947. )
  32948. IOMETHODS(
  32949. nolockIoFinder, /* Finder function name */
  32950. nolockIoMethods, /* sqlite3_io_methods object name */
  32951. 3, /* shared memory is disabled */
  32952. nolockClose, /* xClose method */
  32953. nolockLock, /* xLock method */
  32954. nolockUnlock, /* xUnlock method */
  32955. nolockCheckReservedLock, /* xCheckReservedLock method */
  32956. 0 /* xShmMap method */
  32957. )
  32958. IOMETHODS(
  32959. dotlockIoFinder, /* Finder function name */
  32960. dotlockIoMethods, /* sqlite3_io_methods object name */
  32961. 1, /* shared memory is disabled */
  32962. dotlockClose, /* xClose method */
  32963. dotlockLock, /* xLock method */
  32964. dotlockUnlock, /* xUnlock method */
  32965. dotlockCheckReservedLock, /* xCheckReservedLock method */
  32966. 0 /* xShmMap method */
  32967. )
  32968. #if SQLITE_ENABLE_LOCKING_STYLE
  32969. IOMETHODS(
  32970. flockIoFinder, /* Finder function name */
  32971. flockIoMethods, /* sqlite3_io_methods object name */
  32972. 1, /* shared memory is disabled */
  32973. flockClose, /* xClose method */
  32974. flockLock, /* xLock method */
  32975. flockUnlock, /* xUnlock method */
  32976. flockCheckReservedLock, /* xCheckReservedLock method */
  32977. 0 /* xShmMap method */
  32978. )
  32979. #endif
  32980. #if OS_VXWORKS
  32981. IOMETHODS(
  32982. semIoFinder, /* Finder function name */
  32983. semIoMethods, /* sqlite3_io_methods object name */
  32984. 1, /* shared memory is disabled */
  32985. semXClose, /* xClose method */
  32986. semXLock, /* xLock method */
  32987. semXUnlock, /* xUnlock method */
  32988. semXCheckReservedLock, /* xCheckReservedLock method */
  32989. 0 /* xShmMap method */
  32990. )
  32991. #endif
  32992. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  32993. IOMETHODS(
  32994. afpIoFinder, /* Finder function name */
  32995. afpIoMethods, /* sqlite3_io_methods object name */
  32996. 1, /* shared memory is disabled */
  32997. afpClose, /* xClose method */
  32998. afpLock, /* xLock method */
  32999. afpUnlock, /* xUnlock method */
  33000. afpCheckReservedLock, /* xCheckReservedLock method */
  33001. 0 /* xShmMap method */
  33002. )
  33003. #endif
  33004. /*
  33005. ** The proxy locking method is a "super-method" in the sense that it
  33006. ** opens secondary file descriptors for the conch and lock files and
  33007. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  33008. ** secondary files. For this reason, the division that implements
  33009. ** proxy locking is located much further down in the file. But we need
  33010. ** to go ahead and define the sqlite3_io_methods and finder function
  33011. ** for proxy locking here. So we forward declare the I/O methods.
  33012. */
  33013. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33014. static int proxyClose(sqlite3_file*);
  33015. static int proxyLock(sqlite3_file*, int);
  33016. static int proxyUnlock(sqlite3_file*, int);
  33017. static int proxyCheckReservedLock(sqlite3_file*, int*);
  33018. IOMETHODS(
  33019. proxyIoFinder, /* Finder function name */
  33020. proxyIoMethods, /* sqlite3_io_methods object name */
  33021. 1, /* shared memory is disabled */
  33022. proxyClose, /* xClose method */
  33023. proxyLock, /* xLock method */
  33024. proxyUnlock, /* xUnlock method */
  33025. proxyCheckReservedLock, /* xCheckReservedLock method */
  33026. 0 /* xShmMap method */
  33027. )
  33028. #endif
  33029. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  33030. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33031. IOMETHODS(
  33032. nfsIoFinder, /* Finder function name */
  33033. nfsIoMethods, /* sqlite3_io_methods object name */
  33034. 1, /* shared memory is disabled */
  33035. unixClose, /* xClose method */
  33036. unixLock, /* xLock method */
  33037. nfsUnlock, /* xUnlock method */
  33038. unixCheckReservedLock, /* xCheckReservedLock method */
  33039. 0 /* xShmMap method */
  33040. )
  33041. #endif
  33042. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33043. /*
  33044. ** This "finder" function attempts to determine the best locking strategy
  33045. ** for the database file "filePath". It then returns the sqlite3_io_methods
  33046. ** object that implements that strategy.
  33047. **
  33048. ** This is for MacOSX only.
  33049. */
  33050. static const sqlite3_io_methods *autolockIoFinderImpl(
  33051. const char *filePath, /* name of the database file */
  33052. unixFile *pNew /* open file object for the database file */
  33053. ){
  33054. static const struct Mapping {
  33055. const char *zFilesystem; /* Filesystem type name */
  33056. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  33057. } aMap[] = {
  33058. { "hfs", &posixIoMethods },
  33059. { "ufs", &posixIoMethods },
  33060. { "afpfs", &afpIoMethods },
  33061. { "smbfs", &afpIoMethods },
  33062. { "webdav", &nolockIoMethods },
  33063. { 0, 0 }
  33064. };
  33065. int i;
  33066. struct statfs fsInfo;
  33067. struct flock lockInfo;
  33068. if( !filePath ){
  33069. /* If filePath==NULL that means we are dealing with a transient file
  33070. ** that does not need to be locked. */
  33071. return &nolockIoMethods;
  33072. }
  33073. if( statfs(filePath, &fsInfo) != -1 ){
  33074. if( fsInfo.f_flags & MNT_RDONLY ){
  33075. return &nolockIoMethods;
  33076. }
  33077. for(i=0; aMap[i].zFilesystem; i++){
  33078. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  33079. return aMap[i].pMethods;
  33080. }
  33081. }
  33082. }
  33083. /* Default case. Handles, amongst others, "nfs".
  33084. ** Test byte-range lock using fcntl(). If the call succeeds,
  33085. ** assume that the file-system supports POSIX style locks.
  33086. */
  33087. lockInfo.l_len = 1;
  33088. lockInfo.l_start = 0;
  33089. lockInfo.l_whence = SEEK_SET;
  33090. lockInfo.l_type = F_RDLCK;
  33091. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  33092. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  33093. return &nfsIoMethods;
  33094. } else {
  33095. return &posixIoMethods;
  33096. }
  33097. }else{
  33098. return &dotlockIoMethods;
  33099. }
  33100. }
  33101. static const sqlite3_io_methods
  33102. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  33103. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33104. #if OS_VXWORKS
  33105. /*
  33106. ** This "finder" function for VxWorks checks to see if posix advisory
  33107. ** locking works. If it does, then that is what is used. If it does not
  33108. ** work, then fallback to named semaphore locking.
  33109. */
  33110. static const sqlite3_io_methods *vxworksIoFinderImpl(
  33111. const char *filePath, /* name of the database file */
  33112. unixFile *pNew /* the open file object */
  33113. ){
  33114. struct flock lockInfo;
  33115. if( !filePath ){
  33116. /* If filePath==NULL that means we are dealing with a transient file
  33117. ** that does not need to be locked. */
  33118. return &nolockIoMethods;
  33119. }
  33120. /* Test if fcntl() is supported and use POSIX style locks.
  33121. ** Otherwise fall back to the named semaphore method.
  33122. */
  33123. lockInfo.l_len = 1;
  33124. lockInfo.l_start = 0;
  33125. lockInfo.l_whence = SEEK_SET;
  33126. lockInfo.l_type = F_RDLCK;
  33127. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  33128. return &posixIoMethods;
  33129. }else{
  33130. return &semIoMethods;
  33131. }
  33132. }
  33133. static const sqlite3_io_methods
  33134. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  33135. #endif /* OS_VXWORKS */
  33136. /*
  33137. ** An abstract type for a pointer to an IO method finder function:
  33138. */
  33139. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  33140. /****************************************************************************
  33141. **************************** sqlite3_vfs methods ****************************
  33142. **
  33143. ** This division contains the implementation of methods on the
  33144. ** sqlite3_vfs object.
  33145. */
  33146. /*
  33147. ** Initialize the contents of the unixFile structure pointed to by pId.
  33148. */
  33149. static int fillInUnixFile(
  33150. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  33151. int h, /* Open file descriptor of file being opened */
  33152. sqlite3_file *pId, /* Write to the unixFile structure here */
  33153. const char *zFilename, /* Name of the file being opened */
  33154. int ctrlFlags /* Zero or more UNIXFILE_* values */
  33155. ){
  33156. const sqlite3_io_methods *pLockingStyle;
  33157. unixFile *pNew = (unixFile *)pId;
  33158. int rc = SQLITE_OK;
  33159. assert( pNew->pInode==NULL );
  33160. /* Usually the path zFilename should not be a relative pathname. The
  33161. ** exception is when opening the proxy "conch" file in builds that
  33162. ** include the special Apple locking styles.
  33163. */
  33164. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33165. assert( zFilename==0 || zFilename[0]=='/'
  33166. || pVfs->pAppData==(void*)&autolockIoFinder );
  33167. #else
  33168. assert( zFilename==0 || zFilename[0]=='/' );
  33169. #endif
  33170. /* No locking occurs in temporary files */
  33171. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  33172. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  33173. pNew->h = h;
  33174. pNew->pVfs = pVfs;
  33175. pNew->zPath = zFilename;
  33176. pNew->ctrlFlags = (u8)ctrlFlags;
  33177. #if SQLITE_MAX_MMAP_SIZE>0
  33178. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  33179. #endif
  33180. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  33181. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  33182. pNew->ctrlFlags |= UNIXFILE_PSOW;
  33183. }
  33184. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  33185. pNew->ctrlFlags |= UNIXFILE_EXCL;
  33186. }
  33187. #if OS_VXWORKS
  33188. pNew->pId = vxworksFindFileId(zFilename);
  33189. if( pNew->pId==0 ){
  33190. ctrlFlags |= UNIXFILE_NOLOCK;
  33191. rc = SQLITE_NOMEM_BKPT;
  33192. }
  33193. #endif
  33194. if( ctrlFlags & UNIXFILE_NOLOCK ){
  33195. pLockingStyle = &nolockIoMethods;
  33196. }else{
  33197. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  33198. #if SQLITE_ENABLE_LOCKING_STYLE
  33199. /* Cache zFilename in the locking context (AFP and dotlock override) for
  33200. ** proxyLock activation is possible (remote proxy is based on db name)
  33201. ** zFilename remains valid until file is closed, to support */
  33202. pNew->lockingContext = (void*)zFilename;
  33203. #endif
  33204. }
  33205. if( pLockingStyle == &posixIoMethods
  33206. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33207. || pLockingStyle == &nfsIoMethods
  33208. #endif
  33209. ){
  33210. unixEnterMutex();
  33211. rc = findInodeInfo(pNew, &pNew->pInode);
  33212. if( rc!=SQLITE_OK ){
  33213. /* If an error occurred in findInodeInfo(), close the file descriptor
  33214. ** immediately, before releasing the mutex. findInodeInfo() may fail
  33215. ** in two scenarios:
  33216. **
  33217. ** (a) A call to fstat() failed.
  33218. ** (b) A malloc failed.
  33219. **
  33220. ** Scenario (b) may only occur if the process is holding no other
  33221. ** file descriptors open on the same file. If there were other file
  33222. ** descriptors on this file, then no malloc would be required by
  33223. ** findInodeInfo(). If this is the case, it is quite safe to close
  33224. ** handle h - as it is guaranteed that no posix locks will be released
  33225. ** by doing so.
  33226. **
  33227. ** If scenario (a) caused the error then things are not so safe. The
  33228. ** implicit assumption here is that if fstat() fails, things are in
  33229. ** such bad shape that dropping a lock or two doesn't matter much.
  33230. */
  33231. robust_close(pNew, h, __LINE__);
  33232. h = -1;
  33233. }
  33234. unixLeaveMutex();
  33235. }
  33236. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33237. else if( pLockingStyle == &afpIoMethods ){
  33238. /* AFP locking uses the file path so it needs to be included in
  33239. ** the afpLockingContext.
  33240. */
  33241. afpLockingContext *pCtx;
  33242. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  33243. if( pCtx==0 ){
  33244. rc = SQLITE_NOMEM_BKPT;
  33245. }else{
  33246. /* NB: zFilename exists and remains valid until the file is closed
  33247. ** according to requirement F11141. So we do not need to make a
  33248. ** copy of the filename. */
  33249. pCtx->dbPath = zFilename;
  33250. pCtx->reserved = 0;
  33251. srandomdev();
  33252. unixEnterMutex();
  33253. rc = findInodeInfo(pNew, &pNew->pInode);
  33254. if( rc!=SQLITE_OK ){
  33255. sqlite3_free(pNew->lockingContext);
  33256. robust_close(pNew, h, __LINE__);
  33257. h = -1;
  33258. }
  33259. unixLeaveMutex();
  33260. }
  33261. }
  33262. #endif
  33263. else if( pLockingStyle == &dotlockIoMethods ){
  33264. /* Dotfile locking uses the file path so it needs to be included in
  33265. ** the dotlockLockingContext
  33266. */
  33267. char *zLockFile;
  33268. int nFilename;
  33269. assert( zFilename!=0 );
  33270. nFilename = (int)strlen(zFilename) + 6;
  33271. zLockFile = (char *)sqlite3_malloc64(nFilename);
  33272. if( zLockFile==0 ){
  33273. rc = SQLITE_NOMEM_BKPT;
  33274. }else{
  33275. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  33276. }
  33277. pNew->lockingContext = zLockFile;
  33278. }
  33279. #if OS_VXWORKS
  33280. else if( pLockingStyle == &semIoMethods ){
  33281. /* Named semaphore locking uses the file path so it needs to be
  33282. ** included in the semLockingContext
  33283. */
  33284. unixEnterMutex();
  33285. rc = findInodeInfo(pNew, &pNew->pInode);
  33286. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  33287. char *zSemName = pNew->pInode->aSemName;
  33288. int n;
  33289. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  33290. pNew->pId->zCanonicalName);
  33291. for( n=1; zSemName[n]; n++ )
  33292. if( zSemName[n]=='/' ) zSemName[n] = '_';
  33293. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  33294. if( pNew->pInode->pSem == SEM_FAILED ){
  33295. rc = SQLITE_NOMEM_BKPT;
  33296. pNew->pInode->aSemName[0] = '\0';
  33297. }
  33298. }
  33299. unixLeaveMutex();
  33300. }
  33301. #endif
  33302. storeLastErrno(pNew, 0);
  33303. #if OS_VXWORKS
  33304. if( rc!=SQLITE_OK ){
  33305. if( h>=0 ) robust_close(pNew, h, __LINE__);
  33306. h = -1;
  33307. osUnlink(zFilename);
  33308. pNew->ctrlFlags |= UNIXFILE_DELETE;
  33309. }
  33310. #endif
  33311. if( rc!=SQLITE_OK ){
  33312. if( h>=0 ) robust_close(pNew, h, __LINE__);
  33313. }else{
  33314. pNew->pMethod = pLockingStyle;
  33315. OpenCounter(+1);
  33316. verifyDbFile(pNew);
  33317. }
  33318. return rc;
  33319. }
  33320. /*
  33321. ** Return the name of a directory in which to put temporary files.
  33322. ** If no suitable temporary file directory can be found, return NULL.
  33323. */
  33324. static const char *unixTempFileDir(void){
  33325. static const char *azDirs[] = {
  33326. 0,
  33327. 0,
  33328. "/var/tmp",
  33329. "/usr/tmp",
  33330. "/tmp",
  33331. "."
  33332. };
  33333. unsigned int i = 0;
  33334. struct stat buf;
  33335. const char *zDir = sqlite3_temp_directory;
  33336. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  33337. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  33338. while(1){
  33339. if( zDir!=0
  33340. && osStat(zDir, &buf)==0
  33341. && S_ISDIR(buf.st_mode)
  33342. && osAccess(zDir, 03)==0
  33343. ){
  33344. return zDir;
  33345. }
  33346. if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
  33347. zDir = azDirs[i++];
  33348. }
  33349. return 0;
  33350. }
  33351. /*
  33352. ** Create a temporary file name in zBuf. zBuf must be allocated
  33353. ** by the calling process and must be big enough to hold at least
  33354. ** pVfs->mxPathname bytes.
  33355. */
  33356. static int unixGetTempname(int nBuf, char *zBuf){
  33357. const char *zDir;
  33358. int iLimit = 0;
  33359. /* It's odd to simulate an io-error here, but really this is just
  33360. ** using the io-error infrastructure to test that SQLite handles this
  33361. ** function failing.
  33362. */
  33363. zBuf[0] = 0;
  33364. SimulateIOError( return SQLITE_IOERR );
  33365. zDir = unixTempFileDir();
  33366. if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
  33367. do{
  33368. u64 r;
  33369. sqlite3_randomness(sizeof(r), &r);
  33370. assert( nBuf>2 );
  33371. zBuf[nBuf-2] = 0;
  33372. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  33373. zDir, r, 0);
  33374. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  33375. }while( osAccess(zBuf,0)==0 );
  33376. return SQLITE_OK;
  33377. }
  33378. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33379. /*
  33380. ** Routine to transform a unixFile into a proxy-locking unixFile.
  33381. ** Implementation in the proxy-lock division, but used by unixOpen()
  33382. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  33383. */
  33384. static int proxyTransformUnixFile(unixFile*, const char*);
  33385. #endif
  33386. /*
  33387. ** Search for an unused file descriptor that was opened on the database
  33388. ** file (not a journal or master-journal file) identified by pathname
  33389. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  33390. ** argument to this function.
  33391. **
  33392. ** Such a file descriptor may exist if a database connection was closed
  33393. ** but the associated file descriptor could not be closed because some
  33394. ** other file descriptor open on the same file is holding a file-lock.
  33395. ** Refer to comments in the unixClose() function and the lengthy comment
  33396. ** describing "Posix Advisory Locking" at the start of this file for
  33397. ** further details. Also, ticket #4018.
  33398. **
  33399. ** If a suitable file descriptor is found, then it is returned. If no
  33400. ** such file descriptor is located, -1 is returned.
  33401. */
  33402. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  33403. UnixUnusedFd *pUnused = 0;
  33404. /* Do not search for an unused file descriptor on vxworks. Not because
  33405. ** vxworks would not benefit from the change (it might, we're not sure),
  33406. ** but because no way to test it is currently available. It is better
  33407. ** not to risk breaking vxworks support for the sake of such an obscure
  33408. ** feature. */
  33409. #if !OS_VXWORKS
  33410. struct stat sStat; /* Results of stat() call */
  33411. /* A stat() call may fail for various reasons. If this happens, it is
  33412. ** almost certain that an open() call on the same path will also fail.
  33413. ** For this reason, if an error occurs in the stat() call here, it is
  33414. ** ignored and -1 is returned. The caller will try to open a new file
  33415. ** descriptor on the same path, fail, and return an error to SQLite.
  33416. **
  33417. ** Even if a subsequent open() call does succeed, the consequences of
  33418. ** not searching for a reusable file descriptor are not dire. */
  33419. if( 0==osStat(zPath, &sStat) ){
  33420. unixInodeInfo *pInode;
  33421. unixEnterMutex();
  33422. pInode = inodeList;
  33423. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  33424. || pInode->fileId.ino!=(u64)sStat.st_ino) ){
  33425. pInode = pInode->pNext;
  33426. }
  33427. if( pInode ){
  33428. UnixUnusedFd **pp;
  33429. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  33430. pUnused = *pp;
  33431. if( pUnused ){
  33432. *pp = pUnused->pNext;
  33433. }
  33434. }
  33435. unixLeaveMutex();
  33436. }
  33437. #endif /* if !OS_VXWORKS */
  33438. return pUnused;
  33439. }
  33440. /*
  33441. ** Find the mode, uid and gid of file zFile.
  33442. */
  33443. static int getFileMode(
  33444. const char *zFile, /* File name */
  33445. mode_t *pMode, /* OUT: Permissions of zFile */
  33446. uid_t *pUid, /* OUT: uid of zFile. */
  33447. gid_t *pGid /* OUT: gid of zFile. */
  33448. ){
  33449. struct stat sStat; /* Output of stat() on database file */
  33450. int rc = SQLITE_OK;
  33451. if( 0==osStat(zFile, &sStat) ){
  33452. *pMode = sStat.st_mode & 0777;
  33453. *pUid = sStat.st_uid;
  33454. *pGid = sStat.st_gid;
  33455. }else{
  33456. rc = SQLITE_IOERR_FSTAT;
  33457. }
  33458. return rc;
  33459. }
  33460. /*
  33461. ** This function is called by unixOpen() to determine the unix permissions
  33462. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  33463. ** and a value suitable for passing as the third argument to open(2) is
  33464. ** written to *pMode. If an IO error occurs, an SQLite error code is
  33465. ** returned and the value of *pMode is not modified.
  33466. **
  33467. ** In most cases, this routine sets *pMode to 0, which will become
  33468. ** an indication to robust_open() to create the file using
  33469. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  33470. ** But if the file being opened is a WAL or regular journal file, then
  33471. ** this function queries the file-system for the permissions on the
  33472. ** corresponding database file and sets *pMode to this value. Whenever
  33473. ** possible, WAL and journal files are created using the same permissions
  33474. ** as the associated database file.
  33475. **
  33476. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  33477. ** original filename is unavailable. But 8_3_NAMES is only used for
  33478. ** FAT filesystems and permissions do not matter there, so just use
  33479. ** the default permissions.
  33480. */
  33481. static int findCreateFileMode(
  33482. const char *zPath, /* Path of file (possibly) being created */
  33483. int flags, /* Flags passed as 4th argument to xOpen() */
  33484. mode_t *pMode, /* OUT: Permissions to open file with */
  33485. uid_t *pUid, /* OUT: uid to set on the file */
  33486. gid_t *pGid /* OUT: gid to set on the file */
  33487. ){
  33488. int rc = SQLITE_OK; /* Return Code */
  33489. *pMode = 0;
  33490. *pUid = 0;
  33491. *pGid = 0;
  33492. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  33493. char zDb[MAX_PATHNAME+1]; /* Database file path */
  33494. int nDb; /* Number of valid bytes in zDb */
  33495. /* zPath is a path to a WAL or journal file. The following block derives
  33496. ** the path to the associated database file from zPath. This block handles
  33497. ** the following naming conventions:
  33498. **
  33499. ** "<path to db>-journal"
  33500. ** "<path to db>-wal"
  33501. ** "<path to db>-journalNN"
  33502. ** "<path to db>-walNN"
  33503. **
  33504. ** where NN is a decimal number. The NN naming schemes are
  33505. ** used by the test_multiplex.c module.
  33506. */
  33507. nDb = sqlite3Strlen30(zPath) - 1;
  33508. while( zPath[nDb]!='-' ){
  33509. #ifndef SQLITE_ENABLE_8_3_NAMES
  33510. /* In the normal case (8+3 filenames disabled) the journal filename
  33511. ** is guaranteed to contain a '-' character. */
  33512. assert( nDb>0 );
  33513. assert( sqlite3Isalnum(zPath[nDb]) );
  33514. #else
  33515. /* If 8+3 names are possible, then the journal file might not contain
  33516. ** a '-' character. So check for that case and return early. */
  33517. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  33518. #endif
  33519. nDb--;
  33520. }
  33521. memcpy(zDb, zPath, nDb);
  33522. zDb[nDb] = '\0';
  33523. rc = getFileMode(zDb, pMode, pUid, pGid);
  33524. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  33525. *pMode = 0600;
  33526. }else if( flags & SQLITE_OPEN_URI ){
  33527. /* If this is a main database file and the file was opened using a URI
  33528. ** filename, check for the "modeof" parameter. If present, interpret
  33529. ** its value as a filename and try to copy the mode, uid and gid from
  33530. ** that file. */
  33531. const char *z = sqlite3_uri_parameter(zPath, "modeof");
  33532. if( z ){
  33533. rc = getFileMode(z, pMode, pUid, pGid);
  33534. }
  33535. }
  33536. return rc;
  33537. }
  33538. /*
  33539. ** Open the file zPath.
  33540. **
  33541. ** Previously, the SQLite OS layer used three functions in place of this
  33542. ** one:
  33543. **
  33544. ** sqlite3OsOpenReadWrite();
  33545. ** sqlite3OsOpenReadOnly();
  33546. ** sqlite3OsOpenExclusive();
  33547. **
  33548. ** These calls correspond to the following combinations of flags:
  33549. **
  33550. ** ReadWrite() -> (READWRITE | CREATE)
  33551. ** ReadOnly() -> (READONLY)
  33552. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  33553. **
  33554. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  33555. ** true, the file was configured to be automatically deleted when the
  33556. ** file handle closed. To achieve the same effect using this new
  33557. ** interface, add the DELETEONCLOSE flag to those specified above for
  33558. ** OpenExclusive().
  33559. */
  33560. static int unixOpen(
  33561. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  33562. const char *zPath, /* Pathname of file to be opened */
  33563. sqlite3_file *pFile, /* The file descriptor to be filled in */
  33564. int flags, /* Input flags to control the opening */
  33565. int *pOutFlags /* Output flags returned to SQLite core */
  33566. ){
  33567. unixFile *p = (unixFile *)pFile;
  33568. int fd = -1; /* File descriptor returned by open() */
  33569. int openFlags = 0; /* Flags to pass to open() */
  33570. int eType = flags&0xFFFFFF00; /* Type of file to open */
  33571. int noLock; /* True to omit locking primitives */
  33572. int rc = SQLITE_OK; /* Function Return Code */
  33573. int ctrlFlags = 0; /* UNIXFILE_* flags */
  33574. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  33575. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  33576. int isCreate = (flags & SQLITE_OPEN_CREATE);
  33577. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  33578. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  33579. #if SQLITE_ENABLE_LOCKING_STYLE
  33580. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  33581. #endif
  33582. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  33583. struct statfs fsInfo;
  33584. #endif
  33585. /* If creating a master or main-file journal, this function will open
  33586. ** a file-descriptor on the directory too. The first time unixSync()
  33587. ** is called the directory file descriptor will be fsync()ed and close()d.
  33588. */
  33589. int syncDir = (isCreate && (
  33590. eType==SQLITE_OPEN_MASTER_JOURNAL
  33591. || eType==SQLITE_OPEN_MAIN_JOURNAL
  33592. || eType==SQLITE_OPEN_WAL
  33593. ));
  33594. /* If argument zPath is a NULL pointer, this function is required to open
  33595. ** a temporary file. Use this buffer to store the file name in.
  33596. */
  33597. char zTmpname[MAX_PATHNAME+2];
  33598. const char *zName = zPath;
  33599. /* Check the following statements are true:
  33600. **
  33601. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  33602. ** (b) if CREATE is set, then READWRITE must also be set, and
  33603. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  33604. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  33605. */
  33606. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  33607. assert(isCreate==0 || isReadWrite);
  33608. assert(isExclusive==0 || isCreate);
  33609. assert(isDelete==0 || isCreate);
  33610. /* The main DB, main journal, WAL file and master journal are never
  33611. ** automatically deleted. Nor are they ever temporary files. */
  33612. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  33613. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  33614. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  33615. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  33616. /* Assert that the upper layer has set one of the "file-type" flags. */
  33617. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  33618. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  33619. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  33620. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  33621. );
  33622. /* Detect a pid change and reset the PRNG. There is a race condition
  33623. ** here such that two or more threads all trying to open databases at
  33624. ** the same instant might all reset the PRNG. But multiple resets
  33625. ** are harmless.
  33626. */
  33627. if( randomnessPid!=osGetpid(0) ){
  33628. randomnessPid = osGetpid(0);
  33629. sqlite3_randomness(0,0);
  33630. }
  33631. memset(p, 0, sizeof(unixFile));
  33632. if( eType==SQLITE_OPEN_MAIN_DB ){
  33633. UnixUnusedFd *pUnused;
  33634. pUnused = findReusableFd(zName, flags);
  33635. if( pUnused ){
  33636. fd = pUnused->fd;
  33637. }else{
  33638. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  33639. if( !pUnused ){
  33640. return SQLITE_NOMEM_BKPT;
  33641. }
  33642. }
  33643. p->pUnused = pUnused;
  33644. /* Database filenames are double-zero terminated if they are not
  33645. ** URIs with parameters. Hence, they can always be passed into
  33646. ** sqlite3_uri_parameter(). */
  33647. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  33648. }else if( !zName ){
  33649. /* If zName is NULL, the upper layer is requesting a temp file. */
  33650. assert(isDelete && !syncDir);
  33651. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  33652. if( rc!=SQLITE_OK ){
  33653. return rc;
  33654. }
  33655. zName = zTmpname;
  33656. /* Generated temporary filenames are always double-zero terminated
  33657. ** for use by sqlite3_uri_parameter(). */
  33658. assert( zName[strlen(zName)+1]==0 );
  33659. }
  33660. /* Determine the value of the flags parameter passed to POSIX function
  33661. ** open(). These must be calculated even if open() is not called, as
  33662. ** they may be stored as part of the file handle and used by the
  33663. ** 'conch file' locking functions later on. */
  33664. if( isReadonly ) openFlags |= O_RDONLY;
  33665. if( isReadWrite ) openFlags |= O_RDWR;
  33666. if( isCreate ) openFlags |= O_CREAT;
  33667. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  33668. openFlags |= (O_LARGEFILE|O_BINARY);
  33669. if( fd<0 ){
  33670. mode_t openMode; /* Permissions to create file with */
  33671. uid_t uid; /* Userid for the file */
  33672. gid_t gid; /* Groupid for the file */
  33673. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  33674. if( rc!=SQLITE_OK ){
  33675. assert( !p->pUnused );
  33676. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  33677. return rc;
  33678. }
  33679. fd = robust_open(zName, openFlags, openMode);
  33680. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  33681. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  33682. if( fd<0 && errno!=EISDIR && isReadWrite ){
  33683. /* Failed to open the file for read/write access. Try read-only. */
  33684. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  33685. openFlags &= ~(O_RDWR|O_CREAT);
  33686. flags |= SQLITE_OPEN_READONLY;
  33687. openFlags |= O_RDONLY;
  33688. isReadonly = 1;
  33689. fd = robust_open(zName, openFlags, openMode);
  33690. }
  33691. if( fd<0 ){
  33692. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  33693. goto open_finished;
  33694. }
  33695. /* If this process is running as root and if creating a new rollback
  33696. ** journal or WAL file, set the ownership of the journal or WAL to be
  33697. ** the same as the original database.
  33698. */
  33699. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  33700. robustFchown(fd, uid, gid);
  33701. }
  33702. }
  33703. assert( fd>=0 );
  33704. if( pOutFlags ){
  33705. *pOutFlags = flags;
  33706. }
  33707. if( p->pUnused ){
  33708. p->pUnused->fd = fd;
  33709. p->pUnused->flags = flags;
  33710. }
  33711. if( isDelete ){
  33712. #if OS_VXWORKS
  33713. zPath = zName;
  33714. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  33715. zPath = sqlite3_mprintf("%s", zName);
  33716. if( zPath==0 ){
  33717. robust_close(p, fd, __LINE__);
  33718. return SQLITE_NOMEM_BKPT;
  33719. }
  33720. #else
  33721. osUnlink(zName);
  33722. #endif
  33723. }
  33724. #if SQLITE_ENABLE_LOCKING_STYLE
  33725. else{
  33726. p->openFlags = openFlags;
  33727. }
  33728. #endif
  33729. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  33730. if( fstatfs(fd, &fsInfo) == -1 ){
  33731. storeLastErrno(p, errno);
  33732. robust_close(p, fd, __LINE__);
  33733. return SQLITE_IOERR_ACCESS;
  33734. }
  33735. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  33736. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  33737. }
  33738. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  33739. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  33740. }
  33741. #endif
  33742. /* Set up appropriate ctrlFlags */
  33743. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  33744. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  33745. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  33746. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  33747. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  33748. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  33749. #if SQLITE_ENABLE_LOCKING_STYLE
  33750. #if SQLITE_PREFER_PROXY_LOCKING
  33751. isAutoProxy = 1;
  33752. #endif
  33753. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  33754. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  33755. int useProxy = 0;
  33756. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  33757. ** never use proxy, NULL means use proxy for non-local files only. */
  33758. if( envforce!=NULL ){
  33759. useProxy = atoi(envforce)>0;
  33760. }else{
  33761. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  33762. }
  33763. if( useProxy ){
  33764. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  33765. if( rc==SQLITE_OK ){
  33766. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  33767. if( rc!=SQLITE_OK ){
  33768. /* Use unixClose to clean up the resources added in fillInUnixFile
  33769. ** and clear all the structure's references. Specifically,
  33770. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  33771. */
  33772. unixClose(pFile);
  33773. return rc;
  33774. }
  33775. }
  33776. goto open_finished;
  33777. }
  33778. }
  33779. #endif
  33780. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  33781. open_finished:
  33782. if( rc!=SQLITE_OK ){
  33783. sqlite3_free(p->pUnused);
  33784. }
  33785. return rc;
  33786. }
  33787. /*
  33788. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  33789. ** the directory after deleting the file.
  33790. */
  33791. static int unixDelete(
  33792. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  33793. const char *zPath, /* Name of file to be deleted */
  33794. int dirSync /* If true, fsync() directory after deleting file */
  33795. ){
  33796. int rc = SQLITE_OK;
  33797. UNUSED_PARAMETER(NotUsed);
  33798. SimulateIOError(return SQLITE_IOERR_DELETE);
  33799. if( osUnlink(zPath)==(-1) ){
  33800. if( errno==ENOENT
  33801. #if OS_VXWORKS
  33802. || osAccess(zPath,0)!=0
  33803. #endif
  33804. ){
  33805. rc = SQLITE_IOERR_DELETE_NOENT;
  33806. }else{
  33807. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  33808. }
  33809. return rc;
  33810. }
  33811. #ifndef SQLITE_DISABLE_DIRSYNC
  33812. if( (dirSync & 1)!=0 ){
  33813. int fd;
  33814. rc = osOpenDirectory(zPath, &fd);
  33815. if( rc==SQLITE_OK ){
  33816. if( full_fsync(fd,0,0) ){
  33817. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  33818. }
  33819. robust_close(0, fd, __LINE__);
  33820. }else{
  33821. assert( rc==SQLITE_CANTOPEN );
  33822. rc = SQLITE_OK;
  33823. }
  33824. }
  33825. #endif
  33826. return rc;
  33827. }
  33828. /*
  33829. ** Test the existence of or access permissions of file zPath. The
  33830. ** test performed depends on the value of flags:
  33831. **
  33832. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  33833. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  33834. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  33835. **
  33836. ** Otherwise return 0.
  33837. */
  33838. static int unixAccess(
  33839. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  33840. const char *zPath, /* Path of the file to examine */
  33841. int flags, /* What do we want to learn about the zPath file? */
  33842. int *pResOut /* Write result boolean here */
  33843. ){
  33844. UNUSED_PARAMETER(NotUsed);
  33845. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  33846. assert( pResOut!=0 );
  33847. /* The spec says there are three possible values for flags. But only
  33848. ** two of them are actually used */
  33849. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  33850. if( flags==SQLITE_ACCESS_EXISTS ){
  33851. struct stat buf;
  33852. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  33853. }else{
  33854. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  33855. }
  33856. return SQLITE_OK;
  33857. }
  33858. /*
  33859. **
  33860. */
  33861. static int mkFullPathname(
  33862. const char *zPath, /* Input path */
  33863. char *zOut, /* Output buffer */
  33864. int nOut /* Allocated size of buffer zOut */
  33865. ){
  33866. int nPath = sqlite3Strlen30(zPath);
  33867. int iOff = 0;
  33868. if( zPath[0]!='/' ){
  33869. if( osGetcwd(zOut, nOut-2)==0 ){
  33870. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  33871. }
  33872. iOff = sqlite3Strlen30(zOut);
  33873. zOut[iOff++] = '/';
  33874. }
  33875. if( (iOff+nPath+1)>nOut ){
  33876. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  33877. ** even if it returns an error. */
  33878. zOut[iOff] = '\0';
  33879. return SQLITE_CANTOPEN_BKPT;
  33880. }
  33881. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  33882. return SQLITE_OK;
  33883. }
  33884. /*
  33885. ** Turn a relative pathname into a full pathname. The relative path
  33886. ** is stored as a nul-terminated string in the buffer pointed to by
  33887. ** zPath.
  33888. **
  33889. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  33890. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  33891. ** this buffer before returning.
  33892. */
  33893. static int unixFullPathname(
  33894. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  33895. const char *zPath, /* Possibly relative input path */
  33896. int nOut, /* Size of output buffer in bytes */
  33897. char *zOut /* Output buffer */
  33898. ){
  33899. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  33900. return mkFullPathname(zPath, zOut, nOut);
  33901. #else
  33902. int rc = SQLITE_OK;
  33903. int nByte;
  33904. int nLink = 1; /* Number of symbolic links followed so far */
  33905. const char *zIn = zPath; /* Input path for each iteration of loop */
  33906. char *zDel = 0;
  33907. assert( pVfs->mxPathname==MAX_PATHNAME );
  33908. UNUSED_PARAMETER(pVfs);
  33909. /* It's odd to simulate an io-error here, but really this is just
  33910. ** using the io-error infrastructure to test that SQLite handles this
  33911. ** function failing. This function could fail if, for example, the
  33912. ** current working directory has been unlinked.
  33913. */
  33914. SimulateIOError( return SQLITE_ERROR );
  33915. do {
  33916. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  33917. ** link, or false otherwise. */
  33918. int bLink = 0;
  33919. struct stat buf;
  33920. if( osLstat(zIn, &buf)!=0 ){
  33921. if( errno!=ENOENT ){
  33922. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  33923. }
  33924. }else{
  33925. bLink = S_ISLNK(buf.st_mode);
  33926. }
  33927. if( bLink ){
  33928. if( zDel==0 ){
  33929. zDel = sqlite3_malloc(nOut);
  33930. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  33931. }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
  33932. rc = SQLITE_CANTOPEN_BKPT;
  33933. }
  33934. if( rc==SQLITE_OK ){
  33935. nByte = osReadlink(zIn, zDel, nOut-1);
  33936. if( nByte<0 ){
  33937. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  33938. }else{
  33939. if( zDel[0]!='/' ){
  33940. int n;
  33941. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  33942. if( nByte+n+1>nOut ){
  33943. rc = SQLITE_CANTOPEN_BKPT;
  33944. }else{
  33945. memmove(&zDel[n], zDel, nByte+1);
  33946. memcpy(zDel, zIn, n);
  33947. nByte += n;
  33948. }
  33949. }
  33950. zDel[nByte] = '\0';
  33951. }
  33952. }
  33953. zIn = zDel;
  33954. }
  33955. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  33956. if( rc==SQLITE_OK && zIn!=zOut ){
  33957. rc = mkFullPathname(zIn, zOut, nOut);
  33958. }
  33959. if( bLink==0 ) break;
  33960. zIn = zOut;
  33961. }while( rc==SQLITE_OK );
  33962. sqlite3_free(zDel);
  33963. return rc;
  33964. #endif /* HAVE_READLINK && HAVE_LSTAT */
  33965. }
  33966. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  33967. /*
  33968. ** Interfaces for opening a shared library, finding entry points
  33969. ** within the shared library, and closing the shared library.
  33970. */
  33971. #include <dlfcn.h>
  33972. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  33973. UNUSED_PARAMETER(NotUsed);
  33974. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  33975. }
  33976. /*
  33977. ** SQLite calls this function immediately after a call to unixDlSym() or
  33978. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  33979. ** message is available, it is written to zBufOut. If no error message
  33980. ** is available, zBufOut is left unmodified and SQLite uses a default
  33981. ** error message.
  33982. */
  33983. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  33984. const char *zErr;
  33985. UNUSED_PARAMETER(NotUsed);
  33986. unixEnterMutex();
  33987. zErr = dlerror();
  33988. if( zErr ){
  33989. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  33990. }
  33991. unixLeaveMutex();
  33992. }
  33993. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  33994. /*
  33995. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  33996. ** cast into a pointer to a function. And yet the library dlsym() routine
  33997. ** returns a void* which is really a pointer to a function. So how do we
  33998. ** use dlsym() with -pedantic-errors?
  33999. **
  34000. ** Variable x below is defined to be a pointer to a function taking
  34001. ** parameters void* and const char* and returning a pointer to a function.
  34002. ** We initialize x by assigning it a pointer to the dlsym() function.
  34003. ** (That assignment requires a cast.) Then we call the function that
  34004. ** x points to.
  34005. **
  34006. ** This work-around is unlikely to work correctly on any system where
  34007. ** you really cannot cast a function pointer into void*. But then, on the
  34008. ** other hand, dlsym() will not work on such a system either, so we have
  34009. ** not really lost anything.
  34010. */
  34011. void (*(*x)(void*,const char*))(void);
  34012. UNUSED_PARAMETER(NotUsed);
  34013. x = (void(*(*)(void*,const char*))(void))dlsym;
  34014. return (*x)(p, zSym);
  34015. }
  34016. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  34017. UNUSED_PARAMETER(NotUsed);
  34018. dlclose(pHandle);
  34019. }
  34020. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  34021. #define unixDlOpen 0
  34022. #define unixDlError 0
  34023. #define unixDlSym 0
  34024. #define unixDlClose 0
  34025. #endif
  34026. /*
  34027. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  34028. */
  34029. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  34030. UNUSED_PARAMETER(NotUsed);
  34031. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  34032. /* We have to initialize zBuf to prevent valgrind from reporting
  34033. ** errors. The reports issued by valgrind are incorrect - we would
  34034. ** prefer that the randomness be increased by making use of the
  34035. ** uninitialized space in zBuf - but valgrind errors tend to worry
  34036. ** some users. Rather than argue, it seems easier just to initialize
  34037. ** the whole array and silence valgrind, even if that means less randomness
  34038. ** in the random seed.
  34039. **
  34040. ** When testing, initializing zBuf[] to zero is all we do. That means
  34041. ** that we always use the same random number sequence. This makes the
  34042. ** tests repeatable.
  34043. */
  34044. memset(zBuf, 0, nBuf);
  34045. randomnessPid = osGetpid(0);
  34046. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  34047. {
  34048. int fd, got;
  34049. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  34050. if( fd<0 ){
  34051. time_t t;
  34052. time(&t);
  34053. memcpy(zBuf, &t, sizeof(t));
  34054. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  34055. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  34056. nBuf = sizeof(t) + sizeof(randomnessPid);
  34057. }else{
  34058. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  34059. robust_close(0, fd, __LINE__);
  34060. }
  34061. }
  34062. #endif
  34063. return nBuf;
  34064. }
  34065. /*
  34066. ** Sleep for a little while. Return the amount of time slept.
  34067. ** The argument is the number of microseconds we want to sleep.
  34068. ** The return value is the number of microseconds of sleep actually
  34069. ** requested from the underlying operating system, a number which
  34070. ** might be greater than or equal to the argument, but not less
  34071. ** than the argument.
  34072. */
  34073. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  34074. #if OS_VXWORKS
  34075. struct timespec sp;
  34076. sp.tv_sec = microseconds / 1000000;
  34077. sp.tv_nsec = (microseconds % 1000000) * 1000;
  34078. nanosleep(&sp, NULL);
  34079. UNUSED_PARAMETER(NotUsed);
  34080. return microseconds;
  34081. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  34082. usleep(microseconds);
  34083. UNUSED_PARAMETER(NotUsed);
  34084. return microseconds;
  34085. #else
  34086. int seconds = (microseconds+999999)/1000000;
  34087. sleep(seconds);
  34088. UNUSED_PARAMETER(NotUsed);
  34089. return seconds*1000000;
  34090. #endif
  34091. }
  34092. /*
  34093. ** The following variable, if set to a non-zero value, is interpreted as
  34094. ** the number of seconds since 1970 and is used to set the result of
  34095. ** sqlite3OsCurrentTime() during testing.
  34096. */
  34097. #ifdef SQLITE_TEST
  34098. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  34099. #endif
  34100. /*
  34101. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  34102. ** the current time and date as a Julian Day number times 86_400_000. In
  34103. ** other words, write into *piNow the number of milliseconds since the Julian
  34104. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  34105. ** proleptic Gregorian calendar.
  34106. **
  34107. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  34108. ** cannot be found.
  34109. */
  34110. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  34111. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  34112. int rc = SQLITE_OK;
  34113. #if defined(NO_GETTOD)
  34114. time_t t;
  34115. time(&t);
  34116. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  34117. #elif OS_VXWORKS
  34118. struct timespec sNow;
  34119. clock_gettime(CLOCK_REALTIME, &sNow);
  34120. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  34121. #else
  34122. struct timeval sNow;
  34123. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  34124. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  34125. #endif
  34126. #ifdef SQLITE_TEST
  34127. if( sqlite3_current_time ){
  34128. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  34129. }
  34130. #endif
  34131. UNUSED_PARAMETER(NotUsed);
  34132. return rc;
  34133. }
  34134. #ifndef SQLITE_OMIT_DEPRECATED
  34135. /*
  34136. ** Find the current time (in Universal Coordinated Time). Write the
  34137. ** current time and date as a Julian Day number into *prNow and
  34138. ** return 0. Return 1 if the time and date cannot be found.
  34139. */
  34140. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  34141. sqlite3_int64 i = 0;
  34142. int rc;
  34143. UNUSED_PARAMETER(NotUsed);
  34144. rc = unixCurrentTimeInt64(0, &i);
  34145. *prNow = i/86400000.0;
  34146. return rc;
  34147. }
  34148. #else
  34149. # define unixCurrentTime 0
  34150. #endif
  34151. /*
  34152. ** The xGetLastError() method is designed to return a better
  34153. ** low-level error message when operating-system problems come up
  34154. ** during SQLite operation. Only the integer return code is currently
  34155. ** used.
  34156. */
  34157. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  34158. UNUSED_PARAMETER(NotUsed);
  34159. UNUSED_PARAMETER(NotUsed2);
  34160. UNUSED_PARAMETER(NotUsed3);
  34161. return errno;
  34162. }
  34163. /*
  34164. ************************ End of sqlite3_vfs methods ***************************
  34165. ******************************************************************************/
  34166. /******************************************************************************
  34167. ************************** Begin Proxy Locking ********************************
  34168. **
  34169. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  34170. ** other locking methods on secondary lock files. Proxy locking is a
  34171. ** meta-layer over top of the primitive locking implemented above. For
  34172. ** this reason, the division that implements of proxy locking is deferred
  34173. ** until late in the file (here) after all of the other I/O methods have
  34174. ** been defined - so that the primitive locking methods are available
  34175. ** as services to help with the implementation of proxy locking.
  34176. **
  34177. ****
  34178. **
  34179. ** The default locking schemes in SQLite use byte-range locks on the
  34180. ** database file to coordinate safe, concurrent access by multiple readers
  34181. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  34182. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  34183. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  34184. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  34185. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  34186. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  34187. ** address in the shared range is taken for a SHARED lock, the entire
  34188. ** shared range is taken for an EXCLUSIVE lock):
  34189. **
  34190. ** PENDING_BYTE 0x40000000
  34191. ** RESERVED_BYTE 0x40000001
  34192. ** SHARED_RANGE 0x40000002 -> 0x40000200
  34193. **
  34194. ** This works well on the local file system, but shows a nearly 100x
  34195. ** slowdown in read performance on AFP because the AFP client disables
  34196. ** the read cache when byte-range locks are present. Enabling the read
  34197. ** cache exposes a cache coherency problem that is present on all OS X
  34198. ** supported network file systems. NFS and AFP both observe the
  34199. ** close-to-open semantics for ensuring cache coherency
  34200. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  34201. ** address the requirements for concurrent database access by multiple
  34202. ** readers and writers
  34203. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  34204. **
  34205. ** To address the performance and cache coherency issues, proxy file locking
  34206. ** changes the way database access is controlled by limiting access to a
  34207. ** single host at a time and moving file locks off of the database file
  34208. ** and onto a proxy file on the local file system.
  34209. **
  34210. **
  34211. ** Using proxy locks
  34212. ** -----------------
  34213. **
  34214. ** C APIs
  34215. **
  34216. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  34217. ** <proxy_path> | ":auto:");
  34218. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  34219. ** &<proxy_path>);
  34220. **
  34221. **
  34222. ** SQL pragmas
  34223. **
  34224. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  34225. ** PRAGMA [database.]lock_proxy_file
  34226. **
  34227. ** Specifying ":auto:" means that if there is a conch file with a matching
  34228. ** host ID in it, the proxy path in the conch file will be used, otherwise
  34229. ** a proxy path based on the user's temp dir
  34230. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  34231. ** actual proxy file name is generated from the name and path of the
  34232. ** database file. For example:
  34233. **
  34234. ** For database path "/Users/me/foo.db"
  34235. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  34236. **
  34237. ** Once a lock proxy is configured for a database connection, it can not
  34238. ** be removed, however it may be switched to a different proxy path via
  34239. ** the above APIs (assuming the conch file is not being held by another
  34240. ** connection or process).
  34241. **
  34242. **
  34243. ** How proxy locking works
  34244. ** -----------------------
  34245. **
  34246. ** Proxy file locking relies primarily on two new supporting files:
  34247. **
  34248. ** * conch file to limit access to the database file to a single host
  34249. ** at a time
  34250. **
  34251. ** * proxy file to act as a proxy for the advisory locks normally
  34252. ** taken on the database
  34253. **
  34254. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  34255. ** by taking an sqlite-style shared lock on the conch file, reading the
  34256. ** contents and comparing the host's unique host ID (see below) and lock
  34257. ** proxy path against the values stored in the conch. The conch file is
  34258. ** stored in the same directory as the database file and the file name
  34259. ** is patterned after the database file name as ".<databasename>-conch".
  34260. ** If the conch file does not exist, or its contents do not match the
  34261. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  34262. ** lock and the conch file contents is updated with the host ID and proxy
  34263. ** path and the lock is downgraded to a shared lock again. If the conch
  34264. ** is held by another process (with a shared lock), the exclusive lock
  34265. ** will fail and SQLITE_BUSY is returned.
  34266. **
  34267. ** The proxy file - a single-byte file used for all advisory file locks
  34268. ** normally taken on the database file. This allows for safe sharing
  34269. ** of the database file for multiple readers and writers on the same
  34270. ** host (the conch ensures that they all use the same local lock file).
  34271. **
  34272. ** Requesting the lock proxy does not immediately take the conch, it is
  34273. ** only taken when the first request to lock database file is made.
  34274. ** This matches the semantics of the traditional locking behavior, where
  34275. ** opening a connection to a database file does not take a lock on it.
  34276. ** The shared lock and an open file descriptor are maintained until
  34277. ** the connection to the database is closed.
  34278. **
  34279. ** The proxy file and the lock file are never deleted so they only need
  34280. ** to be created the first time they are used.
  34281. **
  34282. ** Configuration options
  34283. ** ---------------------
  34284. **
  34285. ** SQLITE_PREFER_PROXY_LOCKING
  34286. **
  34287. ** Database files accessed on non-local file systems are
  34288. ** automatically configured for proxy locking, lock files are
  34289. ** named automatically using the same logic as
  34290. ** PRAGMA lock_proxy_file=":auto:"
  34291. **
  34292. ** SQLITE_PROXY_DEBUG
  34293. **
  34294. ** Enables the logging of error messages during host id file
  34295. ** retrieval and creation
  34296. **
  34297. ** LOCKPROXYDIR
  34298. **
  34299. ** Overrides the default directory used for lock proxy files that
  34300. ** are named automatically via the ":auto:" setting
  34301. **
  34302. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  34303. **
  34304. ** Permissions to use when creating a directory for storing the
  34305. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  34306. **
  34307. **
  34308. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  34309. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  34310. ** force proxy locking to be used for every database file opened, and 0
  34311. ** will force automatic proxy locking to be disabled for all database
  34312. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  34313. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  34314. */
  34315. /*
  34316. ** Proxy locking is only available on MacOSX
  34317. */
  34318. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34319. /*
  34320. ** The proxyLockingContext has the path and file structures for the remote
  34321. ** and local proxy files in it
  34322. */
  34323. typedef struct proxyLockingContext proxyLockingContext;
  34324. struct proxyLockingContext {
  34325. unixFile *conchFile; /* Open conch file */
  34326. char *conchFilePath; /* Name of the conch file */
  34327. unixFile *lockProxy; /* Open proxy lock file */
  34328. char *lockProxyPath; /* Name of the proxy lock file */
  34329. char *dbPath; /* Name of the open file */
  34330. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  34331. int nFails; /* Number of conch taking failures */
  34332. void *oldLockingContext; /* Original lockingcontext to restore on close */
  34333. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  34334. };
  34335. /*
  34336. ** The proxy lock file path for the database at dbPath is written into lPath,
  34337. ** which must point to valid, writable memory large enough for a maxLen length
  34338. ** file path.
  34339. */
  34340. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  34341. int len;
  34342. int dbLen;
  34343. int i;
  34344. #ifdef LOCKPROXYDIR
  34345. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  34346. #else
  34347. # ifdef _CS_DARWIN_USER_TEMP_DIR
  34348. {
  34349. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  34350. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  34351. lPath, errno, osGetpid(0)));
  34352. return SQLITE_IOERR_LOCK;
  34353. }
  34354. len = strlcat(lPath, "sqliteplocks", maxLen);
  34355. }
  34356. # else
  34357. len = strlcpy(lPath, "/tmp/", maxLen);
  34358. # endif
  34359. #endif
  34360. if( lPath[len-1]!='/' ){
  34361. len = strlcat(lPath, "/", maxLen);
  34362. }
  34363. /* transform the db path to a unique cache name */
  34364. dbLen = (int)strlen(dbPath);
  34365. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  34366. char c = dbPath[i];
  34367. lPath[i+len] = (c=='/')?'_':c;
  34368. }
  34369. lPath[i+len]='\0';
  34370. strlcat(lPath, ":auto:", maxLen);
  34371. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  34372. return SQLITE_OK;
  34373. }
  34374. /*
  34375. ** Creates the lock file and any missing directories in lockPath
  34376. */
  34377. static int proxyCreateLockPath(const char *lockPath){
  34378. int i, len;
  34379. char buf[MAXPATHLEN];
  34380. int start = 0;
  34381. assert(lockPath!=NULL);
  34382. /* try to create all the intermediate directories */
  34383. len = (int)strlen(lockPath);
  34384. buf[0] = lockPath[0];
  34385. for( i=1; i<len; i++ ){
  34386. if( lockPath[i] == '/' && (i - start > 0) ){
  34387. /* only mkdir if leaf dir != "." or "/" or ".." */
  34388. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  34389. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  34390. buf[i]='\0';
  34391. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  34392. int err=errno;
  34393. if( err!=EEXIST ) {
  34394. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  34395. "'%s' proxy lock path=%s pid=%d\n",
  34396. buf, strerror(err), lockPath, osGetpid(0)));
  34397. return err;
  34398. }
  34399. }
  34400. }
  34401. start=i+1;
  34402. }
  34403. buf[i] = lockPath[i];
  34404. }
  34405. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  34406. return 0;
  34407. }
  34408. /*
  34409. ** Create a new VFS file descriptor (stored in memory obtained from
  34410. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  34411. **
  34412. ** The caller is responsible not only for closing the file descriptor
  34413. ** but also for freeing the memory associated with the file descriptor.
  34414. */
  34415. static int proxyCreateUnixFile(
  34416. const char *path, /* path for the new unixFile */
  34417. unixFile **ppFile, /* unixFile created and returned by ref */
  34418. int islockfile /* if non zero missing dirs will be created */
  34419. ) {
  34420. int fd = -1;
  34421. unixFile *pNew;
  34422. int rc = SQLITE_OK;
  34423. int openFlags = O_RDWR | O_CREAT;
  34424. sqlite3_vfs dummyVfs;
  34425. int terrno = 0;
  34426. UnixUnusedFd *pUnused = NULL;
  34427. /* 1. first try to open/create the file
  34428. ** 2. if that fails, and this is a lock file (not-conch), try creating
  34429. ** the parent directories and then try again.
  34430. ** 3. if that fails, try to open the file read-only
  34431. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  34432. */
  34433. pUnused = findReusableFd(path, openFlags);
  34434. if( pUnused ){
  34435. fd = pUnused->fd;
  34436. }else{
  34437. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  34438. if( !pUnused ){
  34439. return SQLITE_NOMEM_BKPT;
  34440. }
  34441. }
  34442. if( fd<0 ){
  34443. fd = robust_open(path, openFlags, 0);
  34444. terrno = errno;
  34445. if( fd<0 && errno==ENOENT && islockfile ){
  34446. if( proxyCreateLockPath(path) == SQLITE_OK ){
  34447. fd = robust_open(path, openFlags, 0);
  34448. }
  34449. }
  34450. }
  34451. if( fd<0 ){
  34452. openFlags = O_RDONLY;
  34453. fd = robust_open(path, openFlags, 0);
  34454. terrno = errno;
  34455. }
  34456. if( fd<0 ){
  34457. if( islockfile ){
  34458. return SQLITE_BUSY;
  34459. }
  34460. switch (terrno) {
  34461. case EACCES:
  34462. return SQLITE_PERM;
  34463. case EIO:
  34464. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  34465. default:
  34466. return SQLITE_CANTOPEN_BKPT;
  34467. }
  34468. }
  34469. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  34470. if( pNew==NULL ){
  34471. rc = SQLITE_NOMEM_BKPT;
  34472. goto end_create_proxy;
  34473. }
  34474. memset(pNew, 0, sizeof(unixFile));
  34475. pNew->openFlags = openFlags;
  34476. memset(&dummyVfs, 0, sizeof(dummyVfs));
  34477. dummyVfs.pAppData = (void*)&autolockIoFinder;
  34478. dummyVfs.zName = "dummy";
  34479. pUnused->fd = fd;
  34480. pUnused->flags = openFlags;
  34481. pNew->pUnused = pUnused;
  34482. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  34483. if( rc==SQLITE_OK ){
  34484. *ppFile = pNew;
  34485. return SQLITE_OK;
  34486. }
  34487. end_create_proxy:
  34488. robust_close(pNew, fd, __LINE__);
  34489. sqlite3_free(pNew);
  34490. sqlite3_free(pUnused);
  34491. return rc;
  34492. }
  34493. #ifdef SQLITE_TEST
  34494. /* simulate multiple hosts by creating unique hostid file paths */
  34495. SQLITE_API int sqlite3_hostid_num = 0;
  34496. #endif
  34497. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  34498. #ifdef HAVE_GETHOSTUUID
  34499. /* Not always defined in the headers as it ought to be */
  34500. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  34501. #endif
  34502. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  34503. ** bytes of writable memory.
  34504. */
  34505. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  34506. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  34507. memset(pHostID, 0, PROXY_HOSTIDLEN);
  34508. #ifdef HAVE_GETHOSTUUID
  34509. {
  34510. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  34511. if( gethostuuid(pHostID, &timeout) ){
  34512. int err = errno;
  34513. if( pError ){
  34514. *pError = err;
  34515. }
  34516. return SQLITE_IOERR;
  34517. }
  34518. }
  34519. #else
  34520. UNUSED_PARAMETER(pError);
  34521. #endif
  34522. #ifdef SQLITE_TEST
  34523. /* simulate multiple hosts by creating unique hostid file paths */
  34524. if( sqlite3_hostid_num != 0){
  34525. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  34526. }
  34527. #endif
  34528. return SQLITE_OK;
  34529. }
  34530. /* The conch file contains the header, host id and lock file path
  34531. */
  34532. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  34533. #define PROXY_HEADERLEN 1 /* conch file header length */
  34534. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  34535. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  34536. /*
  34537. ** Takes an open conch file, copies the contents to a new path and then moves
  34538. ** it back. The newly created file's file descriptor is assigned to the
  34539. ** conch file structure and finally the original conch file descriptor is
  34540. ** closed. Returns zero if successful.
  34541. */
  34542. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  34543. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  34544. unixFile *conchFile = pCtx->conchFile;
  34545. char tPath[MAXPATHLEN];
  34546. char buf[PROXY_MAXCONCHLEN];
  34547. char *cPath = pCtx->conchFilePath;
  34548. size_t readLen = 0;
  34549. size_t pathLen = 0;
  34550. char errmsg[64] = "";
  34551. int fd = -1;
  34552. int rc = -1;
  34553. UNUSED_PARAMETER(myHostID);
  34554. /* create a new path by replace the trailing '-conch' with '-break' */
  34555. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  34556. if( pathLen>MAXPATHLEN || pathLen<6 ||
  34557. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  34558. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  34559. goto end_breaklock;
  34560. }
  34561. /* read the conch content */
  34562. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  34563. if( readLen<PROXY_PATHINDEX ){
  34564. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  34565. goto end_breaklock;
  34566. }
  34567. /* write it out to the temporary break file */
  34568. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  34569. if( fd<0 ){
  34570. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  34571. goto end_breaklock;
  34572. }
  34573. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  34574. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  34575. goto end_breaklock;
  34576. }
  34577. if( rename(tPath, cPath) ){
  34578. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  34579. goto end_breaklock;
  34580. }
  34581. rc = 0;
  34582. fprintf(stderr, "broke stale lock on %s\n", cPath);
  34583. robust_close(pFile, conchFile->h, __LINE__);
  34584. conchFile->h = fd;
  34585. conchFile->openFlags = O_RDWR | O_CREAT;
  34586. end_breaklock:
  34587. if( rc ){
  34588. if( fd>=0 ){
  34589. osUnlink(tPath);
  34590. robust_close(pFile, fd, __LINE__);
  34591. }
  34592. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  34593. }
  34594. return rc;
  34595. }
  34596. /* Take the requested lock on the conch file and break a stale lock if the
  34597. ** host id matches.
  34598. */
  34599. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  34600. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  34601. unixFile *conchFile = pCtx->conchFile;
  34602. int rc = SQLITE_OK;
  34603. int nTries = 0;
  34604. struct timespec conchModTime;
  34605. memset(&conchModTime, 0, sizeof(conchModTime));
  34606. do {
  34607. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  34608. nTries ++;
  34609. if( rc==SQLITE_BUSY ){
  34610. /* If the lock failed (busy):
  34611. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  34612. * 2nd try: fail if the mod time changed or host id is different, wait
  34613. * 10 sec and try again
  34614. * 3rd try: break the lock unless the mod time has changed.
  34615. */
  34616. struct stat buf;
  34617. if( osFstat(conchFile->h, &buf) ){
  34618. storeLastErrno(pFile, errno);
  34619. return SQLITE_IOERR_LOCK;
  34620. }
  34621. if( nTries==1 ){
  34622. conchModTime = buf.st_mtimespec;
  34623. usleep(500000); /* wait 0.5 sec and try the lock again*/
  34624. continue;
  34625. }
  34626. assert( nTries>1 );
  34627. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  34628. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  34629. return SQLITE_BUSY;
  34630. }
  34631. if( nTries==2 ){
  34632. char tBuf[PROXY_MAXCONCHLEN];
  34633. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  34634. if( len<0 ){
  34635. storeLastErrno(pFile, errno);
  34636. return SQLITE_IOERR_LOCK;
  34637. }
  34638. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  34639. /* don't break the lock if the host id doesn't match */
  34640. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  34641. return SQLITE_BUSY;
  34642. }
  34643. }else{
  34644. /* don't break the lock on short read or a version mismatch */
  34645. return SQLITE_BUSY;
  34646. }
  34647. usleep(10000000); /* wait 10 sec and try the lock again */
  34648. continue;
  34649. }
  34650. assert( nTries==3 );
  34651. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  34652. rc = SQLITE_OK;
  34653. if( lockType==EXCLUSIVE_LOCK ){
  34654. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  34655. }
  34656. if( !rc ){
  34657. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  34658. }
  34659. }
  34660. }
  34661. } while( rc==SQLITE_BUSY && nTries<3 );
  34662. return rc;
  34663. }
  34664. /* Takes the conch by taking a shared lock and read the contents conch, if
  34665. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  34666. ** lockPath means that the lockPath in the conch file will be used if the
  34667. ** host IDs match, or a new lock path will be generated automatically
  34668. ** and written to the conch file.
  34669. */
  34670. static int proxyTakeConch(unixFile *pFile){
  34671. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  34672. if( pCtx->conchHeld!=0 ){
  34673. return SQLITE_OK;
  34674. }else{
  34675. unixFile *conchFile = pCtx->conchFile;
  34676. uuid_t myHostID;
  34677. int pError = 0;
  34678. char readBuf[PROXY_MAXCONCHLEN];
  34679. char lockPath[MAXPATHLEN];
  34680. char *tempLockPath = NULL;
  34681. int rc = SQLITE_OK;
  34682. int createConch = 0;
  34683. int hostIdMatch = 0;
  34684. int readLen = 0;
  34685. int tryOldLockPath = 0;
  34686. int forceNewLockPath = 0;
  34687. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  34688. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  34689. osGetpid(0)));
  34690. rc = proxyGetHostID(myHostID, &pError);
  34691. if( (rc&0xff)==SQLITE_IOERR ){
  34692. storeLastErrno(pFile, pError);
  34693. goto end_takeconch;
  34694. }
  34695. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  34696. if( rc!=SQLITE_OK ){
  34697. goto end_takeconch;
  34698. }
  34699. /* read the existing conch file */
  34700. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  34701. if( readLen<0 ){
  34702. /* I/O error: lastErrno set by seekAndRead */
  34703. storeLastErrno(pFile, conchFile->lastErrno);
  34704. rc = SQLITE_IOERR_READ;
  34705. goto end_takeconch;
  34706. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  34707. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  34708. /* a short read or version format mismatch means we need to create a new
  34709. ** conch file.
  34710. */
  34711. createConch = 1;
  34712. }
  34713. /* if the host id matches and the lock path already exists in the conch
  34714. ** we'll try to use the path there, if we can't open that path, we'll
  34715. ** retry with a new auto-generated path
  34716. */
  34717. do { /* in case we need to try again for an :auto: named lock file */
  34718. if( !createConch && !forceNewLockPath ){
  34719. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  34720. PROXY_HOSTIDLEN);
  34721. /* if the conch has data compare the contents */
  34722. if( !pCtx->lockProxyPath ){
  34723. /* for auto-named local lock file, just check the host ID and we'll
  34724. ** use the local lock file path that's already in there
  34725. */
  34726. if( hostIdMatch ){
  34727. size_t pathLen = (readLen - PROXY_PATHINDEX);
  34728. if( pathLen>=MAXPATHLEN ){
  34729. pathLen=MAXPATHLEN-1;
  34730. }
  34731. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  34732. lockPath[pathLen] = 0;
  34733. tempLockPath = lockPath;
  34734. tryOldLockPath = 1;
  34735. /* create a copy of the lock path if the conch is taken */
  34736. goto end_takeconch;
  34737. }
  34738. }else if( hostIdMatch
  34739. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  34740. readLen-PROXY_PATHINDEX)
  34741. ){
  34742. /* conch host and lock path match */
  34743. goto end_takeconch;
  34744. }
  34745. }
  34746. /* if the conch isn't writable and doesn't match, we can't take it */
  34747. if( (conchFile->openFlags&O_RDWR) == 0 ){
  34748. rc = SQLITE_BUSY;
  34749. goto end_takeconch;
  34750. }
  34751. /* either the conch didn't match or we need to create a new one */
  34752. if( !pCtx->lockProxyPath ){
  34753. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  34754. tempLockPath = lockPath;
  34755. /* create a copy of the lock path _only_ if the conch is taken */
  34756. }
  34757. /* update conch with host and path (this will fail if other process
  34758. ** has a shared lock already), if the host id matches, use the big
  34759. ** stick.
  34760. */
  34761. futimes(conchFile->h, NULL);
  34762. if( hostIdMatch && !createConch ){
  34763. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  34764. /* We are trying for an exclusive lock but another thread in this
  34765. ** same process is still holding a shared lock. */
  34766. rc = SQLITE_BUSY;
  34767. } else {
  34768. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  34769. }
  34770. }else{
  34771. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  34772. }
  34773. if( rc==SQLITE_OK ){
  34774. char writeBuffer[PROXY_MAXCONCHLEN];
  34775. int writeSize = 0;
  34776. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  34777. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  34778. if( pCtx->lockProxyPath!=NULL ){
  34779. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  34780. MAXPATHLEN);
  34781. }else{
  34782. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  34783. }
  34784. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  34785. robust_ftruncate(conchFile->h, writeSize);
  34786. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  34787. full_fsync(conchFile->h,0,0);
  34788. /* If we created a new conch file (not just updated the contents of a
  34789. ** valid conch file), try to match the permissions of the database
  34790. */
  34791. if( rc==SQLITE_OK && createConch ){
  34792. struct stat buf;
  34793. int err = osFstat(pFile->h, &buf);
  34794. if( err==0 ){
  34795. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  34796. S_IROTH|S_IWOTH);
  34797. /* try to match the database file R/W permissions, ignore failure */
  34798. #ifndef SQLITE_PROXY_DEBUG
  34799. osFchmod(conchFile->h, cmode);
  34800. #else
  34801. do{
  34802. rc = osFchmod(conchFile->h, cmode);
  34803. }while( rc==(-1) && errno==EINTR );
  34804. if( rc!=0 ){
  34805. int code = errno;
  34806. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  34807. cmode, code, strerror(code));
  34808. } else {
  34809. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  34810. }
  34811. }else{
  34812. int code = errno;
  34813. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  34814. err, code, strerror(code));
  34815. #endif
  34816. }
  34817. }
  34818. }
  34819. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  34820. end_takeconch:
  34821. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  34822. if( rc==SQLITE_OK && pFile->openFlags ){
  34823. int fd;
  34824. if( pFile->h>=0 ){
  34825. robust_close(pFile, pFile->h, __LINE__);
  34826. }
  34827. pFile->h = -1;
  34828. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  34829. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  34830. if( fd>=0 ){
  34831. pFile->h = fd;
  34832. }else{
  34833. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  34834. during locking */
  34835. }
  34836. }
  34837. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  34838. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  34839. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  34840. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  34841. /* we couldn't create the proxy lock file with the old lock file path
  34842. ** so try again via auto-naming
  34843. */
  34844. forceNewLockPath = 1;
  34845. tryOldLockPath = 0;
  34846. continue; /* go back to the do {} while start point, try again */
  34847. }
  34848. }
  34849. if( rc==SQLITE_OK ){
  34850. /* Need to make a copy of path if we extracted the value
  34851. ** from the conch file or the path was allocated on the stack
  34852. */
  34853. if( tempLockPath ){
  34854. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  34855. if( !pCtx->lockProxyPath ){
  34856. rc = SQLITE_NOMEM_BKPT;
  34857. }
  34858. }
  34859. }
  34860. if( rc==SQLITE_OK ){
  34861. pCtx->conchHeld = 1;
  34862. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  34863. afpLockingContext *afpCtx;
  34864. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  34865. afpCtx->dbPath = pCtx->lockProxyPath;
  34866. }
  34867. } else {
  34868. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  34869. }
  34870. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  34871. rc==SQLITE_OK?"ok":"failed"));
  34872. return rc;
  34873. } while (1); /* in case we need to retry the :auto: lock file -
  34874. ** we should never get here except via the 'continue' call. */
  34875. }
  34876. }
  34877. /*
  34878. ** If pFile holds a lock on a conch file, then release that lock.
  34879. */
  34880. static int proxyReleaseConch(unixFile *pFile){
  34881. int rc = SQLITE_OK; /* Subroutine return code */
  34882. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  34883. unixFile *conchFile; /* Name of the conch file */
  34884. pCtx = (proxyLockingContext *)pFile->lockingContext;
  34885. conchFile = pCtx->conchFile;
  34886. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  34887. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  34888. osGetpid(0)));
  34889. if( pCtx->conchHeld>0 ){
  34890. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  34891. }
  34892. pCtx->conchHeld = 0;
  34893. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  34894. (rc==SQLITE_OK ? "ok" : "failed")));
  34895. return rc;
  34896. }
  34897. /*
  34898. ** Given the name of a database file, compute the name of its conch file.
  34899. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  34900. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  34901. ** or SQLITE_NOMEM if unable to obtain memory.
  34902. **
  34903. ** The caller is responsible for ensuring that the allocated memory
  34904. ** space is eventually freed.
  34905. **
  34906. ** *pConchPath is set to NULL if a memory allocation error occurs.
  34907. */
  34908. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  34909. int i; /* Loop counter */
  34910. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  34911. char *conchPath; /* buffer in which to construct conch name */
  34912. /* Allocate space for the conch filename and initialize the name to
  34913. ** the name of the original database file. */
  34914. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  34915. if( conchPath==0 ){
  34916. return SQLITE_NOMEM_BKPT;
  34917. }
  34918. memcpy(conchPath, dbPath, len+1);
  34919. /* now insert a "." before the last / character */
  34920. for( i=(len-1); i>=0; i-- ){
  34921. if( conchPath[i]=='/' ){
  34922. i++;
  34923. break;
  34924. }
  34925. }
  34926. conchPath[i]='.';
  34927. while ( i<len ){
  34928. conchPath[i+1]=dbPath[i];
  34929. i++;
  34930. }
  34931. /* append the "-conch" suffix to the file */
  34932. memcpy(&conchPath[i+1], "-conch", 7);
  34933. assert( (int)strlen(conchPath) == len+7 );
  34934. return SQLITE_OK;
  34935. }
  34936. /* Takes a fully configured proxy locking-style unix file and switches
  34937. ** the local lock file path
  34938. */
  34939. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  34940. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  34941. char *oldPath = pCtx->lockProxyPath;
  34942. int rc = SQLITE_OK;
  34943. if( pFile->eFileLock!=NO_LOCK ){
  34944. return SQLITE_BUSY;
  34945. }
  34946. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  34947. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  34948. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  34949. return SQLITE_OK;
  34950. }else{
  34951. unixFile *lockProxy = pCtx->lockProxy;
  34952. pCtx->lockProxy=NULL;
  34953. pCtx->conchHeld = 0;
  34954. if( lockProxy!=NULL ){
  34955. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  34956. if( rc ) return rc;
  34957. sqlite3_free(lockProxy);
  34958. }
  34959. sqlite3_free(oldPath);
  34960. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  34961. }
  34962. return rc;
  34963. }
  34964. /*
  34965. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  34966. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  34967. **
  34968. ** This routine find the filename associated with pFile and writes it
  34969. ** int dbPath.
  34970. */
  34971. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  34972. #if defined(__APPLE__)
  34973. if( pFile->pMethod == &afpIoMethods ){
  34974. /* afp style keeps a reference to the db path in the filePath field
  34975. ** of the struct */
  34976. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  34977. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  34978. MAXPATHLEN);
  34979. } else
  34980. #endif
  34981. if( pFile->pMethod == &dotlockIoMethods ){
  34982. /* dot lock style uses the locking context to store the dot lock
  34983. ** file path */
  34984. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  34985. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  34986. }else{
  34987. /* all other styles use the locking context to store the db file path */
  34988. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  34989. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  34990. }
  34991. return SQLITE_OK;
  34992. }
  34993. /*
  34994. ** Takes an already filled in unix file and alters it so all file locking
  34995. ** will be performed on the local proxy lock file. The following fields
  34996. ** are preserved in the locking context so that they can be restored and
  34997. ** the unix structure properly cleaned up at close time:
  34998. ** ->lockingContext
  34999. ** ->pMethod
  35000. */
  35001. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  35002. proxyLockingContext *pCtx;
  35003. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  35004. char *lockPath=NULL;
  35005. int rc = SQLITE_OK;
  35006. if( pFile->eFileLock!=NO_LOCK ){
  35007. return SQLITE_BUSY;
  35008. }
  35009. proxyGetDbPathForUnixFile(pFile, dbPath);
  35010. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  35011. lockPath=NULL;
  35012. }else{
  35013. lockPath=(char *)path;
  35014. }
  35015. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  35016. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  35017. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  35018. if( pCtx==0 ){
  35019. return SQLITE_NOMEM_BKPT;
  35020. }
  35021. memset(pCtx, 0, sizeof(*pCtx));
  35022. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  35023. if( rc==SQLITE_OK ){
  35024. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  35025. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  35026. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  35027. ** (c) the file system is read-only, then enable no-locking access.
  35028. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  35029. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  35030. */
  35031. struct statfs fsInfo;
  35032. struct stat conchInfo;
  35033. int goLockless = 0;
  35034. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  35035. int err = errno;
  35036. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  35037. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  35038. }
  35039. }
  35040. if( goLockless ){
  35041. pCtx->conchHeld = -1; /* read only FS/ lockless */
  35042. rc = SQLITE_OK;
  35043. }
  35044. }
  35045. }
  35046. if( rc==SQLITE_OK && lockPath ){
  35047. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  35048. }
  35049. if( rc==SQLITE_OK ){
  35050. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  35051. if( pCtx->dbPath==NULL ){
  35052. rc = SQLITE_NOMEM_BKPT;
  35053. }
  35054. }
  35055. if( rc==SQLITE_OK ){
  35056. /* all memory is allocated, proxys are created and assigned,
  35057. ** switch the locking context and pMethod then return.
  35058. */
  35059. pCtx->oldLockingContext = pFile->lockingContext;
  35060. pFile->lockingContext = pCtx;
  35061. pCtx->pOldMethod = pFile->pMethod;
  35062. pFile->pMethod = &proxyIoMethods;
  35063. }else{
  35064. if( pCtx->conchFile ){
  35065. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  35066. sqlite3_free(pCtx->conchFile);
  35067. }
  35068. sqlite3DbFree(0, pCtx->lockProxyPath);
  35069. sqlite3_free(pCtx->conchFilePath);
  35070. sqlite3_free(pCtx);
  35071. }
  35072. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  35073. (rc==SQLITE_OK ? "ok" : "failed")));
  35074. return rc;
  35075. }
  35076. /*
  35077. ** This routine handles sqlite3_file_control() calls that are specific
  35078. ** to proxy locking.
  35079. */
  35080. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  35081. switch( op ){
  35082. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  35083. unixFile *pFile = (unixFile*)id;
  35084. if( pFile->pMethod == &proxyIoMethods ){
  35085. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  35086. proxyTakeConch(pFile);
  35087. if( pCtx->lockProxyPath ){
  35088. *(const char **)pArg = pCtx->lockProxyPath;
  35089. }else{
  35090. *(const char **)pArg = ":auto: (not held)";
  35091. }
  35092. } else {
  35093. *(const char **)pArg = NULL;
  35094. }
  35095. return SQLITE_OK;
  35096. }
  35097. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  35098. unixFile *pFile = (unixFile*)id;
  35099. int rc = SQLITE_OK;
  35100. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  35101. if( pArg==NULL || (const char *)pArg==0 ){
  35102. if( isProxyStyle ){
  35103. /* turn off proxy locking - not supported. If support is added for
  35104. ** switching proxy locking mode off then it will need to fail if
  35105. ** the journal mode is WAL mode.
  35106. */
  35107. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  35108. }else{
  35109. /* turn off proxy locking - already off - NOOP */
  35110. rc = SQLITE_OK;
  35111. }
  35112. }else{
  35113. const char *proxyPath = (const char *)pArg;
  35114. if( isProxyStyle ){
  35115. proxyLockingContext *pCtx =
  35116. (proxyLockingContext*)pFile->lockingContext;
  35117. if( !strcmp(pArg, ":auto:")
  35118. || (pCtx->lockProxyPath &&
  35119. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  35120. ){
  35121. rc = SQLITE_OK;
  35122. }else{
  35123. rc = switchLockProxyPath(pFile, proxyPath);
  35124. }
  35125. }else{
  35126. /* turn on proxy file locking */
  35127. rc = proxyTransformUnixFile(pFile, proxyPath);
  35128. }
  35129. }
  35130. return rc;
  35131. }
  35132. default: {
  35133. assert( 0 ); /* The call assures that only valid opcodes are sent */
  35134. }
  35135. }
  35136. /*NOTREACHED*/
  35137. return SQLITE_ERROR;
  35138. }
  35139. /*
  35140. ** Within this division (the proxying locking implementation) the procedures
  35141. ** above this point are all utilities. The lock-related methods of the
  35142. ** proxy-locking sqlite3_io_method object follow.
  35143. */
  35144. /*
  35145. ** This routine checks if there is a RESERVED lock held on the specified
  35146. ** file by this or any other process. If such a lock is held, set *pResOut
  35147. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  35148. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  35149. */
  35150. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  35151. unixFile *pFile = (unixFile*)id;
  35152. int rc = proxyTakeConch(pFile);
  35153. if( rc==SQLITE_OK ){
  35154. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35155. if( pCtx->conchHeld>0 ){
  35156. unixFile *proxy = pCtx->lockProxy;
  35157. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  35158. }else{ /* conchHeld < 0 is lockless */
  35159. pResOut=0;
  35160. }
  35161. }
  35162. return rc;
  35163. }
  35164. /*
  35165. ** Lock the file with the lock specified by parameter eFileLock - one
  35166. ** of the following:
  35167. **
  35168. ** (1) SHARED_LOCK
  35169. ** (2) RESERVED_LOCK
  35170. ** (3) PENDING_LOCK
  35171. ** (4) EXCLUSIVE_LOCK
  35172. **
  35173. ** Sometimes when requesting one lock state, additional lock states
  35174. ** are inserted in between. The locking might fail on one of the later
  35175. ** transitions leaving the lock state different from what it started but
  35176. ** still short of its goal. The following chart shows the allowed
  35177. ** transitions and the inserted intermediate states:
  35178. **
  35179. ** UNLOCKED -> SHARED
  35180. ** SHARED -> RESERVED
  35181. ** SHARED -> (PENDING) -> EXCLUSIVE
  35182. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35183. ** PENDING -> EXCLUSIVE
  35184. **
  35185. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  35186. ** routine to lower a locking level.
  35187. */
  35188. static int proxyLock(sqlite3_file *id, int eFileLock) {
  35189. unixFile *pFile = (unixFile*)id;
  35190. int rc = proxyTakeConch(pFile);
  35191. if( rc==SQLITE_OK ){
  35192. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35193. if( pCtx->conchHeld>0 ){
  35194. unixFile *proxy = pCtx->lockProxy;
  35195. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  35196. pFile->eFileLock = proxy->eFileLock;
  35197. }else{
  35198. /* conchHeld < 0 is lockless */
  35199. }
  35200. }
  35201. return rc;
  35202. }
  35203. /*
  35204. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  35205. ** must be either NO_LOCK or SHARED_LOCK.
  35206. **
  35207. ** If the locking level of the file descriptor is already at or below
  35208. ** the requested locking level, this routine is a no-op.
  35209. */
  35210. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  35211. unixFile *pFile = (unixFile*)id;
  35212. int rc = proxyTakeConch(pFile);
  35213. if( rc==SQLITE_OK ){
  35214. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35215. if( pCtx->conchHeld>0 ){
  35216. unixFile *proxy = pCtx->lockProxy;
  35217. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  35218. pFile->eFileLock = proxy->eFileLock;
  35219. }else{
  35220. /* conchHeld < 0 is lockless */
  35221. }
  35222. }
  35223. return rc;
  35224. }
  35225. /*
  35226. ** Close a file that uses proxy locks.
  35227. */
  35228. static int proxyClose(sqlite3_file *id) {
  35229. if( ALWAYS(id) ){
  35230. unixFile *pFile = (unixFile*)id;
  35231. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35232. unixFile *lockProxy = pCtx->lockProxy;
  35233. unixFile *conchFile = pCtx->conchFile;
  35234. int rc = SQLITE_OK;
  35235. if( lockProxy ){
  35236. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  35237. if( rc ) return rc;
  35238. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  35239. if( rc ) return rc;
  35240. sqlite3_free(lockProxy);
  35241. pCtx->lockProxy = 0;
  35242. }
  35243. if( conchFile ){
  35244. if( pCtx->conchHeld ){
  35245. rc = proxyReleaseConch(pFile);
  35246. if( rc ) return rc;
  35247. }
  35248. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  35249. if( rc ) return rc;
  35250. sqlite3_free(conchFile);
  35251. }
  35252. sqlite3DbFree(0, pCtx->lockProxyPath);
  35253. sqlite3_free(pCtx->conchFilePath);
  35254. sqlite3DbFree(0, pCtx->dbPath);
  35255. /* restore the original locking context and pMethod then close it */
  35256. pFile->lockingContext = pCtx->oldLockingContext;
  35257. pFile->pMethod = pCtx->pOldMethod;
  35258. sqlite3_free(pCtx);
  35259. return pFile->pMethod->xClose(id);
  35260. }
  35261. return SQLITE_OK;
  35262. }
  35263. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  35264. /*
  35265. ** The proxy locking style is intended for use with AFP filesystems.
  35266. ** And since AFP is only supported on MacOSX, the proxy locking is also
  35267. ** restricted to MacOSX.
  35268. **
  35269. **
  35270. ******************* End of the proxy lock implementation **********************
  35271. ******************************************************************************/
  35272. /*
  35273. ** Initialize the operating system interface.
  35274. **
  35275. ** This routine registers all VFS implementations for unix-like operating
  35276. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  35277. ** should be the only routines in this file that are visible from other
  35278. ** files.
  35279. **
  35280. ** This routine is called once during SQLite initialization and by a
  35281. ** single thread. The memory allocation and mutex subsystems have not
  35282. ** necessarily been initialized when this routine is called, and so they
  35283. ** should not be used.
  35284. */
  35285. SQLITE_API int sqlite3_os_init(void){
  35286. /*
  35287. ** The following macro defines an initializer for an sqlite3_vfs object.
  35288. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  35289. ** to the "finder" function. (pAppData is a pointer to a pointer because
  35290. ** silly C90 rules prohibit a void* from being cast to a function pointer
  35291. ** and so we have to go through the intermediate pointer to avoid problems
  35292. ** when compiling with -pedantic-errors on GCC.)
  35293. **
  35294. ** The FINDER parameter to this macro is the name of the pointer to the
  35295. ** finder-function. The finder-function returns a pointer to the
  35296. ** sqlite_io_methods object that implements the desired locking
  35297. ** behaviors. See the division above that contains the IOMETHODS
  35298. ** macro for addition information on finder-functions.
  35299. **
  35300. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  35301. ** object. But the "autolockIoFinder" available on MacOSX does a little
  35302. ** more than that; it looks at the filesystem type that hosts the
  35303. ** database file and tries to choose an locking method appropriate for
  35304. ** that filesystem time.
  35305. */
  35306. #define UNIXVFS(VFSNAME, FINDER) { \
  35307. 3, /* iVersion */ \
  35308. sizeof(unixFile), /* szOsFile */ \
  35309. MAX_PATHNAME, /* mxPathname */ \
  35310. 0, /* pNext */ \
  35311. VFSNAME, /* zName */ \
  35312. (void*)&FINDER, /* pAppData */ \
  35313. unixOpen, /* xOpen */ \
  35314. unixDelete, /* xDelete */ \
  35315. unixAccess, /* xAccess */ \
  35316. unixFullPathname, /* xFullPathname */ \
  35317. unixDlOpen, /* xDlOpen */ \
  35318. unixDlError, /* xDlError */ \
  35319. unixDlSym, /* xDlSym */ \
  35320. unixDlClose, /* xDlClose */ \
  35321. unixRandomness, /* xRandomness */ \
  35322. unixSleep, /* xSleep */ \
  35323. unixCurrentTime, /* xCurrentTime */ \
  35324. unixGetLastError, /* xGetLastError */ \
  35325. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  35326. unixSetSystemCall, /* xSetSystemCall */ \
  35327. unixGetSystemCall, /* xGetSystemCall */ \
  35328. unixNextSystemCall, /* xNextSystemCall */ \
  35329. }
  35330. /*
  35331. ** All default VFSes for unix are contained in the following array.
  35332. **
  35333. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  35334. ** by the SQLite core when the VFS is registered. So the following
  35335. ** array cannot be const.
  35336. */
  35337. static sqlite3_vfs aVfs[] = {
  35338. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35339. UNIXVFS("unix", autolockIoFinder ),
  35340. #elif OS_VXWORKS
  35341. UNIXVFS("unix", vxworksIoFinder ),
  35342. #else
  35343. UNIXVFS("unix", posixIoFinder ),
  35344. #endif
  35345. UNIXVFS("unix-none", nolockIoFinder ),
  35346. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  35347. UNIXVFS("unix-excl", posixIoFinder ),
  35348. #if OS_VXWORKS
  35349. UNIXVFS("unix-namedsem", semIoFinder ),
  35350. #endif
  35351. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  35352. UNIXVFS("unix-posix", posixIoFinder ),
  35353. #endif
  35354. #if SQLITE_ENABLE_LOCKING_STYLE
  35355. UNIXVFS("unix-flock", flockIoFinder ),
  35356. #endif
  35357. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35358. UNIXVFS("unix-afp", afpIoFinder ),
  35359. UNIXVFS("unix-nfs", nfsIoFinder ),
  35360. UNIXVFS("unix-proxy", proxyIoFinder ),
  35361. #endif
  35362. };
  35363. unsigned int i; /* Loop counter */
  35364. /* Double-check that the aSyscall[] array has been constructed
  35365. ** correctly. See ticket [bb3a86e890c8e96ab] */
  35366. assert( ArraySize(aSyscall)==28 );
  35367. /* Register all VFSes defined in the aVfs[] array */
  35368. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  35369. sqlite3_vfs_register(&aVfs[i], i==0);
  35370. }
  35371. return SQLITE_OK;
  35372. }
  35373. /*
  35374. ** Shutdown the operating system interface.
  35375. **
  35376. ** Some operating systems might need to do some cleanup in this routine,
  35377. ** to release dynamically allocated objects. But not on unix.
  35378. ** This routine is a no-op for unix.
  35379. */
  35380. SQLITE_API int sqlite3_os_end(void){
  35381. return SQLITE_OK;
  35382. }
  35383. #endif /* SQLITE_OS_UNIX */
  35384. /************** End of os_unix.c *********************************************/
  35385. /************** Begin file os_win.c ******************************************/
  35386. /*
  35387. ** 2004 May 22
  35388. **
  35389. ** The author disclaims copyright to this source code. In place of
  35390. ** a legal notice, here is a blessing:
  35391. **
  35392. ** May you do good and not evil.
  35393. ** May you find forgiveness for yourself and forgive others.
  35394. ** May you share freely, never taking more than you give.
  35395. **
  35396. ******************************************************************************
  35397. **
  35398. ** This file contains code that is specific to Windows.
  35399. */
  35400. /* #include "sqliteInt.h" */
  35401. #if SQLITE_OS_WIN /* This file is used for Windows only */
  35402. /*
  35403. ** Include code that is common to all os_*.c files
  35404. */
  35405. /************** Include os_common.h in the middle of os_win.c ****************/
  35406. /************** Begin file os_common.h ***************************************/
  35407. /*
  35408. ** 2004 May 22
  35409. **
  35410. ** The author disclaims copyright to this source code. In place of
  35411. ** a legal notice, here is a blessing:
  35412. **
  35413. ** May you do good and not evil.
  35414. ** May you find forgiveness for yourself and forgive others.
  35415. ** May you share freely, never taking more than you give.
  35416. **
  35417. ******************************************************************************
  35418. **
  35419. ** This file contains macros and a little bit of code that is common to
  35420. ** all of the platform-specific files (os_*.c) and is #included into those
  35421. ** files.
  35422. **
  35423. ** This file should be #included by the os_*.c files only. It is not a
  35424. ** general purpose header file.
  35425. */
  35426. #ifndef _OS_COMMON_H_
  35427. #define _OS_COMMON_H_
  35428. /*
  35429. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  35430. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  35431. ** switch. The following code should catch this problem at compile-time.
  35432. */
  35433. #ifdef MEMORY_DEBUG
  35434. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  35435. #endif
  35436. /*
  35437. ** Macros for performance tracing. Normally turned off. Only works
  35438. ** on i486 hardware.
  35439. */
  35440. #ifdef SQLITE_PERFORMANCE_TRACE
  35441. /*
  35442. ** hwtime.h contains inline assembler code for implementing
  35443. ** high-performance timing routines.
  35444. */
  35445. /************** Include hwtime.h in the middle of os_common.h ****************/
  35446. /************** Begin file hwtime.h ******************************************/
  35447. /*
  35448. ** 2008 May 27
  35449. **
  35450. ** The author disclaims copyright to this source code. In place of
  35451. ** a legal notice, here is a blessing:
  35452. **
  35453. ** May you do good and not evil.
  35454. ** May you find forgiveness for yourself and forgive others.
  35455. ** May you share freely, never taking more than you give.
  35456. **
  35457. ******************************************************************************
  35458. **
  35459. ** This file contains inline asm code for retrieving "high-performance"
  35460. ** counters for x86 class CPUs.
  35461. */
  35462. #ifndef SQLITE_HWTIME_H
  35463. #define SQLITE_HWTIME_H
  35464. /*
  35465. ** The following routine only works on pentium-class (or newer) processors.
  35466. ** It uses the RDTSC opcode to read the cycle count value out of the
  35467. ** processor and returns that value. This can be used for high-res
  35468. ** profiling.
  35469. */
  35470. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  35471. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  35472. #if defined(__GNUC__)
  35473. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  35474. unsigned int lo, hi;
  35475. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  35476. return (sqlite_uint64)hi << 32 | lo;
  35477. }
  35478. #elif defined(_MSC_VER)
  35479. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  35480. __asm {
  35481. rdtsc
  35482. ret ; return value at EDX:EAX
  35483. }
  35484. }
  35485. #endif
  35486. #elif (defined(__GNUC__) && defined(__x86_64__))
  35487. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  35488. unsigned long val;
  35489. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  35490. return val;
  35491. }
  35492. #elif (defined(__GNUC__) && defined(__ppc__))
  35493. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  35494. unsigned long long retval;
  35495. unsigned long junk;
  35496. __asm__ __volatile__ ("\n\
  35497. 1: mftbu %1\n\
  35498. mftb %L0\n\
  35499. mftbu %0\n\
  35500. cmpw %0,%1\n\
  35501. bne 1b"
  35502. : "=r" (retval), "=r" (junk));
  35503. return retval;
  35504. }
  35505. #else
  35506. #error Need implementation of sqlite3Hwtime() for your platform.
  35507. /*
  35508. ** To compile without implementing sqlite3Hwtime() for your platform,
  35509. ** you can remove the above #error and use the following
  35510. ** stub function. You will lose timing support for many
  35511. ** of the debugging and testing utilities, but it should at
  35512. ** least compile and run.
  35513. */
  35514. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  35515. #endif
  35516. #endif /* !defined(SQLITE_HWTIME_H) */
  35517. /************** End of hwtime.h **********************************************/
  35518. /************** Continuing where we left off in os_common.h ******************/
  35519. static sqlite_uint64 g_start;
  35520. static sqlite_uint64 g_elapsed;
  35521. #define TIMER_START g_start=sqlite3Hwtime()
  35522. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  35523. #define TIMER_ELAPSED g_elapsed
  35524. #else
  35525. #define TIMER_START
  35526. #define TIMER_END
  35527. #define TIMER_ELAPSED ((sqlite_uint64)0)
  35528. #endif
  35529. /*
  35530. ** If we compile with the SQLITE_TEST macro set, then the following block
  35531. ** of code will give us the ability to simulate a disk I/O error. This
  35532. ** is used for testing the I/O recovery logic.
  35533. */
  35534. #if defined(SQLITE_TEST)
  35535. SQLITE_API extern int sqlite3_io_error_hit;
  35536. SQLITE_API extern int sqlite3_io_error_hardhit;
  35537. SQLITE_API extern int sqlite3_io_error_pending;
  35538. SQLITE_API extern int sqlite3_io_error_persist;
  35539. SQLITE_API extern int sqlite3_io_error_benign;
  35540. SQLITE_API extern int sqlite3_diskfull_pending;
  35541. SQLITE_API extern int sqlite3_diskfull;
  35542. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  35543. #define SimulateIOError(CODE) \
  35544. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  35545. || sqlite3_io_error_pending-- == 1 ) \
  35546. { local_ioerr(); CODE; }
  35547. static void local_ioerr(){
  35548. IOTRACE(("IOERR\n"));
  35549. sqlite3_io_error_hit++;
  35550. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  35551. }
  35552. #define SimulateDiskfullError(CODE) \
  35553. if( sqlite3_diskfull_pending ){ \
  35554. if( sqlite3_diskfull_pending == 1 ){ \
  35555. local_ioerr(); \
  35556. sqlite3_diskfull = 1; \
  35557. sqlite3_io_error_hit = 1; \
  35558. CODE; \
  35559. }else{ \
  35560. sqlite3_diskfull_pending--; \
  35561. } \
  35562. }
  35563. #else
  35564. #define SimulateIOErrorBenign(X)
  35565. #define SimulateIOError(A)
  35566. #define SimulateDiskfullError(A)
  35567. #endif /* defined(SQLITE_TEST) */
  35568. /*
  35569. ** When testing, keep a count of the number of open files.
  35570. */
  35571. #if defined(SQLITE_TEST)
  35572. SQLITE_API extern int sqlite3_open_file_count;
  35573. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  35574. #else
  35575. #define OpenCounter(X)
  35576. #endif /* defined(SQLITE_TEST) */
  35577. #endif /* !defined(_OS_COMMON_H_) */
  35578. /************** End of os_common.h *******************************************/
  35579. /************** Continuing where we left off in os_win.c *********************/
  35580. /*
  35581. ** Include the header file for the Windows VFS.
  35582. */
  35583. /* #include "os_win.h" */
  35584. /*
  35585. ** Compiling and using WAL mode requires several APIs that are only
  35586. ** available in Windows platforms based on the NT kernel.
  35587. */
  35588. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  35589. # error "WAL mode requires support from the Windows NT kernel, compile\
  35590. with SQLITE_OMIT_WAL."
  35591. #endif
  35592. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  35593. # error "Memory mapped files require support from the Windows NT kernel,\
  35594. compile with SQLITE_MAX_MMAP_SIZE=0."
  35595. #endif
  35596. /*
  35597. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  35598. ** based on the sub-platform)?
  35599. */
  35600. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  35601. # define SQLITE_WIN32_HAS_ANSI
  35602. #endif
  35603. /*
  35604. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  35605. ** based on the sub-platform)?
  35606. */
  35607. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  35608. !defined(SQLITE_WIN32_NO_WIDE)
  35609. # define SQLITE_WIN32_HAS_WIDE
  35610. #endif
  35611. /*
  35612. ** Make sure at least one set of Win32 APIs is available.
  35613. */
  35614. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  35615. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  35616. must be defined."
  35617. #endif
  35618. /*
  35619. ** Define the required Windows SDK version constants if they are not
  35620. ** already available.
  35621. */
  35622. #ifndef NTDDI_WIN8
  35623. # define NTDDI_WIN8 0x06020000
  35624. #endif
  35625. #ifndef NTDDI_WINBLUE
  35626. # define NTDDI_WINBLUE 0x06030000
  35627. #endif
  35628. #ifndef NTDDI_WINTHRESHOLD
  35629. # define NTDDI_WINTHRESHOLD 0x06040000
  35630. #endif
  35631. /*
  35632. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  35633. ** target system. GetVersionEx was first deprecated in Win8.1.
  35634. */
  35635. #ifndef SQLITE_WIN32_GETVERSIONEX
  35636. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  35637. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  35638. # else
  35639. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  35640. # endif
  35641. #endif
  35642. /*
  35643. ** Check to see if the CreateFileMappingA function is supported on the
  35644. ** target system. It is unavailable when using "mincore.lib" on Win10.
  35645. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  35646. */
  35647. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  35648. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  35649. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  35650. # else
  35651. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  35652. # endif
  35653. #endif
  35654. /*
  35655. ** This constant should already be defined (in the "WinDef.h" SDK file).
  35656. */
  35657. #ifndef MAX_PATH
  35658. # define MAX_PATH (260)
  35659. #endif
  35660. /*
  35661. ** Maximum pathname length (in chars) for Win32. This should normally be
  35662. ** MAX_PATH.
  35663. */
  35664. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  35665. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  35666. #endif
  35667. /*
  35668. ** This constant should already be defined (in the "WinNT.h" SDK file).
  35669. */
  35670. #ifndef UNICODE_STRING_MAX_CHARS
  35671. # define UNICODE_STRING_MAX_CHARS (32767)
  35672. #endif
  35673. /*
  35674. ** Maximum pathname length (in chars) for WinNT. This should normally be
  35675. ** UNICODE_STRING_MAX_CHARS.
  35676. */
  35677. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  35678. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  35679. #endif
  35680. /*
  35681. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  35682. ** characters, so we allocate 4 bytes per character assuming worst-case of
  35683. ** 4-bytes-per-character for UTF8.
  35684. */
  35685. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  35686. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  35687. #endif
  35688. /*
  35689. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  35690. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  35691. */
  35692. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  35693. # define SQLITE_WINNT_MAX_PATH_BYTES \
  35694. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  35695. #endif
  35696. /*
  35697. ** Maximum error message length (in chars) for WinRT.
  35698. */
  35699. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  35700. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  35701. #endif
  35702. /*
  35703. ** Returns non-zero if the character should be treated as a directory
  35704. ** separator.
  35705. */
  35706. #ifndef winIsDirSep
  35707. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  35708. #endif
  35709. /*
  35710. ** This macro is used when a local variable is set to a value that is
  35711. ** [sometimes] not used by the code (e.g. via conditional compilation).
  35712. */
  35713. #ifndef UNUSED_VARIABLE_VALUE
  35714. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  35715. #endif
  35716. /*
  35717. ** Returns the character that should be used as the directory separator.
  35718. */
  35719. #ifndef winGetDirSep
  35720. # define winGetDirSep() '\\'
  35721. #endif
  35722. /*
  35723. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  35724. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  35725. ** CE SDK; however, they are not present in the header file)?
  35726. */
  35727. #if SQLITE_WIN32_FILEMAPPING_API && \
  35728. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  35729. /*
  35730. ** Two of the file mapping APIs are different under WinRT. Figure out which
  35731. ** set we need.
  35732. */
  35733. #if SQLITE_OS_WINRT
  35734. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  35735. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  35736. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  35737. #else
  35738. #if defined(SQLITE_WIN32_HAS_ANSI)
  35739. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  35740. DWORD, DWORD, DWORD, LPCSTR);
  35741. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  35742. #if defined(SQLITE_WIN32_HAS_WIDE)
  35743. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  35744. DWORD, DWORD, DWORD, LPCWSTR);
  35745. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  35746. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  35747. #endif /* SQLITE_OS_WINRT */
  35748. /*
  35749. ** These file mapping APIs are common to both Win32 and WinRT.
  35750. */
  35751. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  35752. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  35753. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  35754. /*
  35755. ** Some Microsoft compilers lack this definition.
  35756. */
  35757. #ifndef INVALID_FILE_ATTRIBUTES
  35758. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  35759. #endif
  35760. #ifndef FILE_FLAG_MASK
  35761. # define FILE_FLAG_MASK (0xFF3C0000)
  35762. #endif
  35763. #ifndef FILE_ATTRIBUTE_MASK
  35764. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  35765. #endif
  35766. #ifndef SQLITE_OMIT_WAL
  35767. /* Forward references to structures used for WAL */
  35768. typedef struct winShm winShm; /* A connection to shared-memory */
  35769. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  35770. #endif
  35771. /*
  35772. ** WinCE lacks native support for file locking so we have to fake it
  35773. ** with some code of our own.
  35774. */
  35775. #if SQLITE_OS_WINCE
  35776. typedef struct winceLock {
  35777. int nReaders; /* Number of reader locks obtained */
  35778. BOOL bPending; /* Indicates a pending lock has been obtained */
  35779. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  35780. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  35781. } winceLock;
  35782. #endif
  35783. /*
  35784. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  35785. ** portability layer.
  35786. */
  35787. typedef struct winFile winFile;
  35788. struct winFile {
  35789. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  35790. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  35791. HANDLE h; /* Handle for accessing the file */
  35792. u8 locktype; /* Type of lock currently held on this file */
  35793. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  35794. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  35795. DWORD lastErrno; /* The Windows errno from the last I/O error */
  35796. #ifndef SQLITE_OMIT_WAL
  35797. winShm *pShm; /* Instance of shared memory on this file */
  35798. #endif
  35799. const char *zPath; /* Full pathname of this file */
  35800. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  35801. #if SQLITE_OS_WINCE
  35802. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  35803. HANDLE hMutex; /* Mutex used to control access to shared lock */
  35804. HANDLE hShared; /* Shared memory segment used for locking */
  35805. winceLock local; /* Locks obtained by this instance of winFile */
  35806. winceLock *shared; /* Global shared lock memory for the file */
  35807. #endif
  35808. #if SQLITE_MAX_MMAP_SIZE>0
  35809. int nFetchOut; /* Number of outstanding xFetch references */
  35810. HANDLE hMap; /* Handle for accessing memory mapping */
  35811. void *pMapRegion; /* Area memory mapped */
  35812. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  35813. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  35814. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  35815. #endif
  35816. };
  35817. /*
  35818. ** The winVfsAppData structure is used for the pAppData member for all of the
  35819. ** Win32 VFS variants.
  35820. */
  35821. typedef struct winVfsAppData winVfsAppData;
  35822. struct winVfsAppData {
  35823. const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
  35824. void *pAppData; /* The extra pAppData, if any. */
  35825. BOOL bNoLock; /* Non-zero if locking is disabled. */
  35826. };
  35827. /*
  35828. ** Allowed values for winFile.ctrlFlags
  35829. */
  35830. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  35831. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  35832. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  35833. /*
  35834. * The size of the buffer used by sqlite3_win32_write_debug().
  35835. */
  35836. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  35837. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  35838. #endif
  35839. /*
  35840. * The value used with sqlite3_win32_set_directory() to specify that
  35841. * the data directory should be changed.
  35842. */
  35843. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  35844. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  35845. #endif
  35846. /*
  35847. * The value used with sqlite3_win32_set_directory() to specify that
  35848. * the temporary directory should be changed.
  35849. */
  35850. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  35851. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  35852. #endif
  35853. /*
  35854. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  35855. * various Win32 API heap functions instead of our own.
  35856. */
  35857. #ifdef SQLITE_WIN32_MALLOC
  35858. /*
  35859. * If this is non-zero, an isolated heap will be created by the native Win32
  35860. * allocator subsystem; otherwise, the default process heap will be used. This
  35861. * setting has no effect when compiling for WinRT. By default, this is enabled
  35862. * and an isolated heap will be created to store all allocated data.
  35863. *
  35864. ******************************************************************************
  35865. * WARNING: It is important to note that when this setting is non-zero and the
  35866. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  35867. * function), all data that was allocated using the isolated heap will
  35868. * be freed immediately and any attempt to access any of that freed
  35869. * data will almost certainly result in an immediate access violation.
  35870. ******************************************************************************
  35871. */
  35872. #ifndef SQLITE_WIN32_HEAP_CREATE
  35873. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  35874. #endif
  35875. /*
  35876. * This is the maximum possible initial size of the Win32-specific heap, in
  35877. * bytes.
  35878. */
  35879. #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
  35880. # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
  35881. #endif
  35882. /*
  35883. * This is the extra space for the initial size of the Win32-specific heap,
  35884. * in bytes. This value may be zero.
  35885. */
  35886. #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
  35887. # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
  35888. #endif
  35889. /*
  35890. * Calculate the maximum legal cache size, in pages, based on the maximum
  35891. * possible initial heap size and the default page size, setting aside the
  35892. * needed extra space.
  35893. */
  35894. #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
  35895. # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
  35896. (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
  35897. (SQLITE_DEFAULT_PAGE_SIZE))
  35898. #endif
  35899. /*
  35900. * This is cache size used in the calculation of the initial size of the
  35901. * Win32-specific heap. It cannot be negative.
  35902. */
  35903. #ifndef SQLITE_WIN32_CACHE_SIZE
  35904. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  35905. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  35906. # else
  35907. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  35908. # endif
  35909. #endif
  35910. /*
  35911. * Make sure that the calculated cache size, in pages, cannot cause the
  35912. * initial size of the Win32-specific heap to exceed the maximum amount
  35913. * of memory that can be specified in the call to HeapCreate.
  35914. */
  35915. #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
  35916. # undef SQLITE_WIN32_CACHE_SIZE
  35917. # define SQLITE_WIN32_CACHE_SIZE (2000)
  35918. #endif
  35919. /*
  35920. * The initial size of the Win32-specific heap. This value may be zero.
  35921. */
  35922. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  35923. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  35924. (SQLITE_DEFAULT_PAGE_SIZE) + \
  35925. (SQLITE_WIN32_HEAP_INIT_EXTRA))
  35926. #endif
  35927. /*
  35928. * The maximum size of the Win32-specific heap. This value may be zero.
  35929. */
  35930. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  35931. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  35932. #endif
  35933. /*
  35934. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  35935. * zero for the default behavior.
  35936. */
  35937. #ifndef SQLITE_WIN32_HEAP_FLAGS
  35938. # define SQLITE_WIN32_HEAP_FLAGS (0)
  35939. #endif
  35940. /*
  35941. ** The winMemData structure stores information required by the Win32-specific
  35942. ** sqlite3_mem_methods implementation.
  35943. */
  35944. typedef struct winMemData winMemData;
  35945. struct winMemData {
  35946. #ifndef NDEBUG
  35947. u32 magic1; /* Magic number to detect structure corruption. */
  35948. #endif
  35949. HANDLE hHeap; /* The handle to our heap. */
  35950. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  35951. #ifndef NDEBUG
  35952. u32 magic2; /* Magic number to detect structure corruption. */
  35953. #endif
  35954. };
  35955. #ifndef NDEBUG
  35956. #define WINMEM_MAGIC1 0x42b2830b
  35957. #define WINMEM_MAGIC2 0xbd4d7cf4
  35958. #endif
  35959. static struct winMemData win_mem_data = {
  35960. #ifndef NDEBUG
  35961. WINMEM_MAGIC1,
  35962. #endif
  35963. NULL, FALSE
  35964. #ifndef NDEBUG
  35965. ,WINMEM_MAGIC2
  35966. #endif
  35967. };
  35968. #ifndef NDEBUG
  35969. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  35970. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  35971. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  35972. #else
  35973. #define winMemAssertMagic()
  35974. #endif
  35975. #define winMemGetDataPtr() &win_mem_data
  35976. #define winMemGetHeap() win_mem_data.hHeap
  35977. #define winMemGetOwned() win_mem_data.bOwned
  35978. static void *winMemMalloc(int nBytes);
  35979. static void winMemFree(void *pPrior);
  35980. static void *winMemRealloc(void *pPrior, int nBytes);
  35981. static int winMemSize(void *p);
  35982. static int winMemRoundup(int n);
  35983. static int winMemInit(void *pAppData);
  35984. static void winMemShutdown(void *pAppData);
  35985. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  35986. #endif /* SQLITE_WIN32_MALLOC */
  35987. /*
  35988. ** The following variable is (normally) set once and never changes
  35989. ** thereafter. It records whether the operating system is Win9x
  35990. ** or WinNT.
  35991. **
  35992. ** 0: Operating system unknown.
  35993. ** 1: Operating system is Win9x.
  35994. ** 2: Operating system is WinNT.
  35995. **
  35996. ** In order to facilitate testing on a WinNT system, the test fixture
  35997. ** can manually set this value to 1 to emulate Win98 behavior.
  35998. */
  35999. #ifdef SQLITE_TEST
  36000. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  36001. #else
  36002. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  36003. #endif
  36004. #ifndef SYSCALL
  36005. # define SYSCALL sqlite3_syscall_ptr
  36006. #endif
  36007. /*
  36008. ** This function is not available on Windows CE or WinRT.
  36009. */
  36010. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  36011. # define osAreFileApisANSI() 1
  36012. #endif
  36013. /*
  36014. ** Many system calls are accessed through pointer-to-functions so that
  36015. ** they may be overridden at runtime to facilitate fault injection during
  36016. ** testing and sandboxing. The following array holds the names and pointers
  36017. ** to all overrideable system calls.
  36018. */
  36019. static struct win_syscall {
  36020. const char *zName; /* Name of the system call */
  36021. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  36022. sqlite3_syscall_ptr pDefault; /* Default value */
  36023. } aSyscall[] = {
  36024. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36025. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  36026. #else
  36027. { "AreFileApisANSI", (SYSCALL)0, 0 },
  36028. #endif
  36029. #ifndef osAreFileApisANSI
  36030. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  36031. #endif
  36032. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  36033. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  36034. #else
  36035. { "CharLowerW", (SYSCALL)0, 0 },
  36036. #endif
  36037. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  36038. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  36039. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  36040. #else
  36041. { "CharUpperW", (SYSCALL)0, 0 },
  36042. #endif
  36043. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  36044. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  36045. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  36046. #if defined(SQLITE_WIN32_HAS_ANSI)
  36047. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  36048. #else
  36049. { "CreateFileA", (SYSCALL)0, 0 },
  36050. #endif
  36051. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  36052. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  36053. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36054. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  36055. #else
  36056. { "CreateFileW", (SYSCALL)0, 0 },
  36057. #endif
  36058. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  36059. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  36060. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  36061. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  36062. SQLITE_WIN32_CREATEFILEMAPPINGA
  36063. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  36064. #else
  36065. { "CreateFileMappingA", (SYSCALL)0, 0 },
  36066. #endif
  36067. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  36068. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  36069. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  36070. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  36071. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  36072. #else
  36073. { "CreateFileMappingW", (SYSCALL)0, 0 },
  36074. #endif
  36075. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  36076. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  36077. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36078. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  36079. #else
  36080. { "CreateMutexW", (SYSCALL)0, 0 },
  36081. #endif
  36082. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  36083. LPCWSTR))aSyscall[8].pCurrent)
  36084. #if defined(SQLITE_WIN32_HAS_ANSI)
  36085. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  36086. #else
  36087. { "DeleteFileA", (SYSCALL)0, 0 },
  36088. #endif
  36089. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  36090. #if defined(SQLITE_WIN32_HAS_WIDE)
  36091. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  36092. #else
  36093. { "DeleteFileW", (SYSCALL)0, 0 },
  36094. #endif
  36095. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  36096. #if SQLITE_OS_WINCE
  36097. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  36098. #else
  36099. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  36100. #endif
  36101. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  36102. LPFILETIME))aSyscall[11].pCurrent)
  36103. #if SQLITE_OS_WINCE
  36104. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  36105. #else
  36106. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  36107. #endif
  36108. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  36109. LPSYSTEMTIME))aSyscall[12].pCurrent)
  36110. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  36111. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  36112. #if defined(SQLITE_WIN32_HAS_ANSI)
  36113. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  36114. #else
  36115. { "FormatMessageA", (SYSCALL)0, 0 },
  36116. #endif
  36117. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  36118. DWORD,va_list*))aSyscall[14].pCurrent)
  36119. #if defined(SQLITE_WIN32_HAS_WIDE)
  36120. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  36121. #else
  36122. { "FormatMessageW", (SYSCALL)0, 0 },
  36123. #endif
  36124. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  36125. DWORD,va_list*))aSyscall[15].pCurrent)
  36126. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36127. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  36128. #else
  36129. { "FreeLibrary", (SYSCALL)0, 0 },
  36130. #endif
  36131. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  36132. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  36133. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  36134. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  36135. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  36136. #else
  36137. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  36138. #endif
  36139. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  36140. LPDWORD))aSyscall[18].pCurrent)
  36141. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36142. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  36143. #else
  36144. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  36145. #endif
  36146. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  36147. LPDWORD))aSyscall[19].pCurrent)
  36148. #if defined(SQLITE_WIN32_HAS_ANSI)
  36149. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  36150. #else
  36151. { "GetFileAttributesA", (SYSCALL)0, 0 },
  36152. #endif
  36153. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  36154. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36155. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  36156. #else
  36157. { "GetFileAttributesW", (SYSCALL)0, 0 },
  36158. #endif
  36159. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  36160. #if defined(SQLITE_WIN32_HAS_WIDE)
  36161. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  36162. #else
  36163. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  36164. #endif
  36165. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  36166. LPVOID))aSyscall[22].pCurrent)
  36167. #if !SQLITE_OS_WINRT
  36168. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  36169. #else
  36170. { "GetFileSize", (SYSCALL)0, 0 },
  36171. #endif
  36172. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  36173. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  36174. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  36175. #else
  36176. { "GetFullPathNameA", (SYSCALL)0, 0 },
  36177. #endif
  36178. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  36179. LPSTR*))aSyscall[24].pCurrent)
  36180. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36181. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  36182. #else
  36183. { "GetFullPathNameW", (SYSCALL)0, 0 },
  36184. #endif
  36185. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  36186. LPWSTR*))aSyscall[25].pCurrent)
  36187. { "GetLastError", (SYSCALL)GetLastError, 0 },
  36188. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  36189. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36190. #if SQLITE_OS_WINCE
  36191. /* The GetProcAddressA() routine is only available on Windows CE. */
  36192. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  36193. #else
  36194. /* All other Windows platforms expect GetProcAddress() to take
  36195. ** an ANSI string regardless of the _UNICODE setting */
  36196. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  36197. #endif
  36198. #else
  36199. { "GetProcAddressA", (SYSCALL)0, 0 },
  36200. #endif
  36201. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  36202. LPCSTR))aSyscall[27].pCurrent)
  36203. #if !SQLITE_OS_WINRT
  36204. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  36205. #else
  36206. { "GetSystemInfo", (SYSCALL)0, 0 },
  36207. #endif
  36208. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  36209. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  36210. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  36211. #if !SQLITE_OS_WINCE
  36212. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  36213. #else
  36214. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  36215. #endif
  36216. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  36217. LPFILETIME))aSyscall[30].pCurrent)
  36218. #if defined(SQLITE_WIN32_HAS_ANSI)
  36219. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  36220. #else
  36221. { "GetTempPathA", (SYSCALL)0, 0 },
  36222. #endif
  36223. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  36224. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36225. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  36226. #else
  36227. { "GetTempPathW", (SYSCALL)0, 0 },
  36228. #endif
  36229. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  36230. #if !SQLITE_OS_WINRT
  36231. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  36232. #else
  36233. { "GetTickCount", (SYSCALL)0, 0 },
  36234. #endif
  36235. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  36236. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  36237. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  36238. #else
  36239. { "GetVersionExA", (SYSCALL)0, 0 },
  36240. #endif
  36241. #define osGetVersionExA ((BOOL(WINAPI*)( \
  36242. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  36243. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  36244. SQLITE_WIN32_GETVERSIONEX
  36245. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  36246. #else
  36247. { "GetVersionExW", (SYSCALL)0, 0 },
  36248. #endif
  36249. #define osGetVersionExW ((BOOL(WINAPI*)( \
  36250. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  36251. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  36252. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  36253. SIZE_T))aSyscall[36].pCurrent)
  36254. #if !SQLITE_OS_WINRT
  36255. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  36256. #else
  36257. { "HeapCreate", (SYSCALL)0, 0 },
  36258. #endif
  36259. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  36260. SIZE_T))aSyscall[37].pCurrent)
  36261. #if !SQLITE_OS_WINRT
  36262. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  36263. #else
  36264. { "HeapDestroy", (SYSCALL)0, 0 },
  36265. #endif
  36266. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  36267. { "HeapFree", (SYSCALL)HeapFree, 0 },
  36268. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  36269. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  36270. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  36271. SIZE_T))aSyscall[40].pCurrent)
  36272. { "HeapSize", (SYSCALL)HeapSize, 0 },
  36273. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  36274. LPCVOID))aSyscall[41].pCurrent)
  36275. #if !SQLITE_OS_WINRT
  36276. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  36277. #else
  36278. { "HeapValidate", (SYSCALL)0, 0 },
  36279. #endif
  36280. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  36281. LPCVOID))aSyscall[42].pCurrent)
  36282. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36283. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  36284. #else
  36285. { "HeapCompact", (SYSCALL)0, 0 },
  36286. #endif
  36287. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  36288. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36289. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  36290. #else
  36291. { "LoadLibraryA", (SYSCALL)0, 0 },
  36292. #endif
  36293. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  36294. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  36295. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36296. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  36297. #else
  36298. { "LoadLibraryW", (SYSCALL)0, 0 },
  36299. #endif
  36300. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  36301. #if !SQLITE_OS_WINRT
  36302. { "LocalFree", (SYSCALL)LocalFree, 0 },
  36303. #else
  36304. { "LocalFree", (SYSCALL)0, 0 },
  36305. #endif
  36306. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  36307. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36308. { "LockFile", (SYSCALL)LockFile, 0 },
  36309. #else
  36310. { "LockFile", (SYSCALL)0, 0 },
  36311. #endif
  36312. #ifndef osLockFile
  36313. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36314. DWORD))aSyscall[47].pCurrent)
  36315. #endif
  36316. #if !SQLITE_OS_WINCE
  36317. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  36318. #else
  36319. { "LockFileEx", (SYSCALL)0, 0 },
  36320. #endif
  36321. #ifndef osLockFileEx
  36322. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  36323. LPOVERLAPPED))aSyscall[48].pCurrent)
  36324. #endif
  36325. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  36326. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  36327. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  36328. #else
  36329. { "MapViewOfFile", (SYSCALL)0, 0 },
  36330. #endif
  36331. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36332. SIZE_T))aSyscall[49].pCurrent)
  36333. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  36334. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  36335. int))aSyscall[50].pCurrent)
  36336. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  36337. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  36338. LARGE_INTEGER*))aSyscall[51].pCurrent)
  36339. { "ReadFile", (SYSCALL)ReadFile, 0 },
  36340. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  36341. LPOVERLAPPED))aSyscall[52].pCurrent)
  36342. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  36343. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  36344. #if !SQLITE_OS_WINRT
  36345. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  36346. #else
  36347. { "SetFilePointer", (SYSCALL)0, 0 },
  36348. #endif
  36349. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  36350. DWORD))aSyscall[54].pCurrent)
  36351. #if !SQLITE_OS_WINRT
  36352. { "Sleep", (SYSCALL)Sleep, 0 },
  36353. #else
  36354. { "Sleep", (SYSCALL)0, 0 },
  36355. #endif
  36356. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  36357. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  36358. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  36359. LPFILETIME))aSyscall[56].pCurrent)
  36360. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36361. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  36362. #else
  36363. { "UnlockFile", (SYSCALL)0, 0 },
  36364. #endif
  36365. #ifndef osUnlockFile
  36366. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36367. DWORD))aSyscall[57].pCurrent)
  36368. #endif
  36369. #if !SQLITE_OS_WINCE
  36370. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  36371. #else
  36372. { "UnlockFileEx", (SYSCALL)0, 0 },
  36373. #endif
  36374. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36375. LPOVERLAPPED))aSyscall[58].pCurrent)
  36376. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  36377. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  36378. #else
  36379. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  36380. #endif
  36381. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  36382. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  36383. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  36384. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  36385. { "WriteFile", (SYSCALL)WriteFile, 0 },
  36386. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  36387. LPOVERLAPPED))aSyscall[61].pCurrent)
  36388. #if SQLITE_OS_WINRT
  36389. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  36390. #else
  36391. { "CreateEventExW", (SYSCALL)0, 0 },
  36392. #endif
  36393. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  36394. DWORD,DWORD))aSyscall[62].pCurrent)
  36395. #if !SQLITE_OS_WINRT
  36396. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  36397. #else
  36398. { "WaitForSingleObject", (SYSCALL)0, 0 },
  36399. #endif
  36400. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  36401. DWORD))aSyscall[63].pCurrent)
  36402. #if !SQLITE_OS_WINCE
  36403. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  36404. #else
  36405. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  36406. #endif
  36407. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  36408. BOOL))aSyscall[64].pCurrent)
  36409. #if SQLITE_OS_WINRT
  36410. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  36411. #else
  36412. { "SetFilePointerEx", (SYSCALL)0, 0 },
  36413. #endif
  36414. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  36415. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  36416. #if SQLITE_OS_WINRT
  36417. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  36418. #else
  36419. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  36420. #endif
  36421. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  36422. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  36423. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  36424. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  36425. #else
  36426. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  36427. #endif
  36428. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  36429. SIZE_T))aSyscall[67].pCurrent)
  36430. #if SQLITE_OS_WINRT
  36431. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  36432. #else
  36433. { "CreateFile2", (SYSCALL)0, 0 },
  36434. #endif
  36435. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  36436. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  36437. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36438. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  36439. #else
  36440. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  36441. #endif
  36442. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  36443. DWORD))aSyscall[69].pCurrent)
  36444. #if SQLITE_OS_WINRT
  36445. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  36446. #else
  36447. { "GetTickCount64", (SYSCALL)0, 0 },
  36448. #endif
  36449. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  36450. #if SQLITE_OS_WINRT
  36451. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  36452. #else
  36453. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  36454. #endif
  36455. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  36456. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  36457. #if defined(SQLITE_WIN32_HAS_ANSI)
  36458. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  36459. #else
  36460. { "OutputDebugStringA", (SYSCALL)0, 0 },
  36461. #endif
  36462. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  36463. #if defined(SQLITE_WIN32_HAS_WIDE)
  36464. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  36465. #else
  36466. { "OutputDebugStringW", (SYSCALL)0, 0 },
  36467. #endif
  36468. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  36469. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  36470. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  36471. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  36472. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  36473. #else
  36474. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  36475. #endif
  36476. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  36477. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  36478. /*
  36479. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  36480. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  36481. ** So do not try to make this is into a redefinable interface.
  36482. */
  36483. #if defined(InterlockedCompareExchange)
  36484. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  36485. #define osInterlockedCompareExchange InterlockedCompareExchange
  36486. #else
  36487. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  36488. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  36489. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  36490. #endif /* defined(InterlockedCompareExchange) */
  36491. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  36492. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  36493. #else
  36494. { "UuidCreate", (SYSCALL)0, 0 },
  36495. #endif
  36496. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  36497. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  36498. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  36499. #else
  36500. { "UuidCreateSequential", (SYSCALL)0, 0 },
  36501. #endif
  36502. #define osUuidCreateSequential \
  36503. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  36504. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  36505. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  36506. #else
  36507. { "FlushViewOfFile", (SYSCALL)0, 0 },
  36508. #endif
  36509. #define osFlushViewOfFile \
  36510. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  36511. }; /* End of the overrideable system calls */
  36512. /*
  36513. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  36514. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  36515. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  36516. ** system call named zName.
  36517. */
  36518. static int winSetSystemCall(
  36519. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  36520. const char *zName, /* Name of system call to override */
  36521. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  36522. ){
  36523. unsigned int i;
  36524. int rc = SQLITE_NOTFOUND;
  36525. UNUSED_PARAMETER(pNotUsed);
  36526. if( zName==0 ){
  36527. /* If no zName is given, restore all system calls to their default
  36528. ** settings and return NULL
  36529. */
  36530. rc = SQLITE_OK;
  36531. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  36532. if( aSyscall[i].pDefault ){
  36533. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  36534. }
  36535. }
  36536. }else{
  36537. /* If zName is specified, operate on only the one system call
  36538. ** specified.
  36539. */
  36540. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  36541. if( strcmp(zName, aSyscall[i].zName)==0 ){
  36542. if( aSyscall[i].pDefault==0 ){
  36543. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  36544. }
  36545. rc = SQLITE_OK;
  36546. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  36547. aSyscall[i].pCurrent = pNewFunc;
  36548. break;
  36549. }
  36550. }
  36551. }
  36552. return rc;
  36553. }
  36554. /*
  36555. ** Return the value of a system call. Return NULL if zName is not a
  36556. ** recognized system call name. NULL is also returned if the system call
  36557. ** is currently undefined.
  36558. */
  36559. static sqlite3_syscall_ptr winGetSystemCall(
  36560. sqlite3_vfs *pNotUsed,
  36561. const char *zName
  36562. ){
  36563. unsigned int i;
  36564. UNUSED_PARAMETER(pNotUsed);
  36565. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  36566. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  36567. }
  36568. return 0;
  36569. }
  36570. /*
  36571. ** Return the name of the first system call after zName. If zName==NULL
  36572. ** then return the name of the first system call. Return NULL if zName
  36573. ** is the last system call or if zName is not the name of a valid
  36574. ** system call.
  36575. */
  36576. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  36577. int i = -1;
  36578. UNUSED_PARAMETER(p);
  36579. if( zName ){
  36580. for(i=0; i<ArraySize(aSyscall)-1; i++){
  36581. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  36582. }
  36583. }
  36584. for(i++; i<ArraySize(aSyscall); i++){
  36585. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  36586. }
  36587. return 0;
  36588. }
  36589. #ifdef SQLITE_WIN32_MALLOC
  36590. /*
  36591. ** If a Win32 native heap has been configured, this function will attempt to
  36592. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  36593. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  36594. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  36595. ** largest committed free block in the heap, in bytes.
  36596. */
  36597. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  36598. int rc = SQLITE_OK;
  36599. UINT nLargest = 0;
  36600. HANDLE hHeap;
  36601. winMemAssertMagic();
  36602. hHeap = winMemGetHeap();
  36603. assert( hHeap!=0 );
  36604. assert( hHeap!=INVALID_HANDLE_VALUE );
  36605. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36606. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  36607. #endif
  36608. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36609. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  36610. DWORD lastErrno = osGetLastError();
  36611. if( lastErrno==NO_ERROR ){
  36612. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  36613. (void*)hHeap);
  36614. rc = SQLITE_NOMEM_BKPT;
  36615. }else{
  36616. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  36617. osGetLastError(), (void*)hHeap);
  36618. rc = SQLITE_ERROR;
  36619. }
  36620. }
  36621. #else
  36622. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  36623. (void*)hHeap);
  36624. rc = SQLITE_NOTFOUND;
  36625. #endif
  36626. if( pnLargest ) *pnLargest = nLargest;
  36627. return rc;
  36628. }
  36629. /*
  36630. ** If a Win32 native heap has been configured, this function will attempt to
  36631. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  36632. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  36633. ** be returned and no changes will be made to the Win32 native heap.
  36634. */
  36635. SQLITE_API int sqlite3_win32_reset_heap(){
  36636. int rc;
  36637. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  36638. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  36639. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  36640. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  36641. sqlite3_mutex_enter(pMaster);
  36642. sqlite3_mutex_enter(pMem);
  36643. winMemAssertMagic();
  36644. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  36645. /*
  36646. ** At this point, there should be no outstanding memory allocations on
  36647. ** the heap. Also, since both the master and memsys locks are currently
  36648. ** being held by us, no other function (i.e. from another thread) should
  36649. ** be able to even access the heap. Attempt to destroy and recreate our
  36650. ** isolated Win32 native heap now.
  36651. */
  36652. assert( winMemGetHeap()!=NULL );
  36653. assert( winMemGetOwned() );
  36654. assert( sqlite3_memory_used()==0 );
  36655. winMemShutdown(winMemGetDataPtr());
  36656. assert( winMemGetHeap()==NULL );
  36657. assert( !winMemGetOwned() );
  36658. assert( sqlite3_memory_used()==0 );
  36659. rc = winMemInit(winMemGetDataPtr());
  36660. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  36661. assert( rc!=SQLITE_OK || winMemGetOwned() );
  36662. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  36663. }else{
  36664. /*
  36665. ** The Win32 native heap cannot be modified because it may be in use.
  36666. */
  36667. rc = SQLITE_BUSY;
  36668. }
  36669. sqlite3_mutex_leave(pMem);
  36670. sqlite3_mutex_leave(pMaster);
  36671. return rc;
  36672. }
  36673. #endif /* SQLITE_WIN32_MALLOC */
  36674. /*
  36675. ** This function outputs the specified (ANSI) string to the Win32 debugger
  36676. ** (if available).
  36677. */
  36678. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  36679. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  36680. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  36681. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  36682. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  36683. #ifdef SQLITE_ENABLE_API_ARMOR
  36684. if( !zBuf ){
  36685. (void)SQLITE_MISUSE_BKPT;
  36686. return;
  36687. }
  36688. #endif
  36689. #if defined(SQLITE_WIN32_HAS_ANSI)
  36690. if( nMin>0 ){
  36691. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  36692. memcpy(zDbgBuf, zBuf, nMin);
  36693. osOutputDebugStringA(zDbgBuf);
  36694. }else{
  36695. osOutputDebugStringA(zBuf);
  36696. }
  36697. #elif defined(SQLITE_WIN32_HAS_WIDE)
  36698. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  36699. if ( osMultiByteToWideChar(
  36700. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  36701. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  36702. return;
  36703. }
  36704. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  36705. #else
  36706. if( nMin>0 ){
  36707. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  36708. memcpy(zDbgBuf, zBuf, nMin);
  36709. fprintf(stderr, "%s", zDbgBuf);
  36710. }else{
  36711. fprintf(stderr, "%s", zBuf);
  36712. }
  36713. #endif
  36714. }
  36715. /*
  36716. ** The following routine suspends the current thread for at least ms
  36717. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  36718. */
  36719. #if SQLITE_OS_WINRT
  36720. static HANDLE sleepObj = NULL;
  36721. #endif
  36722. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  36723. #if SQLITE_OS_WINRT
  36724. if ( sleepObj==NULL ){
  36725. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  36726. SYNCHRONIZE);
  36727. }
  36728. assert( sleepObj!=NULL );
  36729. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  36730. #else
  36731. osSleep(milliseconds);
  36732. #endif
  36733. }
  36734. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  36735. SQLITE_THREADSAFE>0
  36736. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  36737. DWORD rc;
  36738. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  36739. TRUE))==WAIT_IO_COMPLETION ){}
  36740. return rc;
  36741. }
  36742. #endif
  36743. /*
  36744. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  36745. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  36746. **
  36747. ** Here is an interesting observation: Win95, Win98, and WinME lack
  36748. ** the LockFileEx() API. But we can still statically link against that
  36749. ** API as long as we don't call it when running Win95/98/ME. A call to
  36750. ** this routine is used to determine if the host is Win95/98/ME or
  36751. ** WinNT/2K/XP so that we will know whether or not we can safely call
  36752. ** the LockFileEx() API.
  36753. */
  36754. #if !SQLITE_WIN32_GETVERSIONEX
  36755. # define osIsNT() (1)
  36756. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  36757. # define osIsNT() (1)
  36758. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  36759. # define osIsNT() (0)
  36760. #else
  36761. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  36762. #endif
  36763. /*
  36764. ** This function determines if the machine is running a version of Windows
  36765. ** based on the NT kernel.
  36766. */
  36767. SQLITE_API int sqlite3_win32_is_nt(void){
  36768. #if SQLITE_OS_WINRT
  36769. /*
  36770. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  36771. ** kernel.
  36772. */
  36773. return 1;
  36774. #elif SQLITE_WIN32_GETVERSIONEX
  36775. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  36776. #if defined(SQLITE_WIN32_HAS_ANSI)
  36777. OSVERSIONINFOA sInfo;
  36778. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  36779. osGetVersionExA(&sInfo);
  36780. osInterlockedCompareExchange(&sqlite3_os_type,
  36781. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  36782. #elif defined(SQLITE_WIN32_HAS_WIDE)
  36783. OSVERSIONINFOW sInfo;
  36784. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  36785. osGetVersionExW(&sInfo);
  36786. osInterlockedCompareExchange(&sqlite3_os_type,
  36787. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  36788. #endif
  36789. }
  36790. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  36791. #elif SQLITE_TEST
  36792. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  36793. #else
  36794. /*
  36795. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  36796. ** deprecated are always assumed to be based on the NT kernel.
  36797. */
  36798. return 1;
  36799. #endif
  36800. }
  36801. #ifdef SQLITE_WIN32_MALLOC
  36802. /*
  36803. ** Allocate nBytes of memory.
  36804. */
  36805. static void *winMemMalloc(int nBytes){
  36806. HANDLE hHeap;
  36807. void *p;
  36808. winMemAssertMagic();
  36809. hHeap = winMemGetHeap();
  36810. assert( hHeap!=0 );
  36811. assert( hHeap!=INVALID_HANDLE_VALUE );
  36812. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36813. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  36814. #endif
  36815. assert( nBytes>=0 );
  36816. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  36817. if( !p ){
  36818. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  36819. nBytes, osGetLastError(), (void*)hHeap);
  36820. }
  36821. return p;
  36822. }
  36823. /*
  36824. ** Free memory.
  36825. */
  36826. static void winMemFree(void *pPrior){
  36827. HANDLE hHeap;
  36828. winMemAssertMagic();
  36829. hHeap = winMemGetHeap();
  36830. assert( hHeap!=0 );
  36831. assert( hHeap!=INVALID_HANDLE_VALUE );
  36832. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36833. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  36834. #endif
  36835. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  36836. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  36837. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  36838. pPrior, osGetLastError(), (void*)hHeap);
  36839. }
  36840. }
  36841. /*
  36842. ** Change the size of an existing memory allocation
  36843. */
  36844. static void *winMemRealloc(void *pPrior, int nBytes){
  36845. HANDLE hHeap;
  36846. void *p;
  36847. winMemAssertMagic();
  36848. hHeap = winMemGetHeap();
  36849. assert( hHeap!=0 );
  36850. assert( hHeap!=INVALID_HANDLE_VALUE );
  36851. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36852. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  36853. #endif
  36854. assert( nBytes>=0 );
  36855. if( !pPrior ){
  36856. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  36857. }else{
  36858. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  36859. }
  36860. if( !p ){
  36861. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  36862. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  36863. (void*)hHeap);
  36864. }
  36865. return p;
  36866. }
  36867. /*
  36868. ** Return the size of an outstanding allocation, in bytes.
  36869. */
  36870. static int winMemSize(void *p){
  36871. HANDLE hHeap;
  36872. SIZE_T n;
  36873. winMemAssertMagic();
  36874. hHeap = winMemGetHeap();
  36875. assert( hHeap!=0 );
  36876. assert( hHeap!=INVALID_HANDLE_VALUE );
  36877. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36878. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  36879. #endif
  36880. if( !p ) return 0;
  36881. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  36882. if( n==(SIZE_T)-1 ){
  36883. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  36884. p, osGetLastError(), (void*)hHeap);
  36885. return 0;
  36886. }
  36887. return (int)n;
  36888. }
  36889. /*
  36890. ** Round up a request size to the next valid allocation size.
  36891. */
  36892. static int winMemRoundup(int n){
  36893. return n;
  36894. }
  36895. /*
  36896. ** Initialize this module.
  36897. */
  36898. static int winMemInit(void *pAppData){
  36899. winMemData *pWinMemData = (winMemData *)pAppData;
  36900. if( !pWinMemData ) return SQLITE_ERROR;
  36901. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  36902. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  36903. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  36904. if( !pWinMemData->hHeap ){
  36905. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  36906. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  36907. if( dwMaximumSize==0 ){
  36908. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  36909. }else if( dwInitialSize>dwMaximumSize ){
  36910. dwInitialSize = dwMaximumSize;
  36911. }
  36912. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  36913. dwInitialSize, dwMaximumSize);
  36914. if( !pWinMemData->hHeap ){
  36915. sqlite3_log(SQLITE_NOMEM,
  36916. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  36917. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  36918. dwMaximumSize);
  36919. return SQLITE_NOMEM_BKPT;
  36920. }
  36921. pWinMemData->bOwned = TRUE;
  36922. assert( pWinMemData->bOwned );
  36923. }
  36924. #else
  36925. pWinMemData->hHeap = osGetProcessHeap();
  36926. if( !pWinMemData->hHeap ){
  36927. sqlite3_log(SQLITE_NOMEM,
  36928. "failed to GetProcessHeap (%lu)", osGetLastError());
  36929. return SQLITE_NOMEM_BKPT;
  36930. }
  36931. pWinMemData->bOwned = FALSE;
  36932. assert( !pWinMemData->bOwned );
  36933. #endif
  36934. assert( pWinMemData->hHeap!=0 );
  36935. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  36936. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36937. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  36938. #endif
  36939. return SQLITE_OK;
  36940. }
  36941. /*
  36942. ** Deinitialize this module.
  36943. */
  36944. static void winMemShutdown(void *pAppData){
  36945. winMemData *pWinMemData = (winMemData *)pAppData;
  36946. if( !pWinMemData ) return;
  36947. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  36948. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  36949. if( pWinMemData->hHeap ){
  36950. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  36951. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36952. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  36953. #endif
  36954. if( pWinMemData->bOwned ){
  36955. if( !osHeapDestroy(pWinMemData->hHeap) ){
  36956. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  36957. osGetLastError(), (void*)pWinMemData->hHeap);
  36958. }
  36959. pWinMemData->bOwned = FALSE;
  36960. }
  36961. pWinMemData->hHeap = NULL;
  36962. }
  36963. }
  36964. /*
  36965. ** Populate the low-level memory allocation function pointers in
  36966. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  36967. ** arguments specify the block of memory to manage.
  36968. **
  36969. ** This routine is only called by sqlite3_config(), and therefore
  36970. ** is not required to be threadsafe (it is not).
  36971. */
  36972. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  36973. static const sqlite3_mem_methods winMemMethods = {
  36974. winMemMalloc,
  36975. winMemFree,
  36976. winMemRealloc,
  36977. winMemSize,
  36978. winMemRoundup,
  36979. winMemInit,
  36980. winMemShutdown,
  36981. &win_mem_data
  36982. };
  36983. return &winMemMethods;
  36984. }
  36985. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  36986. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  36987. }
  36988. #endif /* SQLITE_WIN32_MALLOC */
  36989. /*
  36990. ** Convert a UTF-8 string to Microsoft Unicode.
  36991. **
  36992. ** Space to hold the returned string is obtained from sqlite3_malloc().
  36993. */
  36994. static LPWSTR winUtf8ToUnicode(const char *zText){
  36995. int nChar;
  36996. LPWSTR zWideText;
  36997. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
  36998. if( nChar==0 ){
  36999. return 0;
  37000. }
  37001. zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
  37002. if( zWideText==0 ){
  37003. return 0;
  37004. }
  37005. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
  37006. nChar);
  37007. if( nChar==0 ){
  37008. sqlite3_free(zWideText);
  37009. zWideText = 0;
  37010. }
  37011. return zWideText;
  37012. }
  37013. /*
  37014. ** Convert a Microsoft Unicode string to UTF-8.
  37015. **
  37016. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37017. */
  37018. static char *winUnicodeToUtf8(LPCWSTR zWideText){
  37019. int nByte;
  37020. char *zText;
  37021. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
  37022. if( nByte == 0 ){
  37023. return 0;
  37024. }
  37025. zText = sqlite3MallocZero( nByte );
  37026. if( zText==0 ){
  37027. return 0;
  37028. }
  37029. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
  37030. 0, 0);
  37031. if( nByte == 0 ){
  37032. sqlite3_free(zText);
  37033. zText = 0;
  37034. }
  37035. return zText;
  37036. }
  37037. /*
  37038. ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
  37039. ** code page.
  37040. **
  37041. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37042. */
  37043. static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
  37044. int nByte;
  37045. LPWSTR zMbcsText;
  37046. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  37047. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
  37048. 0)*sizeof(WCHAR);
  37049. if( nByte==0 ){
  37050. return 0;
  37051. }
  37052. zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
  37053. if( zMbcsText==0 ){
  37054. return 0;
  37055. }
  37056. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
  37057. nByte);
  37058. if( nByte==0 ){
  37059. sqlite3_free(zMbcsText);
  37060. zMbcsText = 0;
  37061. }
  37062. return zMbcsText;
  37063. }
  37064. /*
  37065. ** Convert a Microsoft Unicode string to a multi-byte character string,
  37066. ** using the ANSI or OEM code page.
  37067. **
  37068. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37069. */
  37070. static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
  37071. int nByte;
  37072. char *zText;
  37073. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  37074. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
  37075. if( nByte == 0 ){
  37076. return 0;
  37077. }
  37078. zText = sqlite3MallocZero( nByte );
  37079. if( zText==0 ){
  37080. return 0;
  37081. }
  37082. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
  37083. nByte, 0, 0);
  37084. if( nByte == 0 ){
  37085. sqlite3_free(zText);
  37086. zText = 0;
  37087. }
  37088. return zText;
  37089. }
  37090. /*
  37091. ** Convert a multi-byte character string to UTF-8.
  37092. **
  37093. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37094. */
  37095. static char *winMbcsToUtf8(const char *zText, int useAnsi){
  37096. char *zTextUtf8;
  37097. LPWSTR zTmpWide;
  37098. zTmpWide = winMbcsToUnicode(zText, useAnsi);
  37099. if( zTmpWide==0 ){
  37100. return 0;
  37101. }
  37102. zTextUtf8 = winUnicodeToUtf8(zTmpWide);
  37103. sqlite3_free(zTmpWide);
  37104. return zTextUtf8;
  37105. }
  37106. /*
  37107. ** Convert a UTF-8 string to a multi-byte character string.
  37108. **
  37109. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37110. */
  37111. static char *winUtf8ToMbcs(const char *zText, int useAnsi){
  37112. char *zTextMbcs;
  37113. LPWSTR zTmpWide;
  37114. zTmpWide = winUtf8ToUnicode(zText);
  37115. if( zTmpWide==0 ){
  37116. return 0;
  37117. }
  37118. zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
  37119. sqlite3_free(zTmpWide);
  37120. return zTextMbcs;
  37121. }
  37122. /*
  37123. ** This is a public wrapper for the winUtf8ToUnicode() function.
  37124. */
  37125. SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
  37126. #ifdef SQLITE_ENABLE_API_ARMOR
  37127. if( !zText ){
  37128. (void)SQLITE_MISUSE_BKPT;
  37129. return 0;
  37130. }
  37131. #endif
  37132. #ifndef SQLITE_OMIT_AUTOINIT
  37133. if( sqlite3_initialize() ) return 0;
  37134. #endif
  37135. return winUtf8ToUnicode(zText);
  37136. }
  37137. /*
  37138. ** This is a public wrapper for the winUnicodeToUtf8() function.
  37139. */
  37140. SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
  37141. #ifdef SQLITE_ENABLE_API_ARMOR
  37142. if( !zWideText ){
  37143. (void)SQLITE_MISUSE_BKPT;
  37144. return 0;
  37145. }
  37146. #endif
  37147. #ifndef SQLITE_OMIT_AUTOINIT
  37148. if( sqlite3_initialize() ) return 0;
  37149. #endif
  37150. return winUnicodeToUtf8(zWideText);
  37151. }
  37152. /*
  37153. ** This is a public wrapper for the winMbcsToUtf8() function.
  37154. */
  37155. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
  37156. #ifdef SQLITE_ENABLE_API_ARMOR
  37157. if( !zText ){
  37158. (void)SQLITE_MISUSE_BKPT;
  37159. return 0;
  37160. }
  37161. #endif
  37162. #ifndef SQLITE_OMIT_AUTOINIT
  37163. if( sqlite3_initialize() ) return 0;
  37164. #endif
  37165. return winMbcsToUtf8(zText, osAreFileApisANSI());
  37166. }
  37167. /*
  37168. ** This is a public wrapper for the winMbcsToUtf8() function.
  37169. */
  37170. SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
  37171. #ifdef SQLITE_ENABLE_API_ARMOR
  37172. if( !zText ){
  37173. (void)SQLITE_MISUSE_BKPT;
  37174. return 0;
  37175. }
  37176. #endif
  37177. #ifndef SQLITE_OMIT_AUTOINIT
  37178. if( sqlite3_initialize() ) return 0;
  37179. #endif
  37180. return winMbcsToUtf8(zText, useAnsi);
  37181. }
  37182. /*
  37183. ** This is a public wrapper for the winUtf8ToMbcs() function.
  37184. */
  37185. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
  37186. #ifdef SQLITE_ENABLE_API_ARMOR
  37187. if( !zText ){
  37188. (void)SQLITE_MISUSE_BKPT;
  37189. return 0;
  37190. }
  37191. #endif
  37192. #ifndef SQLITE_OMIT_AUTOINIT
  37193. if( sqlite3_initialize() ) return 0;
  37194. #endif
  37195. return winUtf8ToMbcs(zText, osAreFileApisANSI());
  37196. }
  37197. /*
  37198. ** This is a public wrapper for the winUtf8ToMbcs() function.
  37199. */
  37200. SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
  37201. #ifdef SQLITE_ENABLE_API_ARMOR
  37202. if( !zText ){
  37203. (void)SQLITE_MISUSE_BKPT;
  37204. return 0;
  37205. }
  37206. #endif
  37207. #ifndef SQLITE_OMIT_AUTOINIT
  37208. if( sqlite3_initialize() ) return 0;
  37209. #endif
  37210. return winUtf8ToMbcs(zText, useAnsi);
  37211. }
  37212. /*
  37213. ** This function sets the data directory or the temporary directory based on
  37214. ** the provided arguments. The type argument must be 1 in order to set the
  37215. ** data directory or 2 in order to set the temporary directory. The zValue
  37216. ** argument is the name of the directory to use. The return value will be
  37217. ** SQLITE_OK if successful.
  37218. */
  37219. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  37220. char **ppDirectory = 0;
  37221. #ifndef SQLITE_OMIT_AUTOINIT
  37222. int rc = sqlite3_initialize();
  37223. if( rc ) return rc;
  37224. #endif
  37225. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  37226. ppDirectory = &sqlite3_data_directory;
  37227. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  37228. ppDirectory = &sqlite3_temp_directory;
  37229. }
  37230. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  37231. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  37232. );
  37233. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  37234. if( ppDirectory ){
  37235. char *zValueUtf8 = 0;
  37236. if( zValue && zValue[0] ){
  37237. zValueUtf8 = winUnicodeToUtf8(zValue);
  37238. if ( zValueUtf8==0 ){
  37239. return SQLITE_NOMEM_BKPT;
  37240. }
  37241. }
  37242. sqlite3_free(*ppDirectory);
  37243. *ppDirectory = zValueUtf8;
  37244. return SQLITE_OK;
  37245. }
  37246. return SQLITE_ERROR;
  37247. }
  37248. /*
  37249. ** The return value of winGetLastErrorMsg
  37250. ** is zero if the error message fits in the buffer, or non-zero
  37251. ** otherwise (if the message was truncated).
  37252. */
  37253. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  37254. /* FormatMessage returns 0 on failure. Otherwise it
  37255. ** returns the number of TCHARs written to the output
  37256. ** buffer, excluding the terminating null char.
  37257. */
  37258. DWORD dwLen = 0;
  37259. char *zOut = 0;
  37260. if( osIsNT() ){
  37261. #if SQLITE_OS_WINRT
  37262. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  37263. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  37264. FORMAT_MESSAGE_IGNORE_INSERTS,
  37265. NULL,
  37266. lastErrno,
  37267. 0,
  37268. zTempWide,
  37269. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  37270. 0);
  37271. #else
  37272. LPWSTR zTempWide = NULL;
  37273. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  37274. FORMAT_MESSAGE_FROM_SYSTEM |
  37275. FORMAT_MESSAGE_IGNORE_INSERTS,
  37276. NULL,
  37277. lastErrno,
  37278. 0,
  37279. (LPWSTR) &zTempWide,
  37280. 0,
  37281. 0);
  37282. #endif
  37283. if( dwLen > 0 ){
  37284. /* allocate a buffer and convert to UTF8 */
  37285. sqlite3BeginBenignMalloc();
  37286. zOut = winUnicodeToUtf8(zTempWide);
  37287. sqlite3EndBenignMalloc();
  37288. #if !SQLITE_OS_WINRT
  37289. /* free the system buffer allocated by FormatMessage */
  37290. osLocalFree(zTempWide);
  37291. #endif
  37292. }
  37293. }
  37294. #ifdef SQLITE_WIN32_HAS_ANSI
  37295. else{
  37296. char *zTemp = NULL;
  37297. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  37298. FORMAT_MESSAGE_FROM_SYSTEM |
  37299. FORMAT_MESSAGE_IGNORE_INSERTS,
  37300. NULL,
  37301. lastErrno,
  37302. 0,
  37303. (LPSTR) &zTemp,
  37304. 0,
  37305. 0);
  37306. if( dwLen > 0 ){
  37307. /* allocate a buffer and convert to UTF8 */
  37308. sqlite3BeginBenignMalloc();
  37309. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  37310. sqlite3EndBenignMalloc();
  37311. /* free the system buffer allocated by FormatMessage */
  37312. osLocalFree(zTemp);
  37313. }
  37314. }
  37315. #endif
  37316. if( 0 == dwLen ){
  37317. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  37318. }else{
  37319. /* copy a maximum of nBuf chars to output buffer */
  37320. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  37321. /* free the UTF8 buffer */
  37322. sqlite3_free(zOut);
  37323. }
  37324. return 0;
  37325. }
  37326. /*
  37327. **
  37328. ** This function - winLogErrorAtLine() - is only ever called via the macro
  37329. ** winLogError().
  37330. **
  37331. ** This routine is invoked after an error occurs in an OS function.
  37332. ** It logs a message using sqlite3_log() containing the current value of
  37333. ** error code and, if possible, the human-readable equivalent from
  37334. ** FormatMessage.
  37335. **
  37336. ** The first argument passed to the macro should be the error code that
  37337. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  37338. ** The two subsequent arguments should be the name of the OS function that
  37339. ** failed and the associated file-system path, if any.
  37340. */
  37341. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  37342. static int winLogErrorAtLine(
  37343. int errcode, /* SQLite error code */
  37344. DWORD lastErrno, /* Win32 last error */
  37345. const char *zFunc, /* Name of OS function that failed */
  37346. const char *zPath, /* File path associated with error */
  37347. int iLine /* Source line number where error occurred */
  37348. ){
  37349. char zMsg[500]; /* Human readable error text */
  37350. int i; /* Loop counter */
  37351. zMsg[0] = 0;
  37352. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  37353. assert( errcode!=SQLITE_OK );
  37354. if( zPath==0 ) zPath = "";
  37355. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  37356. zMsg[i] = 0;
  37357. sqlite3_log(errcode,
  37358. "os_win.c:%d: (%lu) %s(%s) - %s",
  37359. iLine, lastErrno, zFunc, zPath, zMsg
  37360. );
  37361. return errcode;
  37362. }
  37363. /*
  37364. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  37365. ** will be retried following a locking error - probably caused by
  37366. ** antivirus software. Also the initial delay before the first retry.
  37367. ** The delay increases linearly with each retry.
  37368. */
  37369. #ifndef SQLITE_WIN32_IOERR_RETRY
  37370. # define SQLITE_WIN32_IOERR_RETRY 10
  37371. #endif
  37372. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  37373. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  37374. #endif
  37375. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  37376. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  37377. /*
  37378. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  37379. ** error code obtained via GetLastError() is eligible to be retried. It
  37380. ** must accept the error code DWORD as its only argument and should return
  37381. ** non-zero if the error code is transient in nature and the operation
  37382. ** responsible for generating the original error might succeed upon being
  37383. ** retried. The argument to this macro should be a variable.
  37384. **
  37385. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  37386. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  37387. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  37388. ** may be used to include additional error codes in the set that should
  37389. ** result in the failing I/O operation being retried by the caller. If
  37390. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  37391. ** identical to those of the "winIoerrCanRetry1" macro.
  37392. */
  37393. #if !defined(winIoerrCanRetry1)
  37394. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  37395. ((a)==ERROR_SHARING_VIOLATION) || \
  37396. ((a)==ERROR_LOCK_VIOLATION) || \
  37397. ((a)==ERROR_DEV_NOT_EXIST) || \
  37398. ((a)==ERROR_NETNAME_DELETED) || \
  37399. ((a)==ERROR_SEM_TIMEOUT) || \
  37400. ((a)==ERROR_NETWORK_UNREACHABLE))
  37401. #endif
  37402. /*
  37403. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  37404. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  37405. ** to give up with an error.
  37406. */
  37407. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  37408. DWORD e = osGetLastError();
  37409. if( *pnRetry>=winIoerrRetry ){
  37410. if( pError ){
  37411. *pError = e;
  37412. }
  37413. return 0;
  37414. }
  37415. if( winIoerrCanRetry1(e) ){
  37416. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  37417. ++*pnRetry;
  37418. return 1;
  37419. }
  37420. #if defined(winIoerrCanRetry2)
  37421. else if( winIoerrCanRetry2(e) ){
  37422. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  37423. ++*pnRetry;
  37424. return 1;
  37425. }
  37426. #endif
  37427. if( pError ){
  37428. *pError = e;
  37429. }
  37430. return 0;
  37431. }
  37432. /*
  37433. ** Log a I/O error retry episode.
  37434. */
  37435. static void winLogIoerr(int nRetry, int lineno){
  37436. if( nRetry ){
  37437. sqlite3_log(SQLITE_NOTICE,
  37438. "delayed %dms for lock/sharing conflict at line %d",
  37439. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  37440. );
  37441. }
  37442. }
  37443. /*
  37444. ** This #if does not rely on the SQLITE_OS_WINCE define because the
  37445. ** corresponding section in "date.c" cannot use it.
  37446. */
  37447. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  37448. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  37449. /*
  37450. ** The MSVC CRT on Windows CE may not have a localtime() function.
  37451. ** So define a substitute.
  37452. */
  37453. /* # include <time.h> */
  37454. struct tm *__cdecl localtime(const time_t *t)
  37455. {
  37456. static struct tm y;
  37457. FILETIME uTm, lTm;
  37458. SYSTEMTIME pTm;
  37459. sqlite3_int64 t64;
  37460. t64 = *t;
  37461. t64 = (t64 + 11644473600)*10000000;
  37462. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  37463. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  37464. osFileTimeToLocalFileTime(&uTm,&lTm);
  37465. osFileTimeToSystemTime(&lTm,&pTm);
  37466. y.tm_year = pTm.wYear - 1900;
  37467. y.tm_mon = pTm.wMonth - 1;
  37468. y.tm_wday = pTm.wDayOfWeek;
  37469. y.tm_mday = pTm.wDay;
  37470. y.tm_hour = pTm.wHour;
  37471. y.tm_min = pTm.wMinute;
  37472. y.tm_sec = pTm.wSecond;
  37473. return &y;
  37474. }
  37475. #endif
  37476. #if SQLITE_OS_WINCE
  37477. /*************************************************************************
  37478. ** This section contains code for WinCE only.
  37479. */
  37480. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  37481. /*
  37482. ** Acquire a lock on the handle h
  37483. */
  37484. static void winceMutexAcquire(HANDLE h){
  37485. DWORD dwErr;
  37486. do {
  37487. dwErr = osWaitForSingleObject(h, INFINITE);
  37488. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  37489. }
  37490. /*
  37491. ** Release a lock acquired by winceMutexAcquire()
  37492. */
  37493. #define winceMutexRelease(h) ReleaseMutex(h)
  37494. /*
  37495. ** Create the mutex and shared memory used for locking in the file
  37496. ** descriptor pFile
  37497. */
  37498. static int winceCreateLock(const char *zFilename, winFile *pFile){
  37499. LPWSTR zTok;
  37500. LPWSTR zName;
  37501. DWORD lastErrno;
  37502. BOOL bLogged = FALSE;
  37503. BOOL bInit = TRUE;
  37504. zName = winUtf8ToUnicode(zFilename);
  37505. if( zName==0 ){
  37506. /* out of memory */
  37507. return SQLITE_IOERR_NOMEM_BKPT;
  37508. }
  37509. /* Initialize the local lockdata */
  37510. memset(&pFile->local, 0, sizeof(pFile->local));
  37511. /* Replace the backslashes from the filename and lowercase it
  37512. ** to derive a mutex name. */
  37513. zTok = osCharLowerW(zName);
  37514. for (;*zTok;zTok++){
  37515. if (*zTok == '\\') *zTok = '_';
  37516. }
  37517. /* Create/open the named mutex */
  37518. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  37519. if (!pFile->hMutex){
  37520. pFile->lastErrno = osGetLastError();
  37521. sqlite3_free(zName);
  37522. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  37523. "winceCreateLock1", zFilename);
  37524. }
  37525. /* Acquire the mutex before continuing */
  37526. winceMutexAcquire(pFile->hMutex);
  37527. /* Since the names of named mutexes, semaphores, file mappings etc are
  37528. ** case-sensitive, take advantage of that by uppercasing the mutex name
  37529. ** and using that as the shared filemapping name.
  37530. */
  37531. osCharUpperW(zName);
  37532. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  37533. PAGE_READWRITE, 0, sizeof(winceLock),
  37534. zName);
  37535. /* Set a flag that indicates we're the first to create the memory so it
  37536. ** must be zero-initialized */
  37537. lastErrno = osGetLastError();
  37538. if (lastErrno == ERROR_ALREADY_EXISTS){
  37539. bInit = FALSE;
  37540. }
  37541. sqlite3_free(zName);
  37542. /* If we succeeded in making the shared memory handle, map it. */
  37543. if( pFile->hShared ){
  37544. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  37545. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  37546. /* If mapping failed, close the shared memory handle and erase it */
  37547. if( !pFile->shared ){
  37548. pFile->lastErrno = osGetLastError();
  37549. winLogError(SQLITE_IOERR, pFile->lastErrno,
  37550. "winceCreateLock2", zFilename);
  37551. bLogged = TRUE;
  37552. osCloseHandle(pFile->hShared);
  37553. pFile->hShared = NULL;
  37554. }
  37555. }
  37556. /* If shared memory could not be created, then close the mutex and fail */
  37557. if( pFile->hShared==NULL ){
  37558. if( !bLogged ){
  37559. pFile->lastErrno = lastErrno;
  37560. winLogError(SQLITE_IOERR, pFile->lastErrno,
  37561. "winceCreateLock3", zFilename);
  37562. bLogged = TRUE;
  37563. }
  37564. winceMutexRelease(pFile->hMutex);
  37565. osCloseHandle(pFile->hMutex);
  37566. pFile->hMutex = NULL;
  37567. return SQLITE_IOERR;
  37568. }
  37569. /* Initialize the shared memory if we're supposed to */
  37570. if( bInit ){
  37571. memset(pFile->shared, 0, sizeof(winceLock));
  37572. }
  37573. winceMutexRelease(pFile->hMutex);
  37574. return SQLITE_OK;
  37575. }
  37576. /*
  37577. ** Destroy the part of winFile that deals with wince locks
  37578. */
  37579. static void winceDestroyLock(winFile *pFile){
  37580. if (pFile->hMutex){
  37581. /* Acquire the mutex */
  37582. winceMutexAcquire(pFile->hMutex);
  37583. /* The following blocks should probably assert in debug mode, but they
  37584. are to cleanup in case any locks remained open */
  37585. if (pFile->local.nReaders){
  37586. pFile->shared->nReaders --;
  37587. }
  37588. if (pFile->local.bReserved){
  37589. pFile->shared->bReserved = FALSE;
  37590. }
  37591. if (pFile->local.bPending){
  37592. pFile->shared->bPending = FALSE;
  37593. }
  37594. if (pFile->local.bExclusive){
  37595. pFile->shared->bExclusive = FALSE;
  37596. }
  37597. /* De-reference and close our copy of the shared memory handle */
  37598. osUnmapViewOfFile(pFile->shared);
  37599. osCloseHandle(pFile->hShared);
  37600. /* Done with the mutex */
  37601. winceMutexRelease(pFile->hMutex);
  37602. osCloseHandle(pFile->hMutex);
  37603. pFile->hMutex = NULL;
  37604. }
  37605. }
  37606. /*
  37607. ** An implementation of the LockFile() API of Windows for CE
  37608. */
  37609. static BOOL winceLockFile(
  37610. LPHANDLE phFile,
  37611. DWORD dwFileOffsetLow,
  37612. DWORD dwFileOffsetHigh,
  37613. DWORD nNumberOfBytesToLockLow,
  37614. DWORD nNumberOfBytesToLockHigh
  37615. ){
  37616. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  37617. BOOL bReturn = FALSE;
  37618. UNUSED_PARAMETER(dwFileOffsetHigh);
  37619. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  37620. if (!pFile->hMutex) return TRUE;
  37621. winceMutexAcquire(pFile->hMutex);
  37622. /* Wanting an exclusive lock? */
  37623. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  37624. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  37625. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  37626. pFile->shared->bExclusive = TRUE;
  37627. pFile->local.bExclusive = TRUE;
  37628. bReturn = TRUE;
  37629. }
  37630. }
  37631. /* Want a read-only lock? */
  37632. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  37633. nNumberOfBytesToLockLow == 1){
  37634. if (pFile->shared->bExclusive == 0){
  37635. pFile->local.nReaders ++;
  37636. if (pFile->local.nReaders == 1){
  37637. pFile->shared->nReaders ++;
  37638. }
  37639. bReturn = TRUE;
  37640. }
  37641. }
  37642. /* Want a pending lock? */
  37643. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  37644. && nNumberOfBytesToLockLow == 1){
  37645. /* If no pending lock has been acquired, then acquire it */
  37646. if (pFile->shared->bPending == 0) {
  37647. pFile->shared->bPending = TRUE;
  37648. pFile->local.bPending = TRUE;
  37649. bReturn = TRUE;
  37650. }
  37651. }
  37652. /* Want a reserved lock? */
  37653. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  37654. && nNumberOfBytesToLockLow == 1){
  37655. if (pFile->shared->bReserved == 0) {
  37656. pFile->shared->bReserved = TRUE;
  37657. pFile->local.bReserved = TRUE;
  37658. bReturn = TRUE;
  37659. }
  37660. }
  37661. winceMutexRelease(pFile->hMutex);
  37662. return bReturn;
  37663. }
  37664. /*
  37665. ** An implementation of the UnlockFile API of Windows for CE
  37666. */
  37667. static BOOL winceUnlockFile(
  37668. LPHANDLE phFile,
  37669. DWORD dwFileOffsetLow,
  37670. DWORD dwFileOffsetHigh,
  37671. DWORD nNumberOfBytesToUnlockLow,
  37672. DWORD nNumberOfBytesToUnlockHigh
  37673. ){
  37674. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  37675. BOOL bReturn = FALSE;
  37676. UNUSED_PARAMETER(dwFileOffsetHigh);
  37677. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  37678. if (!pFile->hMutex) return TRUE;
  37679. winceMutexAcquire(pFile->hMutex);
  37680. /* Releasing a reader lock or an exclusive lock */
  37681. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  37682. /* Did we have an exclusive lock? */
  37683. if (pFile->local.bExclusive){
  37684. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  37685. pFile->local.bExclusive = FALSE;
  37686. pFile->shared->bExclusive = FALSE;
  37687. bReturn = TRUE;
  37688. }
  37689. /* Did we just have a reader lock? */
  37690. else if (pFile->local.nReaders){
  37691. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  37692. || nNumberOfBytesToUnlockLow == 1);
  37693. pFile->local.nReaders --;
  37694. if (pFile->local.nReaders == 0)
  37695. {
  37696. pFile->shared->nReaders --;
  37697. }
  37698. bReturn = TRUE;
  37699. }
  37700. }
  37701. /* Releasing a pending lock */
  37702. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  37703. && nNumberOfBytesToUnlockLow == 1){
  37704. if (pFile->local.bPending){
  37705. pFile->local.bPending = FALSE;
  37706. pFile->shared->bPending = FALSE;
  37707. bReturn = TRUE;
  37708. }
  37709. }
  37710. /* Releasing a reserved lock */
  37711. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  37712. && nNumberOfBytesToUnlockLow == 1){
  37713. if (pFile->local.bReserved) {
  37714. pFile->local.bReserved = FALSE;
  37715. pFile->shared->bReserved = FALSE;
  37716. bReturn = TRUE;
  37717. }
  37718. }
  37719. winceMutexRelease(pFile->hMutex);
  37720. return bReturn;
  37721. }
  37722. /*
  37723. ** End of the special code for wince
  37724. *****************************************************************************/
  37725. #endif /* SQLITE_OS_WINCE */
  37726. /*
  37727. ** Lock a file region.
  37728. */
  37729. static BOOL winLockFile(
  37730. LPHANDLE phFile,
  37731. DWORD flags,
  37732. DWORD offsetLow,
  37733. DWORD offsetHigh,
  37734. DWORD numBytesLow,
  37735. DWORD numBytesHigh
  37736. ){
  37737. #if SQLITE_OS_WINCE
  37738. /*
  37739. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  37740. ** API LockFile.
  37741. */
  37742. return winceLockFile(phFile, offsetLow, offsetHigh,
  37743. numBytesLow, numBytesHigh);
  37744. #else
  37745. if( osIsNT() ){
  37746. OVERLAPPED ovlp;
  37747. memset(&ovlp, 0, sizeof(OVERLAPPED));
  37748. ovlp.Offset = offsetLow;
  37749. ovlp.OffsetHigh = offsetHigh;
  37750. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  37751. }else{
  37752. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  37753. numBytesHigh);
  37754. }
  37755. #endif
  37756. }
  37757. /*
  37758. ** Unlock a file region.
  37759. */
  37760. static BOOL winUnlockFile(
  37761. LPHANDLE phFile,
  37762. DWORD offsetLow,
  37763. DWORD offsetHigh,
  37764. DWORD numBytesLow,
  37765. DWORD numBytesHigh
  37766. ){
  37767. #if SQLITE_OS_WINCE
  37768. /*
  37769. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  37770. ** API UnlockFile.
  37771. */
  37772. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  37773. numBytesLow, numBytesHigh);
  37774. #else
  37775. if( osIsNT() ){
  37776. OVERLAPPED ovlp;
  37777. memset(&ovlp, 0, sizeof(OVERLAPPED));
  37778. ovlp.Offset = offsetLow;
  37779. ovlp.OffsetHigh = offsetHigh;
  37780. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  37781. }else{
  37782. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  37783. numBytesHigh);
  37784. }
  37785. #endif
  37786. }
  37787. /*****************************************************************************
  37788. ** The next group of routines implement the I/O methods specified
  37789. ** by the sqlite3_io_methods object.
  37790. ******************************************************************************/
  37791. /*
  37792. ** Some Microsoft compilers lack this definition.
  37793. */
  37794. #ifndef INVALID_SET_FILE_POINTER
  37795. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  37796. #endif
  37797. /*
  37798. ** Move the current position of the file handle passed as the first
  37799. ** argument to offset iOffset within the file. If successful, return 0.
  37800. ** Otherwise, set pFile->lastErrno and return non-zero.
  37801. */
  37802. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  37803. #if !SQLITE_OS_WINRT
  37804. LONG upperBits; /* Most sig. 32 bits of new offset */
  37805. LONG lowerBits; /* Least sig. 32 bits of new offset */
  37806. DWORD dwRet; /* Value returned by SetFilePointer() */
  37807. DWORD lastErrno; /* Value returned by GetLastError() */
  37808. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  37809. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  37810. lowerBits = (LONG)(iOffset & 0xffffffff);
  37811. /* API oddity: If successful, SetFilePointer() returns a dword
  37812. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  37813. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  37814. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  37815. ** whether an error has actually occurred, it is also necessary to call
  37816. ** GetLastError().
  37817. */
  37818. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  37819. if( (dwRet==INVALID_SET_FILE_POINTER
  37820. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  37821. pFile->lastErrno = lastErrno;
  37822. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  37823. "winSeekFile", pFile->zPath);
  37824. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  37825. return 1;
  37826. }
  37827. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  37828. return 0;
  37829. #else
  37830. /*
  37831. ** Same as above, except that this implementation works for WinRT.
  37832. */
  37833. LARGE_INTEGER x; /* The new offset */
  37834. BOOL bRet; /* Value returned by SetFilePointerEx() */
  37835. x.QuadPart = iOffset;
  37836. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  37837. if(!bRet){
  37838. pFile->lastErrno = osGetLastError();
  37839. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  37840. "winSeekFile", pFile->zPath);
  37841. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  37842. return 1;
  37843. }
  37844. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  37845. return 0;
  37846. #endif
  37847. }
  37848. #if SQLITE_MAX_MMAP_SIZE>0
  37849. /* Forward references to VFS helper methods used for memory mapped files */
  37850. static int winMapfile(winFile*, sqlite3_int64);
  37851. static int winUnmapfile(winFile*);
  37852. #endif
  37853. /*
  37854. ** Close a file.
  37855. **
  37856. ** It is reported that an attempt to close a handle might sometimes
  37857. ** fail. This is a very unreasonable result, but Windows is notorious
  37858. ** for being unreasonable so I do not doubt that it might happen. If
  37859. ** the close fails, we pause for 100 milliseconds and try again. As
  37860. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  37861. ** giving up and returning an error.
  37862. */
  37863. #define MX_CLOSE_ATTEMPT 3
  37864. static int winClose(sqlite3_file *id){
  37865. int rc, cnt = 0;
  37866. winFile *pFile = (winFile*)id;
  37867. assert( id!=0 );
  37868. #ifndef SQLITE_OMIT_WAL
  37869. assert( pFile->pShm==0 );
  37870. #endif
  37871. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  37872. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  37873. osGetCurrentProcessId(), pFile, pFile->h));
  37874. #if SQLITE_MAX_MMAP_SIZE>0
  37875. winUnmapfile(pFile);
  37876. #endif
  37877. do{
  37878. rc = osCloseHandle(pFile->h);
  37879. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  37880. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  37881. #if SQLITE_OS_WINCE
  37882. #define WINCE_DELETION_ATTEMPTS 3
  37883. {
  37884. winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
  37885. if( pAppData==NULL || !pAppData->bNoLock ){
  37886. winceDestroyLock(pFile);
  37887. }
  37888. }
  37889. if( pFile->zDeleteOnClose ){
  37890. int cnt = 0;
  37891. while(
  37892. osDeleteFileW(pFile->zDeleteOnClose)==0
  37893. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  37894. && cnt++ < WINCE_DELETION_ATTEMPTS
  37895. ){
  37896. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  37897. }
  37898. sqlite3_free(pFile->zDeleteOnClose);
  37899. }
  37900. #endif
  37901. if( rc ){
  37902. pFile->h = NULL;
  37903. }
  37904. OpenCounter(-1);
  37905. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  37906. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  37907. return rc ? SQLITE_OK
  37908. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  37909. "winClose", pFile->zPath);
  37910. }
  37911. /*
  37912. ** Read data from a file into a buffer. Return SQLITE_OK if all
  37913. ** bytes were read successfully and SQLITE_IOERR if anything goes
  37914. ** wrong.
  37915. */
  37916. static int winRead(
  37917. sqlite3_file *id, /* File to read from */
  37918. void *pBuf, /* Write content into this buffer */
  37919. int amt, /* Number of bytes to read */
  37920. sqlite3_int64 offset /* Begin reading at this offset */
  37921. ){
  37922. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  37923. OVERLAPPED overlapped; /* The offset for ReadFile. */
  37924. #endif
  37925. winFile *pFile = (winFile*)id; /* file handle */
  37926. DWORD nRead; /* Number of bytes actually read from file */
  37927. int nRetry = 0; /* Number of retrys */
  37928. assert( id!=0 );
  37929. assert( amt>0 );
  37930. assert( offset>=0 );
  37931. SimulateIOError(return SQLITE_IOERR_READ);
  37932. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  37933. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  37934. pFile->h, pBuf, amt, offset, pFile->locktype));
  37935. #if SQLITE_MAX_MMAP_SIZE>0
  37936. /* Deal with as much of this read request as possible by transfering
  37937. ** data from the memory mapping using memcpy(). */
  37938. if( offset<pFile->mmapSize ){
  37939. if( offset+amt <= pFile->mmapSize ){
  37940. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  37941. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  37942. osGetCurrentProcessId(), pFile, pFile->h));
  37943. return SQLITE_OK;
  37944. }else{
  37945. int nCopy = (int)(pFile->mmapSize - offset);
  37946. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  37947. pBuf = &((u8 *)pBuf)[nCopy];
  37948. amt -= nCopy;
  37949. offset += nCopy;
  37950. }
  37951. }
  37952. #endif
  37953. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  37954. if( winSeekFile(pFile, offset) ){
  37955. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  37956. osGetCurrentProcessId(), pFile, pFile->h));
  37957. return SQLITE_FULL;
  37958. }
  37959. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  37960. #else
  37961. memset(&overlapped, 0, sizeof(OVERLAPPED));
  37962. overlapped.Offset = (LONG)(offset & 0xffffffff);
  37963. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  37964. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  37965. osGetLastError()!=ERROR_HANDLE_EOF ){
  37966. #endif
  37967. DWORD lastErrno;
  37968. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  37969. pFile->lastErrno = lastErrno;
  37970. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  37971. osGetCurrentProcessId(), pFile, pFile->h));
  37972. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  37973. "winRead", pFile->zPath);
  37974. }
  37975. winLogIoerr(nRetry, __LINE__);
  37976. if( nRead<(DWORD)amt ){
  37977. /* Unread parts of the buffer must be zero-filled */
  37978. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  37979. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  37980. osGetCurrentProcessId(), pFile, pFile->h));
  37981. return SQLITE_IOERR_SHORT_READ;
  37982. }
  37983. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  37984. osGetCurrentProcessId(), pFile, pFile->h));
  37985. return SQLITE_OK;
  37986. }
  37987. /*
  37988. ** Write data from a buffer into a file. Return SQLITE_OK on success
  37989. ** or some other error code on failure.
  37990. */
  37991. static int winWrite(
  37992. sqlite3_file *id, /* File to write into */
  37993. const void *pBuf, /* The bytes to be written */
  37994. int amt, /* Number of bytes to write */
  37995. sqlite3_int64 offset /* Offset into the file to begin writing at */
  37996. ){
  37997. int rc = 0; /* True if error has occurred, else false */
  37998. winFile *pFile = (winFile*)id; /* File handle */
  37999. int nRetry = 0; /* Number of retries */
  38000. assert( amt>0 );
  38001. assert( pFile );
  38002. SimulateIOError(return SQLITE_IOERR_WRITE);
  38003. SimulateDiskfullError(return SQLITE_FULL);
  38004. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  38005. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  38006. pFile->h, pBuf, amt, offset, pFile->locktype));
  38007. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  38008. /* Deal with as much of this write request as possible by transfering
  38009. ** data from the memory mapping using memcpy(). */
  38010. if( offset<pFile->mmapSize ){
  38011. if( offset+amt <= pFile->mmapSize ){
  38012. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  38013. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38014. osGetCurrentProcessId(), pFile, pFile->h));
  38015. return SQLITE_OK;
  38016. }else{
  38017. int nCopy = (int)(pFile->mmapSize - offset);
  38018. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  38019. pBuf = &((u8 *)pBuf)[nCopy];
  38020. amt -= nCopy;
  38021. offset += nCopy;
  38022. }
  38023. }
  38024. #endif
  38025. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  38026. rc = winSeekFile(pFile, offset);
  38027. if( rc==0 ){
  38028. #else
  38029. {
  38030. #endif
  38031. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38032. OVERLAPPED overlapped; /* The offset for WriteFile. */
  38033. #endif
  38034. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  38035. int nRem = amt; /* Number of bytes yet to be written */
  38036. DWORD nWrite; /* Bytes written by each WriteFile() call */
  38037. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  38038. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38039. memset(&overlapped, 0, sizeof(OVERLAPPED));
  38040. overlapped.Offset = (LONG)(offset & 0xffffffff);
  38041. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  38042. #endif
  38043. while( nRem>0 ){
  38044. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  38045. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  38046. #else
  38047. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  38048. #endif
  38049. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  38050. break;
  38051. }
  38052. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  38053. if( nWrite==0 || nWrite>(DWORD)nRem ){
  38054. lastErrno = osGetLastError();
  38055. break;
  38056. }
  38057. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38058. offset += nWrite;
  38059. overlapped.Offset = (LONG)(offset & 0xffffffff);
  38060. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  38061. #endif
  38062. aRem += nWrite;
  38063. nRem -= nWrite;
  38064. }
  38065. if( nRem>0 ){
  38066. pFile->lastErrno = lastErrno;
  38067. rc = 1;
  38068. }
  38069. }
  38070. if( rc ){
  38071. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  38072. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  38073. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  38074. osGetCurrentProcessId(), pFile, pFile->h));
  38075. return winLogError(SQLITE_FULL, pFile->lastErrno,
  38076. "winWrite1", pFile->zPath);
  38077. }
  38078. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  38079. osGetCurrentProcessId(), pFile, pFile->h));
  38080. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  38081. "winWrite2", pFile->zPath);
  38082. }else{
  38083. winLogIoerr(nRetry, __LINE__);
  38084. }
  38085. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38086. osGetCurrentProcessId(), pFile, pFile->h));
  38087. return SQLITE_OK;
  38088. }
  38089. /*
  38090. ** Truncate an open file to a specified size
  38091. */
  38092. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  38093. winFile *pFile = (winFile*)id; /* File handle object */
  38094. int rc = SQLITE_OK; /* Return code for this function */
  38095. DWORD lastErrno;
  38096. assert( pFile );
  38097. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  38098. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  38099. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  38100. /* If the user has configured a chunk-size for this file, truncate the
  38101. ** file so that it consists of an integer number of chunks (i.e. the
  38102. ** actual file size after the operation may be larger than the requested
  38103. ** size).
  38104. */
  38105. if( pFile->szChunk>0 ){
  38106. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  38107. }
  38108. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  38109. if( winSeekFile(pFile, nByte) ){
  38110. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  38111. "winTruncate1", pFile->zPath);
  38112. }else if( 0==osSetEndOfFile(pFile->h) &&
  38113. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  38114. pFile->lastErrno = lastErrno;
  38115. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  38116. "winTruncate2", pFile->zPath);
  38117. }
  38118. #if SQLITE_MAX_MMAP_SIZE>0
  38119. /* If the file was truncated to a size smaller than the currently
  38120. ** mapped region, reduce the effective mapping size as well. SQLite will
  38121. ** use read() and write() to access data beyond this point from now on.
  38122. */
  38123. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  38124. pFile->mmapSize = nByte;
  38125. }
  38126. #endif
  38127. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  38128. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  38129. return rc;
  38130. }
  38131. #ifdef SQLITE_TEST
  38132. /*
  38133. ** Count the number of fullsyncs and normal syncs. This is used to test
  38134. ** that syncs and fullsyncs are occuring at the right times.
  38135. */
  38136. SQLITE_API int sqlite3_sync_count = 0;
  38137. SQLITE_API int sqlite3_fullsync_count = 0;
  38138. #endif
  38139. /*
  38140. ** Make sure all writes to a particular file are committed to disk.
  38141. */
  38142. static int winSync(sqlite3_file *id, int flags){
  38143. #ifndef SQLITE_NO_SYNC
  38144. /*
  38145. ** Used only when SQLITE_NO_SYNC is not defined.
  38146. */
  38147. BOOL rc;
  38148. #endif
  38149. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  38150. defined(SQLITE_HAVE_OS_TRACE)
  38151. /*
  38152. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  38153. ** OSTRACE() macros.
  38154. */
  38155. winFile *pFile = (winFile*)id;
  38156. #else
  38157. UNUSED_PARAMETER(id);
  38158. #endif
  38159. assert( pFile );
  38160. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  38161. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  38162. || (flags&0x0F)==SQLITE_SYNC_FULL
  38163. );
  38164. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  38165. ** line is to test that doing so does not cause any problems.
  38166. */
  38167. SimulateDiskfullError( return SQLITE_FULL );
  38168. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  38169. osGetCurrentProcessId(), pFile, pFile->h, flags,
  38170. pFile->locktype));
  38171. #ifndef SQLITE_TEST
  38172. UNUSED_PARAMETER(flags);
  38173. #else
  38174. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  38175. sqlite3_fullsync_count++;
  38176. }
  38177. sqlite3_sync_count++;
  38178. #endif
  38179. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  38180. ** no-op
  38181. */
  38182. #ifdef SQLITE_NO_SYNC
  38183. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38184. osGetCurrentProcessId(), pFile, pFile->h));
  38185. return SQLITE_OK;
  38186. #else
  38187. #if SQLITE_MAX_MMAP_SIZE>0
  38188. if( pFile->pMapRegion ){
  38189. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  38190. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  38191. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  38192. pFile, pFile->pMapRegion));
  38193. }else{
  38194. pFile->lastErrno = osGetLastError();
  38195. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  38196. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  38197. pFile, pFile->pMapRegion));
  38198. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  38199. "winSync1", pFile->zPath);
  38200. }
  38201. }
  38202. #endif
  38203. rc = osFlushFileBuffers(pFile->h);
  38204. SimulateIOError( rc=FALSE );
  38205. if( rc ){
  38206. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38207. osGetCurrentProcessId(), pFile, pFile->h));
  38208. return SQLITE_OK;
  38209. }else{
  38210. pFile->lastErrno = osGetLastError();
  38211. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  38212. osGetCurrentProcessId(), pFile, pFile->h));
  38213. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  38214. "winSync2", pFile->zPath);
  38215. }
  38216. #endif
  38217. }
  38218. /*
  38219. ** Determine the current size of a file in bytes
  38220. */
  38221. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  38222. winFile *pFile = (winFile*)id;
  38223. int rc = SQLITE_OK;
  38224. assert( id!=0 );
  38225. assert( pSize!=0 );
  38226. SimulateIOError(return SQLITE_IOERR_FSTAT);
  38227. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  38228. #if SQLITE_OS_WINRT
  38229. {
  38230. FILE_STANDARD_INFO info;
  38231. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  38232. &info, sizeof(info)) ){
  38233. *pSize = info.EndOfFile.QuadPart;
  38234. }else{
  38235. pFile->lastErrno = osGetLastError();
  38236. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  38237. "winFileSize", pFile->zPath);
  38238. }
  38239. }
  38240. #else
  38241. {
  38242. DWORD upperBits;
  38243. DWORD lowerBits;
  38244. DWORD lastErrno;
  38245. lowerBits = osGetFileSize(pFile->h, &upperBits);
  38246. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  38247. if( (lowerBits == INVALID_FILE_SIZE)
  38248. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  38249. pFile->lastErrno = lastErrno;
  38250. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  38251. "winFileSize", pFile->zPath);
  38252. }
  38253. }
  38254. #endif
  38255. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  38256. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  38257. return rc;
  38258. }
  38259. /*
  38260. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  38261. */
  38262. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  38263. # define LOCKFILE_FAIL_IMMEDIATELY 1
  38264. #endif
  38265. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  38266. # define LOCKFILE_EXCLUSIVE_LOCK 2
  38267. #endif
  38268. /*
  38269. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  38270. ** When the LockFile function was used, it was always expected to fail
  38271. ** immediately if the lock could not be obtained. Also, it always expected to
  38272. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  38273. ** and reflect those expectations; therefore, they should not be changed.
  38274. */
  38275. #ifndef SQLITE_LOCKFILE_FLAGS
  38276. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  38277. LOCKFILE_EXCLUSIVE_LOCK)
  38278. #endif
  38279. /*
  38280. ** Currently, SQLite never calls the LockFileEx function without wanting the
  38281. ** call to fail immediately if the lock cannot be obtained.
  38282. */
  38283. #ifndef SQLITE_LOCKFILEEX_FLAGS
  38284. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  38285. #endif
  38286. /*
  38287. ** Acquire a reader lock.
  38288. ** Different API routines are called depending on whether or not this
  38289. ** is Win9x or WinNT.
  38290. */
  38291. static int winGetReadLock(winFile *pFile){
  38292. int res;
  38293. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  38294. if( osIsNT() ){
  38295. #if SQLITE_OS_WINCE
  38296. /*
  38297. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  38298. ** API LockFileEx.
  38299. */
  38300. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  38301. #else
  38302. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  38303. SHARED_SIZE, 0);
  38304. #endif
  38305. }
  38306. #ifdef SQLITE_WIN32_HAS_ANSI
  38307. else{
  38308. int lk;
  38309. sqlite3_randomness(sizeof(lk), &lk);
  38310. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  38311. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  38312. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  38313. }
  38314. #endif
  38315. if( res == 0 ){
  38316. pFile->lastErrno = osGetLastError();
  38317. /* No need to log a failure to lock */
  38318. }
  38319. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  38320. return res;
  38321. }
  38322. /*
  38323. ** Undo a readlock
  38324. */
  38325. static int winUnlockReadLock(winFile *pFile){
  38326. int res;
  38327. DWORD lastErrno;
  38328. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  38329. if( osIsNT() ){
  38330. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  38331. }
  38332. #ifdef SQLITE_WIN32_HAS_ANSI
  38333. else{
  38334. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  38335. }
  38336. #endif
  38337. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  38338. pFile->lastErrno = lastErrno;
  38339. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  38340. "winUnlockReadLock", pFile->zPath);
  38341. }
  38342. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  38343. return res;
  38344. }
  38345. /*
  38346. ** Lock the file with the lock specified by parameter locktype - one
  38347. ** of the following:
  38348. **
  38349. ** (1) SHARED_LOCK
  38350. ** (2) RESERVED_LOCK
  38351. ** (3) PENDING_LOCK
  38352. ** (4) EXCLUSIVE_LOCK
  38353. **
  38354. ** Sometimes when requesting one lock state, additional lock states
  38355. ** are inserted in between. The locking might fail on one of the later
  38356. ** transitions leaving the lock state different from what it started but
  38357. ** still short of its goal. The following chart shows the allowed
  38358. ** transitions and the inserted intermediate states:
  38359. **
  38360. ** UNLOCKED -> SHARED
  38361. ** SHARED -> RESERVED
  38362. ** SHARED -> (PENDING) -> EXCLUSIVE
  38363. ** RESERVED -> (PENDING) -> EXCLUSIVE
  38364. ** PENDING -> EXCLUSIVE
  38365. **
  38366. ** This routine will only increase a lock. The winUnlock() routine
  38367. ** erases all locks at once and returns us immediately to locking level 0.
  38368. ** It is not possible to lower the locking level one step at a time. You
  38369. ** must go straight to locking level 0.
  38370. */
  38371. static int winLock(sqlite3_file *id, int locktype){
  38372. int rc = SQLITE_OK; /* Return code from subroutines */
  38373. int res = 1; /* Result of a Windows lock call */
  38374. int newLocktype; /* Set pFile->locktype to this value before exiting */
  38375. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  38376. winFile *pFile = (winFile*)id;
  38377. DWORD lastErrno = NO_ERROR;
  38378. assert( id!=0 );
  38379. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  38380. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  38381. /* If there is already a lock of this type or more restrictive on the
  38382. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  38383. ** sqlite3OsEnterMutex() hasn't been called yet.
  38384. */
  38385. if( pFile->locktype>=locktype ){
  38386. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  38387. return SQLITE_OK;
  38388. }
  38389. /* Do not allow any kind of write-lock on a read-only database
  38390. */
  38391. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  38392. return SQLITE_IOERR_LOCK;
  38393. }
  38394. /* Make sure the locking sequence is correct
  38395. */
  38396. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  38397. assert( locktype!=PENDING_LOCK );
  38398. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  38399. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  38400. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  38401. ** the PENDING_LOCK byte is temporary.
  38402. */
  38403. newLocktype = pFile->locktype;
  38404. if( pFile->locktype==NO_LOCK
  38405. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  38406. ){
  38407. int cnt = 3;
  38408. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  38409. PENDING_BYTE, 0, 1, 0))==0 ){
  38410. /* Try 3 times to get the pending lock. This is needed to work
  38411. ** around problems caused by indexing and/or anti-virus software on
  38412. ** Windows systems.
  38413. ** If you are using this code as a model for alternative VFSes, do not
  38414. ** copy this retry logic. It is a hack intended for Windows only.
  38415. */
  38416. lastErrno = osGetLastError();
  38417. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  38418. pFile->h, cnt, res));
  38419. if( lastErrno==ERROR_INVALID_HANDLE ){
  38420. pFile->lastErrno = lastErrno;
  38421. rc = SQLITE_IOERR_LOCK;
  38422. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  38423. pFile->h, cnt, sqlite3ErrName(rc)));
  38424. return rc;
  38425. }
  38426. if( cnt ) sqlite3_win32_sleep(1);
  38427. }
  38428. gotPendingLock = res;
  38429. if( !res ){
  38430. lastErrno = osGetLastError();
  38431. }
  38432. }
  38433. /* Acquire a shared lock
  38434. */
  38435. if( locktype==SHARED_LOCK && res ){
  38436. assert( pFile->locktype==NO_LOCK );
  38437. res = winGetReadLock(pFile);
  38438. if( res ){
  38439. newLocktype = SHARED_LOCK;
  38440. }else{
  38441. lastErrno = osGetLastError();
  38442. }
  38443. }
  38444. /* Acquire a RESERVED lock
  38445. */
  38446. if( locktype==RESERVED_LOCK && res ){
  38447. assert( pFile->locktype==SHARED_LOCK );
  38448. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  38449. if( res ){
  38450. newLocktype = RESERVED_LOCK;
  38451. }else{
  38452. lastErrno = osGetLastError();
  38453. }
  38454. }
  38455. /* Acquire a PENDING lock
  38456. */
  38457. if( locktype==EXCLUSIVE_LOCK && res ){
  38458. newLocktype = PENDING_LOCK;
  38459. gotPendingLock = 0;
  38460. }
  38461. /* Acquire an EXCLUSIVE lock
  38462. */
  38463. if( locktype==EXCLUSIVE_LOCK && res ){
  38464. assert( pFile->locktype>=SHARED_LOCK );
  38465. res = winUnlockReadLock(pFile);
  38466. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  38467. SHARED_SIZE, 0);
  38468. if( res ){
  38469. newLocktype = EXCLUSIVE_LOCK;
  38470. }else{
  38471. lastErrno = osGetLastError();
  38472. winGetReadLock(pFile);
  38473. }
  38474. }
  38475. /* If we are holding a PENDING lock that ought to be released, then
  38476. ** release it now.
  38477. */
  38478. if( gotPendingLock && locktype==SHARED_LOCK ){
  38479. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  38480. }
  38481. /* Update the state of the lock has held in the file descriptor then
  38482. ** return the appropriate result code.
  38483. */
  38484. if( res ){
  38485. rc = SQLITE_OK;
  38486. }else{
  38487. pFile->lastErrno = lastErrno;
  38488. rc = SQLITE_BUSY;
  38489. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  38490. pFile->h, locktype, newLocktype));
  38491. }
  38492. pFile->locktype = (u8)newLocktype;
  38493. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  38494. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  38495. return rc;
  38496. }
  38497. /*
  38498. ** This routine checks if there is a RESERVED lock held on the specified
  38499. ** file by this or any other process. If such a lock is held, return
  38500. ** non-zero, otherwise zero.
  38501. */
  38502. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  38503. int res;
  38504. winFile *pFile = (winFile*)id;
  38505. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  38506. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  38507. assert( id!=0 );
  38508. if( pFile->locktype>=RESERVED_LOCK ){
  38509. res = 1;
  38510. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  38511. }else{
  38512. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  38513. if( res ){
  38514. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  38515. }
  38516. res = !res;
  38517. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  38518. }
  38519. *pResOut = res;
  38520. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  38521. pFile->h, pResOut, *pResOut));
  38522. return SQLITE_OK;
  38523. }
  38524. /*
  38525. ** Lower the locking level on file descriptor id to locktype. locktype
  38526. ** must be either NO_LOCK or SHARED_LOCK.
  38527. **
  38528. ** If the locking level of the file descriptor is already at or below
  38529. ** the requested locking level, this routine is a no-op.
  38530. **
  38531. ** It is not possible for this routine to fail if the second argument
  38532. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  38533. ** might return SQLITE_IOERR;
  38534. */
  38535. static int winUnlock(sqlite3_file *id, int locktype){
  38536. int type;
  38537. winFile *pFile = (winFile*)id;
  38538. int rc = SQLITE_OK;
  38539. assert( pFile!=0 );
  38540. assert( locktype<=SHARED_LOCK );
  38541. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  38542. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  38543. type = pFile->locktype;
  38544. if( type>=EXCLUSIVE_LOCK ){
  38545. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  38546. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  38547. /* This should never happen. We should always be able to
  38548. ** reacquire the read lock */
  38549. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  38550. "winUnlock", pFile->zPath);
  38551. }
  38552. }
  38553. if( type>=RESERVED_LOCK ){
  38554. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  38555. }
  38556. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  38557. winUnlockReadLock(pFile);
  38558. }
  38559. if( type>=PENDING_LOCK ){
  38560. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  38561. }
  38562. pFile->locktype = (u8)locktype;
  38563. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  38564. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  38565. return rc;
  38566. }
  38567. /******************************************************************************
  38568. ****************************** No-op Locking **********************************
  38569. **
  38570. ** Of the various locking implementations available, this is by far the
  38571. ** simplest: locking is ignored. No attempt is made to lock the database
  38572. ** file for reading or writing.
  38573. **
  38574. ** This locking mode is appropriate for use on read-only databases
  38575. ** (ex: databases that are burned into CD-ROM, for example.) It can
  38576. ** also be used if the application employs some external mechanism to
  38577. ** prevent simultaneous access of the same database by two or more
  38578. ** database connections. But there is a serious risk of database
  38579. ** corruption if this locking mode is used in situations where multiple
  38580. ** database connections are accessing the same database file at the same
  38581. ** time and one or more of those connections are writing.
  38582. */
  38583. static int winNolockLock(sqlite3_file *id, int locktype){
  38584. UNUSED_PARAMETER(id);
  38585. UNUSED_PARAMETER(locktype);
  38586. return SQLITE_OK;
  38587. }
  38588. static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
  38589. UNUSED_PARAMETER(id);
  38590. UNUSED_PARAMETER(pResOut);
  38591. return SQLITE_OK;
  38592. }
  38593. static int winNolockUnlock(sqlite3_file *id, int locktype){
  38594. UNUSED_PARAMETER(id);
  38595. UNUSED_PARAMETER(locktype);
  38596. return SQLITE_OK;
  38597. }
  38598. /******************* End of the no-op lock implementation *********************
  38599. ******************************************************************************/
  38600. /*
  38601. ** If *pArg is initially negative then this is a query. Set *pArg to
  38602. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  38603. **
  38604. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  38605. */
  38606. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  38607. if( *pArg<0 ){
  38608. *pArg = (pFile->ctrlFlags & mask)!=0;
  38609. }else if( (*pArg)==0 ){
  38610. pFile->ctrlFlags &= ~mask;
  38611. }else{
  38612. pFile->ctrlFlags |= mask;
  38613. }
  38614. }
  38615. /* Forward references to VFS helper methods used for temporary files */
  38616. static int winGetTempname(sqlite3_vfs *, char **);
  38617. static int winIsDir(const void *);
  38618. static BOOL winIsDriveLetterAndColon(const char *);
  38619. /*
  38620. ** Control and query of the open file handle.
  38621. */
  38622. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  38623. winFile *pFile = (winFile*)id;
  38624. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  38625. switch( op ){
  38626. case SQLITE_FCNTL_LOCKSTATE: {
  38627. *(int*)pArg = pFile->locktype;
  38628. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38629. return SQLITE_OK;
  38630. }
  38631. case SQLITE_FCNTL_LAST_ERRNO: {
  38632. *(int*)pArg = (int)pFile->lastErrno;
  38633. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38634. return SQLITE_OK;
  38635. }
  38636. case SQLITE_FCNTL_CHUNK_SIZE: {
  38637. pFile->szChunk = *(int *)pArg;
  38638. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38639. return SQLITE_OK;
  38640. }
  38641. case SQLITE_FCNTL_SIZE_HINT: {
  38642. if( pFile->szChunk>0 ){
  38643. sqlite3_int64 oldSz;
  38644. int rc = winFileSize(id, &oldSz);
  38645. if( rc==SQLITE_OK ){
  38646. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  38647. if( newSz>oldSz ){
  38648. SimulateIOErrorBenign(1);
  38649. rc = winTruncate(id, newSz);
  38650. SimulateIOErrorBenign(0);
  38651. }
  38652. }
  38653. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  38654. return rc;
  38655. }
  38656. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38657. return SQLITE_OK;
  38658. }
  38659. case SQLITE_FCNTL_PERSIST_WAL: {
  38660. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  38661. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38662. return SQLITE_OK;
  38663. }
  38664. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  38665. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  38666. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38667. return SQLITE_OK;
  38668. }
  38669. case SQLITE_FCNTL_VFSNAME: {
  38670. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  38671. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38672. return SQLITE_OK;
  38673. }
  38674. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  38675. int *a = (int*)pArg;
  38676. if( a[0]>0 ){
  38677. winIoerrRetry = a[0];
  38678. }else{
  38679. a[0] = winIoerrRetry;
  38680. }
  38681. if( a[1]>0 ){
  38682. winIoerrRetryDelay = a[1];
  38683. }else{
  38684. a[1] = winIoerrRetryDelay;
  38685. }
  38686. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38687. return SQLITE_OK;
  38688. }
  38689. case SQLITE_FCNTL_WIN32_GET_HANDLE: {
  38690. LPHANDLE phFile = (LPHANDLE)pArg;
  38691. *phFile = pFile->h;
  38692. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38693. return SQLITE_OK;
  38694. }
  38695. #ifdef SQLITE_TEST
  38696. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  38697. LPHANDLE phFile = (LPHANDLE)pArg;
  38698. HANDLE hOldFile = pFile->h;
  38699. pFile->h = *phFile;
  38700. *phFile = hOldFile;
  38701. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  38702. hOldFile, pFile->h));
  38703. return SQLITE_OK;
  38704. }
  38705. #endif
  38706. case SQLITE_FCNTL_TEMPFILENAME: {
  38707. char *zTFile = 0;
  38708. int rc = winGetTempname(pFile->pVfs, &zTFile);
  38709. if( rc==SQLITE_OK ){
  38710. *(char**)pArg = zTFile;
  38711. }
  38712. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  38713. return rc;
  38714. }
  38715. #if SQLITE_MAX_MMAP_SIZE>0
  38716. case SQLITE_FCNTL_MMAP_SIZE: {
  38717. i64 newLimit = *(i64*)pArg;
  38718. int rc = SQLITE_OK;
  38719. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  38720. newLimit = sqlite3GlobalConfig.mxMmap;
  38721. }
  38722. *(i64*)pArg = pFile->mmapSizeMax;
  38723. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  38724. pFile->mmapSizeMax = newLimit;
  38725. if( pFile->mmapSize>0 ){
  38726. winUnmapfile(pFile);
  38727. rc = winMapfile(pFile, -1);
  38728. }
  38729. }
  38730. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  38731. return rc;
  38732. }
  38733. #endif
  38734. }
  38735. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  38736. return SQLITE_NOTFOUND;
  38737. }
  38738. /*
  38739. ** Return the sector size in bytes of the underlying block device for
  38740. ** the specified file. This is almost always 512 bytes, but may be
  38741. ** larger for some devices.
  38742. **
  38743. ** SQLite code assumes this function cannot fail. It also assumes that
  38744. ** if two files are created in the same file-system directory (i.e.
  38745. ** a database and its journal file) that the sector size will be the
  38746. ** same for both.
  38747. */
  38748. static int winSectorSize(sqlite3_file *id){
  38749. (void)id;
  38750. return SQLITE_DEFAULT_SECTOR_SIZE;
  38751. }
  38752. /*
  38753. ** Return a vector of device characteristics.
  38754. */
  38755. static int winDeviceCharacteristics(sqlite3_file *id){
  38756. winFile *p = (winFile*)id;
  38757. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  38758. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  38759. }
  38760. /*
  38761. ** Windows will only let you create file view mappings
  38762. ** on allocation size granularity boundaries.
  38763. ** During sqlite3_os_init() we do a GetSystemInfo()
  38764. ** to get the granularity size.
  38765. */
  38766. static SYSTEM_INFO winSysInfo;
  38767. #ifndef SQLITE_OMIT_WAL
  38768. /*
  38769. ** Helper functions to obtain and relinquish the global mutex. The
  38770. ** global mutex is used to protect the winLockInfo objects used by
  38771. ** this file, all of which may be shared by multiple threads.
  38772. **
  38773. ** Function winShmMutexHeld() is used to assert() that the global mutex
  38774. ** is held when required. This function is only used as part of assert()
  38775. ** statements. e.g.
  38776. **
  38777. ** winShmEnterMutex()
  38778. ** assert( winShmMutexHeld() );
  38779. ** winShmLeaveMutex()
  38780. */
  38781. static void winShmEnterMutex(void){
  38782. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  38783. }
  38784. static void winShmLeaveMutex(void){
  38785. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  38786. }
  38787. #ifndef NDEBUG
  38788. static int winShmMutexHeld(void) {
  38789. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  38790. }
  38791. #endif
  38792. /*
  38793. ** Object used to represent a single file opened and mmapped to provide
  38794. ** shared memory. When multiple threads all reference the same
  38795. ** log-summary, each thread has its own winFile object, but they all
  38796. ** point to a single instance of this object. In other words, each
  38797. ** log-summary is opened only once per process.
  38798. **
  38799. ** winShmMutexHeld() must be true when creating or destroying
  38800. ** this object or while reading or writing the following fields:
  38801. **
  38802. ** nRef
  38803. ** pNext
  38804. **
  38805. ** The following fields are read-only after the object is created:
  38806. **
  38807. ** fid
  38808. ** zFilename
  38809. **
  38810. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  38811. ** winShmMutexHeld() is true when reading or writing any other field
  38812. ** in this structure.
  38813. **
  38814. */
  38815. struct winShmNode {
  38816. sqlite3_mutex *mutex; /* Mutex to access this object */
  38817. char *zFilename; /* Name of the file */
  38818. winFile hFile; /* File handle from winOpen */
  38819. int szRegion; /* Size of shared-memory regions */
  38820. int nRegion; /* Size of array apRegion */
  38821. struct ShmRegion {
  38822. HANDLE hMap; /* File handle from CreateFileMapping */
  38823. void *pMap;
  38824. } *aRegion;
  38825. DWORD lastErrno; /* The Windows errno from the last I/O error */
  38826. int nRef; /* Number of winShm objects pointing to this */
  38827. winShm *pFirst; /* All winShm objects pointing to this */
  38828. winShmNode *pNext; /* Next in list of all winShmNode objects */
  38829. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  38830. u8 nextShmId; /* Next available winShm.id value */
  38831. #endif
  38832. };
  38833. /*
  38834. ** A global array of all winShmNode objects.
  38835. **
  38836. ** The winShmMutexHeld() must be true while reading or writing this list.
  38837. */
  38838. static winShmNode *winShmNodeList = 0;
  38839. /*
  38840. ** Structure used internally by this VFS to record the state of an
  38841. ** open shared memory connection.
  38842. **
  38843. ** The following fields are initialized when this object is created and
  38844. ** are read-only thereafter:
  38845. **
  38846. ** winShm.pShmNode
  38847. ** winShm.id
  38848. **
  38849. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  38850. ** while accessing any read/write fields.
  38851. */
  38852. struct winShm {
  38853. winShmNode *pShmNode; /* The underlying winShmNode object */
  38854. winShm *pNext; /* Next winShm with the same winShmNode */
  38855. u8 hasMutex; /* True if holding the winShmNode mutex */
  38856. u16 sharedMask; /* Mask of shared locks held */
  38857. u16 exclMask; /* Mask of exclusive locks held */
  38858. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  38859. u8 id; /* Id of this connection with its winShmNode */
  38860. #endif
  38861. };
  38862. /*
  38863. ** Constants used for locking
  38864. */
  38865. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  38866. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  38867. /*
  38868. ** Apply advisory locks for all n bytes beginning at ofst.
  38869. */
  38870. #define WINSHM_UNLCK 1
  38871. #define WINSHM_RDLCK 2
  38872. #define WINSHM_WRLCK 3
  38873. static int winShmSystemLock(
  38874. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  38875. int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  38876. int ofst, /* Offset to first byte to be locked/unlocked */
  38877. int nByte /* Number of bytes to lock or unlock */
  38878. ){
  38879. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  38880. /* Access to the winShmNode object is serialized by the caller */
  38881. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  38882. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  38883. pFile->hFile.h, lockType, ofst, nByte));
  38884. /* Release/Acquire the system-level lock */
  38885. if( lockType==WINSHM_UNLCK ){
  38886. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  38887. }else{
  38888. /* Initialize the locking parameters */
  38889. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  38890. if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  38891. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  38892. }
  38893. if( rc!= 0 ){
  38894. rc = SQLITE_OK;
  38895. }else{
  38896. pFile->lastErrno = osGetLastError();
  38897. rc = SQLITE_BUSY;
  38898. }
  38899. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  38900. pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
  38901. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  38902. return rc;
  38903. }
  38904. /* Forward references to VFS methods */
  38905. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  38906. static int winDelete(sqlite3_vfs *,const char*,int);
  38907. /*
  38908. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  38909. **
  38910. ** This is not a VFS shared-memory method; it is a utility function called
  38911. ** by VFS shared-memory methods.
  38912. */
  38913. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  38914. winShmNode **pp;
  38915. winShmNode *p;
  38916. assert( winShmMutexHeld() );
  38917. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  38918. osGetCurrentProcessId(), deleteFlag));
  38919. pp = &winShmNodeList;
  38920. while( (p = *pp)!=0 ){
  38921. if( p->nRef==0 ){
  38922. int i;
  38923. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  38924. for(i=0; i<p->nRegion; i++){
  38925. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  38926. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  38927. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  38928. UNUSED_VARIABLE_VALUE(bRc);
  38929. bRc = osCloseHandle(p->aRegion[i].hMap);
  38930. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  38931. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  38932. UNUSED_VARIABLE_VALUE(bRc);
  38933. }
  38934. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  38935. SimulateIOErrorBenign(1);
  38936. winClose((sqlite3_file *)&p->hFile);
  38937. SimulateIOErrorBenign(0);
  38938. }
  38939. if( deleteFlag ){
  38940. SimulateIOErrorBenign(1);
  38941. sqlite3BeginBenignMalloc();
  38942. winDelete(pVfs, p->zFilename, 0);
  38943. sqlite3EndBenignMalloc();
  38944. SimulateIOErrorBenign(0);
  38945. }
  38946. *pp = p->pNext;
  38947. sqlite3_free(p->aRegion);
  38948. sqlite3_free(p);
  38949. }else{
  38950. pp = &p->pNext;
  38951. }
  38952. }
  38953. }
  38954. /*
  38955. ** Open the shared-memory area associated with database file pDbFd.
  38956. **
  38957. ** When opening a new shared-memory file, if no other instances of that
  38958. ** file are currently open, in this process or in other processes, then
  38959. ** the file must be truncated to zero length or have its header cleared.
  38960. */
  38961. static int winOpenSharedMemory(winFile *pDbFd){
  38962. struct winShm *p; /* The connection to be opened */
  38963. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  38964. int rc; /* Result code */
  38965. struct winShmNode *pNew; /* Newly allocated winShmNode */
  38966. int nName; /* Size of zName in bytes */
  38967. assert( pDbFd->pShm==0 ); /* Not previously opened */
  38968. /* Allocate space for the new sqlite3_shm object. Also speculatively
  38969. ** allocate space for a new winShmNode and filename.
  38970. */
  38971. p = sqlite3MallocZero( sizeof(*p) );
  38972. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  38973. nName = sqlite3Strlen30(pDbFd->zPath);
  38974. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  38975. if( pNew==0 ){
  38976. sqlite3_free(p);
  38977. return SQLITE_IOERR_NOMEM_BKPT;
  38978. }
  38979. pNew->zFilename = (char*)&pNew[1];
  38980. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  38981. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  38982. /* Look to see if there is an existing winShmNode that can be used.
  38983. ** If no matching winShmNode currently exists, create a new one.
  38984. */
  38985. winShmEnterMutex();
  38986. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  38987. /* TBD need to come up with better match here. Perhaps
  38988. ** use FILE_ID_BOTH_DIR_INFO Structure.
  38989. */
  38990. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  38991. }
  38992. if( pShmNode ){
  38993. sqlite3_free(pNew);
  38994. }else{
  38995. pShmNode = pNew;
  38996. pNew = 0;
  38997. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  38998. pShmNode->pNext = winShmNodeList;
  38999. winShmNodeList = pShmNode;
  39000. if( sqlite3GlobalConfig.bCoreMutex ){
  39001. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  39002. if( pShmNode->mutex==0 ){
  39003. rc = SQLITE_IOERR_NOMEM_BKPT;
  39004. goto shm_open_err;
  39005. }
  39006. }
  39007. rc = winOpen(pDbFd->pVfs,
  39008. pShmNode->zFilename, /* Name of the file (UTF-8) */
  39009. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  39010. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  39011. 0);
  39012. if( SQLITE_OK!=rc ){
  39013. goto shm_open_err;
  39014. }
  39015. /* Check to see if another process is holding the dead-man switch.
  39016. ** If not, truncate the file to zero length.
  39017. */
  39018. if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  39019. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  39020. if( rc!=SQLITE_OK ){
  39021. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  39022. "winOpenShm", pDbFd->zPath);
  39023. }
  39024. }
  39025. if( rc==SQLITE_OK ){
  39026. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  39027. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
  39028. }
  39029. if( rc ) goto shm_open_err;
  39030. }
  39031. /* Make the new connection a child of the winShmNode */
  39032. p->pShmNode = pShmNode;
  39033. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  39034. p->id = pShmNode->nextShmId++;
  39035. #endif
  39036. pShmNode->nRef++;
  39037. pDbFd->pShm = p;
  39038. winShmLeaveMutex();
  39039. /* The reference count on pShmNode has already been incremented under
  39040. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  39041. ** new (struct winShm) object to the pShmNode has been set. All that is
  39042. ** left to do is to link the new object into the linked list starting
  39043. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  39044. ** mutex.
  39045. */
  39046. sqlite3_mutex_enter(pShmNode->mutex);
  39047. p->pNext = pShmNode->pFirst;
  39048. pShmNode->pFirst = p;
  39049. sqlite3_mutex_leave(pShmNode->mutex);
  39050. return SQLITE_OK;
  39051. /* Jump here on any error */
  39052. shm_open_err:
  39053. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  39054. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  39055. sqlite3_free(p);
  39056. sqlite3_free(pNew);
  39057. winShmLeaveMutex();
  39058. return rc;
  39059. }
  39060. /*
  39061. ** Close a connection to shared-memory. Delete the underlying
  39062. ** storage if deleteFlag is true.
  39063. */
  39064. static int winShmUnmap(
  39065. sqlite3_file *fd, /* Database holding shared memory */
  39066. int deleteFlag /* Delete after closing if true */
  39067. ){
  39068. winFile *pDbFd; /* Database holding shared-memory */
  39069. winShm *p; /* The connection to be closed */
  39070. winShmNode *pShmNode; /* The underlying shared-memory file */
  39071. winShm **pp; /* For looping over sibling connections */
  39072. pDbFd = (winFile*)fd;
  39073. p = pDbFd->pShm;
  39074. if( p==0 ) return SQLITE_OK;
  39075. pShmNode = p->pShmNode;
  39076. /* Remove connection p from the set of connections associated
  39077. ** with pShmNode */
  39078. sqlite3_mutex_enter(pShmNode->mutex);
  39079. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  39080. *pp = p->pNext;
  39081. /* Free the connection p */
  39082. sqlite3_free(p);
  39083. pDbFd->pShm = 0;
  39084. sqlite3_mutex_leave(pShmNode->mutex);
  39085. /* If pShmNode->nRef has reached 0, then close the underlying
  39086. ** shared-memory file, too */
  39087. winShmEnterMutex();
  39088. assert( pShmNode->nRef>0 );
  39089. pShmNode->nRef--;
  39090. if( pShmNode->nRef==0 ){
  39091. winShmPurge(pDbFd->pVfs, deleteFlag);
  39092. }
  39093. winShmLeaveMutex();
  39094. return SQLITE_OK;
  39095. }
  39096. /*
  39097. ** Change the lock state for a shared-memory segment.
  39098. */
  39099. static int winShmLock(
  39100. sqlite3_file *fd, /* Database file holding the shared memory */
  39101. int ofst, /* First lock to acquire or release */
  39102. int n, /* Number of locks to acquire or release */
  39103. int flags /* What to do with the lock */
  39104. ){
  39105. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  39106. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  39107. winShm *pX; /* For looping over all siblings */
  39108. winShmNode *pShmNode = p->pShmNode;
  39109. int rc = SQLITE_OK; /* Result code */
  39110. u16 mask; /* Mask of locks to take or release */
  39111. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  39112. assert( n>=1 );
  39113. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  39114. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  39115. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  39116. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  39117. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  39118. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  39119. assert( n>1 || mask==(1<<ofst) );
  39120. sqlite3_mutex_enter(pShmNode->mutex);
  39121. if( flags & SQLITE_SHM_UNLOCK ){
  39122. u16 allMask = 0; /* Mask of locks held by siblings */
  39123. /* See if any siblings hold this same lock */
  39124. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  39125. if( pX==p ) continue;
  39126. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  39127. allMask |= pX->sharedMask;
  39128. }
  39129. /* Unlock the system-level locks */
  39130. if( (mask & allMask)==0 ){
  39131. rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
  39132. }else{
  39133. rc = SQLITE_OK;
  39134. }
  39135. /* Undo the local locks */
  39136. if( rc==SQLITE_OK ){
  39137. p->exclMask &= ~mask;
  39138. p->sharedMask &= ~mask;
  39139. }
  39140. }else if( flags & SQLITE_SHM_SHARED ){
  39141. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  39142. /* Find out which shared locks are already held by sibling connections.
  39143. ** If any sibling already holds an exclusive lock, go ahead and return
  39144. ** SQLITE_BUSY.
  39145. */
  39146. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  39147. if( (pX->exclMask & mask)!=0 ){
  39148. rc = SQLITE_BUSY;
  39149. break;
  39150. }
  39151. allShared |= pX->sharedMask;
  39152. }
  39153. /* Get shared locks at the system level, if necessary */
  39154. if( rc==SQLITE_OK ){
  39155. if( (allShared & mask)==0 ){
  39156. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
  39157. }else{
  39158. rc = SQLITE_OK;
  39159. }
  39160. }
  39161. /* Get the local shared locks */
  39162. if( rc==SQLITE_OK ){
  39163. p->sharedMask |= mask;
  39164. }
  39165. }else{
  39166. /* Make sure no sibling connections hold locks that will block this
  39167. ** lock. If any do, return SQLITE_BUSY right away.
  39168. */
  39169. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  39170. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  39171. rc = SQLITE_BUSY;
  39172. break;
  39173. }
  39174. }
  39175. /* Get the exclusive locks at the system level. Then if successful
  39176. ** also mark the local connection as being locked.
  39177. */
  39178. if( rc==SQLITE_OK ){
  39179. rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
  39180. if( rc==SQLITE_OK ){
  39181. assert( (p->sharedMask & mask)==0 );
  39182. p->exclMask |= mask;
  39183. }
  39184. }
  39185. }
  39186. sqlite3_mutex_leave(pShmNode->mutex);
  39187. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  39188. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  39189. sqlite3ErrName(rc)));
  39190. return rc;
  39191. }
  39192. /*
  39193. ** Implement a memory barrier or memory fence on shared memory.
  39194. **
  39195. ** All loads and stores begun before the barrier must complete before
  39196. ** any load or store begun after the barrier.
  39197. */
  39198. static void winShmBarrier(
  39199. sqlite3_file *fd /* Database holding the shared memory */
  39200. ){
  39201. UNUSED_PARAMETER(fd);
  39202. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  39203. winShmEnterMutex(); /* Also mutex, for redundancy */
  39204. winShmLeaveMutex();
  39205. }
  39206. /*
  39207. ** This function is called to obtain a pointer to region iRegion of the
  39208. ** shared-memory associated with the database file fd. Shared-memory regions
  39209. ** are numbered starting from zero. Each shared-memory region is szRegion
  39210. ** bytes in size.
  39211. **
  39212. ** If an error occurs, an error code is returned and *pp is set to NULL.
  39213. **
  39214. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  39215. ** region has not been allocated (by any client, including one running in a
  39216. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  39217. ** isWrite is non-zero and the requested shared-memory region has not yet
  39218. ** been allocated, it is allocated by this function.
  39219. **
  39220. ** If the shared-memory region has already been allocated or is allocated by
  39221. ** this call as described above, then it is mapped into this processes
  39222. ** address space (if it is not already), *pp is set to point to the mapped
  39223. ** memory and SQLITE_OK returned.
  39224. */
  39225. static int winShmMap(
  39226. sqlite3_file *fd, /* Handle open on database file */
  39227. int iRegion, /* Region to retrieve */
  39228. int szRegion, /* Size of regions */
  39229. int isWrite, /* True to extend file if necessary */
  39230. void volatile **pp /* OUT: Mapped memory */
  39231. ){
  39232. winFile *pDbFd = (winFile*)fd;
  39233. winShm *pShm = pDbFd->pShm;
  39234. winShmNode *pShmNode;
  39235. int rc = SQLITE_OK;
  39236. if( !pShm ){
  39237. rc = winOpenSharedMemory(pDbFd);
  39238. if( rc!=SQLITE_OK ) return rc;
  39239. pShm = pDbFd->pShm;
  39240. }
  39241. pShmNode = pShm->pShmNode;
  39242. sqlite3_mutex_enter(pShmNode->mutex);
  39243. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  39244. if( pShmNode->nRegion<=iRegion ){
  39245. struct ShmRegion *apNew; /* New aRegion[] array */
  39246. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  39247. sqlite3_int64 sz; /* Current size of wal-index file */
  39248. pShmNode->szRegion = szRegion;
  39249. /* The requested region is not mapped into this processes address space.
  39250. ** Check to see if it has been allocated (i.e. if the wal-index file is
  39251. ** large enough to contain the requested region).
  39252. */
  39253. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  39254. if( rc!=SQLITE_OK ){
  39255. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  39256. "winShmMap1", pDbFd->zPath);
  39257. goto shmpage_out;
  39258. }
  39259. if( sz<nByte ){
  39260. /* The requested memory region does not exist. If isWrite is set to
  39261. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  39262. **
  39263. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  39264. ** the requested memory region.
  39265. */
  39266. if( !isWrite ) goto shmpage_out;
  39267. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  39268. if( rc!=SQLITE_OK ){
  39269. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  39270. "winShmMap2", pDbFd->zPath);
  39271. goto shmpage_out;
  39272. }
  39273. }
  39274. /* Map the requested memory region into this processes address space. */
  39275. apNew = (struct ShmRegion *)sqlite3_realloc64(
  39276. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  39277. );
  39278. if( !apNew ){
  39279. rc = SQLITE_IOERR_NOMEM_BKPT;
  39280. goto shmpage_out;
  39281. }
  39282. pShmNode->aRegion = apNew;
  39283. while( pShmNode->nRegion<=iRegion ){
  39284. HANDLE hMap = NULL; /* file-mapping handle */
  39285. void *pMap = 0; /* Mapped memory region */
  39286. #if SQLITE_OS_WINRT
  39287. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  39288. NULL, PAGE_READWRITE, nByte, NULL
  39289. );
  39290. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39291. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  39292. NULL, PAGE_READWRITE, 0, nByte, NULL
  39293. );
  39294. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  39295. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  39296. NULL, PAGE_READWRITE, 0, nByte, NULL
  39297. );
  39298. #endif
  39299. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  39300. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  39301. hMap ? "ok" : "failed"));
  39302. if( hMap ){
  39303. int iOffset = pShmNode->nRegion*szRegion;
  39304. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  39305. #if SQLITE_OS_WINRT
  39306. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  39307. iOffset - iOffsetShift, szRegion + iOffsetShift
  39308. );
  39309. #else
  39310. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  39311. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  39312. );
  39313. #endif
  39314. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  39315. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  39316. szRegion, pMap ? "ok" : "failed"));
  39317. }
  39318. if( !pMap ){
  39319. pShmNode->lastErrno = osGetLastError();
  39320. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  39321. "winShmMap3", pDbFd->zPath);
  39322. if( hMap ) osCloseHandle(hMap);
  39323. goto shmpage_out;
  39324. }
  39325. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  39326. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  39327. pShmNode->nRegion++;
  39328. }
  39329. }
  39330. shmpage_out:
  39331. if( pShmNode->nRegion>iRegion ){
  39332. int iOffset = iRegion*szRegion;
  39333. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  39334. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  39335. *pp = (void *)&p[iOffsetShift];
  39336. }else{
  39337. *pp = 0;
  39338. }
  39339. sqlite3_mutex_leave(pShmNode->mutex);
  39340. return rc;
  39341. }
  39342. #else
  39343. # define winShmMap 0
  39344. # define winShmLock 0
  39345. # define winShmBarrier 0
  39346. # define winShmUnmap 0
  39347. #endif /* #ifndef SQLITE_OMIT_WAL */
  39348. /*
  39349. ** Cleans up the mapped region of the specified file, if any.
  39350. */
  39351. #if SQLITE_MAX_MMAP_SIZE>0
  39352. static int winUnmapfile(winFile *pFile){
  39353. assert( pFile!=0 );
  39354. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  39355. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  39356. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  39357. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  39358. if( pFile->pMapRegion ){
  39359. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  39360. pFile->lastErrno = osGetLastError();
  39361. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  39362. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  39363. pFile->pMapRegion));
  39364. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  39365. "winUnmapfile1", pFile->zPath);
  39366. }
  39367. pFile->pMapRegion = 0;
  39368. pFile->mmapSize = 0;
  39369. pFile->mmapSizeActual = 0;
  39370. }
  39371. if( pFile->hMap!=NULL ){
  39372. if( !osCloseHandle(pFile->hMap) ){
  39373. pFile->lastErrno = osGetLastError();
  39374. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  39375. osGetCurrentProcessId(), pFile, pFile->hMap));
  39376. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  39377. "winUnmapfile2", pFile->zPath);
  39378. }
  39379. pFile->hMap = NULL;
  39380. }
  39381. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  39382. osGetCurrentProcessId(), pFile));
  39383. return SQLITE_OK;
  39384. }
  39385. /*
  39386. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  39387. ** is already mapped, the existing mapping is replaced by the new). Or, if
  39388. ** there already exists a mapping for this file, and there are still
  39389. ** outstanding xFetch() references to it, this function is a no-op.
  39390. **
  39391. ** If parameter nByte is non-negative, then it is the requested size of
  39392. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  39393. ** requested size is the size of the file on disk. The actual size of the
  39394. ** created mapping is either the requested size or the value configured
  39395. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  39396. **
  39397. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  39398. ** recreated as a result of outstanding references) or an SQLite error
  39399. ** code otherwise.
  39400. */
  39401. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  39402. sqlite3_int64 nMap = nByte;
  39403. int rc;
  39404. assert( nMap>=0 || pFd->nFetchOut==0 );
  39405. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  39406. osGetCurrentProcessId(), pFd, nByte));
  39407. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  39408. if( nMap<0 ){
  39409. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  39410. if( rc ){
  39411. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  39412. osGetCurrentProcessId(), pFd));
  39413. return SQLITE_IOERR_FSTAT;
  39414. }
  39415. }
  39416. if( nMap>pFd->mmapSizeMax ){
  39417. nMap = pFd->mmapSizeMax;
  39418. }
  39419. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  39420. if( nMap==0 && pFd->mmapSize>0 ){
  39421. winUnmapfile(pFd);
  39422. }
  39423. if( nMap!=pFd->mmapSize ){
  39424. void *pNew = 0;
  39425. DWORD protect = PAGE_READONLY;
  39426. DWORD flags = FILE_MAP_READ;
  39427. winUnmapfile(pFd);
  39428. #ifdef SQLITE_MMAP_READWRITE
  39429. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  39430. protect = PAGE_READWRITE;
  39431. flags |= FILE_MAP_WRITE;
  39432. }
  39433. #endif
  39434. #if SQLITE_OS_WINRT
  39435. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  39436. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39437. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  39438. (DWORD)((nMap>>32) & 0xffffffff),
  39439. (DWORD)(nMap & 0xffffffff), NULL);
  39440. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  39441. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  39442. (DWORD)((nMap>>32) & 0xffffffff),
  39443. (DWORD)(nMap & 0xffffffff), NULL);
  39444. #endif
  39445. if( pFd->hMap==NULL ){
  39446. pFd->lastErrno = osGetLastError();
  39447. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  39448. "winMapfile1", pFd->zPath);
  39449. /* Log the error, but continue normal operation using xRead/xWrite */
  39450. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  39451. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  39452. return SQLITE_OK;
  39453. }
  39454. assert( (nMap % winSysInfo.dwPageSize)==0 );
  39455. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  39456. #if SQLITE_OS_WINRT
  39457. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  39458. #else
  39459. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  39460. #endif
  39461. if( pNew==NULL ){
  39462. osCloseHandle(pFd->hMap);
  39463. pFd->hMap = NULL;
  39464. pFd->lastErrno = osGetLastError();
  39465. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  39466. "winMapfile2", pFd->zPath);
  39467. /* Log the error, but continue normal operation using xRead/xWrite */
  39468. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  39469. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  39470. return SQLITE_OK;
  39471. }
  39472. pFd->pMapRegion = pNew;
  39473. pFd->mmapSize = nMap;
  39474. pFd->mmapSizeActual = nMap;
  39475. }
  39476. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  39477. osGetCurrentProcessId(), pFd));
  39478. return SQLITE_OK;
  39479. }
  39480. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  39481. /*
  39482. ** If possible, return a pointer to a mapping of file fd starting at offset
  39483. ** iOff. The mapping must be valid for at least nAmt bytes.
  39484. **
  39485. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  39486. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  39487. ** Finally, if an error does occur, return an SQLite error code. The final
  39488. ** value of *pp is undefined in this case.
  39489. **
  39490. ** If this function does return a pointer, the caller must eventually
  39491. ** release the reference by calling winUnfetch().
  39492. */
  39493. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  39494. #if SQLITE_MAX_MMAP_SIZE>0
  39495. winFile *pFd = (winFile*)fd; /* The underlying database file */
  39496. #endif
  39497. *pp = 0;
  39498. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  39499. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  39500. #if SQLITE_MAX_MMAP_SIZE>0
  39501. if( pFd->mmapSizeMax>0 ){
  39502. if( pFd->pMapRegion==0 ){
  39503. int rc = winMapfile(pFd, -1);
  39504. if( rc!=SQLITE_OK ){
  39505. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  39506. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  39507. return rc;
  39508. }
  39509. }
  39510. if( pFd->mmapSize >= iOff+nAmt ){
  39511. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  39512. pFd->nFetchOut++;
  39513. }
  39514. }
  39515. #endif
  39516. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  39517. osGetCurrentProcessId(), fd, pp, *pp));
  39518. return SQLITE_OK;
  39519. }
  39520. /*
  39521. ** If the third argument is non-NULL, then this function releases a
  39522. ** reference obtained by an earlier call to winFetch(). The second
  39523. ** argument passed to this function must be the same as the corresponding
  39524. ** argument that was passed to the winFetch() invocation.
  39525. **
  39526. ** Or, if the third argument is NULL, then this function is being called
  39527. ** to inform the VFS layer that, according to POSIX, any existing mapping
  39528. ** may now be invalid and should be unmapped.
  39529. */
  39530. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  39531. #if SQLITE_MAX_MMAP_SIZE>0
  39532. winFile *pFd = (winFile*)fd; /* The underlying database file */
  39533. /* If p==0 (unmap the entire file) then there must be no outstanding
  39534. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  39535. ** then there must be at least one outstanding. */
  39536. assert( (p==0)==(pFd->nFetchOut==0) );
  39537. /* If p!=0, it must match the iOff value. */
  39538. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  39539. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  39540. osGetCurrentProcessId(), pFd, iOff, p));
  39541. if( p ){
  39542. pFd->nFetchOut--;
  39543. }else{
  39544. /* FIXME: If Windows truly always prevents truncating or deleting a
  39545. ** file while a mapping is held, then the following winUnmapfile() call
  39546. ** is unnecessary can be omitted - potentially improving
  39547. ** performance. */
  39548. winUnmapfile(pFd);
  39549. }
  39550. assert( pFd->nFetchOut>=0 );
  39551. #endif
  39552. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  39553. osGetCurrentProcessId(), fd));
  39554. return SQLITE_OK;
  39555. }
  39556. /*
  39557. ** Here ends the implementation of all sqlite3_file methods.
  39558. **
  39559. ********************** End sqlite3_file Methods *******************************
  39560. ******************************************************************************/
  39561. /*
  39562. ** This vector defines all the methods that can operate on an
  39563. ** sqlite3_file for win32.
  39564. */
  39565. static const sqlite3_io_methods winIoMethod = {
  39566. 3, /* iVersion */
  39567. winClose, /* xClose */
  39568. winRead, /* xRead */
  39569. winWrite, /* xWrite */
  39570. winTruncate, /* xTruncate */
  39571. winSync, /* xSync */
  39572. winFileSize, /* xFileSize */
  39573. winLock, /* xLock */
  39574. winUnlock, /* xUnlock */
  39575. winCheckReservedLock, /* xCheckReservedLock */
  39576. winFileControl, /* xFileControl */
  39577. winSectorSize, /* xSectorSize */
  39578. winDeviceCharacteristics, /* xDeviceCharacteristics */
  39579. winShmMap, /* xShmMap */
  39580. winShmLock, /* xShmLock */
  39581. winShmBarrier, /* xShmBarrier */
  39582. winShmUnmap, /* xShmUnmap */
  39583. winFetch, /* xFetch */
  39584. winUnfetch /* xUnfetch */
  39585. };
  39586. /*
  39587. ** This vector defines all the methods that can operate on an
  39588. ** sqlite3_file for win32 without performing any locking.
  39589. */
  39590. static const sqlite3_io_methods winIoNolockMethod = {
  39591. 3, /* iVersion */
  39592. winClose, /* xClose */
  39593. winRead, /* xRead */
  39594. winWrite, /* xWrite */
  39595. winTruncate, /* xTruncate */
  39596. winSync, /* xSync */
  39597. winFileSize, /* xFileSize */
  39598. winNolockLock, /* xLock */
  39599. winNolockUnlock, /* xUnlock */
  39600. winNolockCheckReservedLock, /* 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. static winVfsAppData winAppData = {
  39612. &winIoMethod, /* pMethod */
  39613. 0, /* pAppData */
  39614. 0 /* bNoLock */
  39615. };
  39616. static winVfsAppData winNolockAppData = {
  39617. &winIoNolockMethod, /* pMethod */
  39618. 0, /* pAppData */
  39619. 1 /* bNoLock */
  39620. };
  39621. /****************************************************************************
  39622. **************************** sqlite3_vfs methods ****************************
  39623. **
  39624. ** This division contains the implementation of methods on the
  39625. ** sqlite3_vfs object.
  39626. */
  39627. #if defined(__CYGWIN__)
  39628. /*
  39629. ** Convert a filename from whatever the underlying operating system
  39630. ** supports for filenames into UTF-8. Space to hold the result is
  39631. ** obtained from malloc and must be freed by the calling function.
  39632. */
  39633. static char *winConvertToUtf8Filename(const void *zFilename){
  39634. char *zConverted = 0;
  39635. if( osIsNT() ){
  39636. zConverted = winUnicodeToUtf8(zFilename);
  39637. }
  39638. #ifdef SQLITE_WIN32_HAS_ANSI
  39639. else{
  39640. zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
  39641. }
  39642. #endif
  39643. /* caller will handle out of memory */
  39644. return zConverted;
  39645. }
  39646. #endif
  39647. /*
  39648. ** Convert a UTF-8 filename into whatever form the underlying
  39649. ** operating system wants filenames in. Space to hold the result
  39650. ** is obtained from malloc and must be freed by the calling
  39651. ** function.
  39652. */
  39653. static void *winConvertFromUtf8Filename(const char *zFilename){
  39654. void *zConverted = 0;
  39655. if( osIsNT() ){
  39656. zConverted = winUtf8ToUnicode(zFilename);
  39657. }
  39658. #ifdef SQLITE_WIN32_HAS_ANSI
  39659. else{
  39660. zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  39661. }
  39662. #endif
  39663. /* caller will handle out of memory */
  39664. return zConverted;
  39665. }
  39666. /*
  39667. ** This function returns non-zero if the specified UTF-8 string buffer
  39668. ** ends with a directory separator character or one was successfully
  39669. ** added to it.
  39670. */
  39671. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  39672. if( zBuf ){
  39673. int nLen = sqlite3Strlen30(zBuf);
  39674. if( nLen>0 ){
  39675. if( winIsDirSep(zBuf[nLen-1]) ){
  39676. return 1;
  39677. }else if( nLen+1<nBuf ){
  39678. zBuf[nLen] = winGetDirSep();
  39679. zBuf[nLen+1] = '\0';
  39680. return 1;
  39681. }
  39682. }
  39683. }
  39684. return 0;
  39685. }
  39686. /*
  39687. ** Create a temporary file name and store the resulting pointer into pzBuf.
  39688. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  39689. */
  39690. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  39691. static char zChars[] =
  39692. "abcdefghijklmnopqrstuvwxyz"
  39693. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  39694. "0123456789";
  39695. size_t i, j;
  39696. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  39697. int nMax, nBuf, nDir, nLen;
  39698. char *zBuf;
  39699. /* It's odd to simulate an io-error here, but really this is just
  39700. ** using the io-error infrastructure to test that SQLite handles this
  39701. ** function failing.
  39702. */
  39703. SimulateIOError( return SQLITE_IOERR );
  39704. /* Allocate a temporary buffer to store the fully qualified file
  39705. ** name for the temporary file. If this fails, we cannot continue.
  39706. */
  39707. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  39708. zBuf = sqlite3MallocZero( nBuf );
  39709. if( !zBuf ){
  39710. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39711. return SQLITE_IOERR_NOMEM_BKPT;
  39712. }
  39713. /* Figure out the effective temporary directory. First, check if one
  39714. ** has been explicitly set by the application; otherwise, use the one
  39715. ** configured by the operating system.
  39716. */
  39717. nDir = nMax - (nPre + 15);
  39718. assert( nDir>0 );
  39719. if( sqlite3_temp_directory ){
  39720. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  39721. if( nDirLen>0 ){
  39722. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  39723. nDirLen++;
  39724. }
  39725. if( nDirLen>nDir ){
  39726. sqlite3_free(zBuf);
  39727. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  39728. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  39729. }
  39730. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  39731. }
  39732. }
  39733. #if defined(__CYGWIN__)
  39734. else{
  39735. static const char *azDirs[] = {
  39736. 0, /* getenv("SQLITE_TMPDIR") */
  39737. 0, /* getenv("TMPDIR") */
  39738. 0, /* getenv("TMP") */
  39739. 0, /* getenv("TEMP") */
  39740. 0, /* getenv("USERPROFILE") */
  39741. "/var/tmp",
  39742. "/usr/tmp",
  39743. "/tmp",
  39744. ".",
  39745. 0 /* List terminator */
  39746. };
  39747. unsigned int i;
  39748. const char *zDir = 0;
  39749. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  39750. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  39751. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  39752. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  39753. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  39754. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  39755. void *zConverted;
  39756. if( zDir==0 ) continue;
  39757. /* If the path starts with a drive letter followed by the colon
  39758. ** character, assume it is already a native Win32 path; otherwise,
  39759. ** it must be converted to a native Win32 path via the Cygwin API
  39760. ** prior to using it.
  39761. */
  39762. if( winIsDriveLetterAndColon(zDir) ){
  39763. zConverted = winConvertFromUtf8Filename(zDir);
  39764. if( !zConverted ){
  39765. sqlite3_free(zBuf);
  39766. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39767. return SQLITE_IOERR_NOMEM_BKPT;
  39768. }
  39769. if( winIsDir(zConverted) ){
  39770. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  39771. sqlite3_free(zConverted);
  39772. break;
  39773. }
  39774. sqlite3_free(zConverted);
  39775. }else{
  39776. zConverted = sqlite3MallocZero( nMax+1 );
  39777. if( !zConverted ){
  39778. sqlite3_free(zBuf);
  39779. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39780. return SQLITE_IOERR_NOMEM_BKPT;
  39781. }
  39782. if( cygwin_conv_path(
  39783. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  39784. zConverted, nMax+1)<0 ){
  39785. sqlite3_free(zConverted);
  39786. sqlite3_free(zBuf);
  39787. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  39788. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  39789. "winGetTempname2", zDir);
  39790. }
  39791. if( winIsDir(zConverted) ){
  39792. /* At this point, we know the candidate directory exists and should
  39793. ** be used. However, we may need to convert the string containing
  39794. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  39795. */
  39796. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  39797. if( !zUtf8 ){
  39798. sqlite3_free(zConverted);
  39799. sqlite3_free(zBuf);
  39800. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39801. return SQLITE_IOERR_NOMEM_BKPT;
  39802. }
  39803. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  39804. sqlite3_free(zUtf8);
  39805. sqlite3_free(zConverted);
  39806. break;
  39807. }
  39808. sqlite3_free(zConverted);
  39809. }
  39810. }
  39811. }
  39812. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  39813. else if( osIsNT() ){
  39814. char *zMulti;
  39815. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  39816. if( !zWidePath ){
  39817. sqlite3_free(zBuf);
  39818. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39819. return SQLITE_IOERR_NOMEM_BKPT;
  39820. }
  39821. if( osGetTempPathW(nMax, zWidePath)==0 ){
  39822. sqlite3_free(zWidePath);
  39823. sqlite3_free(zBuf);
  39824. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  39825. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  39826. "winGetTempname2", 0);
  39827. }
  39828. zMulti = winUnicodeToUtf8(zWidePath);
  39829. if( zMulti ){
  39830. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  39831. sqlite3_free(zMulti);
  39832. sqlite3_free(zWidePath);
  39833. }else{
  39834. sqlite3_free(zWidePath);
  39835. sqlite3_free(zBuf);
  39836. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39837. return SQLITE_IOERR_NOMEM_BKPT;
  39838. }
  39839. }
  39840. #ifdef SQLITE_WIN32_HAS_ANSI
  39841. else{
  39842. char *zUtf8;
  39843. char *zMbcsPath = sqlite3MallocZero( nMax );
  39844. if( !zMbcsPath ){
  39845. sqlite3_free(zBuf);
  39846. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39847. return SQLITE_IOERR_NOMEM_BKPT;
  39848. }
  39849. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  39850. sqlite3_free(zBuf);
  39851. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  39852. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  39853. "winGetTempname3", 0);
  39854. }
  39855. zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
  39856. if( zUtf8 ){
  39857. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  39858. sqlite3_free(zUtf8);
  39859. }else{
  39860. sqlite3_free(zBuf);
  39861. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39862. return SQLITE_IOERR_NOMEM_BKPT;
  39863. }
  39864. }
  39865. #endif /* SQLITE_WIN32_HAS_ANSI */
  39866. #endif /* !SQLITE_OS_WINRT */
  39867. /*
  39868. ** Check to make sure the temporary directory ends with an appropriate
  39869. ** separator. If it does not and there is not enough space left to add
  39870. ** one, fail.
  39871. */
  39872. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  39873. sqlite3_free(zBuf);
  39874. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  39875. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  39876. }
  39877. /*
  39878. ** Check that the output buffer is large enough for the temporary file
  39879. ** name in the following format:
  39880. **
  39881. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  39882. **
  39883. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  39884. ** account for the space used by the 15 character random suffix and the
  39885. ** two trailing NUL characters. The final directory separator character
  39886. ** has already added if it was not already present.
  39887. */
  39888. nLen = sqlite3Strlen30(zBuf);
  39889. if( (nLen + nPre + 17) > nBuf ){
  39890. sqlite3_free(zBuf);
  39891. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  39892. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  39893. }
  39894. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  39895. j = sqlite3Strlen30(zBuf);
  39896. sqlite3_randomness(15, &zBuf[j]);
  39897. for(i=0; i<15; i++, j++){
  39898. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  39899. }
  39900. zBuf[j] = 0;
  39901. zBuf[j+1] = 0;
  39902. *pzBuf = zBuf;
  39903. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  39904. return SQLITE_OK;
  39905. }
  39906. /*
  39907. ** Return TRUE if the named file is really a directory. Return false if
  39908. ** it is something other than a directory, or if there is any kind of memory
  39909. ** allocation failure.
  39910. */
  39911. static int winIsDir(const void *zConverted){
  39912. DWORD attr;
  39913. int rc = 0;
  39914. DWORD lastErrno;
  39915. if( osIsNT() ){
  39916. int cnt = 0;
  39917. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  39918. memset(&sAttrData, 0, sizeof(sAttrData));
  39919. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  39920. GetFileExInfoStandard,
  39921. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  39922. if( !rc ){
  39923. return 0; /* Invalid name? */
  39924. }
  39925. attr = sAttrData.dwFileAttributes;
  39926. #if SQLITE_OS_WINCE==0
  39927. }else{
  39928. attr = osGetFileAttributesA((char*)zConverted);
  39929. #endif
  39930. }
  39931. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  39932. }
  39933. /*
  39934. ** Open a file.
  39935. */
  39936. static int winOpen(
  39937. sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
  39938. const char *zName, /* Name of the file (UTF-8) */
  39939. sqlite3_file *id, /* Write the SQLite file handle here */
  39940. int flags, /* Open mode flags */
  39941. int *pOutFlags /* Status return flags */
  39942. ){
  39943. HANDLE h;
  39944. DWORD lastErrno = 0;
  39945. DWORD dwDesiredAccess;
  39946. DWORD dwShareMode;
  39947. DWORD dwCreationDisposition;
  39948. DWORD dwFlagsAndAttributes = 0;
  39949. #if SQLITE_OS_WINCE
  39950. int isTemp = 0;
  39951. #endif
  39952. winVfsAppData *pAppData;
  39953. winFile *pFile = (winFile*)id;
  39954. void *zConverted; /* Filename in OS encoding */
  39955. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  39956. int cnt = 0;
  39957. /* If argument zPath is a NULL pointer, this function is required to open
  39958. ** a temporary file. Use this buffer to store the file name in.
  39959. */
  39960. char *zTmpname = 0; /* For temporary filename, if necessary. */
  39961. int rc = SQLITE_OK; /* Function Return Code */
  39962. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  39963. int eType = flags&0xFFFFFF00; /* Type of file to open */
  39964. #endif
  39965. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  39966. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  39967. int isCreate = (flags & SQLITE_OPEN_CREATE);
  39968. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  39969. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  39970. #ifndef NDEBUG
  39971. int isOpenJournal = (isCreate && (
  39972. eType==SQLITE_OPEN_MASTER_JOURNAL
  39973. || eType==SQLITE_OPEN_MAIN_JOURNAL
  39974. || eType==SQLITE_OPEN_WAL
  39975. ));
  39976. #endif
  39977. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  39978. zUtf8Name, id, flags, pOutFlags));
  39979. /* Check the following statements are true:
  39980. **
  39981. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  39982. ** (b) if CREATE is set, then READWRITE must also be set, and
  39983. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  39984. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  39985. */
  39986. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  39987. assert(isCreate==0 || isReadWrite);
  39988. assert(isExclusive==0 || isCreate);
  39989. assert(isDelete==0 || isCreate);
  39990. /* The main DB, main journal, WAL file and master journal are never
  39991. ** automatically deleted. Nor are they ever temporary files. */
  39992. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  39993. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  39994. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  39995. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  39996. /* Assert that the upper layer has set one of the "file-type" flags. */
  39997. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  39998. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  39999. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  40000. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  40001. );
  40002. assert( pFile!=0 );
  40003. memset(pFile, 0, sizeof(winFile));
  40004. pFile->h = INVALID_HANDLE_VALUE;
  40005. #if SQLITE_OS_WINRT
  40006. if( !zUtf8Name && !sqlite3_temp_directory ){
  40007. sqlite3_log(SQLITE_ERROR,
  40008. "sqlite3_temp_directory variable should be set for WinRT");
  40009. }
  40010. #endif
  40011. /* If the second argument to this function is NULL, generate a
  40012. ** temporary file name to use
  40013. */
  40014. if( !zUtf8Name ){
  40015. assert( isDelete && !isOpenJournal );
  40016. rc = winGetTempname(pVfs, &zTmpname);
  40017. if( rc!=SQLITE_OK ){
  40018. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  40019. return rc;
  40020. }
  40021. zUtf8Name = zTmpname;
  40022. }
  40023. /* Database filenames are double-zero terminated if they are not
  40024. ** URIs with parameters. Hence, they can always be passed into
  40025. ** sqlite3_uri_parameter().
  40026. */
  40027. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  40028. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  40029. /* Convert the filename to the system encoding. */
  40030. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  40031. if( zConverted==0 ){
  40032. sqlite3_free(zTmpname);
  40033. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  40034. return SQLITE_IOERR_NOMEM_BKPT;
  40035. }
  40036. if( winIsDir(zConverted) ){
  40037. sqlite3_free(zConverted);
  40038. sqlite3_free(zTmpname);
  40039. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  40040. return SQLITE_CANTOPEN_ISDIR;
  40041. }
  40042. if( isReadWrite ){
  40043. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  40044. }else{
  40045. dwDesiredAccess = GENERIC_READ;
  40046. }
  40047. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  40048. ** created. SQLite doesn't use it to indicate "exclusive access"
  40049. ** as it is usually understood.
  40050. */
  40051. if( isExclusive ){
  40052. /* Creates a new file, only if it does not already exist. */
  40053. /* If the file exists, it fails. */
  40054. dwCreationDisposition = CREATE_NEW;
  40055. }else if( isCreate ){
  40056. /* Open existing file, or create if it doesn't exist */
  40057. dwCreationDisposition = OPEN_ALWAYS;
  40058. }else{
  40059. /* Opens a file, only if it exists. */
  40060. dwCreationDisposition = OPEN_EXISTING;
  40061. }
  40062. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  40063. if( isDelete ){
  40064. #if SQLITE_OS_WINCE
  40065. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  40066. isTemp = 1;
  40067. #else
  40068. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  40069. | FILE_ATTRIBUTE_HIDDEN
  40070. | FILE_FLAG_DELETE_ON_CLOSE;
  40071. #endif
  40072. }else{
  40073. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  40074. }
  40075. /* Reports from the internet are that performance is always
  40076. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  40077. #if SQLITE_OS_WINCE
  40078. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  40079. #endif
  40080. if( osIsNT() ){
  40081. #if SQLITE_OS_WINRT
  40082. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  40083. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  40084. extendedParameters.dwFileAttributes =
  40085. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  40086. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  40087. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  40088. extendedParameters.lpSecurityAttributes = NULL;
  40089. extendedParameters.hTemplateFile = NULL;
  40090. while( (h = osCreateFile2((LPCWSTR)zConverted,
  40091. dwDesiredAccess,
  40092. dwShareMode,
  40093. dwCreationDisposition,
  40094. &extendedParameters))==INVALID_HANDLE_VALUE &&
  40095. winRetryIoerr(&cnt, &lastErrno) ){
  40096. /* Noop */
  40097. }
  40098. #else
  40099. while( (h = osCreateFileW((LPCWSTR)zConverted,
  40100. dwDesiredAccess,
  40101. dwShareMode, NULL,
  40102. dwCreationDisposition,
  40103. dwFlagsAndAttributes,
  40104. NULL))==INVALID_HANDLE_VALUE &&
  40105. winRetryIoerr(&cnt, &lastErrno) ){
  40106. /* Noop */
  40107. }
  40108. #endif
  40109. }
  40110. #ifdef SQLITE_WIN32_HAS_ANSI
  40111. else{
  40112. while( (h = osCreateFileA((LPCSTR)zConverted,
  40113. dwDesiredAccess,
  40114. dwShareMode, NULL,
  40115. dwCreationDisposition,
  40116. dwFlagsAndAttributes,
  40117. NULL))==INVALID_HANDLE_VALUE &&
  40118. winRetryIoerr(&cnt, &lastErrno) ){
  40119. /* Noop */
  40120. }
  40121. }
  40122. #endif
  40123. winLogIoerr(cnt, __LINE__);
  40124. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  40125. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  40126. if( h==INVALID_HANDLE_VALUE ){
  40127. pFile->lastErrno = lastErrno;
  40128. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  40129. sqlite3_free(zConverted);
  40130. sqlite3_free(zTmpname);
  40131. if( isReadWrite && !isExclusive ){
  40132. return winOpen(pVfs, zName, id,
  40133. ((flags|SQLITE_OPEN_READONLY) &
  40134. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  40135. pOutFlags);
  40136. }else{
  40137. return SQLITE_CANTOPEN_BKPT;
  40138. }
  40139. }
  40140. if( pOutFlags ){
  40141. if( isReadWrite ){
  40142. *pOutFlags = SQLITE_OPEN_READWRITE;
  40143. }else{
  40144. *pOutFlags = SQLITE_OPEN_READONLY;
  40145. }
  40146. }
  40147. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  40148. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  40149. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  40150. pAppData = (winVfsAppData*)pVfs->pAppData;
  40151. #if SQLITE_OS_WINCE
  40152. {
  40153. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  40154. && ((pAppData==NULL) || !pAppData->bNoLock)
  40155. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  40156. ){
  40157. osCloseHandle(h);
  40158. sqlite3_free(zConverted);
  40159. sqlite3_free(zTmpname);
  40160. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  40161. return rc;
  40162. }
  40163. }
  40164. if( isTemp ){
  40165. pFile->zDeleteOnClose = zConverted;
  40166. }else
  40167. #endif
  40168. {
  40169. sqlite3_free(zConverted);
  40170. }
  40171. sqlite3_free(zTmpname);
  40172. pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
  40173. pFile->pVfs = pVfs;
  40174. pFile->h = h;
  40175. if( isReadonly ){
  40176. pFile->ctrlFlags |= WINFILE_RDONLY;
  40177. }
  40178. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  40179. pFile->ctrlFlags |= WINFILE_PSOW;
  40180. }
  40181. pFile->lastErrno = NO_ERROR;
  40182. pFile->zPath = zName;
  40183. #if SQLITE_MAX_MMAP_SIZE>0
  40184. pFile->hMap = NULL;
  40185. pFile->pMapRegion = 0;
  40186. pFile->mmapSize = 0;
  40187. pFile->mmapSizeActual = 0;
  40188. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  40189. #endif
  40190. OpenCounter(+1);
  40191. return rc;
  40192. }
  40193. /*
  40194. ** Delete the named file.
  40195. **
  40196. ** Note that Windows does not allow a file to be deleted if some other
  40197. ** process has it open. Sometimes a virus scanner or indexing program
  40198. ** will open a journal file shortly after it is created in order to do
  40199. ** whatever it does. While this other process is holding the
  40200. ** file open, we will be unable to delete it. To work around this
  40201. ** problem, we delay 100 milliseconds and try to delete again. Up
  40202. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  40203. ** up and returning an error.
  40204. */
  40205. static int winDelete(
  40206. sqlite3_vfs *pVfs, /* Not used on win32 */
  40207. const char *zFilename, /* Name of file to delete */
  40208. int syncDir /* Not used on win32 */
  40209. ){
  40210. int cnt = 0;
  40211. int rc;
  40212. DWORD attr;
  40213. DWORD lastErrno = 0;
  40214. void *zConverted;
  40215. UNUSED_PARAMETER(pVfs);
  40216. UNUSED_PARAMETER(syncDir);
  40217. SimulateIOError(return SQLITE_IOERR_DELETE);
  40218. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  40219. zConverted = winConvertFromUtf8Filename(zFilename);
  40220. if( zConverted==0 ){
  40221. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  40222. return SQLITE_IOERR_NOMEM_BKPT;
  40223. }
  40224. if( osIsNT() ){
  40225. do {
  40226. #if SQLITE_OS_WINRT
  40227. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  40228. memset(&sAttrData, 0, sizeof(sAttrData));
  40229. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  40230. &sAttrData) ){
  40231. attr = sAttrData.dwFileAttributes;
  40232. }else{
  40233. lastErrno = osGetLastError();
  40234. if( lastErrno==ERROR_FILE_NOT_FOUND
  40235. || lastErrno==ERROR_PATH_NOT_FOUND ){
  40236. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  40237. }else{
  40238. rc = SQLITE_ERROR;
  40239. }
  40240. break;
  40241. }
  40242. #else
  40243. attr = osGetFileAttributesW(zConverted);
  40244. #endif
  40245. if ( attr==INVALID_FILE_ATTRIBUTES ){
  40246. lastErrno = osGetLastError();
  40247. if( lastErrno==ERROR_FILE_NOT_FOUND
  40248. || lastErrno==ERROR_PATH_NOT_FOUND ){
  40249. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  40250. }else{
  40251. rc = SQLITE_ERROR;
  40252. }
  40253. break;
  40254. }
  40255. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  40256. rc = SQLITE_ERROR; /* Files only. */
  40257. break;
  40258. }
  40259. if ( osDeleteFileW(zConverted) ){
  40260. rc = SQLITE_OK; /* Deleted OK. */
  40261. break;
  40262. }
  40263. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  40264. rc = SQLITE_ERROR; /* No more retries. */
  40265. break;
  40266. }
  40267. } while(1);
  40268. }
  40269. #ifdef SQLITE_WIN32_HAS_ANSI
  40270. else{
  40271. do {
  40272. attr = osGetFileAttributesA(zConverted);
  40273. if ( attr==INVALID_FILE_ATTRIBUTES ){
  40274. lastErrno = osGetLastError();
  40275. if( lastErrno==ERROR_FILE_NOT_FOUND
  40276. || lastErrno==ERROR_PATH_NOT_FOUND ){
  40277. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  40278. }else{
  40279. rc = SQLITE_ERROR;
  40280. }
  40281. break;
  40282. }
  40283. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  40284. rc = SQLITE_ERROR; /* Files only. */
  40285. break;
  40286. }
  40287. if ( osDeleteFileA(zConverted) ){
  40288. rc = SQLITE_OK; /* Deleted OK. */
  40289. break;
  40290. }
  40291. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  40292. rc = SQLITE_ERROR; /* No more retries. */
  40293. break;
  40294. }
  40295. } while(1);
  40296. }
  40297. #endif
  40298. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  40299. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  40300. }else{
  40301. winLogIoerr(cnt, __LINE__);
  40302. }
  40303. sqlite3_free(zConverted);
  40304. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  40305. return rc;
  40306. }
  40307. /*
  40308. ** Check the existence and status of a file.
  40309. */
  40310. static int winAccess(
  40311. sqlite3_vfs *pVfs, /* Not used on win32 */
  40312. const char *zFilename, /* Name of file to check */
  40313. int flags, /* Type of test to make on this file */
  40314. int *pResOut /* OUT: Result */
  40315. ){
  40316. DWORD attr;
  40317. int rc = 0;
  40318. DWORD lastErrno = 0;
  40319. void *zConverted;
  40320. UNUSED_PARAMETER(pVfs);
  40321. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  40322. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  40323. zFilename, flags, pResOut));
  40324. zConverted = winConvertFromUtf8Filename(zFilename);
  40325. if( zConverted==0 ){
  40326. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  40327. return SQLITE_IOERR_NOMEM_BKPT;
  40328. }
  40329. if( osIsNT() ){
  40330. int cnt = 0;
  40331. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  40332. memset(&sAttrData, 0, sizeof(sAttrData));
  40333. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  40334. GetFileExInfoStandard,
  40335. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  40336. if( rc ){
  40337. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  40338. ** as if it does not exist.
  40339. */
  40340. if( flags==SQLITE_ACCESS_EXISTS
  40341. && sAttrData.nFileSizeHigh==0
  40342. && sAttrData.nFileSizeLow==0 ){
  40343. attr = INVALID_FILE_ATTRIBUTES;
  40344. }else{
  40345. attr = sAttrData.dwFileAttributes;
  40346. }
  40347. }else{
  40348. winLogIoerr(cnt, __LINE__);
  40349. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  40350. sqlite3_free(zConverted);
  40351. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  40352. zFilename);
  40353. }else{
  40354. attr = INVALID_FILE_ATTRIBUTES;
  40355. }
  40356. }
  40357. }
  40358. #ifdef SQLITE_WIN32_HAS_ANSI
  40359. else{
  40360. attr = osGetFileAttributesA((char*)zConverted);
  40361. }
  40362. #endif
  40363. sqlite3_free(zConverted);
  40364. switch( flags ){
  40365. case SQLITE_ACCESS_READ:
  40366. case SQLITE_ACCESS_EXISTS:
  40367. rc = attr!=INVALID_FILE_ATTRIBUTES;
  40368. break;
  40369. case SQLITE_ACCESS_READWRITE:
  40370. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  40371. (attr & FILE_ATTRIBUTE_READONLY)==0;
  40372. break;
  40373. default:
  40374. assert(!"Invalid flags argument");
  40375. }
  40376. *pResOut = rc;
  40377. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  40378. zFilename, pResOut, *pResOut));
  40379. return SQLITE_OK;
  40380. }
  40381. /*
  40382. ** Returns non-zero if the specified path name starts with a drive letter
  40383. ** followed by a colon character.
  40384. */
  40385. static BOOL winIsDriveLetterAndColon(
  40386. const char *zPathname
  40387. ){
  40388. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  40389. }
  40390. /*
  40391. ** Returns non-zero if the specified path name should be used verbatim. If
  40392. ** non-zero is returned from this function, the calling function must simply
  40393. ** use the provided path name verbatim -OR- resolve it into a full path name
  40394. ** using the GetFullPathName Win32 API function (if available).
  40395. */
  40396. static BOOL winIsVerbatimPathname(
  40397. const char *zPathname
  40398. ){
  40399. /*
  40400. ** If the path name starts with a forward slash or a backslash, it is either
  40401. ** a legal UNC name, a volume relative path, or an absolute path name in the
  40402. ** "Unix" format on Windows. There is no easy way to differentiate between
  40403. ** the final two cases; therefore, we return the safer return value of TRUE
  40404. ** so that callers of this function will simply use it verbatim.
  40405. */
  40406. if ( winIsDirSep(zPathname[0]) ){
  40407. return TRUE;
  40408. }
  40409. /*
  40410. ** If the path name starts with a letter and a colon it is either a volume
  40411. ** relative path or an absolute path. Callers of this function must not
  40412. ** attempt to treat it as a relative path name (i.e. they should simply use
  40413. ** it verbatim).
  40414. */
  40415. if ( winIsDriveLetterAndColon(zPathname) ){
  40416. return TRUE;
  40417. }
  40418. /*
  40419. ** If we get to this point, the path name should almost certainly be a purely
  40420. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  40421. */
  40422. return FALSE;
  40423. }
  40424. /*
  40425. ** Turn a relative pathname into a full pathname. Write the full
  40426. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  40427. ** bytes in size.
  40428. */
  40429. static int winFullPathname(
  40430. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  40431. const char *zRelative, /* Possibly relative input path */
  40432. int nFull, /* Size of output buffer in bytes */
  40433. char *zFull /* Output buffer */
  40434. ){
  40435. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  40436. DWORD nByte;
  40437. void *zConverted;
  40438. char *zOut;
  40439. #endif
  40440. /* If this path name begins with "/X:", where "X" is any alphabetic
  40441. ** character, discard the initial "/" from the pathname.
  40442. */
  40443. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  40444. zRelative++;
  40445. }
  40446. #if defined(__CYGWIN__)
  40447. SimulateIOError( return SQLITE_ERROR );
  40448. UNUSED_PARAMETER(nFull);
  40449. assert( nFull>=pVfs->mxPathname );
  40450. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  40451. /*
  40452. ** NOTE: We are dealing with a relative path name and the data
  40453. ** directory has been set. Therefore, use it as the basis
  40454. ** for converting the relative path name to an absolute
  40455. ** one by prepending the data directory and a slash.
  40456. */
  40457. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  40458. if( !zOut ){
  40459. return SQLITE_IOERR_NOMEM_BKPT;
  40460. }
  40461. if( cygwin_conv_path(
  40462. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  40463. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  40464. sqlite3_free(zOut);
  40465. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  40466. "winFullPathname1", zRelative);
  40467. }else{
  40468. char *zUtf8 = winConvertToUtf8Filename(zOut);
  40469. if( !zUtf8 ){
  40470. sqlite3_free(zOut);
  40471. return SQLITE_IOERR_NOMEM_BKPT;
  40472. }
  40473. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  40474. sqlite3_data_directory, winGetDirSep(), zUtf8);
  40475. sqlite3_free(zUtf8);
  40476. sqlite3_free(zOut);
  40477. }
  40478. }else{
  40479. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  40480. if( !zOut ){
  40481. return SQLITE_IOERR_NOMEM_BKPT;
  40482. }
  40483. if( cygwin_conv_path(
  40484. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  40485. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  40486. sqlite3_free(zOut);
  40487. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  40488. "winFullPathname2", zRelative);
  40489. }else{
  40490. char *zUtf8 = winConvertToUtf8Filename(zOut);
  40491. if( !zUtf8 ){
  40492. sqlite3_free(zOut);
  40493. return SQLITE_IOERR_NOMEM_BKPT;
  40494. }
  40495. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  40496. sqlite3_free(zUtf8);
  40497. sqlite3_free(zOut);
  40498. }
  40499. }
  40500. return SQLITE_OK;
  40501. #endif
  40502. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  40503. SimulateIOError( return SQLITE_ERROR );
  40504. /* WinCE has no concept of a relative pathname, or so I am told. */
  40505. /* WinRT has no way to convert a relative path to an absolute one. */
  40506. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  40507. /*
  40508. ** NOTE: We are dealing with a relative path name and the data
  40509. ** directory has been set. Therefore, use it as the basis
  40510. ** for converting the relative path name to an absolute
  40511. ** one by prepending the data directory and a backslash.
  40512. */
  40513. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  40514. sqlite3_data_directory, winGetDirSep(), zRelative);
  40515. }else{
  40516. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  40517. }
  40518. return SQLITE_OK;
  40519. #endif
  40520. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  40521. /* It's odd to simulate an io-error here, but really this is just
  40522. ** using the io-error infrastructure to test that SQLite handles this
  40523. ** function failing. This function could fail if, for example, the
  40524. ** current working directory has been unlinked.
  40525. */
  40526. SimulateIOError( return SQLITE_ERROR );
  40527. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  40528. /*
  40529. ** NOTE: We are dealing with a relative path name and the data
  40530. ** directory has been set. Therefore, use it as the basis
  40531. ** for converting the relative path name to an absolute
  40532. ** one by prepending the data directory and a backslash.
  40533. */
  40534. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  40535. sqlite3_data_directory, winGetDirSep(), zRelative);
  40536. return SQLITE_OK;
  40537. }
  40538. zConverted = winConvertFromUtf8Filename(zRelative);
  40539. if( zConverted==0 ){
  40540. return SQLITE_IOERR_NOMEM_BKPT;
  40541. }
  40542. if( osIsNT() ){
  40543. LPWSTR zTemp;
  40544. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  40545. if( nByte==0 ){
  40546. sqlite3_free(zConverted);
  40547. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  40548. "winFullPathname1", zRelative);
  40549. }
  40550. nByte += 3;
  40551. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  40552. if( zTemp==0 ){
  40553. sqlite3_free(zConverted);
  40554. return SQLITE_IOERR_NOMEM_BKPT;
  40555. }
  40556. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  40557. if( nByte==0 ){
  40558. sqlite3_free(zConverted);
  40559. sqlite3_free(zTemp);
  40560. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  40561. "winFullPathname2", zRelative);
  40562. }
  40563. sqlite3_free(zConverted);
  40564. zOut = winUnicodeToUtf8(zTemp);
  40565. sqlite3_free(zTemp);
  40566. }
  40567. #ifdef SQLITE_WIN32_HAS_ANSI
  40568. else{
  40569. char *zTemp;
  40570. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  40571. if( nByte==0 ){
  40572. sqlite3_free(zConverted);
  40573. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  40574. "winFullPathname3", zRelative);
  40575. }
  40576. nByte += 3;
  40577. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  40578. if( zTemp==0 ){
  40579. sqlite3_free(zConverted);
  40580. return SQLITE_IOERR_NOMEM_BKPT;
  40581. }
  40582. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  40583. if( nByte==0 ){
  40584. sqlite3_free(zConverted);
  40585. sqlite3_free(zTemp);
  40586. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  40587. "winFullPathname4", zRelative);
  40588. }
  40589. sqlite3_free(zConverted);
  40590. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  40591. sqlite3_free(zTemp);
  40592. }
  40593. #endif
  40594. if( zOut ){
  40595. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  40596. sqlite3_free(zOut);
  40597. return SQLITE_OK;
  40598. }else{
  40599. return SQLITE_IOERR_NOMEM_BKPT;
  40600. }
  40601. #endif
  40602. }
  40603. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  40604. /*
  40605. ** Interfaces for opening a shared library, finding entry points
  40606. ** within the shared library, and closing the shared library.
  40607. */
  40608. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  40609. HANDLE h;
  40610. #if defined(__CYGWIN__)
  40611. int nFull = pVfs->mxPathname+1;
  40612. char *zFull = sqlite3MallocZero( nFull );
  40613. void *zConverted = 0;
  40614. if( zFull==0 ){
  40615. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  40616. return 0;
  40617. }
  40618. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  40619. sqlite3_free(zFull);
  40620. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  40621. return 0;
  40622. }
  40623. zConverted = winConvertFromUtf8Filename(zFull);
  40624. sqlite3_free(zFull);
  40625. #else
  40626. void *zConverted = winConvertFromUtf8Filename(zFilename);
  40627. UNUSED_PARAMETER(pVfs);
  40628. #endif
  40629. if( zConverted==0 ){
  40630. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  40631. return 0;
  40632. }
  40633. if( osIsNT() ){
  40634. #if SQLITE_OS_WINRT
  40635. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  40636. #else
  40637. h = osLoadLibraryW((LPCWSTR)zConverted);
  40638. #endif
  40639. }
  40640. #ifdef SQLITE_WIN32_HAS_ANSI
  40641. else{
  40642. h = osLoadLibraryA((char*)zConverted);
  40643. }
  40644. #endif
  40645. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  40646. sqlite3_free(zConverted);
  40647. return (void*)h;
  40648. }
  40649. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  40650. UNUSED_PARAMETER(pVfs);
  40651. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  40652. }
  40653. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  40654. FARPROC proc;
  40655. UNUSED_PARAMETER(pVfs);
  40656. proc = osGetProcAddressA((HANDLE)pH, zSym);
  40657. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  40658. (void*)pH, zSym, (void*)proc));
  40659. return (void(*)(void))proc;
  40660. }
  40661. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  40662. UNUSED_PARAMETER(pVfs);
  40663. osFreeLibrary((HANDLE)pHandle);
  40664. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  40665. }
  40666. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  40667. #define winDlOpen 0
  40668. #define winDlError 0
  40669. #define winDlSym 0
  40670. #define winDlClose 0
  40671. #endif
  40672. /* State information for the randomness gatherer. */
  40673. typedef struct EntropyGatherer EntropyGatherer;
  40674. struct EntropyGatherer {
  40675. unsigned char *a; /* Gather entropy into this buffer */
  40676. int na; /* Size of a[] in bytes */
  40677. int i; /* XOR next input into a[i] */
  40678. int nXor; /* Number of XOR operations done */
  40679. };
  40680. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  40681. /* Mix sz bytes of entropy into p. */
  40682. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  40683. int j, k;
  40684. for(j=0, k=p->i; j<sz; j++){
  40685. p->a[k++] ^= x[j];
  40686. if( k>=p->na ) k = 0;
  40687. }
  40688. p->i = k;
  40689. p->nXor += sz;
  40690. }
  40691. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  40692. /*
  40693. ** Write up to nBuf bytes of randomness into zBuf.
  40694. */
  40695. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  40696. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  40697. UNUSED_PARAMETER(pVfs);
  40698. memset(zBuf, 0, nBuf);
  40699. return nBuf;
  40700. #else
  40701. EntropyGatherer e;
  40702. UNUSED_PARAMETER(pVfs);
  40703. memset(zBuf, 0, nBuf);
  40704. #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
  40705. rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
  40706. #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
  40707. e.a = (unsigned char*)zBuf;
  40708. e.na = nBuf;
  40709. e.nXor = 0;
  40710. e.i = 0;
  40711. {
  40712. SYSTEMTIME x;
  40713. osGetSystemTime(&x);
  40714. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  40715. }
  40716. {
  40717. DWORD pid = osGetCurrentProcessId();
  40718. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  40719. }
  40720. #if SQLITE_OS_WINRT
  40721. {
  40722. ULONGLONG cnt = osGetTickCount64();
  40723. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  40724. }
  40725. #else
  40726. {
  40727. DWORD cnt = osGetTickCount();
  40728. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  40729. }
  40730. #endif /* SQLITE_OS_WINRT */
  40731. {
  40732. LARGE_INTEGER i;
  40733. osQueryPerformanceCounter(&i);
  40734. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  40735. }
  40736. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  40737. {
  40738. UUID id;
  40739. memset(&id, 0, sizeof(UUID));
  40740. osUuidCreate(&id);
  40741. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  40742. memset(&id, 0, sizeof(UUID));
  40743. osUuidCreateSequential(&id);
  40744. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  40745. }
  40746. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  40747. return e.nXor>nBuf ? nBuf : e.nXor;
  40748. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  40749. }
  40750. /*
  40751. ** Sleep for a little while. Return the amount of time slept.
  40752. */
  40753. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  40754. sqlite3_win32_sleep((microsec+999)/1000);
  40755. UNUSED_PARAMETER(pVfs);
  40756. return ((microsec+999)/1000)*1000;
  40757. }
  40758. /*
  40759. ** The following variable, if set to a non-zero value, is interpreted as
  40760. ** the number of seconds since 1970 and is used to set the result of
  40761. ** sqlite3OsCurrentTime() during testing.
  40762. */
  40763. #ifdef SQLITE_TEST
  40764. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  40765. #endif
  40766. /*
  40767. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  40768. ** the current time and date as a Julian Day number times 86_400_000. In
  40769. ** other words, write into *piNow the number of milliseconds since the Julian
  40770. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  40771. ** proleptic Gregorian calendar.
  40772. **
  40773. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  40774. ** cannot be found.
  40775. */
  40776. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  40777. /* FILETIME structure is a 64-bit value representing the number of
  40778. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  40779. */
  40780. FILETIME ft;
  40781. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  40782. #ifdef SQLITE_TEST
  40783. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  40784. #endif
  40785. /* 2^32 - to avoid use of LL and warnings in gcc */
  40786. static const sqlite3_int64 max32BitValue =
  40787. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  40788. (sqlite3_int64)294967296;
  40789. #if SQLITE_OS_WINCE
  40790. SYSTEMTIME time;
  40791. osGetSystemTime(&time);
  40792. /* if SystemTimeToFileTime() fails, it returns zero. */
  40793. if (!osSystemTimeToFileTime(&time,&ft)){
  40794. return SQLITE_ERROR;
  40795. }
  40796. #else
  40797. osGetSystemTimeAsFileTime( &ft );
  40798. #endif
  40799. *piNow = winFiletimeEpoch +
  40800. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  40801. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  40802. #ifdef SQLITE_TEST
  40803. if( sqlite3_current_time ){
  40804. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  40805. }
  40806. #endif
  40807. UNUSED_PARAMETER(pVfs);
  40808. return SQLITE_OK;
  40809. }
  40810. /*
  40811. ** Find the current time (in Universal Coordinated Time). Write the
  40812. ** current time and date as a Julian Day number into *prNow and
  40813. ** return 0. Return 1 if the time and date cannot be found.
  40814. */
  40815. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  40816. int rc;
  40817. sqlite3_int64 i;
  40818. rc = winCurrentTimeInt64(pVfs, &i);
  40819. if( !rc ){
  40820. *prNow = i/86400000.0;
  40821. }
  40822. return rc;
  40823. }
  40824. /*
  40825. ** The idea is that this function works like a combination of
  40826. ** GetLastError() and FormatMessage() on Windows (or errno and
  40827. ** strerror_r() on Unix). After an error is returned by an OS
  40828. ** function, SQLite calls this function with zBuf pointing to
  40829. ** a buffer of nBuf bytes. The OS layer should populate the
  40830. ** buffer with a nul-terminated UTF-8 encoded error message
  40831. ** describing the last IO error to have occurred within the calling
  40832. ** thread.
  40833. **
  40834. ** If the error message is too large for the supplied buffer,
  40835. ** it should be truncated. The return value of xGetLastError
  40836. ** is zero if the error message fits in the buffer, or non-zero
  40837. ** otherwise (if the message was truncated). If non-zero is returned,
  40838. ** then it is not necessary to include the nul-terminator character
  40839. ** in the output buffer.
  40840. **
  40841. ** Not supplying an error message will have no adverse effect
  40842. ** on SQLite. It is fine to have an implementation that never
  40843. ** returns an error message:
  40844. **
  40845. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  40846. ** assert(zBuf[0]=='\0');
  40847. ** return 0;
  40848. ** }
  40849. **
  40850. ** However if an error message is supplied, it will be incorporated
  40851. ** by sqlite into the error message available to the user using
  40852. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  40853. */
  40854. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  40855. DWORD e = osGetLastError();
  40856. UNUSED_PARAMETER(pVfs);
  40857. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  40858. return e;
  40859. }
  40860. /*
  40861. ** Initialize and deinitialize the operating system interface.
  40862. */
  40863. SQLITE_API int sqlite3_os_init(void){
  40864. static sqlite3_vfs winVfs = {
  40865. 3, /* iVersion */
  40866. sizeof(winFile), /* szOsFile */
  40867. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  40868. 0, /* pNext */
  40869. "win32", /* zName */
  40870. &winAppData, /* pAppData */
  40871. winOpen, /* xOpen */
  40872. winDelete, /* xDelete */
  40873. winAccess, /* xAccess */
  40874. winFullPathname, /* xFullPathname */
  40875. winDlOpen, /* xDlOpen */
  40876. winDlError, /* xDlError */
  40877. winDlSym, /* xDlSym */
  40878. winDlClose, /* xDlClose */
  40879. winRandomness, /* xRandomness */
  40880. winSleep, /* xSleep */
  40881. winCurrentTime, /* xCurrentTime */
  40882. winGetLastError, /* xGetLastError */
  40883. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  40884. winSetSystemCall, /* xSetSystemCall */
  40885. winGetSystemCall, /* xGetSystemCall */
  40886. winNextSystemCall, /* xNextSystemCall */
  40887. };
  40888. #if defined(SQLITE_WIN32_HAS_WIDE)
  40889. static sqlite3_vfs winLongPathVfs = {
  40890. 3, /* iVersion */
  40891. sizeof(winFile), /* szOsFile */
  40892. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  40893. 0, /* pNext */
  40894. "win32-longpath", /* 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. #endif
  40914. static sqlite3_vfs winNolockVfs = {
  40915. 3, /* iVersion */
  40916. sizeof(winFile), /* szOsFile */
  40917. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  40918. 0, /* pNext */
  40919. "win32-none", /* zName */
  40920. &winNolockAppData, /* 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. #if defined(SQLITE_WIN32_HAS_WIDE)
  40939. static sqlite3_vfs winLongPathNolockVfs = {
  40940. 3, /* iVersion */
  40941. sizeof(winFile), /* szOsFile */
  40942. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  40943. 0, /* pNext */
  40944. "win32-longpath-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. #endif
  40964. /* Double-check that the aSyscall[] array has been constructed
  40965. ** correctly. See ticket [bb3a86e890c8e96ab] */
  40966. assert( ArraySize(aSyscall)==80 );
  40967. /* get memory map allocation granularity */
  40968. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  40969. #if SQLITE_OS_WINRT
  40970. osGetNativeSystemInfo(&winSysInfo);
  40971. #else
  40972. osGetSystemInfo(&winSysInfo);
  40973. #endif
  40974. assert( winSysInfo.dwAllocationGranularity>0 );
  40975. assert( winSysInfo.dwPageSize>0 );
  40976. sqlite3_vfs_register(&winVfs, 1);
  40977. #if defined(SQLITE_WIN32_HAS_WIDE)
  40978. sqlite3_vfs_register(&winLongPathVfs, 0);
  40979. #endif
  40980. sqlite3_vfs_register(&winNolockVfs, 0);
  40981. #if defined(SQLITE_WIN32_HAS_WIDE)
  40982. sqlite3_vfs_register(&winLongPathNolockVfs, 0);
  40983. #endif
  40984. return SQLITE_OK;
  40985. }
  40986. SQLITE_API int sqlite3_os_end(void){
  40987. #if SQLITE_OS_WINRT
  40988. if( sleepObj!=NULL ){
  40989. osCloseHandle(sleepObj);
  40990. sleepObj = NULL;
  40991. }
  40992. #endif
  40993. return SQLITE_OK;
  40994. }
  40995. #endif /* SQLITE_OS_WIN */
  40996. /************** End of os_win.c **********************************************/
  40997. /************** Begin file bitvec.c ******************************************/
  40998. /*
  40999. ** 2008 February 16
  41000. **
  41001. ** The author disclaims copyright to this source code. In place of
  41002. ** a legal notice, here is a blessing:
  41003. **
  41004. ** May you do good and not evil.
  41005. ** May you find forgiveness for yourself and forgive others.
  41006. ** May you share freely, never taking more than you give.
  41007. **
  41008. *************************************************************************
  41009. ** This file implements an object that represents a fixed-length
  41010. ** bitmap. Bits are numbered starting with 1.
  41011. **
  41012. ** A bitmap is used to record which pages of a database file have been
  41013. ** journalled during a transaction, or which pages have the "dont-write"
  41014. ** property. Usually only a few pages are meet either condition.
  41015. ** So the bitmap is usually sparse and has low cardinality.
  41016. ** But sometimes (for example when during a DROP of a large table) most
  41017. ** or all of the pages in a database can get journalled. In those cases,
  41018. ** the bitmap becomes dense with high cardinality. The algorithm needs
  41019. ** to handle both cases well.
  41020. **
  41021. ** The size of the bitmap is fixed when the object is created.
  41022. **
  41023. ** All bits are clear when the bitmap is created. Individual bits
  41024. ** may be set or cleared one at a time.
  41025. **
  41026. ** Test operations are about 100 times more common that set operations.
  41027. ** Clear operations are exceedingly rare. There are usually between
  41028. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  41029. ** sometimes grow into tens of thousands or larger. The size of the
  41030. ** Bitvec object is the number of pages in the database file at the
  41031. ** start of a transaction, and is thus usually less than a few thousand,
  41032. ** but can be as large as 2 billion for a really big database.
  41033. */
  41034. /* #include "sqliteInt.h" */
  41035. /* Size of the Bitvec structure in bytes. */
  41036. #define BITVEC_SZ 512
  41037. /* Round the union size down to the nearest pointer boundary, since that's how
  41038. ** it will be aligned within the Bitvec struct. */
  41039. #define BITVEC_USIZE \
  41040. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  41041. /* Type of the array "element" for the bitmap representation.
  41042. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  41043. ** Setting this to the "natural word" size of your CPU may improve
  41044. ** performance. */
  41045. #define BITVEC_TELEM u8
  41046. /* Size, in bits, of the bitmap element. */
  41047. #define BITVEC_SZELEM 8
  41048. /* Number of elements in a bitmap array. */
  41049. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  41050. /* Number of bits in the bitmap array. */
  41051. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  41052. /* Number of u32 values in hash table. */
  41053. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  41054. /* Maximum number of entries in hash table before
  41055. ** sub-dividing and re-hashing. */
  41056. #define BITVEC_MXHASH (BITVEC_NINT/2)
  41057. /* Hashing function for the aHash representation.
  41058. ** Empirical testing showed that the *37 multiplier
  41059. ** (an arbitrary prime)in the hash function provided
  41060. ** no fewer collisions than the no-op *1. */
  41061. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  41062. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  41063. /*
  41064. ** A bitmap is an instance of the following structure.
  41065. **
  41066. ** This bitmap records the existence of zero or more bits
  41067. ** with values between 1 and iSize, inclusive.
  41068. **
  41069. ** There are three possible representations of the bitmap.
  41070. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  41071. ** bitmap. The least significant bit is bit 1.
  41072. **
  41073. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  41074. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  41075. **
  41076. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  41077. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  41078. ** handles up to iDivisor separate values of i. apSub[0] holds
  41079. ** values between 1 and iDivisor. apSub[1] holds values between
  41080. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  41081. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  41082. ** to hold deal with values between 1 and iDivisor.
  41083. */
  41084. struct Bitvec {
  41085. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  41086. u32 nSet; /* Number of bits that are set - only valid for aHash
  41087. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  41088. ** this would be 125. */
  41089. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  41090. /* Should >=0 for apSub element. */
  41091. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  41092. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  41093. union {
  41094. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  41095. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  41096. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  41097. } u;
  41098. };
  41099. /*
  41100. ** Create a new bitmap object able to handle bits between 0 and iSize,
  41101. ** inclusive. Return a pointer to the new object. Return NULL if
  41102. ** malloc fails.
  41103. */
  41104. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  41105. Bitvec *p;
  41106. assert( sizeof(*p)==BITVEC_SZ );
  41107. p = sqlite3MallocZero( sizeof(*p) );
  41108. if( p ){
  41109. p->iSize = iSize;
  41110. }
  41111. return p;
  41112. }
  41113. /*
  41114. ** Check to see if the i-th bit is set. Return true or false.
  41115. ** If p is NULL (if the bitmap has not been created) or if
  41116. ** i is out of range, then return false.
  41117. */
  41118. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  41119. assert( p!=0 );
  41120. i--;
  41121. if( i>=p->iSize ) return 0;
  41122. while( p->iDivisor ){
  41123. u32 bin = i/p->iDivisor;
  41124. i = i%p->iDivisor;
  41125. p = p->u.apSub[bin];
  41126. if (!p) {
  41127. return 0;
  41128. }
  41129. }
  41130. if( p->iSize<=BITVEC_NBIT ){
  41131. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  41132. } else{
  41133. u32 h = BITVEC_HASH(i++);
  41134. while( p->u.aHash[h] ){
  41135. if( p->u.aHash[h]==i ) return 1;
  41136. h = (h+1) % BITVEC_NINT;
  41137. }
  41138. return 0;
  41139. }
  41140. }
  41141. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  41142. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  41143. }
  41144. /*
  41145. ** Set the i-th bit. Return 0 on success and an error code if
  41146. ** anything goes wrong.
  41147. **
  41148. ** This routine might cause sub-bitmaps to be allocated. Failing
  41149. ** to get the memory needed to hold the sub-bitmap is the only
  41150. ** that can go wrong with an insert, assuming p and i are valid.
  41151. **
  41152. ** The calling function must ensure that p is a valid Bitvec object
  41153. ** and that the value for "i" is within range of the Bitvec object.
  41154. ** Otherwise the behavior is undefined.
  41155. */
  41156. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  41157. u32 h;
  41158. if( p==0 ) return SQLITE_OK;
  41159. assert( i>0 );
  41160. assert( i<=p->iSize );
  41161. i--;
  41162. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  41163. u32 bin = i/p->iDivisor;
  41164. i = i%p->iDivisor;
  41165. if( p->u.apSub[bin]==0 ){
  41166. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  41167. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  41168. }
  41169. p = p->u.apSub[bin];
  41170. }
  41171. if( p->iSize<=BITVEC_NBIT ){
  41172. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  41173. return SQLITE_OK;
  41174. }
  41175. h = BITVEC_HASH(i++);
  41176. /* if there wasn't a hash collision, and this doesn't */
  41177. /* completely fill the hash, then just add it without */
  41178. /* worring about sub-dividing and re-hashing. */
  41179. if( !p->u.aHash[h] ){
  41180. if (p->nSet<(BITVEC_NINT-1)) {
  41181. goto bitvec_set_end;
  41182. } else {
  41183. goto bitvec_set_rehash;
  41184. }
  41185. }
  41186. /* there was a collision, check to see if it's already */
  41187. /* in hash, if not, try to find a spot for it */
  41188. do {
  41189. if( p->u.aHash[h]==i ) return SQLITE_OK;
  41190. h++;
  41191. if( h>=BITVEC_NINT ) h = 0;
  41192. } while( p->u.aHash[h] );
  41193. /* we didn't find it in the hash. h points to the first */
  41194. /* available free spot. check to see if this is going to */
  41195. /* make our hash too "full". */
  41196. bitvec_set_rehash:
  41197. if( p->nSet>=BITVEC_MXHASH ){
  41198. unsigned int j;
  41199. int rc;
  41200. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  41201. if( aiValues==0 ){
  41202. return SQLITE_NOMEM_BKPT;
  41203. }else{
  41204. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  41205. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  41206. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  41207. rc = sqlite3BitvecSet(p, i);
  41208. for(j=0; j<BITVEC_NINT; j++){
  41209. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  41210. }
  41211. sqlite3StackFree(0, aiValues);
  41212. return rc;
  41213. }
  41214. }
  41215. bitvec_set_end:
  41216. p->nSet++;
  41217. p->u.aHash[h] = i;
  41218. return SQLITE_OK;
  41219. }
  41220. /*
  41221. ** Clear the i-th bit.
  41222. **
  41223. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  41224. ** that BitvecClear can use to rebuilt its hash table.
  41225. */
  41226. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  41227. if( p==0 ) return;
  41228. assert( i>0 );
  41229. i--;
  41230. while( p->iDivisor ){
  41231. u32 bin = i/p->iDivisor;
  41232. i = i%p->iDivisor;
  41233. p = p->u.apSub[bin];
  41234. if (!p) {
  41235. return;
  41236. }
  41237. }
  41238. if( p->iSize<=BITVEC_NBIT ){
  41239. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  41240. }else{
  41241. unsigned int j;
  41242. u32 *aiValues = pBuf;
  41243. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  41244. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  41245. p->nSet = 0;
  41246. for(j=0; j<BITVEC_NINT; j++){
  41247. if( aiValues[j] && aiValues[j]!=(i+1) ){
  41248. u32 h = BITVEC_HASH(aiValues[j]-1);
  41249. p->nSet++;
  41250. while( p->u.aHash[h] ){
  41251. h++;
  41252. if( h>=BITVEC_NINT ) h = 0;
  41253. }
  41254. p->u.aHash[h] = aiValues[j];
  41255. }
  41256. }
  41257. }
  41258. }
  41259. /*
  41260. ** Destroy a bitmap object. Reclaim all memory used.
  41261. */
  41262. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  41263. if( p==0 ) return;
  41264. if( p->iDivisor ){
  41265. unsigned int i;
  41266. for(i=0; i<BITVEC_NPTR; i++){
  41267. sqlite3BitvecDestroy(p->u.apSub[i]);
  41268. }
  41269. }
  41270. sqlite3_free(p);
  41271. }
  41272. /*
  41273. ** Return the value of the iSize parameter specified when Bitvec *p
  41274. ** was created.
  41275. */
  41276. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  41277. return p->iSize;
  41278. }
  41279. #ifndef SQLITE_UNTESTABLE
  41280. /*
  41281. ** Let V[] be an array of unsigned characters sufficient to hold
  41282. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  41283. ** Then the following macros can be used to set, clear, or test
  41284. ** individual bits within V.
  41285. */
  41286. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  41287. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  41288. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  41289. /*
  41290. ** This routine runs an extensive test of the Bitvec code.
  41291. **
  41292. ** The input is an array of integers that acts as a program
  41293. ** to test the Bitvec. The integers are opcodes followed
  41294. ** by 0, 1, or 3 operands, depending on the opcode. Another
  41295. ** opcode follows immediately after the last operand.
  41296. **
  41297. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  41298. ** "halt" opcode and causes the test to end.
  41299. **
  41300. ** 0 Halt and return the number of errors
  41301. ** 1 N S X Set N bits beginning with S and incrementing by X
  41302. ** 2 N S X Clear N bits beginning with S and incrementing by X
  41303. ** 3 N Set N randomly chosen bits
  41304. ** 4 N Clear N randomly chosen bits
  41305. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  41306. **
  41307. ** The opcodes 1 through 4 perform set and clear operations are performed
  41308. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  41309. ** Opcode 5 works on the linear array only, not on the Bitvec.
  41310. ** Opcode 5 is used to deliberately induce a fault in order to
  41311. ** confirm that error detection works.
  41312. **
  41313. ** At the conclusion of the test the linear array is compared
  41314. ** against the Bitvec object. If there are any differences,
  41315. ** an error is returned. If they are the same, zero is returned.
  41316. **
  41317. ** If a memory allocation error occurs, return -1.
  41318. */
  41319. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  41320. Bitvec *pBitvec = 0;
  41321. unsigned char *pV = 0;
  41322. int rc = -1;
  41323. int i, nx, pc, op;
  41324. void *pTmpSpace;
  41325. /* Allocate the Bitvec to be tested and a linear array of
  41326. ** bits to act as the reference */
  41327. pBitvec = sqlite3BitvecCreate( sz );
  41328. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  41329. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  41330. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  41331. /* NULL pBitvec tests */
  41332. sqlite3BitvecSet(0, 1);
  41333. sqlite3BitvecClear(0, 1, pTmpSpace);
  41334. /* Run the program */
  41335. pc = 0;
  41336. while( (op = aOp[pc])!=0 ){
  41337. switch( op ){
  41338. case 1:
  41339. case 2:
  41340. case 5: {
  41341. nx = 4;
  41342. i = aOp[pc+2] - 1;
  41343. aOp[pc+2] += aOp[pc+3];
  41344. break;
  41345. }
  41346. case 3:
  41347. case 4:
  41348. default: {
  41349. nx = 2;
  41350. sqlite3_randomness(sizeof(i), &i);
  41351. break;
  41352. }
  41353. }
  41354. if( (--aOp[pc+1]) > 0 ) nx = 0;
  41355. pc += nx;
  41356. i = (i & 0x7fffffff)%sz;
  41357. if( (op & 1)!=0 ){
  41358. SETBIT(pV, (i+1));
  41359. if( op!=5 ){
  41360. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  41361. }
  41362. }else{
  41363. CLEARBIT(pV, (i+1));
  41364. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  41365. }
  41366. }
  41367. /* Test to make sure the linear array exactly matches the
  41368. ** Bitvec object. Start with the assumption that they do
  41369. ** match (rc==0). Change rc to non-zero if a discrepancy
  41370. ** is found.
  41371. */
  41372. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  41373. + sqlite3BitvecTest(pBitvec, 0)
  41374. + (sqlite3BitvecSize(pBitvec) - sz);
  41375. for(i=1; i<=sz; i++){
  41376. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  41377. rc = i;
  41378. break;
  41379. }
  41380. }
  41381. /* Free allocated structure */
  41382. bitvec_end:
  41383. sqlite3_free(pTmpSpace);
  41384. sqlite3_free(pV);
  41385. sqlite3BitvecDestroy(pBitvec);
  41386. return rc;
  41387. }
  41388. #endif /* SQLITE_UNTESTABLE */
  41389. /************** End of bitvec.c **********************************************/
  41390. /************** Begin file pcache.c ******************************************/
  41391. /*
  41392. ** 2008 August 05
  41393. **
  41394. ** The author disclaims copyright to this source code. In place of
  41395. ** a legal notice, here is a blessing:
  41396. **
  41397. ** May you do good and not evil.
  41398. ** May you find forgiveness for yourself and forgive others.
  41399. ** May you share freely, never taking more than you give.
  41400. **
  41401. *************************************************************************
  41402. ** This file implements that page cache.
  41403. */
  41404. /* #include "sqliteInt.h" */
  41405. /*
  41406. ** A complete page cache is an instance of this structure. Every
  41407. ** entry in the cache holds a single page of the database file. The
  41408. ** btree layer only operates on the cached copy of the database pages.
  41409. **
  41410. ** A page cache entry is "clean" if it exactly matches what is currently
  41411. ** on disk. A page is "dirty" if it has been modified and needs to be
  41412. ** persisted to disk.
  41413. **
  41414. ** pDirty, pDirtyTail, pSynced:
  41415. ** All dirty pages are linked into the doubly linked list using
  41416. ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
  41417. ** such that p was added to the list more recently than p->pDirtyNext.
  41418. ** PCache.pDirty points to the first (newest) element in the list and
  41419. ** pDirtyTail to the last (oldest).
  41420. **
  41421. ** The PCache.pSynced variable is used to optimize searching for a dirty
  41422. ** page to eject from the cache mid-transaction. It is better to eject
  41423. ** a page that does not require a journal sync than one that does.
  41424. ** Therefore, pSynced is maintained to that it *almost* always points
  41425. ** to either the oldest page in the pDirty/pDirtyTail list that has a
  41426. ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
  41427. ** (so that the right page to eject can be found by following pDirtyPrev
  41428. ** pointers).
  41429. */
  41430. struct PCache {
  41431. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  41432. PgHdr *pSynced; /* Last synced page in dirty page list */
  41433. int nRefSum; /* Sum of ref counts over all pages */
  41434. int szCache; /* Configured cache size */
  41435. int szSpill; /* Size before spilling occurs */
  41436. int szPage; /* Size of every page in this cache */
  41437. int szExtra; /* Size of extra space for each page */
  41438. u8 bPurgeable; /* True if pages are on backing store */
  41439. u8 eCreate; /* eCreate value for for xFetch() */
  41440. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  41441. void *pStress; /* Argument to xStress */
  41442. sqlite3_pcache *pCache; /* Pluggable cache module */
  41443. };
  41444. /********************************** Test and Debug Logic **********************/
  41445. /*
  41446. ** Debug tracing macros. Enable by by changing the "0" to "1" and
  41447. ** recompiling.
  41448. **
  41449. ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
  41450. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
  41451. ** is displayed for many operations, resulting in a lot of output.
  41452. */
  41453. #if defined(SQLITE_DEBUG) && 0
  41454. int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
  41455. int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
  41456. # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  41457. void pcacheDump(PCache *pCache){
  41458. int N;
  41459. int i, j;
  41460. sqlite3_pcache_page *pLower;
  41461. PgHdr *pPg;
  41462. unsigned char *a;
  41463. if( sqlite3PcacheTrace<2 ) return;
  41464. if( pCache->pCache==0 ) return;
  41465. N = sqlite3PcachePagecount(pCache);
  41466. if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
  41467. for(i=1; i<=N; i++){
  41468. pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
  41469. if( pLower==0 ) continue;
  41470. pPg = (PgHdr*)pLower->pExtra;
  41471. printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
  41472. a = (unsigned char *)pLower->pBuf;
  41473. for(j=0; j<12; j++) printf("%02x", a[j]);
  41474. printf("\n");
  41475. if( pPg->pPage==0 ){
  41476. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
  41477. }
  41478. }
  41479. }
  41480. #else
  41481. # define pcacheTrace(X)
  41482. # define pcacheDump(X)
  41483. #endif
  41484. /*
  41485. ** Check invariants on a PgHdr entry. Return true if everything is OK.
  41486. ** Return false if any invariant is violated.
  41487. **
  41488. ** This routine is for use inside of assert() statements only. For
  41489. ** example:
  41490. **
  41491. ** assert( sqlite3PcachePageSanity(pPg) );
  41492. */
  41493. #ifdef SQLITE_DEBUG
  41494. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
  41495. PCache *pCache;
  41496. assert( pPg!=0 );
  41497. assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
  41498. pCache = pPg->pCache;
  41499. assert( pCache!=0 ); /* Every page has an associated PCache */
  41500. if( pPg->flags & PGHDR_CLEAN ){
  41501. assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
  41502. assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
  41503. assert( pCache->pDirtyTail!=pPg );
  41504. }
  41505. /* WRITEABLE pages must also be DIRTY */
  41506. if( pPg->flags & PGHDR_WRITEABLE ){
  41507. assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
  41508. }
  41509. /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
  41510. ** for example, when using the sqlite3PagerDontWrite() optimization:
  41511. ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
  41512. ** (2) Page X moved to freelist, WRITEABLE is cleared
  41513. ** (3) Page X reused, WRITEABLE is set again
  41514. ** If NEED_SYNC had been cleared in step 2, then it would not be reset
  41515. ** in step 3, and page might be written into the database without first
  41516. ** syncing the rollback journal, which might cause corruption on a power
  41517. ** loss.
  41518. **
  41519. ** Another example is when the database page size is smaller than the
  41520. ** disk sector size. When any page of a sector is journalled, all pages
  41521. ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
  41522. ** in case they are later modified, since all pages in the same sector
  41523. ** must be journalled and synced before any of those pages can be safely
  41524. ** written.
  41525. */
  41526. return 1;
  41527. }
  41528. #endif /* SQLITE_DEBUG */
  41529. /********************************** Linked List Management ********************/
  41530. /* Allowed values for second argument to pcacheManageDirtyList() */
  41531. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  41532. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  41533. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  41534. /*
  41535. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  41536. ** argument determines what operation to do. The 0x01 bit means first
  41537. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  41538. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  41539. */
  41540. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  41541. PCache *p = pPage->pCache;
  41542. pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
  41543. addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
  41544. pPage->pgno));
  41545. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  41546. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  41547. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  41548. /* Update the PCache1.pSynced variable if necessary. */
  41549. if( p->pSynced==pPage ){
  41550. p->pSynced = pPage->pDirtyPrev;
  41551. }
  41552. if( pPage->pDirtyNext ){
  41553. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  41554. }else{
  41555. assert( pPage==p->pDirtyTail );
  41556. p->pDirtyTail = pPage->pDirtyPrev;
  41557. }
  41558. if( pPage->pDirtyPrev ){
  41559. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  41560. }else{
  41561. /* If there are now no dirty pages in the cache, set eCreate to 2.
  41562. ** This is an optimization that allows sqlite3PcacheFetch() to skip
  41563. ** searching for a dirty page to eject from the cache when it might
  41564. ** otherwise have to. */
  41565. assert( pPage==p->pDirty );
  41566. p->pDirty = pPage->pDirtyNext;
  41567. assert( p->bPurgeable || p->eCreate==2 );
  41568. if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
  41569. assert( p->bPurgeable==0 || p->eCreate==1 );
  41570. p->eCreate = 2;
  41571. }
  41572. }
  41573. pPage->pDirtyNext = 0;
  41574. pPage->pDirtyPrev = 0;
  41575. }
  41576. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  41577. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  41578. pPage->pDirtyNext = p->pDirty;
  41579. if( pPage->pDirtyNext ){
  41580. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  41581. pPage->pDirtyNext->pDirtyPrev = pPage;
  41582. }else{
  41583. p->pDirtyTail = pPage;
  41584. if( p->bPurgeable ){
  41585. assert( p->eCreate==2 );
  41586. p->eCreate = 1;
  41587. }
  41588. }
  41589. p->pDirty = pPage;
  41590. /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
  41591. ** pSynced to point to it. Checking the NEED_SYNC flag is an
  41592. ** optimization, as if pSynced points to a page with the NEED_SYNC
  41593. ** flag set sqlite3PcacheFetchStress() searches through all newer
  41594. ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
  41595. if( !p->pSynced
  41596. && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
  41597. ){
  41598. p->pSynced = pPage;
  41599. }
  41600. }
  41601. pcacheDump(p);
  41602. }
  41603. /*
  41604. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  41605. ** being used for an in-memory database, this function is a no-op.
  41606. */
  41607. static void pcacheUnpin(PgHdr *p){
  41608. if( p->pCache->bPurgeable ){
  41609. pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
  41610. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  41611. pcacheDump(p->pCache);
  41612. }
  41613. }
  41614. /*
  41615. ** Compute the number of pages of cache requested. p->szCache is the
  41616. ** cache size requested by the "PRAGMA cache_size" statement.
  41617. */
  41618. static int numberOfCachePages(PCache *p){
  41619. if( p->szCache>=0 ){
  41620. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  41621. ** suggested cache size is set to N. */
  41622. return p->szCache;
  41623. }else{
  41624. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  41625. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  41626. ** bytes of memory. */
  41627. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  41628. }
  41629. }
  41630. /*************************************************** General Interfaces ******
  41631. **
  41632. ** Initialize and shutdown the page cache subsystem. Neither of these
  41633. ** functions are threadsafe.
  41634. */
  41635. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  41636. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  41637. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  41638. ** built-in default page cache is used instead of the application defined
  41639. ** page cache. */
  41640. sqlite3PCacheSetDefault();
  41641. }
  41642. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  41643. }
  41644. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  41645. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  41646. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  41647. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  41648. }
  41649. }
  41650. /*
  41651. ** Return the size in bytes of a PCache object.
  41652. */
  41653. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  41654. /*
  41655. ** Create a new PCache object. Storage space to hold the object
  41656. ** has already been allocated and is passed in as the p pointer.
  41657. ** The caller discovers how much space needs to be allocated by
  41658. ** calling sqlite3PcacheSize().
  41659. **
  41660. ** szExtra is some extra space allocated for each page. The first
  41661. ** 8 bytes of the extra space will be zeroed as the page is allocated,
  41662. ** but remaining content will be uninitialized. Though it is opaque
  41663. ** to this module, the extra space really ends up being the MemPage
  41664. ** structure in the pager.
  41665. */
  41666. SQLITE_PRIVATE int sqlite3PcacheOpen(
  41667. int szPage, /* Size of every page */
  41668. int szExtra, /* Extra space associated with each page */
  41669. int bPurgeable, /* True if pages are on backing store */
  41670. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  41671. void *pStress, /* Argument to xStress */
  41672. PCache *p /* Preallocated space for the PCache */
  41673. ){
  41674. memset(p, 0, sizeof(PCache));
  41675. p->szPage = 1;
  41676. p->szExtra = szExtra;
  41677. assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
  41678. p->bPurgeable = bPurgeable;
  41679. p->eCreate = 2;
  41680. p->xStress = xStress;
  41681. p->pStress = pStress;
  41682. p->szCache = 100;
  41683. p->szSpill = 1;
  41684. pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
  41685. return sqlite3PcacheSetPageSize(p, szPage);
  41686. }
  41687. /*
  41688. ** Change the page size for PCache object. The caller must ensure that there
  41689. ** are no outstanding page references when this function is called.
  41690. */
  41691. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  41692. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  41693. if( pCache->szPage ){
  41694. sqlite3_pcache *pNew;
  41695. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  41696. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  41697. pCache->bPurgeable
  41698. );
  41699. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  41700. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  41701. if( pCache->pCache ){
  41702. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  41703. }
  41704. pCache->pCache = pNew;
  41705. pCache->szPage = szPage;
  41706. pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
  41707. }
  41708. return SQLITE_OK;
  41709. }
  41710. /*
  41711. ** Try to obtain a page from the cache.
  41712. **
  41713. ** This routine returns a pointer to an sqlite3_pcache_page object if
  41714. ** such an object is already in cache, or if a new one is created.
  41715. ** This routine returns a NULL pointer if the object was not in cache
  41716. ** and could not be created.
  41717. **
  41718. ** The createFlags should be 0 to check for existing pages and should
  41719. ** be 3 (not 1, but 3) to try to create a new page.
  41720. **
  41721. ** If the createFlag is 0, then NULL is always returned if the page
  41722. ** is not already in the cache. If createFlag is 1, then a new page
  41723. ** is created only if that can be done without spilling dirty pages
  41724. ** and without exceeding the cache size limit.
  41725. **
  41726. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  41727. ** initialize the sqlite3_pcache_page object and convert it into a
  41728. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  41729. ** routines are split this way for performance reasons. When separated
  41730. ** they can both (usually) operate without having to push values to
  41731. ** the stack on entry and pop them back off on exit, which saves a
  41732. ** lot of pushing and popping.
  41733. */
  41734. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  41735. PCache *pCache, /* Obtain the page from this cache */
  41736. Pgno pgno, /* Page number to obtain */
  41737. int createFlag /* If true, create page if it does not exist already */
  41738. ){
  41739. int eCreate;
  41740. sqlite3_pcache_page *pRes;
  41741. assert( pCache!=0 );
  41742. assert( pCache->pCache!=0 );
  41743. assert( createFlag==3 || createFlag==0 );
  41744. assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
  41745. /* eCreate defines what to do if the page does not exist.
  41746. ** 0 Do not allocate a new page. (createFlag==0)
  41747. ** 1 Allocate a new page if doing so is inexpensive.
  41748. ** (createFlag==1 AND bPurgeable AND pDirty)
  41749. ** 2 Allocate a new page even it doing so is difficult.
  41750. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  41751. */
  41752. eCreate = createFlag & pCache->eCreate;
  41753. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  41754. assert( createFlag==0 || pCache->eCreate==eCreate );
  41755. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  41756. pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  41757. pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
  41758. createFlag?" create":"",pRes));
  41759. return pRes;
  41760. }
  41761. /*
  41762. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  41763. ** page because no clean pages are available for reuse and the cache
  41764. ** size limit has been reached, then this routine can be invoked to
  41765. ** try harder to allocate a page. This routine might invoke the stress
  41766. ** callback to spill dirty pages to the journal. It will then try to
  41767. ** allocate the new page and will only fail to allocate a new page on
  41768. ** an OOM error.
  41769. **
  41770. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  41771. */
  41772. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  41773. PCache *pCache, /* Obtain the page from this cache */
  41774. Pgno pgno, /* Page number to obtain */
  41775. sqlite3_pcache_page **ppPage /* Write result here */
  41776. ){
  41777. PgHdr *pPg;
  41778. if( pCache->eCreate==2 ) return 0;
  41779. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  41780. /* Find a dirty page to write-out and recycle. First try to find a
  41781. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  41782. ** cleared), but if that is not possible settle for any other
  41783. ** unreferenced dirty page.
  41784. **
  41785. ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
  41786. ** flag is currently referenced, then the following may leave pSynced
  41787. ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
  41788. ** cleared). This is Ok, as pSynced is just an optimization. */
  41789. for(pPg=pCache->pSynced;
  41790. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  41791. pPg=pPg->pDirtyPrev
  41792. );
  41793. pCache->pSynced = pPg;
  41794. if( !pPg ){
  41795. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  41796. }
  41797. if( pPg ){
  41798. int rc;
  41799. #ifdef SQLITE_LOG_CACHE_SPILL
  41800. sqlite3_log(SQLITE_FULL,
  41801. "spill page %d making room for %d - cache used: %d/%d",
  41802. pPg->pgno, pgno,
  41803. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  41804. numberOfCachePages(pCache));
  41805. #endif
  41806. pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
  41807. rc = pCache->xStress(pCache->pStress, pPg);
  41808. pcacheDump(pCache);
  41809. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  41810. return rc;
  41811. }
  41812. }
  41813. }
  41814. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  41815. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  41816. }
  41817. /*
  41818. ** This is a helper routine for sqlite3PcacheFetchFinish()
  41819. **
  41820. ** In the uncommon case where the page being fetched has not been
  41821. ** initialized, this routine is invoked to do the initialization.
  41822. ** This routine is broken out into a separate function since it
  41823. ** requires extra stack manipulation that can be avoided in the common
  41824. ** case.
  41825. */
  41826. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  41827. PCache *pCache, /* Obtain the page from this cache */
  41828. Pgno pgno, /* Page number obtained */
  41829. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  41830. ){
  41831. PgHdr *pPgHdr;
  41832. assert( pPage!=0 );
  41833. pPgHdr = (PgHdr*)pPage->pExtra;
  41834. assert( pPgHdr->pPage==0 );
  41835. memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
  41836. pPgHdr->pPage = pPage;
  41837. pPgHdr->pData = pPage->pBuf;
  41838. pPgHdr->pExtra = (void *)&pPgHdr[1];
  41839. memset(pPgHdr->pExtra, 0, 8);
  41840. pPgHdr->pCache = pCache;
  41841. pPgHdr->pgno = pgno;
  41842. pPgHdr->flags = PGHDR_CLEAN;
  41843. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  41844. }
  41845. /*
  41846. ** This routine converts the sqlite3_pcache_page object returned by
  41847. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  41848. ** must be called after sqlite3PcacheFetch() in order to get a usable
  41849. ** result.
  41850. */
  41851. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  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. if( !pPgHdr->pPage ){
  41860. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  41861. }
  41862. pCache->nRefSum++;
  41863. pPgHdr->nRef++;
  41864. assert( sqlite3PcachePageSanity(pPgHdr) );
  41865. return pPgHdr;
  41866. }
  41867. /*
  41868. ** Decrement the reference count on a page. If the page is clean and the
  41869. ** reference count drops to 0, then it is made eligible for recycling.
  41870. */
  41871. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  41872. assert( p->nRef>0 );
  41873. p->pCache->nRefSum--;
  41874. if( (--p->nRef)==0 ){
  41875. if( p->flags&PGHDR_CLEAN ){
  41876. pcacheUnpin(p);
  41877. }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
  41878. /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
  41879. ** then page p is already at the head of the dirty list and the
  41880. ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
  41881. ** tag above. */
  41882. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  41883. }
  41884. }
  41885. }
  41886. /*
  41887. ** Increase the reference count of a supplied page by 1.
  41888. */
  41889. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  41890. assert(p->nRef>0);
  41891. assert( sqlite3PcachePageSanity(p) );
  41892. p->nRef++;
  41893. p->pCache->nRefSum++;
  41894. }
  41895. /*
  41896. ** Drop a page from the cache. There must be exactly one reference to the
  41897. ** page. This function deletes that reference, so after it returns the
  41898. ** page pointed to by p is invalid.
  41899. */
  41900. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  41901. assert( p->nRef==1 );
  41902. assert( sqlite3PcachePageSanity(p) );
  41903. if( p->flags&PGHDR_DIRTY ){
  41904. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  41905. }
  41906. p->pCache->nRefSum--;
  41907. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  41908. }
  41909. /*
  41910. ** Make sure the page is marked as dirty. If it isn't dirty already,
  41911. ** make it so.
  41912. */
  41913. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  41914. assert( p->nRef>0 );
  41915. assert( sqlite3PcachePageSanity(p) );
  41916. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
  41917. p->flags &= ~PGHDR_DONT_WRITE;
  41918. if( p->flags & PGHDR_CLEAN ){
  41919. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  41920. pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
  41921. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  41922. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  41923. }
  41924. assert( sqlite3PcachePageSanity(p) );
  41925. }
  41926. }
  41927. /*
  41928. ** Make sure the page is marked as clean. If it isn't clean already,
  41929. ** make it so.
  41930. */
  41931. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  41932. assert( sqlite3PcachePageSanity(p) );
  41933. if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
  41934. assert( (p->flags & PGHDR_CLEAN)==0 );
  41935. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  41936. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  41937. p->flags |= PGHDR_CLEAN;
  41938. pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
  41939. assert( sqlite3PcachePageSanity(p) );
  41940. if( p->nRef==0 ){
  41941. pcacheUnpin(p);
  41942. }
  41943. }
  41944. }
  41945. /*
  41946. ** Make every page in the cache clean.
  41947. */
  41948. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  41949. PgHdr *p;
  41950. pcacheTrace(("%p.CLEAN-ALL\n",pCache));
  41951. while( (p = pCache->pDirty)!=0 ){
  41952. sqlite3PcacheMakeClean(p);
  41953. }
  41954. }
  41955. /*
  41956. ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
  41957. */
  41958. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
  41959. PgHdr *p;
  41960. pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
  41961. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  41962. p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  41963. }
  41964. pCache->pSynced = pCache->pDirtyTail;
  41965. }
  41966. /*
  41967. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  41968. */
  41969. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  41970. PgHdr *p;
  41971. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  41972. p->flags &= ~PGHDR_NEED_SYNC;
  41973. }
  41974. pCache->pSynced = pCache->pDirtyTail;
  41975. }
  41976. /*
  41977. ** Change the page number of page p to newPgno.
  41978. */
  41979. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  41980. PCache *pCache = p->pCache;
  41981. assert( p->nRef>0 );
  41982. assert( newPgno>0 );
  41983. assert( sqlite3PcachePageSanity(p) );
  41984. pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
  41985. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  41986. p->pgno = newPgno;
  41987. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  41988. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  41989. }
  41990. }
  41991. /*
  41992. ** Drop every cache entry whose page number is greater than "pgno". The
  41993. ** caller must ensure that there are no outstanding references to any pages
  41994. ** other than page 1 with a page number greater than pgno.
  41995. **
  41996. ** If there is a reference to page 1 and the pgno parameter passed to this
  41997. ** function is 0, then the data area associated with page 1 is zeroed, but
  41998. ** the page object is not dropped.
  41999. */
  42000. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  42001. if( pCache->pCache ){
  42002. PgHdr *p;
  42003. PgHdr *pNext;
  42004. pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
  42005. for(p=pCache->pDirty; p; p=pNext){
  42006. pNext = p->pDirtyNext;
  42007. /* This routine never gets call with a positive pgno except right
  42008. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  42009. ** it must be that pgno==0.
  42010. */
  42011. assert( p->pgno>0 );
  42012. if( p->pgno>pgno ){
  42013. assert( p->flags&PGHDR_DIRTY );
  42014. sqlite3PcacheMakeClean(p);
  42015. }
  42016. }
  42017. if( pgno==0 && pCache->nRefSum ){
  42018. sqlite3_pcache_page *pPage1;
  42019. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  42020. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  42021. ** pCache->nRefSum>0 */
  42022. memset(pPage1->pBuf, 0, pCache->szPage);
  42023. pgno = 1;
  42024. }
  42025. }
  42026. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  42027. }
  42028. }
  42029. /*
  42030. ** Close a cache.
  42031. */
  42032. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  42033. assert( pCache->pCache!=0 );
  42034. pcacheTrace(("%p.CLOSE\n",pCache));
  42035. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  42036. }
  42037. /*
  42038. ** Discard the contents of the cache.
  42039. */
  42040. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  42041. sqlite3PcacheTruncate(pCache, 0);
  42042. }
  42043. /*
  42044. ** Merge two lists of pages connected by pDirty and in pgno order.
  42045. ** Do not bother fixing the pDirtyPrev pointers.
  42046. */
  42047. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  42048. PgHdr result, *pTail;
  42049. pTail = &result;
  42050. assert( pA!=0 && pB!=0 );
  42051. for(;;){
  42052. if( pA->pgno<pB->pgno ){
  42053. pTail->pDirty = pA;
  42054. pTail = pA;
  42055. pA = pA->pDirty;
  42056. if( pA==0 ){
  42057. pTail->pDirty = pB;
  42058. break;
  42059. }
  42060. }else{
  42061. pTail->pDirty = pB;
  42062. pTail = pB;
  42063. pB = pB->pDirty;
  42064. if( pB==0 ){
  42065. pTail->pDirty = pA;
  42066. break;
  42067. }
  42068. }
  42069. }
  42070. return result.pDirty;
  42071. }
  42072. /*
  42073. ** Sort the list of pages in accending order by pgno. Pages are
  42074. ** connected by pDirty pointers. The pDirtyPrev pointers are
  42075. ** corrupted by this sort.
  42076. **
  42077. ** Since there cannot be more than 2^31 distinct pages in a database,
  42078. ** there cannot be more than 31 buckets required by the merge sorter.
  42079. ** One extra bucket is added to catch overflow in case something
  42080. ** ever changes to make the previous sentence incorrect.
  42081. */
  42082. #define N_SORT_BUCKET 32
  42083. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  42084. PgHdr *a[N_SORT_BUCKET], *p;
  42085. int i;
  42086. memset(a, 0, sizeof(a));
  42087. while( pIn ){
  42088. p = pIn;
  42089. pIn = p->pDirty;
  42090. p->pDirty = 0;
  42091. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  42092. if( a[i]==0 ){
  42093. a[i] = p;
  42094. break;
  42095. }else{
  42096. p = pcacheMergeDirtyList(a[i], p);
  42097. a[i] = 0;
  42098. }
  42099. }
  42100. if( NEVER(i==N_SORT_BUCKET-1) ){
  42101. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  42102. ** the input list. But that is impossible.
  42103. */
  42104. a[i] = pcacheMergeDirtyList(a[i], p);
  42105. }
  42106. }
  42107. p = a[0];
  42108. for(i=1; i<N_SORT_BUCKET; i++){
  42109. if( a[i]==0 ) continue;
  42110. p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
  42111. }
  42112. return p;
  42113. }
  42114. /*
  42115. ** Return a list of all dirty pages in the cache, sorted by page number.
  42116. */
  42117. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  42118. PgHdr *p;
  42119. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  42120. p->pDirty = p->pDirtyNext;
  42121. }
  42122. return pcacheSortDirtyList(pCache->pDirty);
  42123. }
  42124. /*
  42125. ** Return the total number of references to all pages held by the cache.
  42126. **
  42127. ** This is not the total number of pages referenced, but the sum of the
  42128. ** reference count for all pages.
  42129. */
  42130. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  42131. return pCache->nRefSum;
  42132. }
  42133. /*
  42134. ** Return the number of references to the page supplied as an argument.
  42135. */
  42136. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  42137. return p->nRef;
  42138. }
  42139. /*
  42140. ** Return the total number of pages in the cache.
  42141. */
  42142. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  42143. assert( pCache->pCache!=0 );
  42144. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  42145. }
  42146. #ifdef SQLITE_TEST
  42147. /*
  42148. ** Get the suggested cache-size value.
  42149. */
  42150. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  42151. return numberOfCachePages(pCache);
  42152. }
  42153. #endif
  42154. /*
  42155. ** Set the suggested cache-size value.
  42156. */
  42157. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  42158. assert( pCache->pCache!=0 );
  42159. pCache->szCache = mxPage;
  42160. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  42161. numberOfCachePages(pCache));
  42162. }
  42163. /*
  42164. ** Set the suggested cache-spill value. Make no changes if if the
  42165. ** argument is zero. Return the effective cache-spill size, which will
  42166. ** be the larger of the szSpill and szCache.
  42167. */
  42168. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  42169. int res;
  42170. assert( p->pCache!=0 );
  42171. if( mxPage ){
  42172. if( mxPage<0 ){
  42173. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  42174. }
  42175. p->szSpill = mxPage;
  42176. }
  42177. res = numberOfCachePages(p);
  42178. if( res<p->szSpill ) res = p->szSpill;
  42179. return res;
  42180. }
  42181. /*
  42182. ** Free up as much memory as possible from the page cache.
  42183. */
  42184. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  42185. assert( pCache->pCache!=0 );
  42186. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  42187. }
  42188. /*
  42189. ** Return the size of the header added by this middleware layer
  42190. ** in the page-cache hierarchy.
  42191. */
  42192. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  42193. /*
  42194. ** Return the number of dirty pages currently in the cache, as a percentage
  42195. ** of the configured cache size.
  42196. */
  42197. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
  42198. PgHdr *pDirty;
  42199. int nDirty = 0;
  42200. int nCache = numberOfCachePages(pCache);
  42201. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
  42202. return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
  42203. }
  42204. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  42205. /*
  42206. ** For all dirty pages currently in the cache, invoke the specified
  42207. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  42208. ** defined.
  42209. */
  42210. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  42211. PgHdr *pDirty;
  42212. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  42213. xIter(pDirty);
  42214. }
  42215. }
  42216. #endif
  42217. /************** End of pcache.c **********************************************/
  42218. /************** Begin file pcache1.c *****************************************/
  42219. /*
  42220. ** 2008 November 05
  42221. **
  42222. ** The author disclaims copyright to this source code. In place of
  42223. ** a legal notice, here is a blessing:
  42224. **
  42225. ** May you do good and not evil.
  42226. ** May you find forgiveness for yourself and forgive others.
  42227. ** May you share freely, never taking more than you give.
  42228. **
  42229. *************************************************************************
  42230. **
  42231. ** This file implements the default page cache implementation (the
  42232. ** sqlite3_pcache interface). It also contains part of the implementation
  42233. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  42234. ** If the default page cache implementation is overridden, then neither of
  42235. ** these two features are available.
  42236. **
  42237. ** A Page cache line looks like this:
  42238. **
  42239. ** -------------------------------------------------------------
  42240. ** | database page content | PgHdr1 | MemPage | PgHdr |
  42241. ** -------------------------------------------------------------
  42242. **
  42243. ** The database page content is up front (so that buffer overreads tend to
  42244. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  42245. ** is the extension added by the btree.c module containing information such
  42246. ** as the database page number and how that database page is used. PgHdr
  42247. ** is added by the pcache.c layer and contains information used to keep track
  42248. ** of which pages are "dirty". PgHdr1 is an extension added by this
  42249. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  42250. ** PgHdr1 contains information needed to look up a page by its page number.
  42251. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  42252. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  42253. **
  42254. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  42255. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  42256. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  42257. ** size can vary according to architecture, compile-time options, and
  42258. ** SQLite library version number.
  42259. **
  42260. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  42261. ** using a separate memory allocation from the database page content. This
  42262. ** seeks to overcome the "clownshoe" problem (also called "internal
  42263. ** fragmentation" in academic literature) of allocating a few bytes more
  42264. ** than a power of two with the memory allocator rounding up to the next
  42265. ** power of two, and leaving the rounded-up space unused.
  42266. **
  42267. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  42268. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  42269. **
  42270. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  42271. ** The btree.c module deals with pointers to MemPage objects.
  42272. **
  42273. ** SOURCE OF PAGE CACHE MEMORY:
  42274. **
  42275. ** Memory for a page might come from any of three sources:
  42276. **
  42277. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  42278. ** (2) Global page-cache memory provided using sqlite3_config() with
  42279. ** SQLITE_CONFIG_PAGECACHE.
  42280. ** (3) PCache-local bulk allocation.
  42281. **
  42282. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  42283. ** that is allocated when the page cache is created. The size of the local
  42284. ** bulk allocation can be adjusted using
  42285. **
  42286. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  42287. **
  42288. ** If N is positive, then N pages worth of memory are allocated using a single
  42289. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  42290. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  42291. ** for as many pages as can be accomodated.
  42292. **
  42293. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  42294. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  42295. ** memory allocator (1).
  42296. **
  42297. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  42298. ** show that method (3) with N==100 provides about a 5% performance boost for
  42299. ** common workloads.
  42300. */
  42301. /* #include "sqliteInt.h" */
  42302. typedef struct PCache1 PCache1;
  42303. typedef struct PgHdr1 PgHdr1;
  42304. typedef struct PgFreeslot PgFreeslot;
  42305. typedef struct PGroup PGroup;
  42306. /*
  42307. ** Each cache entry is represented by an instance of the following
  42308. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  42309. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  42310. ** in memory.
  42311. */
  42312. struct PgHdr1 {
  42313. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  42314. unsigned int iKey; /* Key value (page number) */
  42315. u8 isPinned; /* Page in use, not on the LRU list */
  42316. u8 isBulkLocal; /* This page from bulk local storage */
  42317. u8 isAnchor; /* This is the PGroup.lru element */
  42318. PgHdr1 *pNext; /* Next in hash table chain */
  42319. PCache1 *pCache; /* Cache that currently owns this page */
  42320. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  42321. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  42322. };
  42323. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  42324. ** of one or more PCaches that are able to recycle each other's unpinned
  42325. ** pages when they are under memory pressure. A PGroup is an instance of
  42326. ** the following object.
  42327. **
  42328. ** This page cache implementation works in one of two modes:
  42329. **
  42330. ** (1) Every PCache is the sole member of its own PGroup. There is
  42331. ** one PGroup per PCache.
  42332. **
  42333. ** (2) There is a single global PGroup that all PCaches are a member
  42334. ** of.
  42335. **
  42336. ** Mode 1 uses more memory (since PCache instances are not able to rob
  42337. ** unused pages from other PCaches) but it also operates without a mutex,
  42338. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  42339. ** threadsafe, but recycles pages more efficiently.
  42340. **
  42341. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  42342. ** PGroup which is the pcache1.grp global variable and its mutex is
  42343. ** SQLITE_MUTEX_STATIC_LRU.
  42344. */
  42345. struct PGroup {
  42346. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  42347. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  42348. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  42349. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  42350. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  42351. PgHdr1 lru; /* The beginning and end of the LRU list */
  42352. };
  42353. /* Each page cache is an instance of the following object. Every
  42354. ** open database file (including each in-memory database and each
  42355. ** temporary or transient database) has a single page cache which
  42356. ** is an instance of this object.
  42357. **
  42358. ** Pointers to structures of this type are cast and returned as
  42359. ** opaque sqlite3_pcache* handles.
  42360. */
  42361. struct PCache1 {
  42362. /* Cache configuration parameters. Page size (szPage) and the purgeable
  42363. ** flag (bPurgeable) are set when the cache is created. nMax may be
  42364. ** modified at any time by a call to the pcache1Cachesize() method.
  42365. ** The PGroup mutex must be held when accessing nMax.
  42366. */
  42367. PGroup *pGroup; /* PGroup this cache belongs to */
  42368. int szPage; /* Size of database content section */
  42369. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  42370. int szAlloc; /* Total size of one pcache line */
  42371. int bPurgeable; /* True if cache is purgeable */
  42372. unsigned int nMin; /* Minimum number of pages reserved */
  42373. unsigned int nMax; /* Configured "cache_size" value */
  42374. unsigned int n90pct; /* nMax*9/10 */
  42375. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  42376. /* Hash table of all pages. The following variables may only be accessed
  42377. ** when the accessor is holding the PGroup mutex.
  42378. */
  42379. unsigned int nRecyclable; /* Number of pages in the LRU list */
  42380. unsigned int nPage; /* Total number of pages in apHash */
  42381. unsigned int nHash; /* Number of slots in apHash[] */
  42382. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  42383. PgHdr1 *pFree; /* List of unused pcache-local pages */
  42384. void *pBulk; /* Bulk memory used by pcache-local */
  42385. };
  42386. /*
  42387. ** Free slots in the allocator used to divide up the global page cache
  42388. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  42389. */
  42390. struct PgFreeslot {
  42391. PgFreeslot *pNext; /* Next free slot */
  42392. };
  42393. /*
  42394. ** Global data used by this cache.
  42395. */
  42396. static SQLITE_WSD struct PCacheGlobal {
  42397. PGroup grp; /* The global PGroup for mode (2) */
  42398. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  42399. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  42400. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  42401. ** The nFreeSlot and pFree values do require mutex protection.
  42402. */
  42403. int isInit; /* True if initialized */
  42404. int separateCache; /* Use a new PGroup for each PCache */
  42405. int nInitPage; /* Initial bulk allocation size */
  42406. int szSlot; /* Size of each free slot */
  42407. int nSlot; /* The number of pcache slots */
  42408. int nReserve; /* Try to keep nFreeSlot above this */
  42409. void *pStart, *pEnd; /* Bounds of global page cache memory */
  42410. /* Above requires no mutex. Use mutex below for variable that follow. */
  42411. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  42412. PgFreeslot *pFree; /* Free page blocks */
  42413. int nFreeSlot; /* Number of unused pcache slots */
  42414. /* The following value requires a mutex to change. We skip the mutex on
  42415. ** reading because (1) most platforms read a 32-bit integer atomically and
  42416. ** (2) even if an incorrect value is read, no great harm is done since this
  42417. ** is really just an optimization. */
  42418. int bUnderPressure; /* True if low on PAGECACHE memory */
  42419. } pcache1_g;
  42420. /*
  42421. ** All code in this file should access the global structure above via the
  42422. ** alias "pcache1". This ensures that the WSD emulation is used when
  42423. ** compiling for systems that do not support real WSD.
  42424. */
  42425. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  42426. /*
  42427. ** Macros to enter and leave the PCache LRU mutex.
  42428. */
  42429. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  42430. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  42431. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  42432. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  42433. #else
  42434. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  42435. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  42436. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  42437. #endif
  42438. /******************************************************************************/
  42439. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  42440. /*
  42441. ** This function is called during initialization if a static buffer is
  42442. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  42443. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  42444. ** enough to contain 'n' buffers of 'sz' bytes each.
  42445. **
  42446. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  42447. ** to be serialized already. There is no need for further mutexing.
  42448. */
  42449. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  42450. if( pcache1.isInit ){
  42451. PgFreeslot *p;
  42452. if( pBuf==0 ) sz = n = 0;
  42453. sz = ROUNDDOWN8(sz);
  42454. pcache1.szSlot = sz;
  42455. pcache1.nSlot = pcache1.nFreeSlot = n;
  42456. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  42457. pcache1.pStart = pBuf;
  42458. pcache1.pFree = 0;
  42459. pcache1.bUnderPressure = 0;
  42460. while( n-- ){
  42461. p = (PgFreeslot*)pBuf;
  42462. p->pNext = pcache1.pFree;
  42463. pcache1.pFree = p;
  42464. pBuf = (void*)&((char*)pBuf)[sz];
  42465. }
  42466. pcache1.pEnd = pBuf;
  42467. }
  42468. }
  42469. /*
  42470. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  42471. ** true if pCache->pFree ends up containing one or more free pages.
  42472. */
  42473. static int pcache1InitBulk(PCache1 *pCache){
  42474. i64 szBulk;
  42475. char *zBulk;
  42476. if( pcache1.nInitPage==0 ) return 0;
  42477. /* Do not bother with a bulk allocation if the cache size very small */
  42478. if( pCache->nMax<3 ) return 0;
  42479. sqlite3BeginBenignMalloc();
  42480. if( pcache1.nInitPage>0 ){
  42481. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  42482. }else{
  42483. szBulk = -1024 * (i64)pcache1.nInitPage;
  42484. }
  42485. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  42486. szBulk = pCache->szAlloc*(i64)pCache->nMax;
  42487. }
  42488. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  42489. sqlite3EndBenignMalloc();
  42490. if( zBulk ){
  42491. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  42492. do{
  42493. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  42494. pX->page.pBuf = zBulk;
  42495. pX->page.pExtra = &pX[1];
  42496. pX->isBulkLocal = 1;
  42497. pX->isAnchor = 0;
  42498. pX->pNext = pCache->pFree;
  42499. pCache->pFree = pX;
  42500. zBulk += pCache->szAlloc;
  42501. }while( --nBulk );
  42502. }
  42503. return pCache->pFree!=0;
  42504. }
  42505. /*
  42506. ** Malloc function used within this file to allocate space from the buffer
  42507. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  42508. ** such buffer exists or there is no space left in it, this function falls
  42509. ** back to sqlite3Malloc().
  42510. **
  42511. ** Multiple threads can run this routine at the same time. Global variables
  42512. ** in pcache1 need to be protected via mutex.
  42513. */
  42514. static void *pcache1Alloc(int nByte){
  42515. void *p = 0;
  42516. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  42517. if( nByte<=pcache1.szSlot ){
  42518. sqlite3_mutex_enter(pcache1.mutex);
  42519. p = (PgHdr1 *)pcache1.pFree;
  42520. if( p ){
  42521. pcache1.pFree = pcache1.pFree->pNext;
  42522. pcache1.nFreeSlot--;
  42523. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  42524. assert( pcache1.nFreeSlot>=0 );
  42525. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  42526. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  42527. }
  42528. sqlite3_mutex_leave(pcache1.mutex);
  42529. }
  42530. if( p==0 ){
  42531. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  42532. ** it from sqlite3Malloc instead.
  42533. */
  42534. p = sqlite3Malloc(nByte);
  42535. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  42536. if( p ){
  42537. int sz = sqlite3MallocSize(p);
  42538. sqlite3_mutex_enter(pcache1.mutex);
  42539. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  42540. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  42541. sqlite3_mutex_leave(pcache1.mutex);
  42542. }
  42543. #endif
  42544. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  42545. }
  42546. return p;
  42547. }
  42548. /*
  42549. ** Free an allocated buffer obtained from pcache1Alloc().
  42550. */
  42551. static void pcache1Free(void *p){
  42552. if( p==0 ) return;
  42553. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  42554. PgFreeslot *pSlot;
  42555. sqlite3_mutex_enter(pcache1.mutex);
  42556. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  42557. pSlot = (PgFreeslot*)p;
  42558. pSlot->pNext = pcache1.pFree;
  42559. pcache1.pFree = pSlot;
  42560. pcache1.nFreeSlot++;
  42561. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  42562. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  42563. sqlite3_mutex_leave(pcache1.mutex);
  42564. }else{
  42565. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  42566. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  42567. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  42568. {
  42569. int nFreed = 0;
  42570. nFreed = sqlite3MallocSize(p);
  42571. sqlite3_mutex_enter(pcache1.mutex);
  42572. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  42573. sqlite3_mutex_leave(pcache1.mutex);
  42574. }
  42575. #endif
  42576. sqlite3_free(p);
  42577. }
  42578. }
  42579. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  42580. /*
  42581. ** Return the size of a pcache allocation
  42582. */
  42583. static int pcache1MemSize(void *p){
  42584. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  42585. return pcache1.szSlot;
  42586. }else{
  42587. int iSize;
  42588. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  42589. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  42590. iSize = sqlite3MallocSize(p);
  42591. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  42592. return iSize;
  42593. }
  42594. }
  42595. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  42596. /*
  42597. ** Allocate a new page object initially associated with cache pCache.
  42598. */
  42599. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  42600. PgHdr1 *p = 0;
  42601. void *pPg;
  42602. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  42603. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  42604. p = pCache->pFree;
  42605. pCache->pFree = p->pNext;
  42606. p->pNext = 0;
  42607. }else{
  42608. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  42609. /* The group mutex must be released before pcache1Alloc() is called. This
  42610. ** is because it might call sqlite3_release_memory(), which assumes that
  42611. ** this mutex is not held. */
  42612. assert( pcache1.separateCache==0 );
  42613. assert( pCache->pGroup==&pcache1.grp );
  42614. pcache1LeaveMutex(pCache->pGroup);
  42615. #endif
  42616. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  42617. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  42618. pPg = pcache1Alloc(pCache->szPage);
  42619. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  42620. if( !pPg || !p ){
  42621. pcache1Free(pPg);
  42622. sqlite3_free(p);
  42623. pPg = 0;
  42624. }
  42625. #else
  42626. pPg = pcache1Alloc(pCache->szAlloc);
  42627. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  42628. #endif
  42629. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  42630. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  42631. pcache1EnterMutex(pCache->pGroup);
  42632. #endif
  42633. if( pPg==0 ) return 0;
  42634. p->page.pBuf = pPg;
  42635. p->page.pExtra = &p[1];
  42636. p->isBulkLocal = 0;
  42637. p->isAnchor = 0;
  42638. }
  42639. if( pCache->bPurgeable ){
  42640. pCache->pGroup->nCurrentPage++;
  42641. }
  42642. return p;
  42643. }
  42644. /*
  42645. ** Free a page object allocated by pcache1AllocPage().
  42646. */
  42647. static void pcache1FreePage(PgHdr1 *p){
  42648. PCache1 *pCache;
  42649. assert( p!=0 );
  42650. pCache = p->pCache;
  42651. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  42652. if( p->isBulkLocal ){
  42653. p->pNext = pCache->pFree;
  42654. pCache->pFree = p;
  42655. }else{
  42656. pcache1Free(p->page.pBuf);
  42657. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  42658. sqlite3_free(p);
  42659. #endif
  42660. }
  42661. if( pCache->bPurgeable ){
  42662. pCache->pGroup->nCurrentPage--;
  42663. }
  42664. }
  42665. /*
  42666. ** Malloc function used by SQLite to obtain space from the buffer configured
  42667. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  42668. ** exists, this function falls back to sqlite3Malloc().
  42669. */
  42670. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  42671. return pcache1Alloc(sz);
  42672. }
  42673. /*
  42674. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  42675. */
  42676. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  42677. pcache1Free(p);
  42678. }
  42679. /*
  42680. ** Return true if it desirable to avoid allocating a new page cache
  42681. ** entry.
  42682. **
  42683. ** If memory was allocated specifically to the page cache using
  42684. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  42685. ** it is desirable to avoid allocating a new page cache entry because
  42686. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  42687. ** for all page cache needs and we should not need to spill the
  42688. ** allocation onto the heap.
  42689. **
  42690. ** Or, the heap is used for all page cache memory but the heap is
  42691. ** under memory pressure, then again it is desirable to avoid
  42692. ** allocating a new page cache entry in order to avoid stressing
  42693. ** the heap even further.
  42694. */
  42695. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  42696. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  42697. return pcache1.bUnderPressure;
  42698. }else{
  42699. return sqlite3HeapNearlyFull();
  42700. }
  42701. }
  42702. /******************************************************************************/
  42703. /******** General Implementation Functions ************************************/
  42704. /*
  42705. ** This function is used to resize the hash table used by the cache passed
  42706. ** as the first argument.
  42707. **
  42708. ** The PCache mutex must be held when this function is called.
  42709. */
  42710. static void pcache1ResizeHash(PCache1 *p){
  42711. PgHdr1 **apNew;
  42712. unsigned int nNew;
  42713. unsigned int i;
  42714. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  42715. nNew = p->nHash*2;
  42716. if( nNew<256 ){
  42717. nNew = 256;
  42718. }
  42719. pcache1LeaveMutex(p->pGroup);
  42720. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  42721. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  42722. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  42723. pcache1EnterMutex(p->pGroup);
  42724. if( apNew ){
  42725. for(i=0; i<p->nHash; i++){
  42726. PgHdr1 *pPage;
  42727. PgHdr1 *pNext = p->apHash[i];
  42728. while( (pPage = pNext)!=0 ){
  42729. unsigned int h = pPage->iKey % nNew;
  42730. pNext = pPage->pNext;
  42731. pPage->pNext = apNew[h];
  42732. apNew[h] = pPage;
  42733. }
  42734. }
  42735. sqlite3_free(p->apHash);
  42736. p->apHash = apNew;
  42737. p->nHash = nNew;
  42738. }
  42739. }
  42740. /*
  42741. ** This function is used internally to remove the page pPage from the
  42742. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  42743. ** LRU list, then this function is a no-op.
  42744. **
  42745. ** The PGroup mutex must be held when this function is called.
  42746. */
  42747. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  42748. PCache1 *pCache;
  42749. assert( pPage!=0 );
  42750. assert( pPage->isPinned==0 );
  42751. pCache = pPage->pCache;
  42752. assert( pPage->pLruNext );
  42753. assert( pPage->pLruPrev );
  42754. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  42755. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  42756. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  42757. pPage->pLruNext = 0;
  42758. pPage->pLruPrev = 0;
  42759. pPage->isPinned = 1;
  42760. assert( pPage->isAnchor==0 );
  42761. assert( pCache->pGroup->lru.isAnchor==1 );
  42762. pCache->nRecyclable--;
  42763. return pPage;
  42764. }
  42765. /*
  42766. ** Remove the page supplied as an argument from the hash table
  42767. ** (PCache1.apHash structure) that it is currently stored in.
  42768. ** Also free the page if freePage is true.
  42769. **
  42770. ** The PGroup mutex must be held when this function is called.
  42771. */
  42772. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  42773. unsigned int h;
  42774. PCache1 *pCache = pPage->pCache;
  42775. PgHdr1 **pp;
  42776. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  42777. h = pPage->iKey % pCache->nHash;
  42778. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  42779. *pp = (*pp)->pNext;
  42780. pCache->nPage--;
  42781. if( freeFlag ) pcache1FreePage(pPage);
  42782. }
  42783. /*
  42784. ** If there are currently more than nMaxPage pages allocated, try
  42785. ** to recycle pages to reduce the number allocated to nMaxPage.
  42786. */
  42787. static void pcache1EnforceMaxPage(PCache1 *pCache){
  42788. PGroup *pGroup = pCache->pGroup;
  42789. PgHdr1 *p;
  42790. assert( sqlite3_mutex_held(pGroup->mutex) );
  42791. while( pGroup->nCurrentPage>pGroup->nMaxPage
  42792. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  42793. ){
  42794. assert( p->pCache->pGroup==pGroup );
  42795. assert( p->isPinned==0 );
  42796. pcache1PinPage(p);
  42797. pcache1RemoveFromHash(p, 1);
  42798. }
  42799. if( pCache->nPage==0 && pCache->pBulk ){
  42800. sqlite3_free(pCache->pBulk);
  42801. pCache->pBulk = pCache->pFree = 0;
  42802. }
  42803. }
  42804. /*
  42805. ** Discard all pages from cache pCache with a page number (key value)
  42806. ** greater than or equal to iLimit. Any pinned pages that meet this
  42807. ** criteria are unpinned before they are discarded.
  42808. **
  42809. ** The PCache mutex must be held when this function is called.
  42810. */
  42811. static void pcache1TruncateUnsafe(
  42812. PCache1 *pCache, /* The cache to truncate */
  42813. unsigned int iLimit /* Drop pages with this pgno or larger */
  42814. ){
  42815. TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
  42816. unsigned int h, iStop;
  42817. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  42818. assert( pCache->iMaxKey >= iLimit );
  42819. assert( pCache->nHash > 0 );
  42820. if( pCache->iMaxKey - iLimit < pCache->nHash ){
  42821. /* If we are just shaving the last few pages off the end of the
  42822. ** cache, then there is no point in scanning the entire hash table.
  42823. ** Only scan those hash slots that might contain pages that need to
  42824. ** be removed. */
  42825. h = iLimit % pCache->nHash;
  42826. iStop = pCache->iMaxKey % pCache->nHash;
  42827. TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
  42828. }else{
  42829. /* This is the general case where many pages are being removed.
  42830. ** It is necessary to scan the entire hash table */
  42831. h = pCache->nHash/2;
  42832. iStop = h - 1;
  42833. }
  42834. for(;;){
  42835. PgHdr1 **pp;
  42836. PgHdr1 *pPage;
  42837. assert( h<pCache->nHash );
  42838. pp = &pCache->apHash[h];
  42839. while( (pPage = *pp)!=0 ){
  42840. if( pPage->iKey>=iLimit ){
  42841. pCache->nPage--;
  42842. *pp = pPage->pNext;
  42843. if( !pPage->isPinned ) pcache1PinPage(pPage);
  42844. pcache1FreePage(pPage);
  42845. }else{
  42846. pp = &pPage->pNext;
  42847. TESTONLY( if( nPage>=0 ) nPage++; )
  42848. }
  42849. }
  42850. if( h==iStop ) break;
  42851. h = (h+1) % pCache->nHash;
  42852. }
  42853. assert( nPage<0 || pCache->nPage==(unsigned)nPage );
  42854. }
  42855. /******************************************************************************/
  42856. /******** sqlite3_pcache Methods **********************************************/
  42857. /*
  42858. ** Implementation of the sqlite3_pcache.xInit method.
  42859. */
  42860. static int pcache1Init(void *NotUsed){
  42861. UNUSED_PARAMETER(NotUsed);
  42862. assert( pcache1.isInit==0 );
  42863. memset(&pcache1, 0, sizeof(pcache1));
  42864. /*
  42865. ** The pcache1.separateCache variable is true if each PCache has its own
  42866. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  42867. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  42868. **
  42869. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  42870. **
  42871. ** * Use a unified cache in single-threaded applications that have
  42872. ** configured a start-time buffer for use as page-cache memory using
  42873. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  42874. ** pBuf argument.
  42875. **
  42876. ** * Otherwise use separate caches (mode-1)
  42877. */
  42878. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  42879. pcache1.separateCache = 0;
  42880. #elif SQLITE_THREADSAFE
  42881. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  42882. || sqlite3GlobalConfig.bCoreMutex>0;
  42883. #else
  42884. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  42885. #endif
  42886. #if SQLITE_THREADSAFE
  42887. if( sqlite3GlobalConfig.bCoreMutex ){
  42888. pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
  42889. pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
  42890. }
  42891. #endif
  42892. if( pcache1.separateCache
  42893. && sqlite3GlobalConfig.nPage!=0
  42894. && sqlite3GlobalConfig.pPage==0
  42895. ){
  42896. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  42897. }else{
  42898. pcache1.nInitPage = 0;
  42899. }
  42900. pcache1.grp.mxPinned = 10;
  42901. pcache1.isInit = 1;
  42902. return SQLITE_OK;
  42903. }
  42904. /*
  42905. ** Implementation of the sqlite3_pcache.xShutdown method.
  42906. ** Note that the static mutex allocated in xInit does
  42907. ** not need to be freed.
  42908. */
  42909. static void pcache1Shutdown(void *NotUsed){
  42910. UNUSED_PARAMETER(NotUsed);
  42911. assert( pcache1.isInit!=0 );
  42912. memset(&pcache1, 0, sizeof(pcache1));
  42913. }
  42914. /* forward declaration */
  42915. static void pcache1Destroy(sqlite3_pcache *p);
  42916. /*
  42917. ** Implementation of the sqlite3_pcache.xCreate method.
  42918. **
  42919. ** Allocate a new cache.
  42920. */
  42921. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  42922. PCache1 *pCache; /* The newly created page cache */
  42923. PGroup *pGroup; /* The group the new page cache will belong to */
  42924. int sz; /* Bytes of memory required to allocate the new cache */
  42925. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  42926. assert( szExtra < 300 );
  42927. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  42928. pCache = (PCache1 *)sqlite3MallocZero(sz);
  42929. if( pCache ){
  42930. if( pcache1.separateCache ){
  42931. pGroup = (PGroup*)&pCache[1];
  42932. pGroup->mxPinned = 10;
  42933. }else{
  42934. pGroup = &pcache1.grp;
  42935. }
  42936. if( pGroup->lru.isAnchor==0 ){
  42937. pGroup->lru.isAnchor = 1;
  42938. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  42939. }
  42940. pCache->pGroup = pGroup;
  42941. pCache->szPage = szPage;
  42942. pCache->szExtra = szExtra;
  42943. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  42944. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  42945. pcache1EnterMutex(pGroup);
  42946. pcache1ResizeHash(pCache);
  42947. if( bPurgeable ){
  42948. pCache->nMin = 10;
  42949. pGroup->nMinPage += pCache->nMin;
  42950. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  42951. }
  42952. pcache1LeaveMutex(pGroup);
  42953. if( pCache->nHash==0 ){
  42954. pcache1Destroy((sqlite3_pcache*)pCache);
  42955. pCache = 0;
  42956. }
  42957. }
  42958. return (sqlite3_pcache *)pCache;
  42959. }
  42960. /*
  42961. ** Implementation of the sqlite3_pcache.xCachesize method.
  42962. **
  42963. ** Configure the cache_size limit for a cache.
  42964. */
  42965. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  42966. PCache1 *pCache = (PCache1 *)p;
  42967. if( pCache->bPurgeable ){
  42968. PGroup *pGroup = pCache->pGroup;
  42969. pcache1EnterMutex(pGroup);
  42970. pGroup->nMaxPage += (nMax - pCache->nMax);
  42971. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  42972. pCache->nMax = nMax;
  42973. pCache->n90pct = pCache->nMax*9/10;
  42974. pcache1EnforceMaxPage(pCache);
  42975. pcache1LeaveMutex(pGroup);
  42976. }
  42977. }
  42978. /*
  42979. ** Implementation of the sqlite3_pcache.xShrink method.
  42980. **
  42981. ** Free up as much memory as possible.
  42982. */
  42983. static void pcache1Shrink(sqlite3_pcache *p){
  42984. PCache1 *pCache = (PCache1*)p;
  42985. if( pCache->bPurgeable ){
  42986. PGroup *pGroup = pCache->pGroup;
  42987. int savedMaxPage;
  42988. pcache1EnterMutex(pGroup);
  42989. savedMaxPage = pGroup->nMaxPage;
  42990. pGroup->nMaxPage = 0;
  42991. pcache1EnforceMaxPage(pCache);
  42992. pGroup->nMaxPage = savedMaxPage;
  42993. pcache1LeaveMutex(pGroup);
  42994. }
  42995. }
  42996. /*
  42997. ** Implementation of the sqlite3_pcache.xPagecount method.
  42998. */
  42999. static int pcache1Pagecount(sqlite3_pcache *p){
  43000. int n;
  43001. PCache1 *pCache = (PCache1*)p;
  43002. pcache1EnterMutex(pCache->pGroup);
  43003. n = pCache->nPage;
  43004. pcache1LeaveMutex(pCache->pGroup);
  43005. return n;
  43006. }
  43007. /*
  43008. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  43009. ** in the header of the pcache1Fetch() procedure.
  43010. **
  43011. ** This steps are broken out into a separate procedure because they are
  43012. ** usually not needed, and by avoiding the stack initialization required
  43013. ** for these steps, the main pcache1Fetch() procedure can run faster.
  43014. */
  43015. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  43016. PCache1 *pCache,
  43017. unsigned int iKey,
  43018. int createFlag
  43019. ){
  43020. unsigned int nPinned;
  43021. PGroup *pGroup = pCache->pGroup;
  43022. PgHdr1 *pPage = 0;
  43023. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  43024. assert( pCache->nPage >= pCache->nRecyclable );
  43025. nPinned = pCache->nPage - pCache->nRecyclable;
  43026. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  43027. assert( pCache->n90pct == pCache->nMax*9/10 );
  43028. if( createFlag==1 && (
  43029. nPinned>=pGroup->mxPinned
  43030. || nPinned>=pCache->n90pct
  43031. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  43032. )){
  43033. return 0;
  43034. }
  43035. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  43036. assert( pCache->nHash>0 && pCache->apHash );
  43037. /* Step 4. Try to recycle a page. */
  43038. if( pCache->bPurgeable
  43039. && !pGroup->lru.pLruPrev->isAnchor
  43040. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  43041. ){
  43042. PCache1 *pOther;
  43043. pPage = pGroup->lru.pLruPrev;
  43044. assert( pPage->isPinned==0 );
  43045. pcache1RemoveFromHash(pPage, 0);
  43046. pcache1PinPage(pPage);
  43047. pOther = pPage->pCache;
  43048. if( pOther->szAlloc != pCache->szAlloc ){
  43049. pcache1FreePage(pPage);
  43050. pPage = 0;
  43051. }else{
  43052. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  43053. }
  43054. }
  43055. /* Step 5. If a usable page buffer has still not been found,
  43056. ** attempt to allocate a new one.
  43057. */
  43058. if( !pPage ){
  43059. pPage = pcache1AllocPage(pCache, createFlag==1);
  43060. }
  43061. if( pPage ){
  43062. unsigned int h = iKey % pCache->nHash;
  43063. pCache->nPage++;
  43064. pPage->iKey = iKey;
  43065. pPage->pNext = pCache->apHash[h];
  43066. pPage->pCache = pCache;
  43067. pPage->pLruPrev = 0;
  43068. pPage->pLruNext = 0;
  43069. pPage->isPinned = 1;
  43070. *(void **)pPage->page.pExtra = 0;
  43071. pCache->apHash[h] = pPage;
  43072. if( iKey>pCache->iMaxKey ){
  43073. pCache->iMaxKey = iKey;
  43074. }
  43075. }
  43076. return pPage;
  43077. }
  43078. /*
  43079. ** Implementation of the sqlite3_pcache.xFetch method.
  43080. **
  43081. ** Fetch a page by key value.
  43082. **
  43083. ** Whether or not a new page may be allocated by this function depends on
  43084. ** the value of the createFlag argument. 0 means do not allocate a new
  43085. ** page. 1 means allocate a new page if space is easily available. 2
  43086. ** means to try really hard to allocate a new page.
  43087. **
  43088. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  43089. ** database) there is really no difference between createFlag 1 and 2. So
  43090. ** the calling function (pcache.c) will never have a createFlag of 1 on
  43091. ** a non-purgeable cache.
  43092. **
  43093. ** There are three different approaches to obtaining space for a page,
  43094. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  43095. **
  43096. ** 1. Regardless of the value of createFlag, the cache is searched for a
  43097. ** copy of the requested page. If one is found, it is returned.
  43098. **
  43099. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  43100. ** returned.
  43101. **
  43102. ** 3. If createFlag is 1, and the page is not already in the cache, then
  43103. ** return NULL (do not allocate a new page) if any of the following
  43104. ** conditions are true:
  43105. **
  43106. ** (a) the number of pages pinned by the cache is greater than
  43107. ** PCache1.nMax, or
  43108. **
  43109. ** (b) the number of pages pinned by the cache is greater than
  43110. ** the sum of nMax for all purgeable caches, less the sum of
  43111. ** nMin for all other purgeable caches, or
  43112. **
  43113. ** 4. If none of the first three conditions apply and the cache is marked
  43114. ** as purgeable, and if one of the following is true:
  43115. **
  43116. ** (a) The number of pages allocated for the cache is already
  43117. ** PCache1.nMax, or
  43118. **
  43119. ** (b) The number of pages allocated for all purgeable caches is
  43120. ** already equal to or greater than the sum of nMax for all
  43121. ** purgeable caches,
  43122. **
  43123. ** (c) The system is under memory pressure and wants to avoid
  43124. ** unnecessary pages cache entry allocations
  43125. **
  43126. ** then attempt to recycle a page from the LRU list. If it is the right
  43127. ** size, return the recycled buffer. Otherwise, free the buffer and
  43128. ** proceed to step 5.
  43129. **
  43130. ** 5. Otherwise, allocate and return a new page buffer.
  43131. **
  43132. ** There are two versions of this routine. pcache1FetchWithMutex() is
  43133. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  43134. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  43135. ** invokes the appropriate routine.
  43136. */
  43137. static PgHdr1 *pcache1FetchNoMutex(
  43138. sqlite3_pcache *p,
  43139. unsigned int iKey,
  43140. int createFlag
  43141. ){
  43142. PCache1 *pCache = (PCache1 *)p;
  43143. PgHdr1 *pPage = 0;
  43144. /* Step 1: Search the hash table for an existing entry. */
  43145. pPage = pCache->apHash[iKey % pCache->nHash];
  43146. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  43147. /* Step 2: If the page was found in the hash table, then return it.
  43148. ** If the page was not in the hash table and createFlag is 0, abort.
  43149. ** Otherwise (page not in hash and createFlag!=0) continue with
  43150. ** subsequent steps to try to create the page. */
  43151. if( pPage ){
  43152. if( !pPage->isPinned ){
  43153. return pcache1PinPage(pPage);
  43154. }else{
  43155. return pPage;
  43156. }
  43157. }else if( createFlag ){
  43158. /* Steps 3, 4, and 5 implemented by this subroutine */
  43159. return pcache1FetchStage2(pCache, iKey, createFlag);
  43160. }else{
  43161. return 0;
  43162. }
  43163. }
  43164. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  43165. static PgHdr1 *pcache1FetchWithMutex(
  43166. sqlite3_pcache *p,
  43167. unsigned int iKey,
  43168. int createFlag
  43169. ){
  43170. PCache1 *pCache = (PCache1 *)p;
  43171. PgHdr1 *pPage;
  43172. pcache1EnterMutex(pCache->pGroup);
  43173. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  43174. assert( pPage==0 || pCache->iMaxKey>=iKey );
  43175. pcache1LeaveMutex(pCache->pGroup);
  43176. return pPage;
  43177. }
  43178. #endif
  43179. static sqlite3_pcache_page *pcache1Fetch(
  43180. sqlite3_pcache *p,
  43181. unsigned int iKey,
  43182. int createFlag
  43183. ){
  43184. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  43185. PCache1 *pCache = (PCache1 *)p;
  43186. #endif
  43187. assert( offsetof(PgHdr1,page)==0 );
  43188. assert( pCache->bPurgeable || createFlag!=1 );
  43189. assert( pCache->bPurgeable || pCache->nMin==0 );
  43190. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  43191. assert( pCache->nMin==0 || pCache->bPurgeable );
  43192. assert( pCache->nHash>0 );
  43193. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  43194. if( pCache->pGroup->mutex ){
  43195. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  43196. }else
  43197. #endif
  43198. {
  43199. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  43200. }
  43201. }
  43202. /*
  43203. ** Implementation of the sqlite3_pcache.xUnpin method.
  43204. **
  43205. ** Mark a page as unpinned (eligible for asynchronous recycling).
  43206. */
  43207. static void pcache1Unpin(
  43208. sqlite3_pcache *p,
  43209. sqlite3_pcache_page *pPg,
  43210. int reuseUnlikely
  43211. ){
  43212. PCache1 *pCache = (PCache1 *)p;
  43213. PgHdr1 *pPage = (PgHdr1 *)pPg;
  43214. PGroup *pGroup = pCache->pGroup;
  43215. assert( pPage->pCache==pCache );
  43216. pcache1EnterMutex(pGroup);
  43217. /* It is an error to call this function if the page is already
  43218. ** part of the PGroup LRU list.
  43219. */
  43220. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  43221. assert( pPage->isPinned==1 );
  43222. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  43223. pcache1RemoveFromHash(pPage, 1);
  43224. }else{
  43225. /* Add the page to the PGroup LRU list. */
  43226. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  43227. pPage->pLruPrev = &pGroup->lru;
  43228. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  43229. *ppFirst = pPage;
  43230. pCache->nRecyclable++;
  43231. pPage->isPinned = 0;
  43232. }
  43233. pcache1LeaveMutex(pCache->pGroup);
  43234. }
  43235. /*
  43236. ** Implementation of the sqlite3_pcache.xRekey method.
  43237. */
  43238. static void pcache1Rekey(
  43239. sqlite3_pcache *p,
  43240. sqlite3_pcache_page *pPg,
  43241. unsigned int iOld,
  43242. unsigned int iNew
  43243. ){
  43244. PCache1 *pCache = (PCache1 *)p;
  43245. PgHdr1 *pPage = (PgHdr1 *)pPg;
  43246. PgHdr1 **pp;
  43247. unsigned int h;
  43248. assert( pPage->iKey==iOld );
  43249. assert( pPage->pCache==pCache );
  43250. pcache1EnterMutex(pCache->pGroup);
  43251. h = iOld%pCache->nHash;
  43252. pp = &pCache->apHash[h];
  43253. while( (*pp)!=pPage ){
  43254. pp = &(*pp)->pNext;
  43255. }
  43256. *pp = pPage->pNext;
  43257. h = iNew%pCache->nHash;
  43258. pPage->iKey = iNew;
  43259. pPage->pNext = pCache->apHash[h];
  43260. pCache->apHash[h] = pPage;
  43261. if( iNew>pCache->iMaxKey ){
  43262. pCache->iMaxKey = iNew;
  43263. }
  43264. pcache1LeaveMutex(pCache->pGroup);
  43265. }
  43266. /*
  43267. ** Implementation of the sqlite3_pcache.xTruncate method.
  43268. **
  43269. ** Discard all unpinned pages in the cache with a page number equal to
  43270. ** or greater than parameter iLimit. Any pinned pages with a page number
  43271. ** equal to or greater than iLimit are implicitly unpinned.
  43272. */
  43273. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  43274. PCache1 *pCache = (PCache1 *)p;
  43275. pcache1EnterMutex(pCache->pGroup);
  43276. if( iLimit<=pCache->iMaxKey ){
  43277. pcache1TruncateUnsafe(pCache, iLimit);
  43278. pCache->iMaxKey = iLimit-1;
  43279. }
  43280. pcache1LeaveMutex(pCache->pGroup);
  43281. }
  43282. /*
  43283. ** Implementation of the sqlite3_pcache.xDestroy method.
  43284. **
  43285. ** Destroy a cache allocated using pcache1Create().
  43286. */
  43287. static void pcache1Destroy(sqlite3_pcache *p){
  43288. PCache1 *pCache = (PCache1 *)p;
  43289. PGroup *pGroup = pCache->pGroup;
  43290. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  43291. pcache1EnterMutex(pGroup);
  43292. if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  43293. assert( pGroup->nMaxPage >= pCache->nMax );
  43294. pGroup->nMaxPage -= pCache->nMax;
  43295. assert( pGroup->nMinPage >= pCache->nMin );
  43296. pGroup->nMinPage -= pCache->nMin;
  43297. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  43298. pcache1EnforceMaxPage(pCache);
  43299. pcache1LeaveMutex(pGroup);
  43300. sqlite3_free(pCache->pBulk);
  43301. sqlite3_free(pCache->apHash);
  43302. sqlite3_free(pCache);
  43303. }
  43304. /*
  43305. ** This function is called during initialization (sqlite3_initialize()) to
  43306. ** install the default pluggable cache module, assuming the user has not
  43307. ** already provided an alternative.
  43308. */
  43309. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  43310. static const sqlite3_pcache_methods2 defaultMethods = {
  43311. 1, /* iVersion */
  43312. 0, /* pArg */
  43313. pcache1Init, /* xInit */
  43314. pcache1Shutdown, /* xShutdown */
  43315. pcache1Create, /* xCreate */
  43316. pcache1Cachesize, /* xCachesize */
  43317. pcache1Pagecount, /* xPagecount */
  43318. pcache1Fetch, /* xFetch */
  43319. pcache1Unpin, /* xUnpin */
  43320. pcache1Rekey, /* xRekey */
  43321. pcache1Truncate, /* xTruncate */
  43322. pcache1Destroy, /* xDestroy */
  43323. pcache1Shrink /* xShrink */
  43324. };
  43325. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  43326. }
  43327. /*
  43328. ** Return the size of the header on each page of this PCACHE implementation.
  43329. */
  43330. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  43331. /*
  43332. ** Return the global mutex used by this PCACHE implementation. The
  43333. ** sqlite3_status() routine needs access to this mutex.
  43334. */
  43335. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  43336. return pcache1.mutex;
  43337. }
  43338. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  43339. /*
  43340. ** This function is called to free superfluous dynamically allocated memory
  43341. ** held by the pager system. Memory in use by any SQLite pager allocated
  43342. ** by the current thread may be sqlite3_free()ed.
  43343. **
  43344. ** nReq is the number of bytes of memory required. Once this much has
  43345. ** been released, the function returns. The return value is the total number
  43346. ** of bytes of memory released.
  43347. */
  43348. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  43349. int nFree = 0;
  43350. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  43351. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  43352. if( sqlite3GlobalConfig.pPage==0 ){
  43353. PgHdr1 *p;
  43354. pcache1EnterMutex(&pcache1.grp);
  43355. while( (nReq<0 || nFree<nReq)
  43356. && (p=pcache1.grp.lru.pLruPrev)!=0
  43357. && p->isAnchor==0
  43358. ){
  43359. nFree += pcache1MemSize(p->page.pBuf);
  43360. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  43361. nFree += sqlite3MemSize(p);
  43362. #endif
  43363. assert( p->isPinned==0 );
  43364. pcache1PinPage(p);
  43365. pcache1RemoveFromHash(p, 1);
  43366. }
  43367. pcache1LeaveMutex(&pcache1.grp);
  43368. }
  43369. return nFree;
  43370. }
  43371. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  43372. #ifdef SQLITE_TEST
  43373. /*
  43374. ** This function is used by test procedures to inspect the internal state
  43375. ** of the global cache.
  43376. */
  43377. SQLITE_PRIVATE void sqlite3PcacheStats(
  43378. int *pnCurrent, /* OUT: Total number of pages cached */
  43379. int *pnMax, /* OUT: Global maximum cache size */
  43380. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  43381. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  43382. ){
  43383. PgHdr1 *p;
  43384. int nRecyclable = 0;
  43385. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  43386. assert( p->isPinned==0 );
  43387. nRecyclable++;
  43388. }
  43389. *pnCurrent = pcache1.grp.nCurrentPage;
  43390. *pnMax = (int)pcache1.grp.nMaxPage;
  43391. *pnMin = (int)pcache1.grp.nMinPage;
  43392. *pnRecyclable = nRecyclable;
  43393. }
  43394. #endif
  43395. /************** End of pcache1.c *********************************************/
  43396. /************** Begin file rowset.c ******************************************/
  43397. /*
  43398. ** 2008 December 3
  43399. **
  43400. ** The author disclaims copyright to this source code. In place of
  43401. ** a legal notice, here is a blessing:
  43402. **
  43403. ** May you do good and not evil.
  43404. ** May you find forgiveness for yourself and forgive others.
  43405. ** May you share freely, never taking more than you give.
  43406. **
  43407. *************************************************************************
  43408. **
  43409. ** This module implements an object we call a "RowSet".
  43410. **
  43411. ** The RowSet object is a collection of rowids. Rowids
  43412. ** are inserted into the RowSet in an arbitrary order. Inserts
  43413. ** can be intermixed with tests to see if a given rowid has been
  43414. ** previously inserted into the RowSet.
  43415. **
  43416. ** After all inserts are finished, it is possible to extract the
  43417. ** elements of the RowSet in sorted order. Once this extraction
  43418. ** process has started, no new elements may be inserted.
  43419. **
  43420. ** Hence, the primitive operations for a RowSet are:
  43421. **
  43422. ** CREATE
  43423. ** INSERT
  43424. ** TEST
  43425. ** SMALLEST
  43426. ** DESTROY
  43427. **
  43428. ** The CREATE and DESTROY primitives are the constructor and destructor,
  43429. ** obviously. The INSERT primitive adds a new element to the RowSet.
  43430. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  43431. ** extracts the least value from the RowSet.
  43432. **
  43433. ** The INSERT primitive might allocate additional memory. Memory is
  43434. ** allocated in chunks so most INSERTs do no allocation. There is an
  43435. ** upper bound on the size of allocated memory. No memory is freed
  43436. ** until DESTROY.
  43437. **
  43438. ** The TEST primitive includes a "batch" number. The TEST primitive
  43439. ** will only see elements that were inserted before the last change
  43440. ** in the batch number. In other words, if an INSERT occurs between
  43441. ** two TESTs where the TESTs have the same batch nubmer, then the
  43442. ** value added by the INSERT will not be visible to the second TEST.
  43443. ** The initial batch number is zero, so if the very first TEST contains
  43444. ** a non-zero batch number, it will see all prior INSERTs.
  43445. **
  43446. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  43447. ** that is attempted.
  43448. **
  43449. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  43450. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  43451. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  43452. ** The cost of a TEST using the same batch number is O(logN). The cost
  43453. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  43454. ** primitives are constant time. The cost of DESTROY is O(N).
  43455. **
  43456. ** TEST and SMALLEST may not be used by the same RowSet. This used to
  43457. ** be possible, but the feature was not used, so it was removed in order
  43458. ** to simplify the code.
  43459. */
  43460. /* #include "sqliteInt.h" */
  43461. /*
  43462. ** Target size for allocation chunks.
  43463. */
  43464. #define ROWSET_ALLOCATION_SIZE 1024
  43465. /*
  43466. ** The number of rowset entries per allocation chunk.
  43467. */
  43468. #define ROWSET_ENTRY_PER_CHUNK \
  43469. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  43470. /*
  43471. ** Each entry in a RowSet is an instance of the following object.
  43472. **
  43473. ** This same object is reused to store a linked list of trees of RowSetEntry
  43474. ** objects. In that alternative use, pRight points to the next entry
  43475. ** in the list, pLeft points to the tree, and v is unused. The
  43476. ** RowSet.pForest value points to the head of this forest list.
  43477. */
  43478. struct RowSetEntry {
  43479. i64 v; /* ROWID value for this entry */
  43480. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  43481. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  43482. };
  43483. /*
  43484. ** RowSetEntry objects are allocated in large chunks (instances of the
  43485. ** following structure) to reduce memory allocation overhead. The
  43486. ** chunks are kept on a linked list so that they can be deallocated
  43487. ** when the RowSet is destroyed.
  43488. */
  43489. struct RowSetChunk {
  43490. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  43491. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  43492. };
  43493. /*
  43494. ** A RowSet in an instance of the following structure.
  43495. **
  43496. ** A typedef of this structure if found in sqliteInt.h.
  43497. */
  43498. struct RowSet {
  43499. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  43500. sqlite3 *db; /* The database connection */
  43501. struct RowSetEntry *pEntry; /* List of entries using pRight */
  43502. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  43503. struct RowSetEntry *pFresh; /* Source of new entry objects */
  43504. struct RowSetEntry *pForest; /* List of binary trees of entries */
  43505. u16 nFresh; /* Number of objects on pFresh */
  43506. u16 rsFlags; /* Various flags */
  43507. int iBatch; /* Current insert batch */
  43508. };
  43509. /*
  43510. ** Allowed values for RowSet.rsFlags
  43511. */
  43512. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  43513. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  43514. /*
  43515. ** Turn bulk memory into a RowSet object. N bytes of memory
  43516. ** are available at pSpace. The db pointer is used as a memory context
  43517. ** for any subsequent allocations that need to occur.
  43518. ** Return a pointer to the new RowSet object.
  43519. **
  43520. ** It must be the case that N is sufficient to make a Rowset. If not
  43521. ** an assertion fault occurs.
  43522. **
  43523. ** If N is larger than the minimum, use the surplus as an initial
  43524. ** allocation of entries available to be filled.
  43525. */
  43526. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  43527. RowSet *p;
  43528. assert( N >= ROUND8(sizeof(*p)) );
  43529. p = pSpace;
  43530. p->pChunk = 0;
  43531. p->db = db;
  43532. p->pEntry = 0;
  43533. p->pLast = 0;
  43534. p->pForest = 0;
  43535. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  43536. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  43537. p->rsFlags = ROWSET_SORTED;
  43538. p->iBatch = 0;
  43539. return p;
  43540. }
  43541. /*
  43542. ** Deallocate all chunks from a RowSet. This frees all memory that
  43543. ** the RowSet has allocated over its lifetime. This routine is
  43544. ** the destructor for the RowSet.
  43545. */
  43546. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  43547. struct RowSetChunk *pChunk, *pNextChunk;
  43548. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  43549. pNextChunk = pChunk->pNextChunk;
  43550. sqlite3DbFree(p->db, pChunk);
  43551. }
  43552. p->pChunk = 0;
  43553. p->nFresh = 0;
  43554. p->pEntry = 0;
  43555. p->pLast = 0;
  43556. p->pForest = 0;
  43557. p->rsFlags = ROWSET_SORTED;
  43558. }
  43559. /*
  43560. ** Allocate a new RowSetEntry object that is associated with the
  43561. ** given RowSet. Return a pointer to the new and completely uninitialized
  43562. ** objected.
  43563. **
  43564. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  43565. ** routine returns NULL.
  43566. */
  43567. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  43568. assert( p!=0 );
  43569. if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43570. /* We could allocate a fresh RowSetEntry each time one is needed, but it
  43571. ** is more efficient to pull a preallocated entry from the pool */
  43572. struct RowSetChunk *pNew;
  43573. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  43574. if( pNew==0 ){
  43575. return 0;
  43576. }
  43577. pNew->pNextChunk = p->pChunk;
  43578. p->pChunk = pNew;
  43579. p->pFresh = pNew->aEntry;
  43580. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  43581. }
  43582. p->nFresh--;
  43583. return p->pFresh++;
  43584. }
  43585. /*
  43586. ** Insert a new value into a RowSet.
  43587. **
  43588. ** The mallocFailed flag of the database connection is set if a
  43589. ** memory allocation fails.
  43590. */
  43591. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  43592. struct RowSetEntry *pEntry; /* The new entry */
  43593. struct RowSetEntry *pLast; /* The last prior entry */
  43594. /* This routine is never called after sqlite3RowSetNext() */
  43595. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  43596. pEntry = rowSetEntryAlloc(p);
  43597. if( pEntry==0 ) return;
  43598. pEntry->v = rowid;
  43599. pEntry->pRight = 0;
  43600. pLast = p->pLast;
  43601. if( pLast ){
  43602. if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
  43603. /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
  43604. ** where possible */
  43605. p->rsFlags &= ~ROWSET_SORTED;
  43606. }
  43607. pLast->pRight = pEntry;
  43608. }else{
  43609. p->pEntry = pEntry;
  43610. }
  43611. p->pLast = pEntry;
  43612. }
  43613. /*
  43614. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  43615. **
  43616. ** The input lists are connected via pRight pointers and are
  43617. ** assumed to each already be in sorted order.
  43618. */
  43619. static struct RowSetEntry *rowSetEntryMerge(
  43620. struct RowSetEntry *pA, /* First sorted list to be merged */
  43621. struct RowSetEntry *pB /* Second sorted list to be merged */
  43622. ){
  43623. struct RowSetEntry head;
  43624. struct RowSetEntry *pTail;
  43625. pTail = &head;
  43626. assert( pA!=0 && pB!=0 );
  43627. for(;;){
  43628. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  43629. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  43630. if( pA->v<=pB->v ){
  43631. if( pA->v<pB->v ) pTail = pTail->pRight = pA;
  43632. pA = pA->pRight;
  43633. if( pA==0 ){
  43634. pTail->pRight = pB;
  43635. break;
  43636. }
  43637. }else{
  43638. pTail = pTail->pRight = pB;
  43639. pB = pB->pRight;
  43640. if( pB==0 ){
  43641. pTail->pRight = pA;
  43642. break;
  43643. }
  43644. }
  43645. }
  43646. return head.pRight;
  43647. }
  43648. /*
  43649. ** Sort all elements on the list of RowSetEntry objects into order of
  43650. ** increasing v.
  43651. */
  43652. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  43653. unsigned int i;
  43654. struct RowSetEntry *pNext, *aBucket[40];
  43655. memset(aBucket, 0, sizeof(aBucket));
  43656. while( pIn ){
  43657. pNext = pIn->pRight;
  43658. pIn->pRight = 0;
  43659. for(i=0; aBucket[i]; i++){
  43660. pIn = rowSetEntryMerge(aBucket[i], pIn);
  43661. aBucket[i] = 0;
  43662. }
  43663. aBucket[i] = pIn;
  43664. pIn = pNext;
  43665. }
  43666. pIn = aBucket[0];
  43667. for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  43668. if( aBucket[i]==0 ) continue;
  43669. pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
  43670. }
  43671. return pIn;
  43672. }
  43673. /*
  43674. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  43675. ** Convert this tree into a linked list connected by the pRight pointers
  43676. ** and return pointers to the first and last elements of the new list.
  43677. */
  43678. static void rowSetTreeToList(
  43679. struct RowSetEntry *pIn, /* Root of the input tree */
  43680. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  43681. struct RowSetEntry **ppLast /* Write tail of the output list here */
  43682. ){
  43683. assert( pIn!=0 );
  43684. if( pIn->pLeft ){
  43685. struct RowSetEntry *p;
  43686. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  43687. p->pRight = pIn;
  43688. }else{
  43689. *ppFirst = pIn;
  43690. }
  43691. if( pIn->pRight ){
  43692. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  43693. }else{
  43694. *ppLast = pIn;
  43695. }
  43696. assert( (*ppLast)->pRight==0 );
  43697. }
  43698. /*
  43699. ** Convert a sorted list of elements (connected by pRight) into a binary
  43700. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  43701. ** node taken from the head of *ppList. A depth of 2 means a tree with
  43702. ** three nodes. And so forth.
  43703. **
  43704. ** Use as many entries from the input list as required and update the
  43705. ** *ppList to point to the unused elements of the list. If the input
  43706. ** list contains too few elements, then construct an incomplete tree
  43707. ** and leave *ppList set to NULL.
  43708. **
  43709. ** Return a pointer to the root of the constructed binary tree.
  43710. */
  43711. static struct RowSetEntry *rowSetNDeepTree(
  43712. struct RowSetEntry **ppList,
  43713. int iDepth
  43714. ){
  43715. struct RowSetEntry *p; /* Root of the new tree */
  43716. struct RowSetEntry *pLeft; /* Left subtree */
  43717. if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
  43718. /* Prevent unnecessary deep recursion when we run out of entries */
  43719. return 0;
  43720. }
  43721. if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
  43722. /* This branch causes a *balanced* tree to be generated. A valid tree
  43723. ** is still generated without this branch, but the tree is wildly
  43724. ** unbalanced and inefficient. */
  43725. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  43726. p = *ppList;
  43727. if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43728. /* It is safe to always return here, but the resulting tree
  43729. ** would be unbalanced */
  43730. return pLeft;
  43731. }
  43732. p->pLeft = pLeft;
  43733. *ppList = p->pRight;
  43734. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  43735. }else{
  43736. p = *ppList;
  43737. *ppList = p->pRight;
  43738. p->pLeft = p->pRight = 0;
  43739. }
  43740. return p;
  43741. }
  43742. /*
  43743. ** Convert a sorted list of elements into a binary tree. Make the tree
  43744. ** as deep as it needs to be in order to contain the entire list.
  43745. */
  43746. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  43747. int iDepth; /* Depth of the tree so far */
  43748. struct RowSetEntry *p; /* Current tree root */
  43749. struct RowSetEntry *pLeft; /* Left subtree */
  43750. assert( pList!=0 );
  43751. p = pList;
  43752. pList = p->pRight;
  43753. p->pLeft = p->pRight = 0;
  43754. for(iDepth=1; pList; iDepth++){
  43755. pLeft = p;
  43756. p = pList;
  43757. pList = p->pRight;
  43758. p->pLeft = pLeft;
  43759. p->pRight = rowSetNDeepTree(&pList, iDepth);
  43760. }
  43761. return p;
  43762. }
  43763. /*
  43764. ** Extract the smallest element from the RowSet.
  43765. ** Write the element into *pRowid. Return 1 on success. Return
  43766. ** 0 if the RowSet is already empty.
  43767. **
  43768. ** After this routine has been called, the sqlite3RowSetInsert()
  43769. ** routine may not be called again.
  43770. **
  43771. ** This routine may not be called after sqlite3RowSetTest() has
  43772. ** been used. Older versions of RowSet allowed that, but as the
  43773. ** capability was not used by the code generator, it was removed
  43774. ** for code economy.
  43775. */
  43776. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  43777. assert( p!=0 );
  43778. assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
  43779. /* Merge the forest into a single sorted list on first call */
  43780. if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43781. if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43782. p->pEntry = rowSetEntrySort(p->pEntry);
  43783. }
  43784. p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
  43785. }
  43786. /* Return the next entry on the list */
  43787. if( p->pEntry ){
  43788. *pRowid = p->pEntry->v;
  43789. p->pEntry = p->pEntry->pRight;
  43790. if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
  43791. /* Free memory immediately, rather than waiting on sqlite3_finalize() */
  43792. sqlite3RowSetClear(p);
  43793. }
  43794. return 1;
  43795. }else{
  43796. return 0;
  43797. }
  43798. }
  43799. /*
  43800. ** Check to see if element iRowid was inserted into the rowset as
  43801. ** part of any insert batch prior to iBatch. Return 1 or 0.
  43802. **
  43803. ** If this is the first test of a new batch and if there exist entries
  43804. ** on pRowSet->pEntry, then sort those entries into the forest at
  43805. ** pRowSet->pForest so that they can be tested.
  43806. */
  43807. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  43808. struct RowSetEntry *p, *pTree;
  43809. /* This routine is never called after sqlite3RowSetNext() */
  43810. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  43811. /* Sort entries into the forest on the first test of a new batch.
  43812. ** To save unnecessary work, only do this when the batch number changes.
  43813. */
  43814. if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
  43815. p = pRowSet->pEntry;
  43816. if( p ){
  43817. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  43818. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43819. /* Only sort the current set of entiries if they need it */
  43820. p = rowSetEntrySort(p);
  43821. }
  43822. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  43823. ppPrevTree = &pTree->pRight;
  43824. if( pTree->pLeft==0 ){
  43825. pTree->pLeft = rowSetListToTree(p);
  43826. break;
  43827. }else{
  43828. struct RowSetEntry *pAux, *pTail;
  43829. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  43830. pTree->pLeft = 0;
  43831. p = rowSetEntryMerge(pAux, p);
  43832. }
  43833. }
  43834. if( pTree==0 ){
  43835. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  43836. if( pTree ){
  43837. pTree->v = 0;
  43838. pTree->pRight = 0;
  43839. pTree->pLeft = rowSetListToTree(p);
  43840. }
  43841. }
  43842. pRowSet->pEntry = 0;
  43843. pRowSet->pLast = 0;
  43844. pRowSet->rsFlags |= ROWSET_SORTED;
  43845. }
  43846. pRowSet->iBatch = iBatch;
  43847. }
  43848. /* Test to see if the iRowid value appears anywhere in the forest.
  43849. ** Return 1 if it does and 0 if not.
  43850. */
  43851. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  43852. p = pTree->pLeft;
  43853. while( p ){
  43854. if( p->v<iRowid ){
  43855. p = p->pRight;
  43856. }else if( p->v>iRowid ){
  43857. p = p->pLeft;
  43858. }else{
  43859. return 1;
  43860. }
  43861. }
  43862. }
  43863. return 0;
  43864. }
  43865. /************** End of rowset.c **********************************************/
  43866. /************** Begin file pager.c *******************************************/
  43867. /*
  43868. ** 2001 September 15
  43869. **
  43870. ** The author disclaims copyright to this source code. In place of
  43871. ** a legal notice, here is a blessing:
  43872. **
  43873. ** May you do good and not evil.
  43874. ** May you find forgiveness for yourself and forgive others.
  43875. ** May you share freely, never taking more than you give.
  43876. **
  43877. *************************************************************************
  43878. ** This is the implementation of the page cache subsystem or "pager".
  43879. **
  43880. ** The pager is used to access a database disk file. It implements
  43881. ** atomic commit and rollback through the use of a journal file that
  43882. ** is separate from the database file. The pager also implements file
  43883. ** locking to prevent two processes from writing the same database
  43884. ** file simultaneously, or one process from reading the database while
  43885. ** another is writing.
  43886. */
  43887. #ifndef SQLITE_OMIT_DISKIO
  43888. /* #include "sqliteInt.h" */
  43889. /************** Include wal.h in the middle of pager.c ***********************/
  43890. /************** Begin file wal.h *********************************************/
  43891. /*
  43892. ** 2010 February 1
  43893. **
  43894. ** The author disclaims copyright to this source code. In place of
  43895. ** a legal notice, here is a blessing:
  43896. **
  43897. ** May you do good and not evil.
  43898. ** May you find forgiveness for yourself and forgive others.
  43899. ** May you share freely, never taking more than you give.
  43900. **
  43901. *************************************************************************
  43902. ** This header file defines the interface to the write-ahead logging
  43903. ** system. Refer to the comments below and the header comment attached to
  43904. ** the implementation of each function in log.c for further details.
  43905. */
  43906. #ifndef SQLITE_WAL_H
  43907. #define SQLITE_WAL_H
  43908. /* #include "sqliteInt.h" */
  43909. /* Additional values that can be added to the sync_flags argument of
  43910. ** sqlite3WalFrames():
  43911. */
  43912. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  43913. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  43914. #ifdef SQLITE_OMIT_WAL
  43915. # define sqlite3WalOpen(x,y,z) 0
  43916. # define sqlite3WalLimit(x,y)
  43917. # define sqlite3WalClose(v,w,x,y,z) 0
  43918. # define sqlite3WalBeginReadTransaction(y,z) 0
  43919. # define sqlite3WalEndReadTransaction(z)
  43920. # define sqlite3WalDbsize(y) 0
  43921. # define sqlite3WalBeginWriteTransaction(y) 0
  43922. # define sqlite3WalEndWriteTransaction(x) 0
  43923. # define sqlite3WalUndo(x,y,z) 0
  43924. # define sqlite3WalSavepoint(y,z)
  43925. # define sqlite3WalSavepointUndo(y,z) 0
  43926. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  43927. # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
  43928. # define sqlite3WalCallback(z) 0
  43929. # define sqlite3WalExclusiveMode(y,z) 0
  43930. # define sqlite3WalHeapMemory(z) 0
  43931. # define sqlite3WalFramesize(z) 0
  43932. # define sqlite3WalFindFrame(x,y,z) 0
  43933. # define sqlite3WalFile(x) 0
  43934. #else
  43935. #define WAL_SAVEPOINT_NDATA 4
  43936. /* Connection to a write-ahead log (WAL) file.
  43937. ** There is one object of this type for each pager.
  43938. */
  43939. typedef struct Wal Wal;
  43940. /* Open and close a connection to a write-ahead log. */
  43941. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  43942. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
  43943. /* Set the limiting size of a WAL file. */
  43944. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  43945. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  43946. ** snapshot is like a read-transaction. It is the state of the database
  43947. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  43948. ** preserves the current state even if the other threads or processes
  43949. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  43950. ** transaction and releases the lock.
  43951. */
  43952. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  43953. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  43954. /* Read a page from the write-ahead log, if it is present. */
  43955. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  43956. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  43957. /* If the WAL is not empty, return the size of the database. */
  43958. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  43959. /* Obtain or release the WRITER lock. */
  43960. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  43961. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  43962. /* Undo any frames written (but not committed) to the log */
  43963. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  43964. /* Return an integer that records the current (uncommitted) write
  43965. ** position in the WAL */
  43966. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  43967. /* Move the write position of the WAL back to iFrame. Called in
  43968. ** response to a ROLLBACK TO command. */
  43969. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  43970. /* Write a frame or frames to the log. */
  43971. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  43972. /* Copy pages from the log to the database file */
  43973. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  43974. Wal *pWal, /* Write-ahead log connection */
  43975. sqlite3 *db, /* Check this handle's interrupt flag */
  43976. int eMode, /* One of PASSIVE, FULL and RESTART */
  43977. int (*xBusy)(void*), /* Function to call when busy */
  43978. void *pBusyArg, /* Context argument for xBusyHandler */
  43979. int sync_flags, /* Flags to sync db file with (or 0) */
  43980. int nBuf, /* Size of buffer nBuf */
  43981. u8 *zBuf, /* Temporary buffer to use */
  43982. int *pnLog, /* OUT: Number of frames in WAL */
  43983. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  43984. );
  43985. /* Return the value to pass to a sqlite3_wal_hook callback, the
  43986. ** number of frames in the WAL at the point of the last commit since
  43987. ** sqlite3WalCallback() was called. If no commits have occurred since
  43988. ** the last call, then return 0.
  43989. */
  43990. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  43991. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  43992. ** by the pager layer on the database file.
  43993. */
  43994. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  43995. /* Return true if the argument is non-NULL and the WAL module is using
  43996. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  43997. ** WAL module is using shared-memory, return false.
  43998. */
  43999. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  44000. #ifdef SQLITE_ENABLE_SNAPSHOT
  44001. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  44002. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  44003. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
  44004. #endif
  44005. #ifdef SQLITE_ENABLE_ZIPVFS
  44006. /* If the WAL file is not empty, return the number of bytes of content
  44007. ** stored in each frame (i.e. the db page-size when the WAL was created).
  44008. */
  44009. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  44010. #endif
  44011. /* Return the sqlite3_file object for the WAL file */
  44012. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  44013. #endif /* ifndef SQLITE_OMIT_WAL */
  44014. #endif /* SQLITE_WAL_H */
  44015. /************** End of wal.h *************************************************/
  44016. /************** Continuing where we left off in pager.c **********************/
  44017. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  44018. **
  44019. ** This comment block describes invariants that hold when using a rollback
  44020. ** journal. These invariants do not apply for journal_mode=WAL,
  44021. ** journal_mode=MEMORY, or journal_mode=OFF.
  44022. **
  44023. ** Within this comment block, a page is deemed to have been synced
  44024. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  44025. ** Otherwise, the page is not synced until the xSync method of the VFS
  44026. ** is called successfully on the file containing the page.
  44027. **
  44028. ** Definition: A page of the database file is said to be "overwriteable" if
  44029. ** one or more of the following are true about the page:
  44030. **
  44031. ** (a) The original content of the page as it was at the beginning of
  44032. ** the transaction has been written into the rollback journal and
  44033. ** synced.
  44034. **
  44035. ** (b) The page was a freelist leaf page at the start of the transaction.
  44036. **
  44037. ** (c) The page number is greater than the largest page that existed in
  44038. ** the database file at the start of the transaction.
  44039. **
  44040. ** (1) A page of the database file is never overwritten unless one of the
  44041. ** following are true:
  44042. **
  44043. ** (a) The page and all other pages on the same sector are overwriteable.
  44044. **
  44045. ** (b) The atomic page write optimization is enabled, and the entire
  44046. ** transaction other than the update of the transaction sequence
  44047. ** number consists of a single page change.
  44048. **
  44049. ** (2) The content of a page written into the rollback journal exactly matches
  44050. ** both the content in the database when the rollback journal was written
  44051. ** and the content in the database at the beginning of the current
  44052. ** transaction.
  44053. **
  44054. ** (3) Writes to the database file are an integer multiple of the page size
  44055. ** in length and are aligned on a page boundary.
  44056. **
  44057. ** (4) Reads from the database file are either aligned on a page boundary and
  44058. ** an integer multiple of the page size in length or are taken from the
  44059. ** first 100 bytes of the database file.
  44060. **
  44061. ** (5) All writes to the database file are synced prior to the rollback journal
  44062. ** being deleted, truncated, or zeroed.
  44063. **
  44064. ** (6) If a master journal file is used, then all writes to the database file
  44065. ** are synced prior to the master journal being deleted.
  44066. **
  44067. ** Definition: Two databases (or the same database at two points it time)
  44068. ** are said to be "logically equivalent" if they give the same answer to
  44069. ** all queries. Note in particular the content of freelist leaf
  44070. ** pages can be changed arbitrarily without affecting the logical equivalence
  44071. ** of the database.
  44072. **
  44073. ** (7) At any time, if any subset, including the empty set and the total set,
  44074. ** of the unsynced changes to a rollback journal are removed and the
  44075. ** journal is rolled back, the resulting database file will be logically
  44076. ** equivalent to the database file at the beginning of the transaction.
  44077. **
  44078. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  44079. ** is called to restore the database file to the same size it was at
  44080. ** the beginning of the transaction. (In some VFSes, the xTruncate
  44081. ** method is a no-op, but that does not change the fact the SQLite will
  44082. ** invoke it.)
  44083. **
  44084. ** (9) Whenever the database file is modified, at least one bit in the range
  44085. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  44086. ** the EXCLUSIVE lock, thus signaling other connections on the same
  44087. ** database to flush their caches.
  44088. **
  44089. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  44090. ** than one billion transactions.
  44091. **
  44092. ** (11) A database file is well-formed at the beginning and at the conclusion
  44093. ** of every transaction.
  44094. **
  44095. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  44096. ** the database file.
  44097. **
  44098. ** (13) A SHARED lock is held on the database file while reading any
  44099. ** content out of the database file.
  44100. **
  44101. ******************************************************************************/
  44102. /*
  44103. ** Macros for troubleshooting. Normally turned off
  44104. */
  44105. #if 0
  44106. int sqlite3PagerTrace=1; /* True to enable tracing */
  44107. #define sqlite3DebugPrintf printf
  44108. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  44109. #else
  44110. #define PAGERTRACE(X)
  44111. #endif
  44112. /*
  44113. ** The following two macros are used within the PAGERTRACE() macros above
  44114. ** to print out file-descriptors.
  44115. **
  44116. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  44117. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  44118. ** struct as its argument.
  44119. */
  44120. #define PAGERID(p) ((int)(p->fd))
  44121. #define FILEHANDLEID(fd) ((int)fd)
  44122. /*
  44123. ** The Pager.eState variable stores the current 'state' of a pager. A
  44124. ** pager may be in any one of the seven states shown in the following
  44125. ** state diagram.
  44126. **
  44127. ** OPEN <------+------+
  44128. ** | | |
  44129. ** V | |
  44130. ** +---------> READER-------+ |
  44131. ** | | |
  44132. ** | V |
  44133. ** |<-------WRITER_LOCKED------> ERROR
  44134. ** | | ^
  44135. ** | V |
  44136. ** |<------WRITER_CACHEMOD-------->|
  44137. ** | | |
  44138. ** | V |
  44139. ** |<-------WRITER_DBMOD---------->|
  44140. ** | | |
  44141. ** | V |
  44142. ** +<------WRITER_FINISHED-------->+
  44143. **
  44144. **
  44145. ** List of state transitions and the C [function] that performs each:
  44146. **
  44147. ** OPEN -> READER [sqlite3PagerSharedLock]
  44148. ** READER -> OPEN [pager_unlock]
  44149. **
  44150. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  44151. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  44152. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  44153. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  44154. ** WRITER_*** -> READER [pager_end_transaction]
  44155. **
  44156. ** WRITER_*** -> ERROR [pager_error]
  44157. ** ERROR -> OPEN [pager_unlock]
  44158. **
  44159. **
  44160. ** OPEN:
  44161. **
  44162. ** The pager starts up in this state. Nothing is guaranteed in this
  44163. ** state - the file may or may not be locked and the database size is
  44164. ** unknown. The database may not be read or written.
  44165. **
  44166. ** * No read or write transaction is active.
  44167. ** * Any lock, or no lock at all, may be held on the database file.
  44168. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  44169. **
  44170. ** READER:
  44171. **
  44172. ** In this state all the requirements for reading the database in
  44173. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  44174. ** was) in exclusive-locking mode, a user-level read transaction is
  44175. ** open. The database size is known in this state.
  44176. **
  44177. ** A connection running with locking_mode=normal enters this state when
  44178. ** it opens a read-transaction on the database and returns to state
  44179. ** OPEN after the read-transaction is completed. However a connection
  44180. ** running in locking_mode=exclusive (including temp databases) remains in
  44181. ** this state even after the read-transaction is closed. The only way
  44182. ** a locking_mode=exclusive connection can transition from READER to OPEN
  44183. ** is via the ERROR state (see below).
  44184. **
  44185. ** * A read transaction may be active (but a write-transaction cannot).
  44186. ** * A SHARED or greater lock is held on the database file.
  44187. ** * The dbSize variable may be trusted (even if a user-level read
  44188. ** transaction is not active). The dbOrigSize and dbFileSize variables
  44189. ** may not be trusted at this point.
  44190. ** * If the database is a WAL database, then the WAL connection is open.
  44191. ** * Even if a read-transaction is not open, it is guaranteed that
  44192. ** there is no hot-journal in the file-system.
  44193. **
  44194. ** WRITER_LOCKED:
  44195. **
  44196. ** The pager moves to this state from READER when a write-transaction
  44197. ** is first opened on the database. In WRITER_LOCKED state, all locks
  44198. ** required to start a write-transaction are held, but no actual
  44199. ** modifications to the cache or database have taken place.
  44200. **
  44201. ** In rollback mode, a RESERVED or (if the transaction was opened with
  44202. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  44203. ** moving to this state, but the journal file is not written to or opened
  44204. ** to in this state. If the transaction is committed or rolled back while
  44205. ** in WRITER_LOCKED state, all that is required is to unlock the database
  44206. ** file.
  44207. **
  44208. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  44209. ** If the connection is running with locking_mode=exclusive, an attempt
  44210. ** is made to obtain an EXCLUSIVE lock on the database file.
  44211. **
  44212. ** * A write transaction is active.
  44213. ** * If the connection is open in rollback-mode, a RESERVED or greater
  44214. ** lock is held on the database file.
  44215. ** * If the connection is open in WAL-mode, a WAL write transaction
  44216. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  44217. ** called).
  44218. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  44219. ** * The contents of the pager cache have not been modified.
  44220. ** * The journal file may or may not be open.
  44221. ** * Nothing (not even the first header) has been written to the journal.
  44222. **
  44223. ** WRITER_CACHEMOD:
  44224. **
  44225. ** A pager moves from WRITER_LOCKED state to this state when a page is
  44226. ** first modified by the upper layer. In rollback mode the journal file
  44227. ** is opened (if it is not already open) and a header written to the
  44228. ** start of it. The database file on disk has not been modified.
  44229. **
  44230. ** * A write transaction is active.
  44231. ** * A RESERVED or greater lock is held on the database file.
  44232. ** * The journal file is open and the first header has been written
  44233. ** to it, but the header has not been synced to disk.
  44234. ** * The contents of the page cache have been modified.
  44235. **
  44236. ** WRITER_DBMOD:
  44237. **
  44238. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  44239. ** when it modifies the contents of the database file. WAL connections
  44240. ** never enter this state (since they do not modify the database file,
  44241. ** just the log file).
  44242. **
  44243. ** * A write transaction is active.
  44244. ** * An EXCLUSIVE or greater lock is held on the database file.
  44245. ** * The journal file is open and the first header has been written
  44246. ** and synced to disk.
  44247. ** * The contents of the page cache have been modified (and possibly
  44248. ** written to disk).
  44249. **
  44250. ** WRITER_FINISHED:
  44251. **
  44252. ** It is not possible for a WAL connection to enter this state.
  44253. **
  44254. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  44255. ** state after the entire transaction has been successfully written into the
  44256. ** database file. In this state the transaction may be committed simply
  44257. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  44258. ** not possible to modify the database further. At this point, the upper
  44259. ** layer must either commit or rollback the transaction.
  44260. **
  44261. ** * A write transaction is active.
  44262. ** * An EXCLUSIVE or greater lock is held on the database file.
  44263. ** * All writing and syncing of journal and database data has finished.
  44264. ** If no error occurred, all that remains is to finalize the journal to
  44265. ** commit the transaction. If an error did occur, the caller will need
  44266. ** to rollback the transaction.
  44267. **
  44268. ** ERROR:
  44269. **
  44270. ** The ERROR state is entered when an IO or disk-full error (including
  44271. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  44272. ** difficult to be sure that the in-memory pager state (cache contents,
  44273. ** db size etc.) are consistent with the contents of the file-system.
  44274. **
  44275. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  44276. ** cannot.
  44277. **
  44278. ** For example, if an IO error occurs while performing a rollback,
  44279. ** the contents of the page-cache may be left in an inconsistent state.
  44280. ** At this point it would be dangerous to change back to READER state
  44281. ** (as usually happens after a rollback). Any subsequent readers might
  44282. ** report database corruption (due to the inconsistent cache), and if
  44283. ** they upgrade to writers, they may inadvertently corrupt the database
  44284. ** file. To avoid this hazard, the pager switches into the ERROR state
  44285. ** instead of READER following such an error.
  44286. **
  44287. ** Once it has entered the ERROR state, any attempt to use the pager
  44288. ** to read or write data returns an error. Eventually, once all
  44289. ** outstanding transactions have been abandoned, the pager is able to
  44290. ** transition back to OPEN state, discarding the contents of the
  44291. ** page-cache and any other in-memory state at the same time. Everything
  44292. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  44293. ** when a read-transaction is next opened on the pager (transitioning
  44294. ** the pager into READER state). At that point the system has recovered
  44295. ** from the error.
  44296. **
  44297. ** Specifically, the pager jumps into the ERROR state if:
  44298. **
  44299. ** 1. An error occurs while attempting a rollback. This happens in
  44300. ** function sqlite3PagerRollback().
  44301. **
  44302. ** 2. An error occurs while attempting to finalize a journal file
  44303. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  44304. **
  44305. ** 3. An error occurs while attempting to write to the journal or
  44306. ** database file in function pagerStress() in order to free up
  44307. ** memory.
  44308. **
  44309. ** In other cases, the error is returned to the b-tree layer. The b-tree
  44310. ** layer then attempts a rollback operation. If the error condition
  44311. ** persists, the pager enters the ERROR state via condition (1) above.
  44312. **
  44313. ** Condition (3) is necessary because it can be triggered by a read-only
  44314. ** statement executed within a transaction. In this case, if the error
  44315. ** code were simply returned to the user, the b-tree layer would not
  44316. ** automatically attempt a rollback, as it assumes that an error in a
  44317. ** read-only statement cannot leave the pager in an internally inconsistent
  44318. ** state.
  44319. **
  44320. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  44321. ** * There are one or more outstanding references to pages (after the
  44322. ** last reference is dropped the pager should move back to OPEN state).
  44323. ** * The pager is not an in-memory pager.
  44324. **
  44325. **
  44326. ** Notes:
  44327. **
  44328. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  44329. ** connection is open in WAL mode. A WAL connection is always in one
  44330. ** of the first four states.
  44331. **
  44332. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  44333. ** state. There are two exceptions: immediately after exclusive-mode has
  44334. ** been turned on (and before any read or write transactions are
  44335. ** executed), and when the pager is leaving the "error state".
  44336. **
  44337. ** * See also: assert_pager_state().
  44338. */
  44339. #define PAGER_OPEN 0
  44340. #define PAGER_READER 1
  44341. #define PAGER_WRITER_LOCKED 2
  44342. #define PAGER_WRITER_CACHEMOD 3
  44343. #define PAGER_WRITER_DBMOD 4
  44344. #define PAGER_WRITER_FINISHED 5
  44345. #define PAGER_ERROR 6
  44346. /*
  44347. ** The Pager.eLock variable is almost always set to one of the
  44348. ** following locking-states, according to the lock currently held on
  44349. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  44350. ** This variable is kept up to date as locks are taken and released by
  44351. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  44352. **
  44353. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  44354. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  44355. ** the operation was successful. In these circumstances pagerLockDb() and
  44356. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  44357. ** when unlocking the file, and only updated when locking the file if the
  44358. ** VFS call is successful. This way, the Pager.eLock variable may be set
  44359. ** to a less exclusive (lower) value than the lock that is actually held
  44360. ** at the system level, but it is never set to a more exclusive value.
  44361. **
  44362. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  44363. ** be a few redundant xLock() calls or a lock may be held for longer than
  44364. ** required, but nothing really goes wrong.
  44365. **
  44366. ** The exception is when the database file is unlocked as the pager moves
  44367. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  44368. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  44369. ** transition, by the same pager or any other). If the call to xUnlock()
  44370. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  44371. ** can confuse the call to xCheckReservedLock() call made later as part
  44372. ** of hot-journal detection.
  44373. **
  44374. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  44375. ** lock held by this process or any others". So xCheckReservedLock may
  44376. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  44377. ** doesn't know it because of a previous error in xUnlock). If this happens
  44378. ** a hot-journal may be mistaken for a journal being created by an active
  44379. ** transaction in another process, causing SQLite to read from the database
  44380. ** without rolling it back.
  44381. **
  44382. ** To work around this, if a call to xUnlock() fails when unlocking the
  44383. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  44384. ** is only changed back to a real locking state after a successful call
  44385. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  44386. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  44387. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  44388. ** lock on the database file before attempting to roll it back. See function
  44389. ** PagerSharedLock() for more detail.
  44390. **
  44391. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  44392. ** PAGER_OPEN state.
  44393. */
  44394. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  44395. /*
  44396. ** A macro used for invoking the codec if there is one
  44397. */
  44398. #ifdef SQLITE_HAS_CODEC
  44399. # define CODEC1(P,D,N,X,E) \
  44400. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  44401. # define CODEC2(P,D,N,X,E,O) \
  44402. if( P->xCodec==0 ){ O=(char*)D; }else \
  44403. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  44404. #else
  44405. # define CODEC1(P,D,N,X,E) /* NO-OP */
  44406. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  44407. #endif
  44408. /*
  44409. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  44410. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  44411. ** This could conceivably cause corruption following a power failure on
  44412. ** such a system. This is currently an undocumented limit.
  44413. */
  44414. #define MAX_SECTOR_SIZE 0x10000
  44415. /*
  44416. ** An instance of the following structure is allocated for each active
  44417. ** savepoint and statement transaction in the system. All such structures
  44418. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  44419. ** resized using sqlite3Realloc().
  44420. **
  44421. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  44422. ** set to 0. If a journal-header is written into the main journal while
  44423. ** the savepoint is active, then iHdrOffset is set to the byte offset
  44424. ** immediately following the last journal record written into the main
  44425. ** journal before the journal-header. This is required during savepoint
  44426. ** rollback (see pagerPlaybackSavepoint()).
  44427. */
  44428. typedef struct PagerSavepoint PagerSavepoint;
  44429. struct PagerSavepoint {
  44430. i64 iOffset; /* Starting offset in main journal */
  44431. i64 iHdrOffset; /* See above */
  44432. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  44433. Pgno nOrig; /* Original number of pages in file */
  44434. Pgno iSubRec; /* Index of first record in sub-journal */
  44435. #ifndef SQLITE_OMIT_WAL
  44436. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  44437. #endif
  44438. };
  44439. /*
  44440. ** Bits of the Pager.doNotSpill flag. See further description below.
  44441. */
  44442. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  44443. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  44444. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  44445. /*
  44446. ** An open page cache is an instance of struct Pager. A description of
  44447. ** some of the more important member variables follows:
  44448. **
  44449. ** eState
  44450. **
  44451. ** The current 'state' of the pager object. See the comment and state
  44452. ** diagram above for a description of the pager state.
  44453. **
  44454. ** eLock
  44455. **
  44456. ** For a real on-disk database, the current lock held on the database file -
  44457. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  44458. **
  44459. ** For a temporary or in-memory database (neither of which require any
  44460. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  44461. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  44462. ** logic into thinking that it already has all the locks it will ever
  44463. ** need (and no reason to release them).
  44464. **
  44465. ** In some (obscure) circumstances, this variable may also be set to
  44466. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  44467. ** details.
  44468. **
  44469. ** changeCountDone
  44470. **
  44471. ** This boolean variable is used to make sure that the change-counter
  44472. ** (the 4-byte header field at byte offset 24 of the database file) is
  44473. ** not updated more often than necessary.
  44474. **
  44475. ** It is set to true when the change-counter field is updated, which
  44476. ** can only happen if an exclusive lock is held on the database file.
  44477. ** It is cleared (set to false) whenever an exclusive lock is
  44478. ** relinquished on the database file. Each time a transaction is committed,
  44479. ** The changeCountDone flag is inspected. If it is true, the work of
  44480. ** updating the change-counter is omitted for the current transaction.
  44481. **
  44482. ** This mechanism means that when running in exclusive mode, a connection
  44483. ** need only update the change-counter once, for the first transaction
  44484. ** committed.
  44485. **
  44486. ** setMaster
  44487. **
  44488. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  44489. ** (or may not) specify a master-journal name to be written into the
  44490. ** journal file before it is synced to disk.
  44491. **
  44492. ** Whether or not a journal file contains a master-journal pointer affects
  44493. ** the way in which the journal file is finalized after the transaction is
  44494. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  44495. ** If a journal file does not contain a master-journal pointer, it is
  44496. ** finalized by overwriting the first journal header with zeroes. If
  44497. ** it does contain a master-journal pointer the journal file is finalized
  44498. ** by truncating it to zero bytes, just as if the connection were
  44499. ** running in "journal_mode=truncate" mode.
  44500. **
  44501. ** Journal files that contain master journal pointers cannot be finalized
  44502. ** simply by overwriting the first journal-header with zeroes, as the
  44503. ** master journal pointer could interfere with hot-journal rollback of any
  44504. ** subsequently interrupted transaction that reuses the journal file.
  44505. **
  44506. ** The flag is cleared as soon as the journal file is finalized (either
  44507. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  44508. ** journal file from being successfully finalized, the setMaster flag
  44509. ** is cleared anyway (and the pager will move to ERROR state).
  44510. **
  44511. ** doNotSpill
  44512. **
  44513. ** This variables control the behavior of cache-spills (calls made by
  44514. ** the pcache module to the pagerStress() routine to write cached data
  44515. ** to the file-system in order to free up memory).
  44516. **
  44517. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  44518. ** writing to the database from pagerStress() is disabled altogether.
  44519. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  44520. ** comes up during savepoint rollback that requires the pcache module
  44521. ** to allocate a new page to prevent the journal file from being written
  44522. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  44523. ** case is a user preference.
  44524. **
  44525. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  44526. ** pagerStress() is permitted, but syncing the journal file is not.
  44527. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  44528. ** is larger than the database page-size in order to prevent a journal sync
  44529. ** from happening in between the journalling of two pages on the same sector.
  44530. **
  44531. ** subjInMemory
  44532. **
  44533. ** This is a boolean variable. If true, then any required sub-journal
  44534. ** is opened as an in-memory journal file. If false, then in-memory
  44535. ** sub-journals are only used for in-memory pager files.
  44536. **
  44537. ** This variable is updated by the upper layer each time a new
  44538. ** write-transaction is opened.
  44539. **
  44540. ** dbSize, dbOrigSize, dbFileSize
  44541. **
  44542. ** Variable dbSize is set to the number of pages in the database file.
  44543. ** It is valid in PAGER_READER and higher states (all states except for
  44544. ** OPEN and ERROR).
  44545. **
  44546. ** dbSize is set based on the size of the database file, which may be
  44547. ** larger than the size of the database (the value stored at offset
  44548. ** 28 of the database header by the btree). If the size of the file
  44549. ** is not an integer multiple of the page-size, the value stored in
  44550. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  44551. ** Except, any file that is greater than 0 bytes in size is considered
  44552. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  44553. ** to dbSize==1).
  44554. **
  44555. ** During a write-transaction, if pages with page-numbers greater than
  44556. ** dbSize are modified in the cache, dbSize is updated accordingly.
  44557. ** Similarly, if the database is truncated using PagerTruncateImage(),
  44558. ** dbSize is updated.
  44559. **
  44560. ** Variables dbOrigSize and dbFileSize are valid in states
  44561. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  44562. ** variable at the start of the transaction. It is used during rollback,
  44563. ** and to determine whether or not pages need to be journalled before
  44564. ** being modified.
  44565. **
  44566. ** Throughout a write-transaction, dbFileSize contains the size of
  44567. ** the file on disk in pages. It is set to a copy of dbSize when the
  44568. ** write-transaction is first opened, and updated when VFS calls are made
  44569. ** to write or truncate the database file on disk.
  44570. **
  44571. ** The only reason the dbFileSize variable is required is to suppress
  44572. ** unnecessary calls to xTruncate() after committing a transaction. If,
  44573. ** when a transaction is committed, the dbFileSize variable indicates
  44574. ** that the database file is larger than the database image (Pager.dbSize),
  44575. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  44576. ** to measure the database file on disk, and then truncates it if required.
  44577. ** dbFileSize is not used when rolling back a transaction. In this case
  44578. ** pager_truncate() is called unconditionally (which means there may be
  44579. ** a call to xFilesize() that is not strictly required). In either case,
  44580. ** pager_truncate() may cause the file to become smaller or larger.
  44581. **
  44582. ** dbHintSize
  44583. **
  44584. ** The dbHintSize variable is used to limit the number of calls made to
  44585. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  44586. **
  44587. ** dbHintSize is set to a copy of the dbSize variable when a
  44588. ** write-transaction is opened (at the same time as dbFileSize and
  44589. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  44590. ** dbHintSize is increased to the number of pages that correspond to the
  44591. ** size-hint passed to the method call. See pager_write_pagelist() for
  44592. ** details.
  44593. **
  44594. ** errCode
  44595. **
  44596. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  44597. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  44598. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  44599. ** sub-codes.
  44600. */
  44601. struct Pager {
  44602. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  44603. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  44604. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  44605. u8 useJournal; /* Use a rollback journal on this file */
  44606. u8 noSync; /* Do not sync the journal if true */
  44607. u8 fullSync; /* Do extra syncs of the journal for robustness */
  44608. u8 extraSync; /* sync directory after journal delete */
  44609. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  44610. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  44611. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  44612. u8 tempFile; /* zFilename is a temporary or immutable file */
  44613. u8 noLock; /* Do not lock (except in WAL mode) */
  44614. u8 readOnly; /* True for a read-only database */
  44615. u8 memDb; /* True to inhibit all file I/O */
  44616. /**************************************************************************
  44617. ** The following block contains those class members that change during
  44618. ** routine operation. Class members not in this block are either fixed
  44619. ** when the pager is first created or else only change when there is a
  44620. ** significant mode change (such as changing the page_size, locking_mode,
  44621. ** or the journal_mode). From another view, these class members describe
  44622. ** the "state" of the pager, while other class members describe the
  44623. ** "configuration" of the pager.
  44624. */
  44625. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  44626. u8 eLock; /* Current lock held on database file */
  44627. u8 changeCountDone; /* Set after incrementing the change-counter */
  44628. u8 setMaster; /* True if a m-j name has been written to jrnl */
  44629. u8 doNotSpill; /* Do not spill the cache when non-zero */
  44630. u8 subjInMemory; /* True to use in-memory sub-journals */
  44631. u8 bUseFetch; /* True to use xFetch() */
  44632. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  44633. Pgno dbSize; /* Number of pages in the database */
  44634. Pgno dbOrigSize; /* dbSize before the current transaction */
  44635. Pgno dbFileSize; /* Number of pages in the database file */
  44636. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  44637. int errCode; /* One of several kinds of errors */
  44638. int nRec; /* Pages journalled since last j-header written */
  44639. u32 cksumInit; /* Quasi-random value added to every checksum */
  44640. u32 nSubRec; /* Number of records written to sub-journal */
  44641. Bitvec *pInJournal; /* One bit for each page in the database file */
  44642. sqlite3_file *fd; /* File descriptor for database */
  44643. sqlite3_file *jfd; /* File descriptor for main journal */
  44644. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  44645. i64 journalOff; /* Current write offset in the journal file */
  44646. i64 journalHdr; /* Byte offset to previous journal header */
  44647. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  44648. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  44649. int nSavepoint; /* Number of elements in aSavepoint[] */
  44650. u32 iDataVersion; /* Changes whenever database content changes */
  44651. char dbFileVers[16]; /* Changes whenever database file changes */
  44652. int nMmapOut; /* Number of mmap pages currently outstanding */
  44653. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  44654. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  44655. /*
  44656. ** End of the routinely-changing class members
  44657. ***************************************************************************/
  44658. u16 nExtra; /* Add this many bytes to each in-memory page */
  44659. i16 nReserve; /* Number of unused bytes at end of each page */
  44660. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  44661. u32 sectorSize; /* Assumed sector size during rollback */
  44662. int pageSize; /* Number of bytes in a page */
  44663. Pgno mxPgno; /* Maximum allowed size of the database */
  44664. i64 journalSizeLimit; /* Size limit for persistent journal files */
  44665. char *zFilename; /* Name of the database file */
  44666. char *zJournal; /* Name of the journal file */
  44667. int (*xBusyHandler)(void*); /* Function to call when busy */
  44668. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  44669. int aStat[3]; /* Total cache hits, misses and writes */
  44670. #ifdef SQLITE_TEST
  44671. int nRead; /* Database pages read */
  44672. #endif
  44673. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  44674. int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
  44675. #ifdef SQLITE_HAS_CODEC
  44676. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  44677. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  44678. void (*xCodecFree)(void*); /* Destructor for the codec */
  44679. void *pCodec; /* First argument to xCodec... methods */
  44680. #endif
  44681. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  44682. PCache *pPCache; /* Pointer to page cache object */
  44683. #ifndef SQLITE_OMIT_WAL
  44684. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  44685. char *zWal; /* File name for write-ahead log */
  44686. #endif
  44687. };
  44688. /*
  44689. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  44690. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  44691. ** or CACHE_WRITE to sqlite3_db_status().
  44692. */
  44693. #define PAGER_STAT_HIT 0
  44694. #define PAGER_STAT_MISS 1
  44695. #define PAGER_STAT_WRITE 2
  44696. /*
  44697. ** The following global variables hold counters used for
  44698. ** testing purposes only. These variables do not exist in
  44699. ** a non-testing build. These variables are not thread-safe.
  44700. */
  44701. #ifdef SQLITE_TEST
  44702. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  44703. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  44704. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  44705. # define PAGER_INCR(v) v++
  44706. #else
  44707. # define PAGER_INCR(v)
  44708. #endif
  44709. /*
  44710. ** Journal files begin with the following magic string. The data
  44711. ** was obtained from /dev/random. It is used only as a sanity check.
  44712. **
  44713. ** Since version 2.8.0, the journal format contains additional sanity
  44714. ** checking information. If the power fails while the journal is being
  44715. ** written, semi-random garbage data might appear in the journal
  44716. ** file after power is restored. If an attempt is then made
  44717. ** to roll the journal back, the database could be corrupted. The additional
  44718. ** sanity checking data is an attempt to discover the garbage in the
  44719. ** journal and ignore it.
  44720. **
  44721. ** The sanity checking information for the new journal format consists
  44722. ** of a 32-bit checksum on each page of data. The checksum covers both
  44723. ** the page number and the pPager->pageSize bytes of data for the page.
  44724. ** This cksum is initialized to a 32-bit random value that appears in the
  44725. ** journal file right after the header. The random initializer is important,
  44726. ** because garbage data that appears at the end of a journal is likely
  44727. ** data that was once in other files that have now been deleted. If the
  44728. ** garbage data came from an obsolete journal file, the checksums might
  44729. ** be correct. But by initializing the checksum to random value which
  44730. ** is different for every journal, we minimize that risk.
  44731. */
  44732. static const unsigned char aJournalMagic[] = {
  44733. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  44734. };
  44735. /*
  44736. ** The size of the of each page record in the journal is given by
  44737. ** the following macro.
  44738. */
  44739. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  44740. /*
  44741. ** The journal header size for this pager. This is usually the same
  44742. ** size as a single disk sector. See also setSectorSize().
  44743. */
  44744. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  44745. /*
  44746. ** The macro MEMDB is true if we are dealing with an in-memory database.
  44747. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  44748. ** the value of MEMDB will be a constant and the compiler will optimize
  44749. ** out code that would never execute.
  44750. */
  44751. #ifdef SQLITE_OMIT_MEMORYDB
  44752. # define MEMDB 0
  44753. #else
  44754. # define MEMDB pPager->memDb
  44755. #endif
  44756. /*
  44757. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  44758. ** interfaces to access the database using memory-mapped I/O.
  44759. */
  44760. #if SQLITE_MAX_MMAP_SIZE>0
  44761. # define USEFETCH(x) ((x)->bUseFetch)
  44762. #else
  44763. # define USEFETCH(x) 0
  44764. #endif
  44765. /*
  44766. ** The maximum legal page number is (2^31 - 1).
  44767. */
  44768. #define PAGER_MAX_PGNO 2147483647
  44769. /*
  44770. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  44771. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  44772. **
  44773. ** This is so that expressions can be written as:
  44774. **
  44775. ** if( isOpen(pPager->jfd) ){ ...
  44776. **
  44777. ** instead of
  44778. **
  44779. ** if( pPager->jfd->pMethods ){ ...
  44780. */
  44781. #define isOpen(pFd) ((pFd)->pMethods!=0)
  44782. /*
  44783. ** Return true if this pager uses a write-ahead log to read page pgno.
  44784. ** Return false if the pager reads pgno directly from the database.
  44785. */
  44786. #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
  44787. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
  44788. u32 iRead = 0;
  44789. int rc;
  44790. if( pPager->pWal==0 ) return 0;
  44791. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
  44792. return rc || iRead;
  44793. }
  44794. #endif
  44795. #ifndef SQLITE_OMIT_WAL
  44796. # define pagerUseWal(x) ((x)->pWal!=0)
  44797. #else
  44798. # define pagerUseWal(x) 0
  44799. # define pagerRollbackWal(x) 0
  44800. # define pagerWalFrames(v,w,x,y) 0
  44801. # define pagerOpenWalIfPresent(z) SQLITE_OK
  44802. # define pagerBeginReadTransaction(z) SQLITE_OK
  44803. #endif
  44804. #ifndef NDEBUG
  44805. /*
  44806. ** Usage:
  44807. **
  44808. ** assert( assert_pager_state(pPager) );
  44809. **
  44810. ** This function runs many asserts to try to find inconsistencies in
  44811. ** the internal state of the Pager object.
  44812. */
  44813. static int assert_pager_state(Pager *p){
  44814. Pager *pPager = p;
  44815. /* State must be valid. */
  44816. assert( p->eState==PAGER_OPEN
  44817. || p->eState==PAGER_READER
  44818. || p->eState==PAGER_WRITER_LOCKED
  44819. || p->eState==PAGER_WRITER_CACHEMOD
  44820. || p->eState==PAGER_WRITER_DBMOD
  44821. || p->eState==PAGER_WRITER_FINISHED
  44822. || p->eState==PAGER_ERROR
  44823. );
  44824. /* Regardless of the current state, a temp-file connection always behaves
  44825. ** as if it has an exclusive lock on the database file. It never updates
  44826. ** the change-counter field, so the changeCountDone flag is always set.
  44827. */
  44828. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  44829. assert( p->tempFile==0 || pPager->changeCountDone );
  44830. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  44831. ** And if the journal-mode is "OFF", the journal file must not be open.
  44832. */
  44833. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  44834. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  44835. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  44836. ** this means an in-memory pager performs no IO at all, it cannot encounter
  44837. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  44838. ** a journal file. (although the in-memory journal implementation may
  44839. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  44840. ** is therefore not possible for an in-memory pager to enter the ERROR
  44841. ** state.
  44842. */
  44843. if( MEMDB ){
  44844. assert( !isOpen(p->fd) );
  44845. assert( p->noSync );
  44846. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  44847. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  44848. );
  44849. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  44850. assert( pagerUseWal(p)==0 );
  44851. }
  44852. /* If changeCountDone is set, a RESERVED lock or greater must be held
  44853. ** on the file.
  44854. */
  44855. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  44856. assert( p->eLock!=PENDING_LOCK );
  44857. switch( p->eState ){
  44858. case PAGER_OPEN:
  44859. assert( !MEMDB );
  44860. assert( pPager->errCode==SQLITE_OK );
  44861. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  44862. break;
  44863. case PAGER_READER:
  44864. assert( pPager->errCode==SQLITE_OK );
  44865. assert( p->eLock!=UNKNOWN_LOCK );
  44866. assert( p->eLock>=SHARED_LOCK );
  44867. break;
  44868. case PAGER_WRITER_LOCKED:
  44869. assert( p->eLock!=UNKNOWN_LOCK );
  44870. assert( pPager->errCode==SQLITE_OK );
  44871. if( !pagerUseWal(pPager) ){
  44872. assert( p->eLock>=RESERVED_LOCK );
  44873. }
  44874. assert( pPager->dbSize==pPager->dbOrigSize );
  44875. assert( pPager->dbOrigSize==pPager->dbFileSize );
  44876. assert( pPager->dbOrigSize==pPager->dbHintSize );
  44877. assert( pPager->setMaster==0 );
  44878. break;
  44879. case PAGER_WRITER_CACHEMOD:
  44880. assert( p->eLock!=UNKNOWN_LOCK );
  44881. assert( pPager->errCode==SQLITE_OK );
  44882. if( !pagerUseWal(pPager) ){
  44883. /* It is possible that if journal_mode=wal here that neither the
  44884. ** journal file nor the WAL file are open. This happens during
  44885. ** a rollback transaction that switches from journal_mode=off
  44886. ** to journal_mode=wal.
  44887. */
  44888. assert( p->eLock>=RESERVED_LOCK );
  44889. assert( isOpen(p->jfd)
  44890. || p->journalMode==PAGER_JOURNALMODE_OFF
  44891. || p->journalMode==PAGER_JOURNALMODE_WAL
  44892. );
  44893. }
  44894. assert( pPager->dbOrigSize==pPager->dbFileSize );
  44895. assert( pPager->dbOrigSize==pPager->dbHintSize );
  44896. break;
  44897. case PAGER_WRITER_DBMOD:
  44898. assert( p->eLock==EXCLUSIVE_LOCK );
  44899. assert( pPager->errCode==SQLITE_OK );
  44900. assert( !pagerUseWal(pPager) );
  44901. assert( p->eLock>=EXCLUSIVE_LOCK );
  44902. assert( isOpen(p->jfd)
  44903. || p->journalMode==PAGER_JOURNALMODE_OFF
  44904. || p->journalMode==PAGER_JOURNALMODE_WAL
  44905. );
  44906. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  44907. break;
  44908. case PAGER_WRITER_FINISHED:
  44909. assert( p->eLock==EXCLUSIVE_LOCK );
  44910. assert( pPager->errCode==SQLITE_OK );
  44911. assert( !pagerUseWal(pPager) );
  44912. assert( isOpen(p->jfd)
  44913. || p->journalMode==PAGER_JOURNALMODE_OFF
  44914. || p->journalMode==PAGER_JOURNALMODE_WAL
  44915. );
  44916. break;
  44917. case PAGER_ERROR:
  44918. /* There must be at least one outstanding reference to the pager if
  44919. ** in ERROR state. Otherwise the pager should have already dropped
  44920. ** back to OPEN state.
  44921. */
  44922. assert( pPager->errCode!=SQLITE_OK );
  44923. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
  44924. break;
  44925. }
  44926. return 1;
  44927. }
  44928. #endif /* ifndef NDEBUG */
  44929. #ifdef SQLITE_DEBUG
  44930. /*
  44931. ** Return a pointer to a human readable string in a static buffer
  44932. ** containing the state of the Pager object passed as an argument. This
  44933. ** is intended to be used within debuggers. For example, as an alternative
  44934. ** to "print *pPager" in gdb:
  44935. **
  44936. ** (gdb) printf "%s", print_pager_state(pPager)
  44937. */
  44938. static char *print_pager_state(Pager *p){
  44939. static char zRet[1024];
  44940. sqlite3_snprintf(1024, zRet,
  44941. "Filename: %s\n"
  44942. "State: %s errCode=%d\n"
  44943. "Lock: %s\n"
  44944. "Locking mode: locking_mode=%s\n"
  44945. "Journal mode: journal_mode=%s\n"
  44946. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  44947. "Journal: journalOff=%lld journalHdr=%lld\n"
  44948. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  44949. , p->zFilename
  44950. , p->eState==PAGER_OPEN ? "OPEN" :
  44951. p->eState==PAGER_READER ? "READER" :
  44952. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  44953. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  44954. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  44955. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  44956. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  44957. , (int)p->errCode
  44958. , p->eLock==NO_LOCK ? "NO_LOCK" :
  44959. p->eLock==RESERVED_LOCK ? "RESERVED" :
  44960. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  44961. p->eLock==SHARED_LOCK ? "SHARED" :
  44962. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  44963. , p->exclusiveMode ? "exclusive" : "normal"
  44964. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  44965. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  44966. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  44967. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  44968. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  44969. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  44970. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  44971. , p->journalOff, p->journalHdr
  44972. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  44973. );
  44974. return zRet;
  44975. }
  44976. #endif
  44977. /* Forward references to the various page getters */
  44978. static int getPageNormal(Pager*,Pgno,DbPage**,int);
  44979. static int getPageError(Pager*,Pgno,DbPage**,int);
  44980. #if SQLITE_MAX_MMAP_SIZE>0
  44981. static int getPageMMap(Pager*,Pgno,DbPage**,int);
  44982. #endif
  44983. /*
  44984. ** Set the Pager.xGet method for the appropriate routine used to fetch
  44985. ** content from the pager.
  44986. */
  44987. static void setGetterMethod(Pager *pPager){
  44988. if( pPager->errCode ){
  44989. pPager->xGet = getPageError;
  44990. #if SQLITE_MAX_MMAP_SIZE>0
  44991. }else if( USEFETCH(pPager)
  44992. #ifdef SQLITE_HAS_CODEC
  44993. && pPager->xCodec==0
  44994. #endif
  44995. ){
  44996. pPager->xGet = getPageMMap;
  44997. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  44998. }else{
  44999. pPager->xGet = getPageNormal;
  45000. }
  45001. }
  45002. /*
  45003. ** Return true if it is necessary to write page *pPg into the sub-journal.
  45004. ** A page needs to be written into the sub-journal if there exists one
  45005. ** or more open savepoints for which:
  45006. **
  45007. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  45008. ** * The bit corresponding to the page-number is not set in
  45009. ** PagerSavepoint.pInSavepoint.
  45010. */
  45011. static int subjRequiresPage(PgHdr *pPg){
  45012. Pager *pPager = pPg->pPager;
  45013. PagerSavepoint *p;
  45014. Pgno pgno = pPg->pgno;
  45015. int i;
  45016. for(i=0; i<pPager->nSavepoint; i++){
  45017. p = &pPager->aSavepoint[i];
  45018. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  45019. return 1;
  45020. }
  45021. }
  45022. return 0;
  45023. }
  45024. #ifdef SQLITE_DEBUG
  45025. /*
  45026. ** Return true if the page is already in the journal file.
  45027. */
  45028. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  45029. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  45030. }
  45031. #endif
  45032. /*
  45033. ** Read a 32-bit integer from the given file descriptor. Store the integer
  45034. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  45035. ** error code is something goes wrong.
  45036. **
  45037. ** All values are stored on disk as big-endian.
  45038. */
  45039. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  45040. unsigned char ac[4];
  45041. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  45042. if( rc==SQLITE_OK ){
  45043. *pRes = sqlite3Get4byte(ac);
  45044. }
  45045. return rc;
  45046. }
  45047. /*
  45048. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  45049. */
  45050. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  45051. /*
  45052. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  45053. ** on success or an error code is something goes wrong.
  45054. */
  45055. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  45056. char ac[4];
  45057. put32bits(ac, val);
  45058. return sqlite3OsWrite(fd, ac, 4, offset);
  45059. }
  45060. /*
  45061. ** Unlock the database file to level eLock, which must be either NO_LOCK
  45062. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  45063. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  45064. **
  45065. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  45066. ** called, do not modify it. See the comment above the #define of
  45067. ** UNKNOWN_LOCK for an explanation of this.
  45068. */
  45069. static int pagerUnlockDb(Pager *pPager, int eLock){
  45070. int rc = SQLITE_OK;
  45071. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  45072. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  45073. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  45074. if( isOpen(pPager->fd) ){
  45075. assert( pPager->eLock>=eLock );
  45076. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  45077. if( pPager->eLock!=UNKNOWN_LOCK ){
  45078. pPager->eLock = (u8)eLock;
  45079. }
  45080. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  45081. }
  45082. return rc;
  45083. }
  45084. /*
  45085. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  45086. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  45087. ** Pager.eLock variable to the new locking state.
  45088. **
  45089. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  45090. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  45091. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  45092. ** of this.
  45093. */
  45094. static int pagerLockDb(Pager *pPager, int eLock){
  45095. int rc = SQLITE_OK;
  45096. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  45097. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  45098. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  45099. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  45100. pPager->eLock = (u8)eLock;
  45101. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  45102. }
  45103. }
  45104. return rc;
  45105. }
  45106. /*
  45107. ** This function determines whether or not the atomic-write optimization
  45108. ** can be used with this pager. The optimization can be used if:
  45109. **
  45110. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  45111. ** a database page may be written atomically, and
  45112. ** (b) the value returned by OsSectorSize() is less than or equal
  45113. ** to the page size.
  45114. **
  45115. ** The optimization is also always enabled for temporary files. It is
  45116. ** an error to call this function if pPager is opened on an in-memory
  45117. ** database.
  45118. **
  45119. ** If the optimization cannot be used, 0 is returned. If it can be used,
  45120. ** then the value returned is the size of the journal file when it
  45121. ** contains rollback data for exactly one page.
  45122. */
  45123. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  45124. static int jrnlBufferSize(Pager *pPager){
  45125. assert( !MEMDB );
  45126. if( !pPager->tempFile ){
  45127. int dc; /* Device characteristics */
  45128. int nSector; /* Sector size */
  45129. int szPage; /* Page size */
  45130. assert( isOpen(pPager->fd) );
  45131. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  45132. nSector = pPager->sectorSize;
  45133. szPage = pPager->pageSize;
  45134. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  45135. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  45136. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  45137. return 0;
  45138. }
  45139. }
  45140. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  45141. }
  45142. #else
  45143. # define jrnlBufferSize(x) 0
  45144. #endif
  45145. /*
  45146. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  45147. ** on the cache using a hash function. This is used for testing
  45148. ** and debugging only.
  45149. */
  45150. #ifdef SQLITE_CHECK_PAGES
  45151. /*
  45152. ** Return a 32-bit hash of the page data for pPage.
  45153. */
  45154. static u32 pager_datahash(int nByte, unsigned char *pData){
  45155. u32 hash = 0;
  45156. int i;
  45157. for(i=0; i<nByte; i++){
  45158. hash = (hash*1039) + pData[i];
  45159. }
  45160. return hash;
  45161. }
  45162. static u32 pager_pagehash(PgHdr *pPage){
  45163. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  45164. }
  45165. static void pager_set_pagehash(PgHdr *pPage){
  45166. pPage->pageHash = pager_pagehash(pPage);
  45167. }
  45168. /*
  45169. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  45170. ** is defined, and NDEBUG is not defined, an assert() statement checks
  45171. ** that the page is either dirty or still matches the calculated page-hash.
  45172. */
  45173. #define CHECK_PAGE(x) checkPage(x)
  45174. static void checkPage(PgHdr *pPg){
  45175. Pager *pPager = pPg->pPager;
  45176. assert( pPager->eState!=PAGER_ERROR );
  45177. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  45178. }
  45179. #else
  45180. #define pager_datahash(X,Y) 0
  45181. #define pager_pagehash(X) 0
  45182. #define pager_set_pagehash(X)
  45183. #define CHECK_PAGE(x)
  45184. #endif /* SQLITE_CHECK_PAGES */
  45185. /*
  45186. ** When this is called the journal file for pager pPager must be open.
  45187. ** This function attempts to read a master journal file name from the
  45188. ** end of the file and, if successful, copies it into memory supplied
  45189. ** by the caller. See comments above writeMasterJournal() for the format
  45190. ** used to store a master journal file name at the end of a journal file.
  45191. **
  45192. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  45193. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  45194. ** enough space to write the master journal name). If the master journal
  45195. ** name in the journal is longer than nMaster bytes (including a
  45196. ** nul-terminator), then this is handled as if no master journal name
  45197. ** were present in the journal.
  45198. **
  45199. ** If a master journal file name is present at the end of the journal
  45200. ** file, then it is copied into the buffer pointed to by zMaster. A
  45201. ** nul-terminator byte is appended to the buffer following the master
  45202. ** journal file name.
  45203. **
  45204. ** If it is determined that no master journal file name is present
  45205. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  45206. **
  45207. ** If an error occurs while reading from the journal file, an SQLite
  45208. ** error code is returned.
  45209. */
  45210. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  45211. int rc; /* Return code */
  45212. u32 len; /* Length in bytes of master journal name */
  45213. i64 szJ; /* Total size in bytes of journal file pJrnl */
  45214. u32 cksum; /* MJ checksum value read from journal */
  45215. u32 u; /* Unsigned loop counter */
  45216. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  45217. zMaster[0] = '\0';
  45218. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  45219. || szJ<16
  45220. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  45221. || len>=nMaster
  45222. || len==0
  45223. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  45224. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  45225. || memcmp(aMagic, aJournalMagic, 8)
  45226. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  45227. ){
  45228. return rc;
  45229. }
  45230. /* See if the checksum matches the master journal name */
  45231. for(u=0; u<len; u++){
  45232. cksum -= zMaster[u];
  45233. }
  45234. if( cksum ){
  45235. /* If the checksum doesn't add up, then one or more of the disk sectors
  45236. ** containing the master journal filename is corrupted. This means
  45237. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  45238. ** master-journal filename.
  45239. */
  45240. len = 0;
  45241. }
  45242. zMaster[len] = '\0';
  45243. return SQLITE_OK;
  45244. }
  45245. /*
  45246. ** Return the offset of the sector boundary at or immediately
  45247. ** following the value in pPager->journalOff, assuming a sector
  45248. ** size of pPager->sectorSize bytes.
  45249. **
  45250. ** i.e for a sector size of 512:
  45251. **
  45252. ** Pager.journalOff Return value
  45253. ** ---------------------------------------
  45254. ** 0 0
  45255. ** 512 512
  45256. ** 100 512
  45257. ** 2000 2048
  45258. **
  45259. */
  45260. static i64 journalHdrOffset(Pager *pPager){
  45261. i64 offset = 0;
  45262. i64 c = pPager->journalOff;
  45263. if( c ){
  45264. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  45265. }
  45266. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  45267. assert( offset>=c );
  45268. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  45269. return offset;
  45270. }
  45271. /*
  45272. ** The journal file must be open when this function is called.
  45273. **
  45274. ** This function is a no-op if the journal file has not been written to
  45275. ** within the current transaction (i.e. if Pager.journalOff==0).
  45276. **
  45277. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  45278. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  45279. ** zero the 28-byte header at the start of the journal file. In either case,
  45280. ** if the pager is not in no-sync mode, sync the journal file immediately
  45281. ** after writing or truncating it.
  45282. **
  45283. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  45284. ** following the truncation or zeroing described above the size of the
  45285. ** journal file in bytes is larger than this value, then truncate the
  45286. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  45287. ** not need to be synced following this operation.
  45288. **
  45289. ** If an IO error occurs, abandon processing and return the IO error code.
  45290. ** Otherwise, return SQLITE_OK.
  45291. */
  45292. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  45293. int rc = SQLITE_OK; /* Return code */
  45294. assert( isOpen(pPager->jfd) );
  45295. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  45296. if( pPager->journalOff ){
  45297. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  45298. IOTRACE(("JZEROHDR %p\n", pPager))
  45299. if( doTruncate || iLimit==0 ){
  45300. rc = sqlite3OsTruncate(pPager->jfd, 0);
  45301. }else{
  45302. static const char zeroHdr[28] = {0};
  45303. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  45304. }
  45305. if( rc==SQLITE_OK && !pPager->noSync ){
  45306. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  45307. }
  45308. /* At this point the transaction is committed but the write lock
  45309. ** is still held on the file. If there is a size limit configured for
  45310. ** the persistent journal and the journal file currently consumes more
  45311. ** space than that limit allows for, truncate it now. There is no need
  45312. ** to sync the file following this operation.
  45313. */
  45314. if( rc==SQLITE_OK && iLimit>0 ){
  45315. i64 sz;
  45316. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  45317. if( rc==SQLITE_OK && sz>iLimit ){
  45318. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  45319. }
  45320. }
  45321. }
  45322. return rc;
  45323. }
  45324. /*
  45325. ** The journal file must be open when this routine is called. A journal
  45326. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  45327. ** current location.
  45328. **
  45329. ** The format for the journal header is as follows:
  45330. ** - 8 bytes: Magic identifying journal format.
  45331. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  45332. ** - 4 bytes: Random number used for page hash.
  45333. ** - 4 bytes: Initial database page count.
  45334. ** - 4 bytes: Sector size used by the process that wrote this journal.
  45335. ** - 4 bytes: Database page size.
  45336. **
  45337. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  45338. */
  45339. static int writeJournalHdr(Pager *pPager){
  45340. int rc = SQLITE_OK; /* Return code */
  45341. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  45342. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  45343. u32 nWrite; /* Bytes of header sector written */
  45344. int ii; /* Loop counter */
  45345. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  45346. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  45347. nHeader = JOURNAL_HDR_SZ(pPager);
  45348. }
  45349. /* If there are active savepoints and any of them were created
  45350. ** since the most recent journal header was written, update the
  45351. ** PagerSavepoint.iHdrOffset fields now.
  45352. */
  45353. for(ii=0; ii<pPager->nSavepoint; ii++){
  45354. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  45355. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  45356. }
  45357. }
  45358. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  45359. /*
  45360. ** Write the nRec Field - the number of page records that follow this
  45361. ** journal header. Normally, zero is written to this value at this time.
  45362. ** After the records are added to the journal (and the journal synced,
  45363. ** if in full-sync mode), the zero is overwritten with the true number
  45364. ** of records (see syncJournal()).
  45365. **
  45366. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  45367. ** reading the journal this value tells SQLite to assume that the
  45368. ** rest of the journal file contains valid page records. This assumption
  45369. ** is dangerous, as if a failure occurred whilst writing to the journal
  45370. ** file it may contain some garbage data. There are two scenarios
  45371. ** where this risk can be ignored:
  45372. **
  45373. ** * When the pager is in no-sync mode. Corruption can follow a
  45374. ** power failure in this case anyway.
  45375. **
  45376. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  45377. ** that garbage data is never appended to the journal file.
  45378. */
  45379. assert( isOpen(pPager->fd) || pPager->noSync );
  45380. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  45381. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  45382. ){
  45383. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  45384. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  45385. }else{
  45386. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  45387. }
  45388. /* The random check-hash initializer */
  45389. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  45390. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  45391. /* The initial database size */
  45392. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  45393. /* The assumed sector size for this process */
  45394. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  45395. /* The page size */
  45396. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  45397. /* Initializing the tail of the buffer is not necessary. Everything
  45398. ** works find if the following memset() is omitted. But initializing
  45399. ** the memory prevents valgrind from complaining, so we are willing to
  45400. ** take the performance hit.
  45401. */
  45402. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  45403. nHeader-(sizeof(aJournalMagic)+20));
  45404. /* In theory, it is only necessary to write the 28 bytes that the
  45405. ** journal header consumes to the journal file here. Then increment the
  45406. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  45407. ** record is written to the following sector (leaving a gap in the file
  45408. ** that will be implicitly filled in by the OS).
  45409. **
  45410. ** However it has been discovered that on some systems this pattern can
  45411. ** be significantly slower than contiguously writing data to the file,
  45412. ** even if that means explicitly writing data to the block of
  45413. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  45414. ** is done.
  45415. **
  45416. ** The loop is required here in case the sector-size is larger than the
  45417. ** database page size. Since the zHeader buffer is only Pager.pageSize
  45418. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  45419. ** to populate the entire journal header sector.
  45420. */
  45421. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  45422. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  45423. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  45424. assert( pPager->journalHdr <= pPager->journalOff );
  45425. pPager->journalOff += nHeader;
  45426. }
  45427. return rc;
  45428. }
  45429. /*
  45430. ** The journal file must be open when this is called. A journal header file
  45431. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  45432. ** file. The current location in the journal file is given by
  45433. ** pPager->journalOff. See comments above function writeJournalHdr() for
  45434. ** a description of the journal header format.
  45435. **
  45436. ** If the header is read successfully, *pNRec is set to the number of
  45437. ** page records following this header and *pDbSize is set to the size of the
  45438. ** database before the transaction began, in pages. Also, pPager->cksumInit
  45439. ** is set to the value read from the journal header. SQLITE_OK is returned
  45440. ** in this case.
  45441. **
  45442. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  45443. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  45444. ** cannot be read from the journal file an error code is returned.
  45445. */
  45446. static int readJournalHdr(
  45447. Pager *pPager, /* Pager object */
  45448. int isHot,
  45449. i64 journalSize, /* Size of the open journal file in bytes */
  45450. u32 *pNRec, /* OUT: Value read from the nRec field */
  45451. u32 *pDbSize /* OUT: Value of original database size field */
  45452. ){
  45453. int rc; /* Return code */
  45454. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  45455. i64 iHdrOff; /* Offset of journal header being read */
  45456. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  45457. /* Advance Pager.journalOff to the start of the next sector. If the
  45458. ** journal file is too small for there to be a header stored at this
  45459. ** point, return SQLITE_DONE.
  45460. */
  45461. pPager->journalOff = journalHdrOffset(pPager);
  45462. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  45463. return SQLITE_DONE;
  45464. }
  45465. iHdrOff = pPager->journalOff;
  45466. /* Read in the first 8 bytes of the journal header. If they do not match
  45467. ** the magic string found at the start of each journal header, return
  45468. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  45469. ** proceed.
  45470. */
  45471. if( isHot || iHdrOff!=pPager->journalHdr ){
  45472. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  45473. if( rc ){
  45474. return rc;
  45475. }
  45476. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  45477. return SQLITE_DONE;
  45478. }
  45479. }
  45480. /* Read the first three 32-bit fields of the journal header: The nRec
  45481. ** field, the checksum-initializer and the database size at the start
  45482. ** of the transaction. Return an error code if anything goes wrong.
  45483. */
  45484. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  45485. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  45486. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  45487. ){
  45488. return rc;
  45489. }
  45490. if( pPager->journalOff==0 ){
  45491. u32 iPageSize; /* Page-size field of journal header */
  45492. u32 iSectorSize; /* Sector-size field of journal header */
  45493. /* Read the page-size and sector-size journal header fields. */
  45494. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  45495. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  45496. ){
  45497. return rc;
  45498. }
  45499. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  45500. ** journal header to zero. In this case, assume that the Pager.pageSize
  45501. ** variable is already set to the correct page size.
  45502. */
  45503. if( iPageSize==0 ){
  45504. iPageSize = pPager->pageSize;
  45505. }
  45506. /* Check that the values read from the page-size and sector-size fields
  45507. ** are within range. To be 'in range', both values need to be a power
  45508. ** of two greater than or equal to 512 or 32, and not greater than their
  45509. ** respective compile time maximum limits.
  45510. */
  45511. if( iPageSize<512 || iSectorSize<32
  45512. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  45513. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  45514. ){
  45515. /* If the either the page-size or sector-size in the journal-header is
  45516. ** invalid, then the process that wrote the journal-header must have
  45517. ** crashed before the header was synced. In this case stop reading
  45518. ** the journal file here.
  45519. */
  45520. return SQLITE_DONE;
  45521. }
  45522. /* Update the page-size to match the value read from the journal.
  45523. ** Use a testcase() macro to make sure that malloc failure within
  45524. ** PagerSetPagesize() is tested.
  45525. */
  45526. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  45527. testcase( rc!=SQLITE_OK );
  45528. /* Update the assumed sector-size to match the value used by
  45529. ** the process that created this journal. If this journal was
  45530. ** created by a process other than this one, then this routine
  45531. ** is being called from within pager_playback(). The local value
  45532. ** of Pager.sectorSize is restored at the end of that routine.
  45533. */
  45534. pPager->sectorSize = iSectorSize;
  45535. }
  45536. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  45537. return rc;
  45538. }
  45539. /*
  45540. ** Write the supplied master journal name into the journal file for pager
  45541. ** pPager at the current location. The master journal name must be the last
  45542. ** thing written to a journal file. If the pager is in full-sync mode, the
  45543. ** journal file descriptor is advanced to the next sector boundary before
  45544. ** anything is written. The format is:
  45545. **
  45546. ** + 4 bytes: PAGER_MJ_PGNO.
  45547. ** + N bytes: Master journal filename in utf-8.
  45548. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  45549. ** + 4 bytes: Master journal name checksum.
  45550. ** + 8 bytes: aJournalMagic[].
  45551. **
  45552. ** The master journal page checksum is the sum of the bytes in the master
  45553. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  45554. **
  45555. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  45556. ** this call is a no-op.
  45557. */
  45558. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  45559. int rc; /* Return code */
  45560. int nMaster; /* Length of string zMaster */
  45561. i64 iHdrOff; /* Offset of header in journal file */
  45562. i64 jrnlSize; /* Size of journal file on disk */
  45563. u32 cksum = 0; /* Checksum of string zMaster */
  45564. assert( pPager->setMaster==0 );
  45565. assert( !pagerUseWal(pPager) );
  45566. if( !zMaster
  45567. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  45568. || !isOpen(pPager->jfd)
  45569. ){
  45570. return SQLITE_OK;
  45571. }
  45572. pPager->setMaster = 1;
  45573. assert( pPager->journalHdr <= pPager->journalOff );
  45574. /* Calculate the length in bytes and the checksum of zMaster */
  45575. for(nMaster=0; zMaster[nMaster]; nMaster++){
  45576. cksum += zMaster[nMaster];
  45577. }
  45578. /* If in full-sync mode, advance to the next disk sector before writing
  45579. ** the master journal name. This is in case the previous page written to
  45580. ** the journal has already been synced.
  45581. */
  45582. if( pPager->fullSync ){
  45583. pPager->journalOff = journalHdrOffset(pPager);
  45584. }
  45585. iHdrOff = pPager->journalOff;
  45586. /* Write the master journal data to the end of the journal file. If
  45587. ** an error occurs, return the error code to the caller.
  45588. */
  45589. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  45590. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  45591. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  45592. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  45593. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  45594. iHdrOff+4+nMaster+8)))
  45595. ){
  45596. return rc;
  45597. }
  45598. pPager->journalOff += (nMaster+20);
  45599. /* If the pager is in peristent-journal mode, then the physical
  45600. ** journal-file may extend past the end of the master-journal name
  45601. ** and 8 bytes of magic data just written to the file. This is
  45602. ** dangerous because the code to rollback a hot-journal file
  45603. ** will not be able to find the master-journal name to determine
  45604. ** whether or not the journal is hot.
  45605. **
  45606. ** Easiest thing to do in this scenario is to truncate the journal
  45607. ** file to the required size.
  45608. */
  45609. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  45610. && jrnlSize>pPager->journalOff
  45611. ){
  45612. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  45613. }
  45614. return rc;
  45615. }
  45616. /*
  45617. ** Discard the entire contents of the in-memory page-cache.
  45618. */
  45619. static void pager_reset(Pager *pPager){
  45620. pPager->iDataVersion++;
  45621. sqlite3BackupRestart(pPager->pBackup);
  45622. sqlite3PcacheClear(pPager->pPCache);
  45623. }
  45624. /*
  45625. ** Return the pPager->iDataVersion value
  45626. */
  45627. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  45628. assert( pPager->eState>PAGER_OPEN );
  45629. return pPager->iDataVersion;
  45630. }
  45631. /*
  45632. ** Free all structures in the Pager.aSavepoint[] array and set both
  45633. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  45634. ** if it is open and the pager is not in exclusive mode.
  45635. */
  45636. static void releaseAllSavepoints(Pager *pPager){
  45637. int ii; /* Iterator for looping through Pager.aSavepoint */
  45638. for(ii=0; ii<pPager->nSavepoint; ii++){
  45639. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  45640. }
  45641. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  45642. sqlite3OsClose(pPager->sjfd);
  45643. }
  45644. sqlite3_free(pPager->aSavepoint);
  45645. pPager->aSavepoint = 0;
  45646. pPager->nSavepoint = 0;
  45647. pPager->nSubRec = 0;
  45648. }
  45649. /*
  45650. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  45651. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  45652. ** or SQLITE_NOMEM if a malloc failure occurs.
  45653. */
  45654. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  45655. int ii; /* Loop counter */
  45656. int rc = SQLITE_OK; /* Result code */
  45657. for(ii=0; ii<pPager->nSavepoint; ii++){
  45658. PagerSavepoint *p = &pPager->aSavepoint[ii];
  45659. if( pgno<=p->nOrig ){
  45660. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  45661. testcase( rc==SQLITE_NOMEM );
  45662. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  45663. }
  45664. }
  45665. return rc;
  45666. }
  45667. /*
  45668. ** This function is a no-op if the pager is in exclusive mode and not
  45669. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  45670. ** state.
  45671. **
  45672. ** If the pager is not in exclusive-access mode, the database file is
  45673. ** completely unlocked. If the file is unlocked and the file-system does
  45674. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  45675. ** closed (if it is open).
  45676. **
  45677. ** If the pager is in ERROR state when this function is called, the
  45678. ** contents of the pager cache are discarded before switching back to
  45679. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  45680. ** or not, any journal file left in the file-system will be treated
  45681. ** as a hot-journal and rolled back the next time a read-transaction
  45682. ** is opened (by this or by any other connection).
  45683. */
  45684. static void pager_unlock(Pager *pPager){
  45685. assert( pPager->eState==PAGER_READER
  45686. || pPager->eState==PAGER_OPEN
  45687. || pPager->eState==PAGER_ERROR
  45688. );
  45689. sqlite3BitvecDestroy(pPager->pInJournal);
  45690. pPager->pInJournal = 0;
  45691. releaseAllSavepoints(pPager);
  45692. if( pagerUseWal(pPager) ){
  45693. assert( !isOpen(pPager->jfd) );
  45694. sqlite3WalEndReadTransaction(pPager->pWal);
  45695. pPager->eState = PAGER_OPEN;
  45696. }else if( !pPager->exclusiveMode ){
  45697. int rc; /* Error code returned by pagerUnlockDb() */
  45698. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  45699. /* If the operating system support deletion of open files, then
  45700. ** close the journal file when dropping the database lock. Otherwise
  45701. ** another connection with journal_mode=delete might delete the file
  45702. ** out from under us.
  45703. */
  45704. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  45705. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  45706. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  45707. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  45708. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  45709. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  45710. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  45711. || 1!=(pPager->journalMode & 5)
  45712. ){
  45713. sqlite3OsClose(pPager->jfd);
  45714. }
  45715. /* If the pager is in the ERROR state and the call to unlock the database
  45716. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  45717. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  45718. ** is necessary.
  45719. */
  45720. rc = pagerUnlockDb(pPager, NO_LOCK);
  45721. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  45722. pPager->eLock = UNKNOWN_LOCK;
  45723. }
  45724. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  45725. ** without clearing the error code. This is intentional - the error
  45726. ** code is cleared and the cache reset in the block below.
  45727. */
  45728. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  45729. pPager->changeCountDone = 0;
  45730. pPager->eState = PAGER_OPEN;
  45731. }
  45732. /* If Pager.errCode is set, the contents of the pager cache cannot be
  45733. ** trusted. Now that there are no outstanding references to the pager,
  45734. ** it can safely move back to PAGER_OPEN state. This happens in both
  45735. ** normal and exclusive-locking mode.
  45736. */
  45737. assert( pPager->errCode==SQLITE_OK || !MEMDB );
  45738. if( pPager->errCode ){
  45739. if( pPager->tempFile==0 ){
  45740. pager_reset(pPager);
  45741. pPager->changeCountDone = 0;
  45742. pPager->eState = PAGER_OPEN;
  45743. }else{
  45744. pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
  45745. }
  45746. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  45747. pPager->errCode = SQLITE_OK;
  45748. setGetterMethod(pPager);
  45749. }
  45750. pPager->journalOff = 0;
  45751. pPager->journalHdr = 0;
  45752. pPager->setMaster = 0;
  45753. }
  45754. /*
  45755. ** This function is called whenever an IOERR or FULL error that requires
  45756. ** the pager to transition into the ERROR state may ahve occurred.
  45757. ** The first argument is a pointer to the pager structure, the second
  45758. ** the error-code about to be returned by a pager API function. The
  45759. ** value returned is a copy of the second argument to this function.
  45760. **
  45761. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  45762. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  45763. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  45764. ** all major API calls on the Pager will immediately return Pager.errCode.
  45765. **
  45766. ** The ERROR state indicates that the contents of the pager-cache
  45767. ** cannot be trusted. This state can be cleared by completely discarding
  45768. ** the contents of the pager-cache. If a transaction was active when
  45769. ** the persistent error occurred, then the rollback journal may need
  45770. ** to be replayed to restore the contents of the database file (as if
  45771. ** it were a hot-journal).
  45772. */
  45773. static int pager_error(Pager *pPager, int rc){
  45774. int rc2 = rc & 0xff;
  45775. assert( rc==SQLITE_OK || !MEMDB );
  45776. assert(
  45777. pPager->errCode==SQLITE_FULL ||
  45778. pPager->errCode==SQLITE_OK ||
  45779. (pPager->errCode & 0xff)==SQLITE_IOERR
  45780. );
  45781. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  45782. pPager->errCode = rc;
  45783. pPager->eState = PAGER_ERROR;
  45784. setGetterMethod(pPager);
  45785. }
  45786. return rc;
  45787. }
  45788. static int pager_truncate(Pager *pPager, Pgno nPage);
  45789. /*
  45790. ** The write transaction open on pPager is being committed (bCommit==1)
  45791. ** or rolled back (bCommit==0).
  45792. **
  45793. ** Return TRUE if and only if all dirty pages should be flushed to disk.
  45794. **
  45795. ** Rules:
  45796. **
  45797. ** * For non-TEMP databases, always sync to disk. This is necessary
  45798. ** for transactions to be durable.
  45799. **
  45800. ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
  45801. ** file has been created already (via a spill on pagerStress()) and
  45802. ** when the number of dirty pages in memory exceeds 25% of the total
  45803. ** cache size.
  45804. */
  45805. static int pagerFlushOnCommit(Pager *pPager, int bCommit){
  45806. if( pPager->tempFile==0 ) return 1;
  45807. if( !bCommit ) return 0;
  45808. if( !isOpen(pPager->fd) ) return 0;
  45809. return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
  45810. }
  45811. /*
  45812. ** This routine ends a transaction. A transaction is usually ended by
  45813. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  45814. ** after rollback of a hot-journal, or if an error occurs while opening
  45815. ** the journal file or writing the very first journal-header of a
  45816. ** database transaction.
  45817. **
  45818. ** This routine is never called in PAGER_ERROR state. If it is called
  45819. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  45820. ** exclusive than a RESERVED lock, it is a no-op.
  45821. **
  45822. ** Otherwise, any active savepoints are released.
  45823. **
  45824. ** If the journal file is open, then it is "finalized". Once a journal
  45825. ** file has been finalized it is not possible to use it to roll back a
  45826. ** transaction. Nor will it be considered to be a hot-journal by this
  45827. ** or any other database connection. Exactly how a journal is finalized
  45828. ** depends on whether or not the pager is running in exclusive mode and
  45829. ** the current journal-mode (Pager.journalMode value), as follows:
  45830. **
  45831. ** journalMode==MEMORY
  45832. ** Journal file descriptor is simply closed. This destroys an
  45833. ** in-memory journal.
  45834. **
  45835. ** journalMode==TRUNCATE
  45836. ** Journal file is truncated to zero bytes in size.
  45837. **
  45838. ** journalMode==PERSIST
  45839. ** The first 28 bytes of the journal file are zeroed. This invalidates
  45840. ** the first journal header in the file, and hence the entire journal
  45841. ** file. An invalid journal file cannot be rolled back.
  45842. **
  45843. ** journalMode==DELETE
  45844. ** The journal file is closed and deleted using sqlite3OsDelete().
  45845. **
  45846. ** If the pager is running in exclusive mode, this method of finalizing
  45847. ** the journal file is never used. Instead, if the journalMode is
  45848. ** DELETE and the pager is in exclusive mode, the method described under
  45849. ** journalMode==PERSIST is used instead.
  45850. **
  45851. ** After the journal is finalized, the pager moves to PAGER_READER state.
  45852. ** If running in non-exclusive rollback mode, the lock on the file is
  45853. ** downgraded to a SHARED_LOCK.
  45854. **
  45855. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  45856. ** any of the IO operations to finalize the journal file or unlock the
  45857. ** database then the IO error code is returned to the user. If the
  45858. ** operation to finalize the journal file fails, then the code still
  45859. ** tries to unlock the database file if not in exclusive mode. If the
  45860. ** unlock operation fails as well, then the first error code related
  45861. ** to the first error encountered (the journal finalization one) is
  45862. ** returned.
  45863. */
  45864. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  45865. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  45866. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  45867. /* Do nothing if the pager does not have an open write transaction
  45868. ** or at least a RESERVED lock. This function may be called when there
  45869. ** is no write-transaction active but a RESERVED or greater lock is
  45870. ** held under two circumstances:
  45871. **
  45872. ** 1. After a successful hot-journal rollback, it is called with
  45873. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  45874. **
  45875. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  45876. ** lock switches back to locking_mode=normal and then executes a
  45877. ** read-transaction, this function is called with eState==PAGER_READER
  45878. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  45879. */
  45880. assert( assert_pager_state(pPager) );
  45881. assert( pPager->eState!=PAGER_ERROR );
  45882. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  45883. return SQLITE_OK;
  45884. }
  45885. releaseAllSavepoints(pPager);
  45886. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  45887. if( isOpen(pPager->jfd) ){
  45888. assert( !pagerUseWal(pPager) );
  45889. /* Finalize the journal file. */
  45890. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  45891. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  45892. sqlite3OsClose(pPager->jfd);
  45893. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  45894. if( pPager->journalOff==0 ){
  45895. rc = SQLITE_OK;
  45896. }else{
  45897. rc = sqlite3OsTruncate(pPager->jfd, 0);
  45898. if( rc==SQLITE_OK && pPager->fullSync ){
  45899. /* Make sure the new file size is written into the inode right away.
  45900. ** Otherwise the journal might resurrect following a power loss and
  45901. ** cause the last transaction to roll back. See
  45902. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  45903. */
  45904. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  45905. }
  45906. }
  45907. pPager->journalOff = 0;
  45908. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  45909. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  45910. ){
  45911. rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
  45912. pPager->journalOff = 0;
  45913. }else{
  45914. /* This branch may be executed with Pager.journalMode==MEMORY if
  45915. ** a hot-journal was just rolled back. In this case the journal
  45916. ** file should be closed and deleted. If this connection writes to
  45917. ** the database file, it will do so using an in-memory journal.
  45918. */
  45919. int bDelete = !pPager->tempFile;
  45920. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  45921. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  45922. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  45923. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  45924. );
  45925. sqlite3OsClose(pPager->jfd);
  45926. if( bDelete ){
  45927. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  45928. }
  45929. }
  45930. }
  45931. #ifdef SQLITE_CHECK_PAGES
  45932. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  45933. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  45934. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  45935. if( p ){
  45936. p->pageHash = 0;
  45937. sqlite3PagerUnrefNotNull(p);
  45938. }
  45939. }
  45940. #endif
  45941. sqlite3BitvecDestroy(pPager->pInJournal);
  45942. pPager->pInJournal = 0;
  45943. pPager->nRec = 0;
  45944. if( rc==SQLITE_OK ){
  45945. if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
  45946. sqlite3PcacheCleanAll(pPager->pPCache);
  45947. }else{
  45948. sqlite3PcacheClearWritable(pPager->pPCache);
  45949. }
  45950. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  45951. }
  45952. if( pagerUseWal(pPager) ){
  45953. /* Drop the WAL write-lock, if any. Also, if the connection was in
  45954. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  45955. ** lock held on the database file.
  45956. */
  45957. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  45958. assert( rc2==SQLITE_OK );
  45959. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  45960. /* This branch is taken when committing a transaction in rollback-journal
  45961. ** mode if the database file on disk is larger than the database image.
  45962. ** At this point the journal has been finalized and the transaction
  45963. ** successfully committed, but the EXCLUSIVE lock is still held on the
  45964. ** file. So it is safe to truncate the database file to its minimum
  45965. ** required size. */
  45966. assert( pPager->eLock==EXCLUSIVE_LOCK );
  45967. rc = pager_truncate(pPager, pPager->dbSize);
  45968. }
  45969. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  45970. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  45971. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  45972. }
  45973. if( !pPager->exclusiveMode
  45974. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  45975. ){
  45976. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  45977. pPager->changeCountDone = 0;
  45978. }
  45979. pPager->eState = PAGER_READER;
  45980. pPager->setMaster = 0;
  45981. return (rc==SQLITE_OK?rc2:rc);
  45982. }
  45983. /*
  45984. ** Execute a rollback if a transaction is active and unlock the
  45985. ** database file.
  45986. **
  45987. ** If the pager has already entered the ERROR state, do not attempt
  45988. ** the rollback at this time. Instead, pager_unlock() is called. The
  45989. ** call to pager_unlock() will discard all in-memory pages, unlock
  45990. ** the database file and move the pager back to OPEN state. If this
  45991. ** means that there is a hot-journal left in the file-system, the next
  45992. ** connection to obtain a shared lock on the pager (which may be this one)
  45993. ** will roll it back.
  45994. **
  45995. ** If the pager has not already entered the ERROR state, but an IO or
  45996. ** malloc error occurs during a rollback, then this will itself cause
  45997. ** the pager to enter the ERROR state. Which will be cleared by the
  45998. ** call to pager_unlock(), as described above.
  45999. */
  46000. static void pagerUnlockAndRollback(Pager *pPager){
  46001. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  46002. assert( assert_pager_state(pPager) );
  46003. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  46004. sqlite3BeginBenignMalloc();
  46005. sqlite3PagerRollback(pPager);
  46006. sqlite3EndBenignMalloc();
  46007. }else if( !pPager->exclusiveMode ){
  46008. assert( pPager->eState==PAGER_READER );
  46009. pager_end_transaction(pPager, 0, 0);
  46010. }
  46011. }
  46012. pager_unlock(pPager);
  46013. }
  46014. /*
  46015. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  46016. ** of data. Compute and return a checksum based ont the contents of the
  46017. ** page of data and the current value of pPager->cksumInit.
  46018. **
  46019. ** This is not a real checksum. It is really just the sum of the
  46020. ** random initial value (pPager->cksumInit) and every 200th byte
  46021. ** of the page data, starting with byte offset (pPager->pageSize%200).
  46022. ** Each byte is interpreted as an 8-bit unsigned integer.
  46023. **
  46024. ** Changing the formula used to compute this checksum results in an
  46025. ** incompatible journal file format.
  46026. **
  46027. ** If journal corruption occurs due to a power failure, the most likely
  46028. ** scenario is that one end or the other of the record will be changed.
  46029. ** It is much less likely that the two ends of the journal record will be
  46030. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  46031. ** though fast and simple, catches the mostly likely kind of corruption.
  46032. */
  46033. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  46034. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  46035. int i = pPager->pageSize-200; /* Loop counter */
  46036. while( i>0 ){
  46037. cksum += aData[i];
  46038. i -= 200;
  46039. }
  46040. return cksum;
  46041. }
  46042. /*
  46043. ** Report the current page size and number of reserved bytes back
  46044. ** to the codec.
  46045. */
  46046. #ifdef SQLITE_HAS_CODEC
  46047. static void pagerReportSize(Pager *pPager){
  46048. if( pPager->xCodecSizeChng ){
  46049. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  46050. (int)pPager->nReserve);
  46051. }
  46052. }
  46053. #else
  46054. # define pagerReportSize(X) /* No-op if we do not support a codec */
  46055. #endif
  46056. #ifdef SQLITE_HAS_CODEC
  46057. /*
  46058. ** Make sure the number of reserved bits is the same in the destination
  46059. ** pager as it is in the source. This comes up when a VACUUM changes the
  46060. ** number of reserved bits to the "optimal" amount.
  46061. */
  46062. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  46063. if( pDest->nReserve!=pSrc->nReserve ){
  46064. pDest->nReserve = pSrc->nReserve;
  46065. pagerReportSize(pDest);
  46066. }
  46067. }
  46068. #endif
  46069. /*
  46070. ** Read a single page from either the journal file (if isMainJrnl==1) or
  46071. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  46072. ** The page begins at offset *pOffset into the file. The *pOffset
  46073. ** value is increased to the start of the next page in the journal.
  46074. **
  46075. ** The main rollback journal uses checksums - the statement journal does
  46076. ** not.
  46077. **
  46078. ** If the page number of the page record read from the (sub-)journal file
  46079. ** is greater than the current value of Pager.dbSize, then playback is
  46080. ** skipped and SQLITE_OK is returned.
  46081. **
  46082. ** If pDone is not NULL, then it is a record of pages that have already
  46083. ** been played back. If the page at *pOffset has already been played back
  46084. ** (if the corresponding pDone bit is set) then skip the playback.
  46085. ** Make sure the pDone bit corresponding to the *pOffset page is set
  46086. ** prior to returning.
  46087. **
  46088. ** If the page record is successfully read from the (sub-)journal file
  46089. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  46090. ** while reading the record from the (sub-)journal file or while writing
  46091. ** to the database file, then the IO error code is returned. If data
  46092. ** is successfully read from the (sub-)journal file but appears to be
  46093. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  46094. ** two circumstances:
  46095. **
  46096. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  46097. ** * If the record is being rolled back from the main journal file
  46098. ** and the checksum field does not match the record content.
  46099. **
  46100. ** Neither of these two scenarios are possible during a savepoint rollback.
  46101. **
  46102. ** If this is a savepoint rollback, then memory may have to be dynamically
  46103. ** allocated by this function. If this is the case and an allocation fails,
  46104. ** SQLITE_NOMEM is returned.
  46105. */
  46106. static int pager_playback_one_page(
  46107. Pager *pPager, /* The pager being played back */
  46108. i64 *pOffset, /* Offset of record to playback */
  46109. Bitvec *pDone, /* Bitvec of pages already played back */
  46110. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  46111. int isSavepnt /* True for a savepoint rollback */
  46112. ){
  46113. int rc;
  46114. PgHdr *pPg; /* An existing page in the cache */
  46115. Pgno pgno; /* The page number of a page in journal */
  46116. u32 cksum; /* Checksum used for sanity checking */
  46117. char *aData; /* Temporary storage for the page */
  46118. sqlite3_file *jfd; /* The file descriptor for the journal file */
  46119. int isSynced; /* True if journal page is synced */
  46120. #ifdef SQLITE_HAS_CODEC
  46121. /* The jrnlEnc flag is true if Journal pages should be passed through
  46122. ** the codec. It is false for pure in-memory journals. */
  46123. const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
  46124. #endif
  46125. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  46126. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  46127. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  46128. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  46129. aData = pPager->pTmpSpace;
  46130. assert( aData ); /* Temp storage must have already been allocated */
  46131. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  46132. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  46133. ** or savepoint rollback done at the request of the caller) or this is
  46134. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  46135. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  46136. ** only reads from the main journal, not the sub-journal.
  46137. */
  46138. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  46139. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  46140. );
  46141. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  46142. /* Read the page number and page data from the journal or sub-journal
  46143. ** file. Return an error code to the caller if an IO error occurs.
  46144. */
  46145. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  46146. rc = read32bits(jfd, *pOffset, &pgno);
  46147. if( rc!=SQLITE_OK ) return rc;
  46148. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  46149. if( rc!=SQLITE_OK ) return rc;
  46150. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  46151. /* Sanity checking on the page. This is more important that I originally
  46152. ** thought. If a power failure occurs while the journal is being written,
  46153. ** it could cause invalid data to be written into the journal. We need to
  46154. ** detect this invalid data (with high probability) and ignore it.
  46155. */
  46156. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  46157. assert( !isSavepnt );
  46158. return SQLITE_DONE;
  46159. }
  46160. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  46161. return SQLITE_OK;
  46162. }
  46163. if( isMainJrnl ){
  46164. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  46165. if( rc ) return rc;
  46166. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  46167. return SQLITE_DONE;
  46168. }
  46169. }
  46170. /* If this page has already been played back before during the current
  46171. ** rollback, then don't bother to play it back again.
  46172. */
  46173. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  46174. return rc;
  46175. }
  46176. /* When playing back page 1, restore the nReserve setting
  46177. */
  46178. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  46179. pPager->nReserve = ((u8*)aData)[20];
  46180. pagerReportSize(pPager);
  46181. }
  46182. /* If the pager is in CACHEMOD state, then there must be a copy of this
  46183. ** page in the pager cache. In this case just update the pager cache,
  46184. ** not the database file. The page is left marked dirty in this case.
  46185. **
  46186. ** An exception to the above rule: If the database is in no-sync mode
  46187. ** and a page is moved during an incremental vacuum then the page may
  46188. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  46189. ** during a Movepage() call, then the page may not be in the cache
  46190. ** either. So the condition described in the above paragraph is not
  46191. ** assert()able.
  46192. **
  46193. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  46194. ** pager cache if it exists and the main file. The page is then marked
  46195. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  46196. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  46197. ** if the pager is in OPEN state.
  46198. **
  46199. ** Ticket #1171: The statement journal might contain page content that is
  46200. ** different from the page content at the start of the transaction.
  46201. ** This occurs when a page is changed prior to the start of a statement
  46202. ** then changed again within the statement. When rolling back such a
  46203. ** statement we must not write to the original database unless we know
  46204. ** for certain that original page contents are synced into the main rollback
  46205. ** journal. Otherwise, a power loss might leave modified data in the
  46206. ** database file without an entry in the rollback journal that can
  46207. ** restore the database to its original form. Two conditions must be
  46208. ** met before writing to the database files. (1) the database must be
  46209. ** locked. (2) we know that the original page content is fully synced
  46210. ** in the main journal either because the page is not in cache or else
  46211. ** the page is marked as needSync==0.
  46212. **
  46213. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  46214. ** is possible to fail a statement on a database that does not yet exist.
  46215. ** Do not attempt to write if database file has never been opened.
  46216. */
  46217. if( pagerUseWal(pPager) ){
  46218. pPg = 0;
  46219. }else{
  46220. pPg = sqlite3PagerLookup(pPager, pgno);
  46221. }
  46222. assert( pPg || !MEMDB );
  46223. assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
  46224. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  46225. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  46226. (isMainJrnl?"main-journal":"sub-journal")
  46227. ));
  46228. if( isMainJrnl ){
  46229. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  46230. }else{
  46231. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  46232. }
  46233. if( isOpen(pPager->fd)
  46234. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  46235. && isSynced
  46236. ){
  46237. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  46238. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  46239. assert( !pagerUseWal(pPager) );
  46240. /* Write the data read from the journal back into the database file.
  46241. ** This is usually safe even for an encrypted database - as the data
  46242. ** was encrypted before it was written to the journal file. The exception
  46243. ** is if the data was just read from an in-memory sub-journal. In that
  46244. ** case it must be encrypted here before it is copied into the database
  46245. ** file. */
  46246. #ifdef SQLITE_HAS_CODEC
  46247. if( !jrnlEnc ){
  46248. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
  46249. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  46250. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  46251. }else
  46252. #endif
  46253. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  46254. if( pgno>pPager->dbFileSize ){
  46255. pPager->dbFileSize = pgno;
  46256. }
  46257. if( pPager->pBackup ){
  46258. #ifdef SQLITE_HAS_CODEC
  46259. if( jrnlEnc ){
  46260. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  46261. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  46262. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
  46263. }else
  46264. #endif
  46265. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  46266. }
  46267. }else if( !isMainJrnl && pPg==0 ){
  46268. /* If this is a rollback of a savepoint and data was not written to
  46269. ** the database and the page is not in-memory, there is a potential
  46270. ** problem. When the page is next fetched by the b-tree layer, it
  46271. ** will be read from the database file, which may or may not be
  46272. ** current.
  46273. **
  46274. ** There are a couple of different ways this can happen. All are quite
  46275. ** obscure. When running in synchronous mode, this can only happen
  46276. ** if the page is on the free-list at the start of the transaction, then
  46277. ** populated, then moved using sqlite3PagerMovepage().
  46278. **
  46279. ** The solution is to add an in-memory page to the cache containing
  46280. ** the data just read from the sub-journal. Mark the page as dirty
  46281. ** and if the pager requires a journal-sync, then mark the page as
  46282. ** requiring a journal-sync before it is written.
  46283. */
  46284. assert( isSavepnt );
  46285. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  46286. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  46287. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  46288. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  46289. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  46290. if( rc!=SQLITE_OK ) return rc;
  46291. sqlite3PcacheMakeDirty(pPg);
  46292. }
  46293. if( pPg ){
  46294. /* No page should ever be explicitly rolled back that is in use, except
  46295. ** for page 1 which is held in use in order to keep the lock on the
  46296. ** database active. However such a page may be rolled back as a result
  46297. ** of an internal error resulting in an automatic call to
  46298. ** sqlite3PagerRollback().
  46299. */
  46300. void *pData;
  46301. pData = pPg->pData;
  46302. memcpy(pData, (u8*)aData, pPager->pageSize);
  46303. pPager->xReiniter(pPg);
  46304. /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
  46305. ** that call was dangerous and had no detectable benefit since the cache
  46306. ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
  46307. ** has been removed. */
  46308. pager_set_pagehash(pPg);
  46309. /* If this was page 1, then restore the value of Pager.dbFileVers.
  46310. ** Do this before any decoding. */
  46311. if( pgno==1 ){
  46312. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  46313. }
  46314. /* Decode the page just read from disk */
  46315. #if SQLITE_HAS_CODEC
  46316. if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
  46317. #endif
  46318. sqlite3PcacheRelease(pPg);
  46319. }
  46320. return rc;
  46321. }
  46322. /*
  46323. ** Parameter zMaster is the name of a master journal file. A single journal
  46324. ** file that referred to the master journal file has just been rolled back.
  46325. ** This routine checks if it is possible to delete the master journal file,
  46326. ** and does so if it is.
  46327. **
  46328. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  46329. ** available for use within this function.
  46330. **
  46331. ** When a master journal file is created, it is populated with the names
  46332. ** of all of its child journals, one after another, formatted as utf-8
  46333. ** encoded text. The end of each child journal file is marked with a
  46334. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  46335. ** file for a transaction involving two databases might be:
  46336. **
  46337. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  46338. **
  46339. ** A master journal file may only be deleted once all of its child
  46340. ** journals have been rolled back.
  46341. **
  46342. ** This function reads the contents of the master-journal file into
  46343. ** memory and loops through each of the child journal names. For
  46344. ** each child journal, it checks if:
  46345. **
  46346. ** * if the child journal exists, and if so
  46347. ** * if the child journal contains a reference to master journal
  46348. ** file zMaster
  46349. **
  46350. ** If a child journal can be found that matches both of the criteria
  46351. ** above, this function returns without doing anything. Otherwise, if
  46352. ** no such child journal can be found, file zMaster is deleted from
  46353. ** the file-system using sqlite3OsDelete().
  46354. **
  46355. ** If an IO error within this function, an error code is returned. This
  46356. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  46357. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  46358. ** occur, SQLITE_OK is returned.
  46359. **
  46360. ** TODO: This function allocates a single block of memory to load
  46361. ** the entire contents of the master journal file. This could be
  46362. ** a couple of kilobytes or so - potentially larger than the page
  46363. ** size.
  46364. */
  46365. static int pager_delmaster(Pager *pPager, const char *zMaster){
  46366. sqlite3_vfs *pVfs = pPager->pVfs;
  46367. int rc; /* Return code */
  46368. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  46369. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  46370. char *zMasterJournal = 0; /* Contents of master journal file */
  46371. i64 nMasterJournal; /* Size of master journal file */
  46372. char *zJournal; /* Pointer to one journal within MJ file */
  46373. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  46374. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  46375. /* Allocate space for both the pJournal and pMaster file descriptors.
  46376. ** If successful, open the master journal file for reading.
  46377. */
  46378. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  46379. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  46380. if( !pMaster ){
  46381. rc = SQLITE_NOMEM_BKPT;
  46382. }else{
  46383. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  46384. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  46385. }
  46386. if( rc!=SQLITE_OK ) goto delmaster_out;
  46387. /* Load the entire master journal file into space obtained from
  46388. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  46389. ** sufficient space (in zMasterPtr) to hold the names of master
  46390. ** journal files extracted from regular rollback-journals.
  46391. */
  46392. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  46393. if( rc!=SQLITE_OK ) goto delmaster_out;
  46394. nMasterPtr = pVfs->mxPathname+1;
  46395. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  46396. if( !zMasterJournal ){
  46397. rc = SQLITE_NOMEM_BKPT;
  46398. goto delmaster_out;
  46399. }
  46400. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  46401. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  46402. if( rc!=SQLITE_OK ) goto delmaster_out;
  46403. zMasterJournal[nMasterJournal] = 0;
  46404. zJournal = zMasterJournal;
  46405. while( (zJournal-zMasterJournal)<nMasterJournal ){
  46406. int exists;
  46407. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  46408. if( rc!=SQLITE_OK ){
  46409. goto delmaster_out;
  46410. }
  46411. if( exists ){
  46412. /* One of the journals pointed to by the master journal exists.
  46413. ** Open it and check if it points at the master journal. If
  46414. ** so, return without deleting the master journal file.
  46415. */
  46416. int c;
  46417. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  46418. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  46419. if( rc!=SQLITE_OK ){
  46420. goto delmaster_out;
  46421. }
  46422. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  46423. sqlite3OsClose(pJournal);
  46424. if( rc!=SQLITE_OK ){
  46425. goto delmaster_out;
  46426. }
  46427. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  46428. if( c ){
  46429. /* We have a match. Do not delete the master journal file. */
  46430. goto delmaster_out;
  46431. }
  46432. }
  46433. zJournal += (sqlite3Strlen30(zJournal)+1);
  46434. }
  46435. sqlite3OsClose(pMaster);
  46436. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  46437. delmaster_out:
  46438. sqlite3_free(zMasterJournal);
  46439. if( pMaster ){
  46440. sqlite3OsClose(pMaster);
  46441. assert( !isOpen(pJournal) );
  46442. sqlite3_free(pMaster);
  46443. }
  46444. return rc;
  46445. }
  46446. /*
  46447. ** This function is used to change the actual size of the database
  46448. ** file in the file-system. This only happens when committing a transaction,
  46449. ** or rolling back a transaction (including rolling back a hot-journal).
  46450. **
  46451. ** If the main database file is not open, or the pager is not in either
  46452. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  46453. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  46454. ** If the file on disk is currently larger than nPage pages, then use the VFS
  46455. ** xTruncate() method to truncate it.
  46456. **
  46457. ** Or, it might be the case that the file on disk is smaller than
  46458. ** nPage pages. Some operating system implementations can get confused if
  46459. ** you try to truncate a file to some size that is larger than it
  46460. ** currently is, so detect this case and write a single zero byte to
  46461. ** the end of the new file instead.
  46462. **
  46463. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  46464. ** the database file, return the error code to the caller.
  46465. */
  46466. static int pager_truncate(Pager *pPager, Pgno nPage){
  46467. int rc = SQLITE_OK;
  46468. assert( pPager->eState!=PAGER_ERROR );
  46469. assert( pPager->eState!=PAGER_READER );
  46470. if( isOpen(pPager->fd)
  46471. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  46472. ){
  46473. i64 currentSize, newSize;
  46474. int szPage = pPager->pageSize;
  46475. assert( pPager->eLock==EXCLUSIVE_LOCK );
  46476. /* TODO: Is it safe to use Pager.dbFileSize here? */
  46477. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  46478. newSize = szPage*(i64)nPage;
  46479. if( rc==SQLITE_OK && currentSize!=newSize ){
  46480. if( currentSize>newSize ){
  46481. rc = sqlite3OsTruncate(pPager->fd, newSize);
  46482. }else if( (currentSize+szPage)<=newSize ){
  46483. char *pTmp = pPager->pTmpSpace;
  46484. memset(pTmp, 0, szPage);
  46485. testcase( (newSize-szPage) == currentSize );
  46486. testcase( (newSize-szPage) > currentSize );
  46487. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  46488. }
  46489. if( rc==SQLITE_OK ){
  46490. pPager->dbFileSize = nPage;
  46491. }
  46492. }
  46493. }
  46494. return rc;
  46495. }
  46496. /*
  46497. ** Return a sanitized version of the sector-size of OS file pFile. The
  46498. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  46499. */
  46500. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  46501. int iRet = sqlite3OsSectorSize(pFile);
  46502. if( iRet<32 ){
  46503. iRet = 512;
  46504. }else if( iRet>MAX_SECTOR_SIZE ){
  46505. assert( MAX_SECTOR_SIZE>=512 );
  46506. iRet = MAX_SECTOR_SIZE;
  46507. }
  46508. return iRet;
  46509. }
  46510. /*
  46511. ** Set the value of the Pager.sectorSize variable for the given
  46512. ** pager based on the value returned by the xSectorSize method
  46513. ** of the open database file. The sector size will be used
  46514. ** to determine the size and alignment of journal header and
  46515. ** master journal pointers within created journal files.
  46516. **
  46517. ** For temporary files the effective sector size is always 512 bytes.
  46518. **
  46519. ** Otherwise, for non-temporary files, the effective sector size is
  46520. ** the value returned by the xSectorSize() method rounded up to 32 if
  46521. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  46522. ** is greater than MAX_SECTOR_SIZE.
  46523. **
  46524. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  46525. ** the effective sector size to its minimum value (512). The purpose of
  46526. ** pPager->sectorSize is to define the "blast radius" of bytes that
  46527. ** might change if a crash occurs while writing to a single byte in
  46528. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  46529. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  46530. ** size. For backwards compatibility of the rollback journal file format,
  46531. ** we cannot reduce the effective sector size below 512.
  46532. */
  46533. static void setSectorSize(Pager *pPager){
  46534. assert( isOpen(pPager->fd) || pPager->tempFile );
  46535. if( pPager->tempFile
  46536. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  46537. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  46538. ){
  46539. /* Sector size doesn't matter for temporary files. Also, the file
  46540. ** may not have been opened yet, in which case the OsSectorSize()
  46541. ** call will segfault. */
  46542. pPager->sectorSize = 512;
  46543. }else{
  46544. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  46545. }
  46546. }
  46547. /*
  46548. ** Playback the journal and thus restore the database file to
  46549. ** the state it was in before we started making changes.
  46550. **
  46551. ** The journal file format is as follows:
  46552. **
  46553. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  46554. ** (2) 4 byte big-endian integer which is the number of valid page records
  46555. ** in the journal. If this value is 0xffffffff, then compute the
  46556. ** number of page records from the journal size.
  46557. ** (3) 4 byte big-endian integer which is the initial value for the
  46558. ** sanity checksum.
  46559. ** (4) 4 byte integer which is the number of pages to truncate the
  46560. ** database to during a rollback.
  46561. ** (5) 4 byte big-endian integer which is the sector size. The header
  46562. ** is this many bytes in size.
  46563. ** (6) 4 byte big-endian integer which is the page size.
  46564. ** (7) zero padding out to the next sector size.
  46565. ** (8) Zero or more pages instances, each as follows:
  46566. ** + 4 byte page number.
  46567. ** + pPager->pageSize bytes of data.
  46568. ** + 4 byte checksum
  46569. **
  46570. ** When we speak of the journal header, we mean the first 7 items above.
  46571. ** Each entry in the journal is an instance of the 8th item.
  46572. **
  46573. ** Call the value from the second bullet "nRec". nRec is the number of
  46574. ** valid page entries in the journal. In most cases, you can compute the
  46575. ** value of nRec from the size of the journal file. But if a power
  46576. ** failure occurred while the journal was being written, it could be the
  46577. ** case that the size of the journal file had already been increased but
  46578. ** the extra entries had not yet made it safely to disk. In such a case,
  46579. ** the value of nRec computed from the file size would be too large. For
  46580. ** that reason, we always use the nRec value in the header.
  46581. **
  46582. ** If the nRec value is 0xffffffff it means that nRec should be computed
  46583. ** from the file size. This value is used when the user selects the
  46584. ** no-sync option for the journal. A power failure could lead to corruption
  46585. ** in this case. But for things like temporary table (which will be
  46586. ** deleted when the power is restored) we don't care.
  46587. **
  46588. ** If the file opened as the journal file is not a well-formed
  46589. ** journal file then all pages up to the first corrupted page are rolled
  46590. ** back (or no pages if the journal header is corrupted). The journal file
  46591. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  46592. ** been encountered.
  46593. **
  46594. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  46595. ** and an error code is returned.
  46596. **
  46597. ** The isHot parameter indicates that we are trying to rollback a journal
  46598. ** that might be a hot journal. Or, it could be that the journal is
  46599. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  46600. ** If the journal really is hot, reset the pager cache prior rolling
  46601. ** back any content. If the journal is merely persistent, no reset is
  46602. ** needed.
  46603. */
  46604. static int pager_playback(Pager *pPager, int isHot){
  46605. sqlite3_vfs *pVfs = pPager->pVfs;
  46606. i64 szJ; /* Size of the journal file in bytes */
  46607. u32 nRec; /* Number of Records in the journal */
  46608. u32 u; /* Unsigned loop counter */
  46609. Pgno mxPg = 0; /* Size of the original file in pages */
  46610. int rc; /* Result code of a subroutine */
  46611. int res = 1; /* Value returned by sqlite3OsAccess() */
  46612. char *zMaster = 0; /* Name of master journal file if any */
  46613. int needPagerReset; /* True to reset page prior to first page rollback */
  46614. int nPlayback = 0; /* Total number of pages restored from journal */
  46615. /* Figure out how many records are in the journal. Abort early if
  46616. ** the journal is empty.
  46617. */
  46618. assert( isOpen(pPager->jfd) );
  46619. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  46620. if( rc!=SQLITE_OK ){
  46621. goto end_playback;
  46622. }
  46623. /* Read the master journal name from the journal, if it is present.
  46624. ** If a master journal file name is specified, but the file is not
  46625. ** present on disk, then the journal is not hot and does not need to be
  46626. ** played back.
  46627. **
  46628. ** TODO: Technically the following is an error because it assumes that
  46629. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  46630. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  46631. ** mxPathname is 512, which is the same as the minimum allowable value
  46632. ** for pageSize.
  46633. */
  46634. zMaster = pPager->pTmpSpace;
  46635. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  46636. if( rc==SQLITE_OK && zMaster[0] ){
  46637. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  46638. }
  46639. zMaster = 0;
  46640. if( rc!=SQLITE_OK || !res ){
  46641. goto end_playback;
  46642. }
  46643. pPager->journalOff = 0;
  46644. needPagerReset = isHot;
  46645. /* This loop terminates either when a readJournalHdr() or
  46646. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  46647. ** occurs.
  46648. */
  46649. while( 1 ){
  46650. /* Read the next journal header from the journal file. If there are
  46651. ** not enough bytes left in the journal file for a complete header, or
  46652. ** it is corrupted, then a process must have failed while writing it.
  46653. ** This indicates nothing more needs to be rolled back.
  46654. */
  46655. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  46656. if( rc!=SQLITE_OK ){
  46657. if( rc==SQLITE_DONE ){
  46658. rc = SQLITE_OK;
  46659. }
  46660. goto end_playback;
  46661. }
  46662. /* If nRec is 0xffffffff, then this journal was created by a process
  46663. ** working in no-sync mode. This means that the rest of the journal
  46664. ** file consists of pages, there are no more journal headers. Compute
  46665. ** the value of nRec based on this assumption.
  46666. */
  46667. if( nRec==0xffffffff ){
  46668. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  46669. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  46670. }
  46671. /* If nRec is 0 and this rollback is of a transaction created by this
  46672. ** process and if this is the final header in the journal, then it means
  46673. ** that this part of the journal was being filled but has not yet been
  46674. ** synced to disk. Compute the number of pages based on the remaining
  46675. ** size of the file.
  46676. **
  46677. ** The third term of the test was added to fix ticket #2565.
  46678. ** When rolling back a hot journal, nRec==0 always means that the next
  46679. ** chunk of the journal contains zero pages to be rolled back. But
  46680. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  46681. ** the journal, it means that the journal might contain additional
  46682. ** pages that need to be rolled back and that the number of pages
  46683. ** should be computed based on the journal file size.
  46684. */
  46685. if( nRec==0 && !isHot &&
  46686. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  46687. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  46688. }
  46689. /* If this is the first header read from the journal, truncate the
  46690. ** database file back to its original size.
  46691. */
  46692. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  46693. rc = pager_truncate(pPager, mxPg);
  46694. if( rc!=SQLITE_OK ){
  46695. goto end_playback;
  46696. }
  46697. pPager->dbSize = mxPg;
  46698. }
  46699. /* Copy original pages out of the journal and back into the
  46700. ** database file and/or page cache.
  46701. */
  46702. for(u=0; u<nRec; u++){
  46703. if( needPagerReset ){
  46704. pager_reset(pPager);
  46705. needPagerReset = 0;
  46706. }
  46707. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  46708. if( rc==SQLITE_OK ){
  46709. nPlayback++;
  46710. }else{
  46711. if( rc==SQLITE_DONE ){
  46712. pPager->journalOff = szJ;
  46713. break;
  46714. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  46715. /* If the journal has been truncated, simply stop reading and
  46716. ** processing the journal. This might happen if the journal was
  46717. ** not completely written and synced prior to a crash. In that
  46718. ** case, the database should have never been written in the
  46719. ** first place so it is OK to simply abandon the rollback. */
  46720. rc = SQLITE_OK;
  46721. goto end_playback;
  46722. }else{
  46723. /* If we are unable to rollback, quit and return the error
  46724. ** code. This will cause the pager to enter the error state
  46725. ** so that no further harm will be done. Perhaps the next
  46726. ** process to come along will be able to rollback the database.
  46727. */
  46728. goto end_playback;
  46729. }
  46730. }
  46731. }
  46732. }
  46733. /*NOTREACHED*/
  46734. assert( 0 );
  46735. end_playback:
  46736. /* Following a rollback, the database file should be back in its original
  46737. ** state prior to the start of the transaction, so invoke the
  46738. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  46739. ** assertion that the transaction counter was modified.
  46740. */
  46741. #ifdef SQLITE_DEBUG
  46742. if( pPager->fd->pMethods ){
  46743. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  46744. }
  46745. #endif
  46746. /* If this playback is happening automatically as a result of an IO or
  46747. ** malloc error that occurred after the change-counter was updated but
  46748. ** before the transaction was committed, then the change-counter
  46749. ** modification may just have been reverted. If this happens in exclusive
  46750. ** mode, then subsequent transactions performed by the connection will not
  46751. ** update the change-counter at all. This may lead to cache inconsistency
  46752. ** problems for other processes at some point in the future. So, just
  46753. ** in case this has happened, clear the changeCountDone flag now.
  46754. */
  46755. pPager->changeCountDone = pPager->tempFile;
  46756. if( rc==SQLITE_OK ){
  46757. zMaster = pPager->pTmpSpace;
  46758. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  46759. testcase( rc!=SQLITE_OK );
  46760. }
  46761. if( rc==SQLITE_OK
  46762. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  46763. ){
  46764. rc = sqlite3PagerSync(pPager, 0);
  46765. }
  46766. if( rc==SQLITE_OK ){
  46767. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  46768. testcase( rc!=SQLITE_OK );
  46769. }
  46770. if( rc==SQLITE_OK && zMaster[0] && res ){
  46771. /* If there was a master journal and this routine will return success,
  46772. ** see if it is possible to delete the master journal.
  46773. */
  46774. rc = pager_delmaster(pPager, zMaster);
  46775. testcase( rc!=SQLITE_OK );
  46776. }
  46777. if( isHot && nPlayback ){
  46778. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  46779. nPlayback, pPager->zJournal);
  46780. }
  46781. /* The Pager.sectorSize variable may have been updated while rolling
  46782. ** back a journal created by a process with a different sector size
  46783. ** value. Reset it to the correct value for this process.
  46784. */
  46785. setSectorSize(pPager);
  46786. return rc;
  46787. }
  46788. /*
  46789. ** Read the content for page pPg out of the database file and into
  46790. ** pPg->pData. A shared lock or greater must be held on the database
  46791. ** file before this function is called.
  46792. **
  46793. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  46794. ** the value read from the database file.
  46795. **
  46796. ** If an IO error occurs, then the IO error is returned to the caller.
  46797. ** Otherwise, SQLITE_OK is returned.
  46798. */
  46799. static int readDbPage(PgHdr *pPg, u32 iFrame){
  46800. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  46801. Pgno pgno = pPg->pgno; /* Page number to read */
  46802. int rc = SQLITE_OK; /* Return code */
  46803. int pgsz = pPager->pageSize; /* Number of bytes to read */
  46804. assert( pPager->eState>=PAGER_READER && !MEMDB );
  46805. assert( isOpen(pPager->fd) );
  46806. #ifndef SQLITE_OMIT_WAL
  46807. if( iFrame ){
  46808. /* Try to pull the page from the write-ahead log. */
  46809. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  46810. }else
  46811. #endif
  46812. {
  46813. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  46814. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  46815. if( rc==SQLITE_IOERR_SHORT_READ ){
  46816. rc = SQLITE_OK;
  46817. }
  46818. }
  46819. if( pgno==1 ){
  46820. if( rc ){
  46821. /* If the read is unsuccessful, set the dbFileVers[] to something
  46822. ** that will never be a valid file version. dbFileVers[] is a copy
  46823. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  46824. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  46825. ** should be page numbers which are never 0xffffffff. So filling
  46826. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  46827. **
  46828. ** For an encrypted database, the situation is more complex: bytes
  46829. ** 24..39 of the database are white noise. But the probability of
  46830. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  46831. ** we should still be ok.
  46832. */
  46833. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  46834. }else{
  46835. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  46836. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  46837. }
  46838. }
  46839. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
  46840. PAGER_INCR(sqlite3_pager_readdb_count);
  46841. PAGER_INCR(pPager->nRead);
  46842. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  46843. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  46844. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  46845. return rc;
  46846. }
  46847. /*
  46848. ** Update the value of the change-counter at offsets 24 and 92 in
  46849. ** the header and the sqlite version number at offset 96.
  46850. **
  46851. ** This is an unconditional update. See also the pager_incr_changecounter()
  46852. ** routine which only updates the change-counter if the update is actually
  46853. ** needed, as determined by the pPager->changeCountDone state variable.
  46854. */
  46855. static void pager_write_changecounter(PgHdr *pPg){
  46856. u32 change_counter;
  46857. /* Increment the value just read and write it back to byte 24. */
  46858. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  46859. put32bits(((char*)pPg->pData)+24, change_counter);
  46860. /* Also store the SQLite version number in bytes 96..99 and in
  46861. ** bytes 92..95 store the change counter for which the version number
  46862. ** is valid. */
  46863. put32bits(((char*)pPg->pData)+92, change_counter);
  46864. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  46865. }
  46866. #ifndef SQLITE_OMIT_WAL
  46867. /*
  46868. ** This function is invoked once for each page that has already been
  46869. ** written into the log file when a WAL transaction is rolled back.
  46870. ** Parameter iPg is the page number of said page. The pCtx argument
  46871. ** is actually a pointer to the Pager structure.
  46872. **
  46873. ** If page iPg is present in the cache, and has no outstanding references,
  46874. ** it is discarded. Otherwise, if there are one or more outstanding
  46875. ** references, the page content is reloaded from the database. If the
  46876. ** attempt to reload content from the database is required and fails,
  46877. ** return an SQLite error code. Otherwise, SQLITE_OK.
  46878. */
  46879. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  46880. int rc = SQLITE_OK;
  46881. Pager *pPager = (Pager *)pCtx;
  46882. PgHdr *pPg;
  46883. assert( pagerUseWal(pPager) );
  46884. pPg = sqlite3PagerLookup(pPager, iPg);
  46885. if( pPg ){
  46886. if( sqlite3PcachePageRefcount(pPg)==1 ){
  46887. sqlite3PcacheDrop(pPg);
  46888. }else{
  46889. u32 iFrame = 0;
  46890. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  46891. if( rc==SQLITE_OK ){
  46892. rc = readDbPage(pPg, iFrame);
  46893. }
  46894. if( rc==SQLITE_OK ){
  46895. pPager->xReiniter(pPg);
  46896. }
  46897. sqlite3PagerUnrefNotNull(pPg);
  46898. }
  46899. }
  46900. /* Normally, if a transaction is rolled back, any backup processes are
  46901. ** updated as data is copied out of the rollback journal and into the
  46902. ** database. This is not generally possible with a WAL database, as
  46903. ** rollback involves simply truncating the log file. Therefore, if one
  46904. ** or more frames have already been written to the log (and therefore
  46905. ** also copied into the backup databases) as part of this transaction,
  46906. ** the backups must be restarted.
  46907. */
  46908. sqlite3BackupRestart(pPager->pBackup);
  46909. return rc;
  46910. }
  46911. /*
  46912. ** This function is called to rollback a transaction on a WAL database.
  46913. */
  46914. static int pagerRollbackWal(Pager *pPager){
  46915. int rc; /* Return Code */
  46916. PgHdr *pList; /* List of dirty pages to revert */
  46917. /* For all pages in the cache that are currently dirty or have already
  46918. ** been written (but not committed) to the log file, do one of the
  46919. ** following:
  46920. **
  46921. ** + Discard the cached page (if refcount==0), or
  46922. ** + Reload page content from the database (if refcount>0).
  46923. */
  46924. pPager->dbSize = pPager->dbOrigSize;
  46925. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  46926. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  46927. while( pList && rc==SQLITE_OK ){
  46928. PgHdr *pNext = pList->pDirty;
  46929. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  46930. pList = pNext;
  46931. }
  46932. return rc;
  46933. }
  46934. /*
  46935. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  46936. ** the contents of the list of pages headed by pList (connected by pDirty),
  46937. ** this function notifies any active backup processes that the pages have
  46938. ** changed.
  46939. **
  46940. ** The list of pages passed into this routine is always sorted by page number.
  46941. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  46942. */
  46943. static int pagerWalFrames(
  46944. Pager *pPager, /* Pager object */
  46945. PgHdr *pList, /* List of frames to log */
  46946. Pgno nTruncate, /* Database size after this commit */
  46947. int isCommit /* True if this is a commit */
  46948. ){
  46949. int rc; /* Return code */
  46950. int nList; /* Number of pages in pList */
  46951. PgHdr *p; /* For looping over pages */
  46952. assert( pPager->pWal );
  46953. assert( pList );
  46954. #ifdef SQLITE_DEBUG
  46955. /* Verify that the page list is in accending order */
  46956. for(p=pList; p && p->pDirty; p=p->pDirty){
  46957. assert( p->pgno < p->pDirty->pgno );
  46958. }
  46959. #endif
  46960. assert( pList->pDirty==0 || isCommit );
  46961. if( isCommit ){
  46962. /* If a WAL transaction is being committed, there is no point in writing
  46963. ** any pages with page numbers greater than nTruncate into the WAL file.
  46964. ** They will never be read by any client. So remove them from the pDirty
  46965. ** list here. */
  46966. PgHdr **ppNext = &pList;
  46967. nList = 0;
  46968. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  46969. if( p->pgno<=nTruncate ){
  46970. ppNext = &p->pDirty;
  46971. nList++;
  46972. }
  46973. }
  46974. assert( pList );
  46975. }else{
  46976. nList = 1;
  46977. }
  46978. pPager->aStat[PAGER_STAT_WRITE] += nList;
  46979. if( pList->pgno==1 ) pager_write_changecounter(pList);
  46980. rc = sqlite3WalFrames(pPager->pWal,
  46981. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  46982. );
  46983. if( rc==SQLITE_OK && pPager->pBackup ){
  46984. for(p=pList; p; p=p->pDirty){
  46985. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  46986. }
  46987. }
  46988. #ifdef SQLITE_CHECK_PAGES
  46989. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  46990. for(p=pList; p; p=p->pDirty){
  46991. pager_set_pagehash(p);
  46992. }
  46993. #endif
  46994. return rc;
  46995. }
  46996. /*
  46997. ** Begin a read transaction on the WAL.
  46998. **
  46999. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  47000. ** makes a snapshot of the database at the current point in time and preserves
  47001. ** that snapshot for use by the reader in spite of concurrently changes by
  47002. ** other writers or checkpointers.
  47003. */
  47004. static int pagerBeginReadTransaction(Pager *pPager){
  47005. int rc; /* Return code */
  47006. int changed = 0; /* True if cache must be reset */
  47007. assert( pagerUseWal(pPager) );
  47008. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  47009. /* sqlite3WalEndReadTransaction() was not called for the previous
  47010. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  47011. ** are in locking_mode=NORMAL and EndRead() was previously called,
  47012. ** the duplicate call is harmless.
  47013. */
  47014. sqlite3WalEndReadTransaction(pPager->pWal);
  47015. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  47016. if( rc!=SQLITE_OK || changed ){
  47017. pager_reset(pPager);
  47018. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  47019. }
  47020. return rc;
  47021. }
  47022. #endif
  47023. /*
  47024. ** This function is called as part of the transition from PAGER_OPEN
  47025. ** to PAGER_READER state to determine the size of the database file
  47026. ** in pages (assuming the page size currently stored in Pager.pageSize).
  47027. **
  47028. ** If no error occurs, SQLITE_OK is returned and the size of the database
  47029. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  47030. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  47031. */
  47032. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  47033. Pgno nPage; /* Value to return via *pnPage */
  47034. /* Query the WAL sub-system for the database size. The WalDbsize()
  47035. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  47036. ** if the database size is not available. The database size is not
  47037. ** available from the WAL sub-system if the log file is empty or
  47038. ** contains no valid committed transactions.
  47039. */
  47040. assert( pPager->eState==PAGER_OPEN );
  47041. assert( pPager->eLock>=SHARED_LOCK );
  47042. assert( isOpen(pPager->fd) );
  47043. assert( pPager->tempFile==0 );
  47044. nPage = sqlite3WalDbsize(pPager->pWal);
  47045. /* If the number of pages in the database is not available from the
  47046. ** WAL sub-system, determine the page counte based on the size of
  47047. ** the database file. If the size of the database file is not an
  47048. ** integer multiple of the page-size, round up the result.
  47049. */
  47050. if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
  47051. i64 n = 0; /* Size of db file in bytes */
  47052. int rc = sqlite3OsFileSize(pPager->fd, &n);
  47053. if( rc!=SQLITE_OK ){
  47054. return rc;
  47055. }
  47056. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  47057. }
  47058. /* If the current number of pages in the file is greater than the
  47059. ** configured maximum pager number, increase the allowed limit so
  47060. ** that the file can be read.
  47061. */
  47062. if( nPage>pPager->mxPgno ){
  47063. pPager->mxPgno = (Pgno)nPage;
  47064. }
  47065. *pnPage = nPage;
  47066. return SQLITE_OK;
  47067. }
  47068. #ifndef SQLITE_OMIT_WAL
  47069. /*
  47070. ** Check if the *-wal file that corresponds to the database opened by pPager
  47071. ** exists if the database is not empy, or verify that the *-wal file does
  47072. ** not exist (by deleting it) if the database file is empty.
  47073. **
  47074. ** If the database is not empty and the *-wal file exists, open the pager
  47075. ** in WAL mode. If the database is empty or if no *-wal file exists and
  47076. ** if no error occurs, make sure Pager.journalMode is not set to
  47077. ** PAGER_JOURNALMODE_WAL.
  47078. **
  47079. ** Return SQLITE_OK or an error code.
  47080. **
  47081. ** The caller must hold a SHARED lock on the database file to call this
  47082. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  47083. ** a WAL on a none-empty database, this ensures there is no race condition
  47084. ** between the xAccess() below and an xDelete() being executed by some
  47085. ** other connection.
  47086. */
  47087. static int pagerOpenWalIfPresent(Pager *pPager){
  47088. int rc = SQLITE_OK;
  47089. assert( pPager->eState==PAGER_OPEN );
  47090. assert( pPager->eLock>=SHARED_LOCK );
  47091. if( !pPager->tempFile ){
  47092. int isWal; /* True if WAL file exists */
  47093. Pgno nPage; /* Size of the database file */
  47094. rc = pagerPagecount(pPager, &nPage);
  47095. if( rc ) return rc;
  47096. if( nPage==0 ){
  47097. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  47098. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  47099. isWal = 0;
  47100. }else{
  47101. rc = sqlite3OsAccess(
  47102. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  47103. );
  47104. }
  47105. if( rc==SQLITE_OK ){
  47106. if( isWal ){
  47107. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  47108. rc = sqlite3PagerOpenWal(pPager, 0);
  47109. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  47110. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  47111. }
  47112. }
  47113. }
  47114. return rc;
  47115. }
  47116. #endif
  47117. /*
  47118. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  47119. ** the entire master journal file. The case pSavepoint==NULL occurs when
  47120. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  47121. ** savepoint.
  47122. **
  47123. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  47124. ** being rolled back), then the rollback consists of up to three stages,
  47125. ** performed in the order specified:
  47126. **
  47127. ** * Pages are played back from the main journal starting at byte
  47128. ** offset PagerSavepoint.iOffset and continuing to
  47129. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  47130. ** file if PagerSavepoint.iHdrOffset is zero.
  47131. **
  47132. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  47133. ** back starting from the journal header immediately following
  47134. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  47135. **
  47136. ** * Pages are then played back from the sub-journal file, starting
  47137. ** with the PagerSavepoint.iSubRec and continuing to the end of
  47138. ** the journal file.
  47139. **
  47140. ** Throughout the rollback process, each time a page is rolled back, the
  47141. ** corresponding bit is set in a bitvec structure (variable pDone in the
  47142. ** implementation below). This is used to ensure that a page is only
  47143. ** rolled back the first time it is encountered in either journal.
  47144. **
  47145. ** If pSavepoint is NULL, then pages are only played back from the main
  47146. ** journal file. There is no need for a bitvec in this case.
  47147. **
  47148. ** In either case, before playback commences the Pager.dbSize variable
  47149. ** is reset to the value that it held at the start of the savepoint
  47150. ** (or transaction). No page with a page-number greater than this value
  47151. ** is played back. If one is encountered it is simply skipped.
  47152. */
  47153. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  47154. i64 szJ; /* Effective size of the main journal */
  47155. i64 iHdrOff; /* End of first segment of main-journal records */
  47156. int rc = SQLITE_OK; /* Return code */
  47157. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  47158. assert( pPager->eState!=PAGER_ERROR );
  47159. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  47160. /* Allocate a bitvec to use to store the set of pages rolled back */
  47161. if( pSavepoint ){
  47162. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  47163. if( !pDone ){
  47164. return SQLITE_NOMEM_BKPT;
  47165. }
  47166. }
  47167. /* Set the database size back to the value it was before the savepoint
  47168. ** being reverted was opened.
  47169. */
  47170. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  47171. pPager->changeCountDone = pPager->tempFile;
  47172. if( !pSavepoint && pagerUseWal(pPager) ){
  47173. return pagerRollbackWal(pPager);
  47174. }
  47175. /* Use pPager->journalOff as the effective size of the main rollback
  47176. ** journal. The actual file might be larger than this in
  47177. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  47178. ** past pPager->journalOff is off-limits to us.
  47179. */
  47180. szJ = pPager->journalOff;
  47181. assert( pagerUseWal(pPager)==0 || szJ==0 );
  47182. /* Begin by rolling back records from the main journal starting at
  47183. ** PagerSavepoint.iOffset and continuing to the next journal header.
  47184. ** There might be records in the main journal that have a page number
  47185. ** greater than the current database size (pPager->dbSize) but those
  47186. ** will be skipped automatically. Pages are added to pDone as they
  47187. ** are played back.
  47188. */
  47189. if( pSavepoint && !pagerUseWal(pPager) ){
  47190. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  47191. pPager->journalOff = pSavepoint->iOffset;
  47192. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  47193. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  47194. }
  47195. assert( rc!=SQLITE_DONE );
  47196. }else{
  47197. pPager->journalOff = 0;
  47198. }
  47199. /* Continue rolling back records out of the main journal starting at
  47200. ** the first journal header seen and continuing until the effective end
  47201. ** of the main journal file. Continue to skip out-of-range pages and
  47202. ** continue adding pages rolled back to pDone.
  47203. */
  47204. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  47205. u32 ii; /* Loop counter */
  47206. u32 nJRec = 0; /* Number of Journal Records */
  47207. u32 dummy;
  47208. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  47209. assert( rc!=SQLITE_DONE );
  47210. /*
  47211. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  47212. ** test is related to ticket #2565. See the discussion in the
  47213. ** pager_playback() function for additional information.
  47214. */
  47215. if( nJRec==0
  47216. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  47217. ){
  47218. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  47219. }
  47220. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  47221. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  47222. }
  47223. assert( rc!=SQLITE_DONE );
  47224. }
  47225. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  47226. /* Finally, rollback pages from the sub-journal. Page that were
  47227. ** previously rolled back out of the main journal (and are hence in pDone)
  47228. ** will be skipped. Out-of-range pages are also skipped.
  47229. */
  47230. if( pSavepoint ){
  47231. u32 ii; /* Loop counter */
  47232. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  47233. if( pagerUseWal(pPager) ){
  47234. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  47235. }
  47236. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  47237. assert( offset==(i64)ii*(4+pPager->pageSize) );
  47238. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  47239. }
  47240. assert( rc!=SQLITE_DONE );
  47241. }
  47242. sqlite3BitvecDestroy(pDone);
  47243. if( rc==SQLITE_OK ){
  47244. pPager->journalOff = szJ;
  47245. }
  47246. return rc;
  47247. }
  47248. /*
  47249. ** Change the maximum number of in-memory pages that are allowed
  47250. ** before attempting to recycle clean and unused pages.
  47251. */
  47252. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  47253. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  47254. }
  47255. /*
  47256. ** Change the maximum number of in-memory pages that are allowed
  47257. ** before attempting to spill pages to journal.
  47258. */
  47259. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  47260. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  47261. }
  47262. /*
  47263. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  47264. */
  47265. static void pagerFixMaplimit(Pager *pPager){
  47266. #if SQLITE_MAX_MMAP_SIZE>0
  47267. sqlite3_file *fd = pPager->fd;
  47268. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  47269. sqlite3_int64 sz;
  47270. sz = pPager->szMmap;
  47271. pPager->bUseFetch = (sz>0);
  47272. setGetterMethod(pPager);
  47273. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  47274. }
  47275. #endif
  47276. }
  47277. /*
  47278. ** Change the maximum size of any memory mapping made of the database file.
  47279. */
  47280. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  47281. pPager->szMmap = szMmap;
  47282. pagerFixMaplimit(pPager);
  47283. }
  47284. /*
  47285. ** Free as much memory as possible from the pager.
  47286. */
  47287. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  47288. sqlite3PcacheShrink(pPager->pPCache);
  47289. }
  47290. /*
  47291. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  47292. **
  47293. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  47294. ** of the database to damage due to OS crashes or power failures by
  47295. ** changing the number of syncs()s when writing the journals.
  47296. ** There are four levels:
  47297. **
  47298. ** OFF sqlite3OsSync() is never called. This is the default
  47299. ** for temporary and transient files.
  47300. **
  47301. ** NORMAL The journal is synced once before writes begin on the
  47302. ** database. This is normally adequate protection, but
  47303. ** it is theoretically possible, though very unlikely,
  47304. ** that an inopertune power failure could leave the journal
  47305. ** in a state which would cause damage to the database
  47306. ** when it is rolled back.
  47307. **
  47308. ** FULL The journal is synced twice before writes begin on the
  47309. ** database (with some additional information - the nRec field
  47310. ** of the journal header - being written in between the two
  47311. ** syncs). If we assume that writing a
  47312. ** single disk sector is atomic, then this mode provides
  47313. ** assurance that the journal will not be corrupted to the
  47314. ** point of causing damage to the database during rollback.
  47315. **
  47316. ** EXTRA This is like FULL except that is also syncs the directory
  47317. ** that contains the rollback journal after the rollback
  47318. ** journal is unlinked.
  47319. **
  47320. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  47321. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  47322. ** prior to the start of checkpoint and that the database file is synced
  47323. ** at the conclusion of the checkpoint if the entire content of the WAL
  47324. ** was written back into the database. But no sync operations occur for
  47325. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  47326. ** file is synced following each commit operation, in addition to the
  47327. ** syncs associated with NORMAL. There is no difference between FULL
  47328. ** and EXTRA for WAL mode.
  47329. **
  47330. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  47331. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  47332. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  47333. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  47334. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  47335. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  47336. ** the xSync primitive is called and is relevant to all platforms.
  47337. **
  47338. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  47339. ** and FULL=3.
  47340. */
  47341. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  47342. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  47343. Pager *pPager, /* The pager to set safety level for */
  47344. unsigned pgFlags /* Various flags */
  47345. ){
  47346. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  47347. if( pPager->tempFile ){
  47348. pPager->noSync = 1;
  47349. pPager->fullSync = 0;
  47350. pPager->extraSync = 0;
  47351. }else{
  47352. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  47353. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  47354. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  47355. }
  47356. if( pPager->noSync ){
  47357. pPager->syncFlags = 0;
  47358. pPager->ckptSyncFlags = 0;
  47359. }else if( pgFlags & PAGER_FULLFSYNC ){
  47360. pPager->syncFlags = SQLITE_SYNC_FULL;
  47361. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  47362. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  47363. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  47364. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  47365. }else{
  47366. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  47367. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  47368. }
  47369. pPager->walSyncFlags = pPager->syncFlags;
  47370. if( pPager->fullSync ){
  47371. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  47372. }
  47373. if( pgFlags & PAGER_CACHESPILL ){
  47374. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  47375. }else{
  47376. pPager->doNotSpill |= SPILLFLAG_OFF;
  47377. }
  47378. }
  47379. #endif
  47380. /*
  47381. ** The following global variable is incremented whenever the library
  47382. ** attempts to open a temporary file. This information is used for
  47383. ** testing and analysis only.
  47384. */
  47385. #ifdef SQLITE_TEST
  47386. SQLITE_API int sqlite3_opentemp_count = 0;
  47387. #endif
  47388. /*
  47389. ** Open a temporary file.
  47390. **
  47391. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  47392. ** or some other error code if we fail. The OS will automatically
  47393. ** delete the temporary file when it is closed.
  47394. **
  47395. ** The flags passed to the VFS layer xOpen() call are those specified
  47396. ** by parameter vfsFlags ORed with the following:
  47397. **
  47398. ** SQLITE_OPEN_READWRITE
  47399. ** SQLITE_OPEN_CREATE
  47400. ** SQLITE_OPEN_EXCLUSIVE
  47401. ** SQLITE_OPEN_DELETEONCLOSE
  47402. */
  47403. static int pagerOpentemp(
  47404. Pager *pPager, /* The pager object */
  47405. sqlite3_file *pFile, /* Write the file descriptor here */
  47406. int vfsFlags /* Flags passed through to the VFS */
  47407. ){
  47408. int rc; /* Return code */
  47409. #ifdef SQLITE_TEST
  47410. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  47411. #endif
  47412. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  47413. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  47414. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  47415. assert( rc!=SQLITE_OK || isOpen(pFile) );
  47416. return rc;
  47417. }
  47418. /*
  47419. ** Set the busy handler function.
  47420. **
  47421. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  47422. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  47423. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  47424. ** lock. It does *not* invoke the busy handler when upgrading from
  47425. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  47426. ** (which occurs during hot-journal rollback). Summary:
  47427. **
  47428. ** Transition | Invokes xBusyHandler
  47429. ** --------------------------------------------------------
  47430. ** NO_LOCK -> SHARED_LOCK | Yes
  47431. ** SHARED_LOCK -> RESERVED_LOCK | No
  47432. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  47433. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  47434. **
  47435. ** If the busy-handler callback returns non-zero, the lock is
  47436. ** retried. If it returns zero, then the SQLITE_BUSY error is
  47437. ** returned to the caller of the pager API function.
  47438. */
  47439. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  47440. Pager *pPager, /* Pager object */
  47441. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  47442. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  47443. ){
  47444. pPager->xBusyHandler = xBusyHandler;
  47445. pPager->pBusyHandlerArg = pBusyHandlerArg;
  47446. if( isOpen(pPager->fd) ){
  47447. void **ap = (void **)&pPager->xBusyHandler;
  47448. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  47449. assert( ap[1]==pBusyHandlerArg );
  47450. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  47451. }
  47452. }
  47453. /*
  47454. ** Change the page size used by the Pager object. The new page size
  47455. ** is passed in *pPageSize.
  47456. **
  47457. ** If the pager is in the error state when this function is called, it
  47458. ** is a no-op. The value returned is the error state error code (i.e.
  47459. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  47460. **
  47461. ** Otherwise, if all of the following are true:
  47462. **
  47463. ** * the new page size (value of *pPageSize) is valid (a power
  47464. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  47465. **
  47466. ** * there are no outstanding page references, and
  47467. **
  47468. ** * the database is either not an in-memory database or it is
  47469. ** an in-memory database that currently consists of zero pages.
  47470. **
  47471. ** then the pager object page size is set to *pPageSize.
  47472. **
  47473. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  47474. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  47475. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  47476. ** In all other cases, SQLITE_OK is returned.
  47477. **
  47478. ** If the page size is not changed, either because one of the enumerated
  47479. ** conditions above is not true, the pager was in error state when this
  47480. ** function was called, or because the memory allocation attempt failed,
  47481. ** then *pPageSize is set to the old, retained page size before returning.
  47482. */
  47483. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  47484. int rc = SQLITE_OK;
  47485. /* It is not possible to do a full assert_pager_state() here, as this
  47486. ** function may be called from within PagerOpen(), before the state
  47487. ** of the Pager object is internally consistent.
  47488. **
  47489. ** At one point this function returned an error if the pager was in
  47490. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  47491. ** there is at least one outstanding page reference, this function
  47492. ** is a no-op for that case anyhow.
  47493. */
  47494. u32 pageSize = *pPageSize;
  47495. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  47496. if( (pPager->memDb==0 || pPager->dbSize==0)
  47497. && sqlite3PcacheRefCount(pPager->pPCache)==0
  47498. && pageSize && pageSize!=(u32)pPager->pageSize
  47499. ){
  47500. char *pNew = NULL; /* New temp space */
  47501. i64 nByte = 0;
  47502. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  47503. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  47504. }
  47505. if( rc==SQLITE_OK ){
  47506. pNew = (char *)sqlite3PageMalloc(pageSize);
  47507. if( !pNew ) rc = SQLITE_NOMEM_BKPT;
  47508. }
  47509. if( rc==SQLITE_OK ){
  47510. pager_reset(pPager);
  47511. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  47512. }
  47513. if( rc==SQLITE_OK ){
  47514. sqlite3PageFree(pPager->pTmpSpace);
  47515. pPager->pTmpSpace = pNew;
  47516. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  47517. pPager->pageSize = pageSize;
  47518. }else{
  47519. sqlite3PageFree(pNew);
  47520. }
  47521. }
  47522. *pPageSize = pPager->pageSize;
  47523. if( rc==SQLITE_OK ){
  47524. if( nReserve<0 ) nReserve = pPager->nReserve;
  47525. assert( nReserve>=0 && nReserve<1000 );
  47526. pPager->nReserve = (i16)nReserve;
  47527. pagerReportSize(pPager);
  47528. pagerFixMaplimit(pPager);
  47529. }
  47530. return rc;
  47531. }
  47532. /*
  47533. ** Return a pointer to the "temporary page" buffer held internally
  47534. ** by the pager. This is a buffer that is big enough to hold the
  47535. ** entire content of a database page. This buffer is used internally
  47536. ** during rollback and will be overwritten whenever a rollback
  47537. ** occurs. But other modules are free to use it too, as long as
  47538. ** no rollbacks are happening.
  47539. */
  47540. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  47541. return pPager->pTmpSpace;
  47542. }
  47543. /*
  47544. ** Attempt to set the maximum database page count if mxPage is positive.
  47545. ** Make no changes if mxPage is zero or negative. And never reduce the
  47546. ** maximum page count below the current size of the database.
  47547. **
  47548. ** Regardless of mxPage, return the current maximum page count.
  47549. */
  47550. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  47551. if( mxPage>0 ){
  47552. pPager->mxPgno = mxPage;
  47553. }
  47554. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  47555. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  47556. return pPager->mxPgno;
  47557. }
  47558. /*
  47559. ** The following set of routines are used to disable the simulated
  47560. ** I/O error mechanism. These routines are used to avoid simulated
  47561. ** errors in places where we do not care about errors.
  47562. **
  47563. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  47564. ** and generate no code.
  47565. */
  47566. #ifdef SQLITE_TEST
  47567. SQLITE_API extern int sqlite3_io_error_pending;
  47568. SQLITE_API extern int sqlite3_io_error_hit;
  47569. static int saved_cnt;
  47570. void disable_simulated_io_errors(void){
  47571. saved_cnt = sqlite3_io_error_pending;
  47572. sqlite3_io_error_pending = -1;
  47573. }
  47574. void enable_simulated_io_errors(void){
  47575. sqlite3_io_error_pending = saved_cnt;
  47576. }
  47577. #else
  47578. # define disable_simulated_io_errors()
  47579. # define enable_simulated_io_errors()
  47580. #endif
  47581. /*
  47582. ** Read the first N bytes from the beginning of the file into memory
  47583. ** that pDest points to.
  47584. **
  47585. ** If the pager was opened on a transient file (zFilename==""), or
  47586. ** opened on a file less than N bytes in size, the output buffer is
  47587. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  47588. ** function is used to read database headers, and a new transient or
  47589. ** zero sized database has a header than consists entirely of zeroes.
  47590. **
  47591. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  47592. ** the error code is returned to the caller and the contents of the
  47593. ** output buffer undefined.
  47594. */
  47595. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  47596. int rc = SQLITE_OK;
  47597. memset(pDest, 0, N);
  47598. assert( isOpen(pPager->fd) || pPager->tempFile );
  47599. /* This routine is only called by btree immediately after creating
  47600. ** the Pager object. There has not been an opportunity to transition
  47601. ** to WAL mode yet.
  47602. */
  47603. assert( !pagerUseWal(pPager) );
  47604. if( isOpen(pPager->fd) ){
  47605. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  47606. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  47607. if( rc==SQLITE_IOERR_SHORT_READ ){
  47608. rc = SQLITE_OK;
  47609. }
  47610. }
  47611. return rc;
  47612. }
  47613. /*
  47614. ** This function may only be called when a read-transaction is open on
  47615. ** the pager. It returns the total number of pages in the database.
  47616. **
  47617. ** However, if the file is between 1 and <page-size> bytes in size, then
  47618. ** this is considered a 1 page file.
  47619. */
  47620. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  47621. assert( pPager->eState>=PAGER_READER );
  47622. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  47623. *pnPage = (int)pPager->dbSize;
  47624. }
  47625. /*
  47626. ** Try to obtain a lock of type locktype on the database file. If
  47627. ** a similar or greater lock is already held, this function is a no-op
  47628. ** (returning SQLITE_OK immediately).
  47629. **
  47630. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  47631. ** the busy callback if the lock is currently not available. Repeat
  47632. ** until the busy callback returns false or until the attempt to
  47633. ** obtain the lock succeeds.
  47634. **
  47635. ** Return SQLITE_OK on success and an error code if we cannot obtain
  47636. ** the lock. If the lock is obtained successfully, set the Pager.state
  47637. ** variable to locktype before returning.
  47638. */
  47639. static int pager_wait_on_lock(Pager *pPager, int locktype){
  47640. int rc; /* Return code */
  47641. /* Check that this is either a no-op (because the requested lock is
  47642. ** already held), or one of the transitions that the busy-handler
  47643. ** may be invoked during, according to the comment above
  47644. ** sqlite3PagerSetBusyhandler().
  47645. */
  47646. assert( (pPager->eLock>=locktype)
  47647. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  47648. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  47649. );
  47650. do {
  47651. rc = pagerLockDb(pPager, locktype);
  47652. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  47653. return rc;
  47654. }
  47655. /*
  47656. ** Function assertTruncateConstraint(pPager) checks that one of the
  47657. ** following is true for all dirty pages currently in the page-cache:
  47658. **
  47659. ** a) The page number is less than or equal to the size of the
  47660. ** current database image, in pages, OR
  47661. **
  47662. ** b) if the page content were written at this time, it would not
  47663. ** be necessary to write the current content out to the sub-journal
  47664. ** (as determined by function subjRequiresPage()).
  47665. **
  47666. ** If the condition asserted by this function were not true, and the
  47667. ** dirty page were to be discarded from the cache via the pagerStress()
  47668. ** routine, pagerStress() would not write the current page content to
  47669. ** the database file. If a savepoint transaction were rolled back after
  47670. ** this happened, the correct behavior would be to restore the current
  47671. ** content of the page. However, since this content is not present in either
  47672. ** the database file or the portion of the rollback journal and
  47673. ** sub-journal rolled back the content could not be restored and the
  47674. ** database image would become corrupt. It is therefore fortunate that
  47675. ** this circumstance cannot arise.
  47676. */
  47677. #if defined(SQLITE_DEBUG)
  47678. static void assertTruncateConstraintCb(PgHdr *pPg){
  47679. assert( pPg->flags&PGHDR_DIRTY );
  47680. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  47681. }
  47682. static void assertTruncateConstraint(Pager *pPager){
  47683. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  47684. }
  47685. #else
  47686. # define assertTruncateConstraint(pPager)
  47687. #endif
  47688. /*
  47689. ** Truncate the in-memory database file image to nPage pages. This
  47690. ** function does not actually modify the database file on disk. It
  47691. ** just sets the internal state of the pager object so that the
  47692. ** truncation will be done when the current transaction is committed.
  47693. **
  47694. ** This function is only called right before committing a transaction.
  47695. ** Once this function has been called, the transaction must either be
  47696. ** rolled back or committed. It is not safe to call this function and
  47697. ** then continue writing to the database.
  47698. */
  47699. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  47700. assert( pPager->dbSize>=nPage );
  47701. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  47702. pPager->dbSize = nPage;
  47703. /* At one point the code here called assertTruncateConstraint() to
  47704. ** ensure that all pages being truncated away by this operation are,
  47705. ** if one or more savepoints are open, present in the savepoint
  47706. ** journal so that they can be restored if the savepoint is rolled
  47707. ** back. This is no longer necessary as this function is now only
  47708. ** called right before committing a transaction. So although the
  47709. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  47710. ** they cannot be rolled back. So the assertTruncateConstraint() call
  47711. ** is no longer correct. */
  47712. }
  47713. /*
  47714. ** This function is called before attempting a hot-journal rollback. It
  47715. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  47716. ** size of the journal file so that the pager_playback() routine knows
  47717. ** that the entire journal file has been synced.
  47718. **
  47719. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  47720. ** that if a power-failure occurs during the rollback, the process that
  47721. ** attempts rollback following system recovery sees the same journal
  47722. ** content as this process.
  47723. **
  47724. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  47725. ** an SQLite error code.
  47726. */
  47727. static int pagerSyncHotJournal(Pager *pPager){
  47728. int rc = SQLITE_OK;
  47729. if( !pPager->noSync ){
  47730. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  47731. }
  47732. if( rc==SQLITE_OK ){
  47733. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  47734. }
  47735. return rc;
  47736. }
  47737. #if SQLITE_MAX_MMAP_SIZE>0
  47738. /*
  47739. ** Obtain a reference to a memory mapped page object for page number pgno.
  47740. ** The new object will use the pointer pData, obtained from xFetch().
  47741. ** If successful, set *ppPage to point to the new page reference
  47742. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  47743. ** *ppPage to zero.
  47744. **
  47745. ** Page references obtained by calling this function should be released
  47746. ** by calling pagerReleaseMapPage().
  47747. */
  47748. static int pagerAcquireMapPage(
  47749. Pager *pPager, /* Pager object */
  47750. Pgno pgno, /* Page number */
  47751. void *pData, /* xFetch()'d data for this page */
  47752. PgHdr **ppPage /* OUT: Acquired page object */
  47753. ){
  47754. PgHdr *p; /* Memory mapped page to return */
  47755. if( pPager->pMmapFreelist ){
  47756. *ppPage = p = pPager->pMmapFreelist;
  47757. pPager->pMmapFreelist = p->pDirty;
  47758. p->pDirty = 0;
  47759. assert( pPager->nExtra>=8 );
  47760. memset(p->pExtra, 0, 8);
  47761. }else{
  47762. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  47763. if( p==0 ){
  47764. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  47765. return SQLITE_NOMEM_BKPT;
  47766. }
  47767. p->pExtra = (void *)&p[1];
  47768. p->flags = PGHDR_MMAP;
  47769. p->nRef = 1;
  47770. p->pPager = pPager;
  47771. }
  47772. assert( p->pExtra==(void *)&p[1] );
  47773. assert( p->pPage==0 );
  47774. assert( p->flags==PGHDR_MMAP );
  47775. assert( p->pPager==pPager );
  47776. assert( p->nRef==1 );
  47777. p->pgno = pgno;
  47778. p->pData = pData;
  47779. pPager->nMmapOut++;
  47780. return SQLITE_OK;
  47781. }
  47782. #endif
  47783. /*
  47784. ** Release a reference to page pPg. pPg must have been returned by an
  47785. ** earlier call to pagerAcquireMapPage().
  47786. */
  47787. static void pagerReleaseMapPage(PgHdr *pPg){
  47788. Pager *pPager = pPg->pPager;
  47789. pPager->nMmapOut--;
  47790. pPg->pDirty = pPager->pMmapFreelist;
  47791. pPager->pMmapFreelist = pPg;
  47792. assert( pPager->fd->pMethods->iVersion>=3 );
  47793. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  47794. }
  47795. /*
  47796. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  47797. */
  47798. static void pagerFreeMapHdrs(Pager *pPager){
  47799. PgHdr *p;
  47800. PgHdr *pNext;
  47801. for(p=pPager->pMmapFreelist; p; p=pNext){
  47802. pNext = p->pDirty;
  47803. sqlite3_free(p);
  47804. }
  47805. }
  47806. /*
  47807. ** Shutdown the page cache. Free all memory and close all files.
  47808. **
  47809. ** If a transaction was in progress when this routine is called, that
  47810. ** transaction is rolled back. All outstanding pages are invalidated
  47811. ** and their memory is freed. Any attempt to use a page associated
  47812. ** with this page cache after this function returns will likely
  47813. ** result in a coredump.
  47814. **
  47815. ** This function always succeeds. If a transaction is active an attempt
  47816. ** is made to roll it back. If an error occurs during the rollback
  47817. ** a hot journal may be left in the filesystem but no error is returned
  47818. ** to the caller.
  47819. */
  47820. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
  47821. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  47822. assert( db || pagerUseWal(pPager)==0 );
  47823. assert( assert_pager_state(pPager) );
  47824. disable_simulated_io_errors();
  47825. sqlite3BeginBenignMalloc();
  47826. pagerFreeMapHdrs(pPager);
  47827. /* pPager->errCode = 0; */
  47828. pPager->exclusiveMode = 0;
  47829. #ifndef SQLITE_OMIT_WAL
  47830. assert( db || pPager->pWal==0 );
  47831. sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags, pPager->pageSize,
  47832. (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp)
  47833. );
  47834. pPager->pWal = 0;
  47835. #endif
  47836. pager_reset(pPager);
  47837. if( MEMDB ){
  47838. pager_unlock(pPager);
  47839. }else{
  47840. /* If it is open, sync the journal file before calling UnlockAndRollback.
  47841. ** If this is not done, then an unsynced portion of the open journal
  47842. ** file may be played back into the database. If a power failure occurs
  47843. ** while this is happening, the database could become corrupt.
  47844. **
  47845. ** If an error occurs while trying to sync the journal, shift the pager
  47846. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  47847. ** database and close the journal file without attempting to roll it
  47848. ** back or finalize it. The next database user will have to do hot-journal
  47849. ** rollback before accessing the database file.
  47850. */
  47851. if( isOpen(pPager->jfd) ){
  47852. pager_error(pPager, pagerSyncHotJournal(pPager));
  47853. }
  47854. pagerUnlockAndRollback(pPager);
  47855. }
  47856. sqlite3EndBenignMalloc();
  47857. enable_simulated_io_errors();
  47858. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  47859. IOTRACE(("CLOSE %p\n", pPager))
  47860. sqlite3OsClose(pPager->jfd);
  47861. sqlite3OsClose(pPager->fd);
  47862. sqlite3PageFree(pTmp);
  47863. sqlite3PcacheClose(pPager->pPCache);
  47864. #ifdef SQLITE_HAS_CODEC
  47865. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  47866. #endif
  47867. assert( !pPager->aSavepoint && !pPager->pInJournal );
  47868. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  47869. sqlite3_free(pPager);
  47870. return SQLITE_OK;
  47871. }
  47872. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  47873. /*
  47874. ** Return the page number for page pPg.
  47875. */
  47876. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  47877. return pPg->pgno;
  47878. }
  47879. #endif
  47880. /*
  47881. ** Increment the reference count for page pPg.
  47882. */
  47883. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  47884. sqlite3PcacheRef(pPg);
  47885. }
  47886. /*
  47887. ** Sync the journal. In other words, make sure all the pages that have
  47888. ** been written to the journal have actually reached the surface of the
  47889. ** disk and can be restored in the event of a hot-journal rollback.
  47890. **
  47891. ** If the Pager.noSync flag is set, then this function is a no-op.
  47892. ** Otherwise, the actions required depend on the journal-mode and the
  47893. ** device characteristics of the file-system, as follows:
  47894. **
  47895. ** * If the journal file is an in-memory journal file, no action need
  47896. ** be taken.
  47897. **
  47898. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  47899. ** then the nRec field of the most recently written journal header
  47900. ** is updated to contain the number of journal records that have
  47901. ** been written following it. If the pager is operating in full-sync
  47902. ** mode, then the journal file is synced before this field is updated.
  47903. **
  47904. ** * If the device does not support the SEQUENTIAL property, then
  47905. ** journal file is synced.
  47906. **
  47907. ** Or, in pseudo-code:
  47908. **
  47909. ** if( NOT <in-memory journal> ){
  47910. ** if( NOT SAFE_APPEND ){
  47911. ** if( <full-sync mode> ) xSync(<journal file>);
  47912. ** <update nRec field>
  47913. ** }
  47914. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  47915. ** }
  47916. **
  47917. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  47918. ** page currently held in memory before returning SQLITE_OK. If an IO
  47919. ** error is encountered, then the IO error code is returned to the caller.
  47920. */
  47921. static int syncJournal(Pager *pPager, int newHdr){
  47922. int rc; /* Return code */
  47923. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  47924. || pPager->eState==PAGER_WRITER_DBMOD
  47925. );
  47926. assert( assert_pager_state(pPager) );
  47927. assert( !pagerUseWal(pPager) );
  47928. rc = sqlite3PagerExclusiveLock(pPager);
  47929. if( rc!=SQLITE_OK ) return rc;
  47930. if( !pPager->noSync ){
  47931. assert( !pPager->tempFile );
  47932. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  47933. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  47934. assert( isOpen(pPager->jfd) );
  47935. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  47936. /* This block deals with an obscure problem. If the last connection
  47937. ** that wrote to this database was operating in persistent-journal
  47938. ** mode, then the journal file may at this point actually be larger
  47939. ** than Pager.journalOff bytes. If the next thing in the journal
  47940. ** file happens to be a journal-header (written as part of the
  47941. ** previous connection's transaction), and a crash or power-failure
  47942. ** occurs after nRec is updated but before this connection writes
  47943. ** anything else to the journal file (or commits/rolls back its
  47944. ** transaction), then SQLite may become confused when doing the
  47945. ** hot-journal rollback following recovery. It may roll back all
  47946. ** of this connections data, then proceed to rolling back the old,
  47947. ** out-of-date data that follows it. Database corruption.
  47948. **
  47949. ** To work around this, if the journal file does appear to contain
  47950. ** a valid header following Pager.journalOff, then write a 0x00
  47951. ** byte to the start of it to prevent it from being recognized.
  47952. **
  47953. ** Variable iNextHdrOffset is set to the offset at which this
  47954. ** problematic header will occur, if it exists. aMagic is used
  47955. ** as a temporary buffer to inspect the first couple of bytes of
  47956. ** the potential journal header.
  47957. */
  47958. i64 iNextHdrOffset;
  47959. u8 aMagic[8];
  47960. u8 zHeader[sizeof(aJournalMagic)+4];
  47961. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  47962. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  47963. iNextHdrOffset = journalHdrOffset(pPager);
  47964. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  47965. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  47966. static const u8 zerobyte = 0;
  47967. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  47968. }
  47969. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  47970. return rc;
  47971. }
  47972. /* Write the nRec value into the journal file header. If in
  47973. ** full-synchronous mode, sync the journal first. This ensures that
  47974. ** all data has really hit the disk before nRec is updated to mark
  47975. ** it as a candidate for rollback.
  47976. **
  47977. ** This is not required if the persistent media supports the
  47978. ** SAFE_APPEND property. Because in this case it is not possible
  47979. ** for garbage data to be appended to the file, the nRec field
  47980. ** is populated with 0xFFFFFFFF when the journal header is written
  47981. ** and never needs to be updated.
  47982. */
  47983. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  47984. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  47985. IOTRACE(("JSYNC %p\n", pPager))
  47986. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  47987. if( rc!=SQLITE_OK ) return rc;
  47988. }
  47989. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  47990. rc = sqlite3OsWrite(
  47991. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  47992. );
  47993. if( rc!=SQLITE_OK ) return rc;
  47994. }
  47995. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  47996. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  47997. IOTRACE(("JSYNC %p\n", pPager))
  47998. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  47999. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  48000. );
  48001. if( rc!=SQLITE_OK ) return rc;
  48002. }
  48003. pPager->journalHdr = pPager->journalOff;
  48004. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  48005. pPager->nRec = 0;
  48006. rc = writeJournalHdr(pPager);
  48007. if( rc!=SQLITE_OK ) return rc;
  48008. }
  48009. }else{
  48010. pPager->journalHdr = pPager->journalOff;
  48011. }
  48012. }
  48013. /* Unless the pager is in noSync mode, the journal file was just
  48014. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  48015. ** all pages.
  48016. */
  48017. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  48018. pPager->eState = PAGER_WRITER_DBMOD;
  48019. assert( assert_pager_state(pPager) );
  48020. return SQLITE_OK;
  48021. }
  48022. /*
  48023. ** The argument is the first in a linked list of dirty pages connected
  48024. ** by the PgHdr.pDirty pointer. This function writes each one of the
  48025. ** in-memory pages in the list to the database file. The argument may
  48026. ** be NULL, representing an empty list. In this case this function is
  48027. ** a no-op.
  48028. **
  48029. ** The pager must hold at least a RESERVED lock when this function
  48030. ** is called. Before writing anything to the database file, this lock
  48031. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  48032. ** SQLITE_BUSY is returned and no data is written to the database file.
  48033. **
  48034. ** If the pager is a temp-file pager and the actual file-system file
  48035. ** is not yet open, it is created and opened before any data is
  48036. ** written out.
  48037. **
  48038. ** Once the lock has been upgraded and, if necessary, the file opened,
  48039. ** the pages are written out to the database file in list order. Writing
  48040. ** a page is skipped if it meets either of the following criteria:
  48041. **
  48042. ** * The page number is greater than Pager.dbSize, or
  48043. ** * The PGHDR_DONT_WRITE flag is set on the page.
  48044. **
  48045. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  48046. ** is updated accordingly. If page 1 is written out, then the value cached
  48047. ** in Pager.dbFileVers[] is updated to match the new value stored in
  48048. ** the database file.
  48049. **
  48050. ** If everything is successful, SQLITE_OK is returned. If an IO error
  48051. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  48052. ** be obtained, SQLITE_BUSY is returned.
  48053. */
  48054. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  48055. int rc = SQLITE_OK; /* Return code */
  48056. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  48057. assert( !pagerUseWal(pPager) );
  48058. assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
  48059. assert( pPager->eLock==EXCLUSIVE_LOCK );
  48060. assert( isOpen(pPager->fd) || pList->pDirty==0 );
  48061. /* If the file is a temp-file has not yet been opened, open it now. It
  48062. ** is not possible for rc to be other than SQLITE_OK if this branch
  48063. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  48064. */
  48065. if( !isOpen(pPager->fd) ){
  48066. assert( pPager->tempFile && rc==SQLITE_OK );
  48067. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  48068. }
  48069. /* Before the first write, give the VFS a hint of what the final
  48070. ** file size will be.
  48071. */
  48072. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  48073. if( rc==SQLITE_OK
  48074. && pPager->dbHintSize<pPager->dbSize
  48075. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  48076. ){
  48077. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  48078. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  48079. pPager->dbHintSize = pPager->dbSize;
  48080. }
  48081. while( rc==SQLITE_OK && pList ){
  48082. Pgno pgno = pList->pgno;
  48083. /* If there are dirty pages in the page cache with page numbers greater
  48084. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  48085. ** make the file smaller (presumably by auto-vacuum code). Do not write
  48086. ** any such pages to the file.
  48087. **
  48088. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  48089. ** set (set by sqlite3PagerDontWrite()).
  48090. */
  48091. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  48092. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  48093. char *pData; /* Data to write */
  48094. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  48095. if( pList->pgno==1 ) pager_write_changecounter(pList);
  48096. /* Encode the database */
  48097. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
  48098. /* Write out the page data. */
  48099. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  48100. /* If page 1 was just written, update Pager.dbFileVers to match
  48101. ** the value now stored in the database file. If writing this
  48102. ** page caused the database file to grow, update dbFileSize.
  48103. */
  48104. if( pgno==1 ){
  48105. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  48106. }
  48107. if( pgno>pPager->dbFileSize ){
  48108. pPager->dbFileSize = pgno;
  48109. }
  48110. pPager->aStat[PAGER_STAT_WRITE]++;
  48111. /* Update any backup objects copying the contents of this pager. */
  48112. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  48113. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  48114. PAGERID(pPager), pgno, pager_pagehash(pList)));
  48115. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  48116. PAGER_INCR(sqlite3_pager_writedb_count);
  48117. }else{
  48118. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  48119. }
  48120. pager_set_pagehash(pList);
  48121. pList = pList->pDirty;
  48122. }
  48123. return rc;
  48124. }
  48125. /*
  48126. ** Ensure that the sub-journal file is open. If it is already open, this
  48127. ** function is a no-op.
  48128. **
  48129. ** SQLITE_OK is returned if everything goes according to plan. An
  48130. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  48131. ** fails.
  48132. */
  48133. static int openSubJournal(Pager *pPager){
  48134. int rc = SQLITE_OK;
  48135. if( !isOpen(pPager->sjfd) ){
  48136. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  48137. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  48138. | SQLITE_OPEN_DELETEONCLOSE;
  48139. int nStmtSpill = sqlite3Config.nStmtSpill;
  48140. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  48141. nStmtSpill = -1;
  48142. }
  48143. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  48144. }
  48145. return rc;
  48146. }
  48147. /*
  48148. ** Append a record of the current state of page pPg to the sub-journal.
  48149. **
  48150. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  48151. ** for all open savepoints before returning.
  48152. **
  48153. ** This function returns SQLITE_OK if everything is successful, an IO
  48154. ** error code if the attempt to write to the sub-journal fails, or
  48155. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  48156. ** bitvec.
  48157. */
  48158. static int subjournalPage(PgHdr *pPg){
  48159. int rc = SQLITE_OK;
  48160. Pager *pPager = pPg->pPager;
  48161. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  48162. /* Open the sub-journal, if it has not already been opened */
  48163. assert( pPager->useJournal );
  48164. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  48165. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  48166. assert( pagerUseWal(pPager)
  48167. || pageInJournal(pPager, pPg)
  48168. || pPg->pgno>pPager->dbOrigSize
  48169. );
  48170. rc = openSubJournal(pPager);
  48171. /* If the sub-journal was opened successfully (or was already open),
  48172. ** write the journal record into the file. */
  48173. if( rc==SQLITE_OK ){
  48174. void *pData = pPg->pData;
  48175. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  48176. char *pData2;
  48177. #if SQLITE_HAS_CODEC
  48178. if( !pPager->subjInMemory ){
  48179. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  48180. }else
  48181. #endif
  48182. pData2 = pData;
  48183. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  48184. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  48185. if( rc==SQLITE_OK ){
  48186. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  48187. }
  48188. }
  48189. }
  48190. if( rc==SQLITE_OK ){
  48191. pPager->nSubRec++;
  48192. assert( pPager->nSavepoint>0 );
  48193. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  48194. }
  48195. return rc;
  48196. }
  48197. static int subjournalPageIfRequired(PgHdr *pPg){
  48198. if( subjRequiresPage(pPg) ){
  48199. return subjournalPage(pPg);
  48200. }else{
  48201. return SQLITE_OK;
  48202. }
  48203. }
  48204. /*
  48205. ** This function is called by the pcache layer when it has reached some
  48206. ** soft memory limit. The first argument is a pointer to a Pager object
  48207. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  48208. ** database). The second argument is a reference to a page that is
  48209. ** currently dirty but has no outstanding references. The page
  48210. ** is always associated with the Pager object passed as the first
  48211. ** argument.
  48212. **
  48213. ** The job of this function is to make pPg clean by writing its contents
  48214. ** out to the database file, if possible. This may involve syncing the
  48215. ** journal file.
  48216. **
  48217. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  48218. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  48219. ** page clean, the IO error code is returned. If the page cannot be
  48220. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  48221. ** is returned by sqlite3PcacheMakeClean() is not called.
  48222. */
  48223. static int pagerStress(void *p, PgHdr *pPg){
  48224. Pager *pPager = (Pager *)p;
  48225. int rc = SQLITE_OK;
  48226. assert( pPg->pPager==pPager );
  48227. assert( pPg->flags&PGHDR_DIRTY );
  48228. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  48229. ** journal (and adding a new header) is not allowed. This occurs
  48230. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  48231. ** pages belonging to the same sector.
  48232. **
  48233. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  48234. ** regardless of whether or not a sync is required. This is set during
  48235. ** a rollback or by user request, respectively.
  48236. **
  48237. ** Spilling is also prohibited when in an error state since that could
  48238. ** lead to database corruption. In the current implementation it
  48239. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  48240. ** while in the error state, hence it is impossible for this routine to
  48241. ** be called in the error state. Nevertheless, we include a NEVER()
  48242. ** test for the error state as a safeguard against future changes.
  48243. */
  48244. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  48245. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  48246. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  48247. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  48248. if( pPager->doNotSpill
  48249. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  48250. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  48251. ){
  48252. return SQLITE_OK;
  48253. }
  48254. pPg->pDirty = 0;
  48255. if( pagerUseWal(pPager) ){
  48256. /* Write a single frame for this page to the log. */
  48257. rc = subjournalPageIfRequired(pPg);
  48258. if( rc==SQLITE_OK ){
  48259. rc = pagerWalFrames(pPager, pPg, 0, 0);
  48260. }
  48261. }else{
  48262. /* Sync the journal file if required. */
  48263. if( pPg->flags&PGHDR_NEED_SYNC
  48264. || pPager->eState==PAGER_WRITER_CACHEMOD
  48265. ){
  48266. rc = syncJournal(pPager, 1);
  48267. }
  48268. /* Write the contents of the page out to the database file. */
  48269. if( rc==SQLITE_OK ){
  48270. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  48271. rc = pager_write_pagelist(pPager, pPg);
  48272. }
  48273. }
  48274. /* Mark the page as clean. */
  48275. if( rc==SQLITE_OK ){
  48276. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  48277. sqlite3PcacheMakeClean(pPg);
  48278. }
  48279. return pager_error(pPager, rc);
  48280. }
  48281. /*
  48282. ** Flush all unreferenced dirty pages to disk.
  48283. */
  48284. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  48285. int rc = pPager->errCode;
  48286. if( !MEMDB ){
  48287. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  48288. assert( assert_pager_state(pPager) );
  48289. while( rc==SQLITE_OK && pList ){
  48290. PgHdr *pNext = pList->pDirty;
  48291. if( pList->nRef==0 ){
  48292. rc = pagerStress((void*)pPager, pList);
  48293. }
  48294. pList = pNext;
  48295. }
  48296. }
  48297. return rc;
  48298. }
  48299. /*
  48300. ** Allocate and initialize a new Pager object and put a pointer to it
  48301. ** in *ppPager. The pager should eventually be freed by passing it
  48302. ** to sqlite3PagerClose().
  48303. **
  48304. ** The zFilename argument is the path to the database file to open.
  48305. ** If zFilename is NULL then a randomly-named temporary file is created
  48306. ** and used as the file to be cached. Temporary files are be deleted
  48307. ** automatically when they are closed. If zFilename is ":memory:" then
  48308. ** all information is held in cache. It is never written to disk.
  48309. ** This can be used to implement an in-memory database.
  48310. **
  48311. ** The nExtra parameter specifies the number of bytes of space allocated
  48312. ** along with each page reference. This space is available to the user
  48313. ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
  48314. ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
  48315. ** (The extra space is used by btree as the MemPage object.)
  48316. **
  48317. ** The flags argument is used to specify properties that affect the
  48318. ** operation of the pager. It should be passed some bitwise combination
  48319. ** of the PAGER_* flags.
  48320. **
  48321. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  48322. ** of the xOpen() method of the supplied VFS when opening files.
  48323. **
  48324. ** If the pager object is allocated and the specified file opened
  48325. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  48326. ** the new pager object. If an error occurs, *ppPager is set to NULL
  48327. ** and error code returned. This function may return SQLITE_NOMEM
  48328. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  48329. ** various SQLITE_IO_XXX errors.
  48330. */
  48331. SQLITE_PRIVATE int sqlite3PagerOpen(
  48332. sqlite3_vfs *pVfs, /* The virtual file system to use */
  48333. Pager **ppPager, /* OUT: Return the Pager structure here */
  48334. const char *zFilename, /* Name of the database file to open */
  48335. int nExtra, /* Extra bytes append to each in-memory page */
  48336. int flags, /* flags controlling this file */
  48337. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  48338. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  48339. ){
  48340. u8 *pPtr;
  48341. Pager *pPager = 0; /* Pager object to allocate and return */
  48342. int rc = SQLITE_OK; /* Return code */
  48343. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  48344. int memDb = 0; /* True if this is an in-memory file */
  48345. int readOnly = 0; /* True if this is a read-only file */
  48346. int journalFileSize; /* Bytes to allocate for each journal fd */
  48347. char *zPathname = 0; /* Full path to database file */
  48348. int nPathname = 0; /* Number of bytes in zPathname */
  48349. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  48350. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  48351. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  48352. const char *zUri = 0; /* URI args to copy */
  48353. int nUri = 0; /* Number of bytes of URI args at *zUri */
  48354. /* Figure out how much space is required for each journal file-handle
  48355. ** (there are two of them, the main journal and the sub-journal). */
  48356. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  48357. /* Set the output variable to NULL in case an error occurs. */
  48358. *ppPager = 0;
  48359. #ifndef SQLITE_OMIT_MEMORYDB
  48360. if( flags & PAGER_MEMORY ){
  48361. memDb = 1;
  48362. if( zFilename && zFilename[0] ){
  48363. zPathname = sqlite3DbStrDup(0, zFilename);
  48364. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  48365. nPathname = sqlite3Strlen30(zPathname);
  48366. zFilename = 0;
  48367. }
  48368. }
  48369. #endif
  48370. /* Compute and store the full pathname in an allocated buffer pointed
  48371. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  48372. ** leave both nPathname and zPathname set to 0.
  48373. */
  48374. if( zFilename && zFilename[0] ){
  48375. const char *z;
  48376. nPathname = pVfs->mxPathname+1;
  48377. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  48378. if( zPathname==0 ){
  48379. return SQLITE_NOMEM_BKPT;
  48380. }
  48381. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  48382. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  48383. nPathname = sqlite3Strlen30(zPathname);
  48384. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  48385. while( *z ){
  48386. z += sqlite3Strlen30(z)+1;
  48387. z += sqlite3Strlen30(z)+1;
  48388. }
  48389. nUri = (int)(&z[1] - zUri);
  48390. assert( nUri>=0 );
  48391. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  48392. /* This branch is taken when the journal path required by
  48393. ** the database being opened will be more than pVfs->mxPathname
  48394. ** bytes in length. This means the database cannot be opened,
  48395. ** as it will not be possible to open the journal file or even
  48396. ** check for a hot-journal before reading.
  48397. */
  48398. rc = SQLITE_CANTOPEN_BKPT;
  48399. }
  48400. if( rc!=SQLITE_OK ){
  48401. sqlite3DbFree(0, zPathname);
  48402. return rc;
  48403. }
  48404. }
  48405. /* Allocate memory for the Pager structure, PCache object, the
  48406. ** three file descriptors, the database file name and the journal
  48407. ** file name. The layout in memory is as follows:
  48408. **
  48409. ** Pager object (sizeof(Pager) bytes)
  48410. ** PCache object (sqlite3PcacheSize() bytes)
  48411. ** Database file handle (pVfs->szOsFile bytes)
  48412. ** Sub-journal file handle (journalFileSize bytes)
  48413. ** Main journal file handle (journalFileSize bytes)
  48414. ** Database file name (nPathname+1 bytes)
  48415. ** Journal file name (nPathname+8+1 bytes)
  48416. */
  48417. pPtr = (u8 *)sqlite3MallocZero(
  48418. ROUND8(sizeof(*pPager)) + /* Pager structure */
  48419. ROUND8(pcacheSize) + /* PCache object */
  48420. ROUND8(pVfs->szOsFile) + /* The main db file */
  48421. journalFileSize * 2 + /* The two journal files */
  48422. nPathname + 1 + nUri + /* zFilename */
  48423. nPathname + 8 + 2 /* zJournal */
  48424. #ifndef SQLITE_OMIT_WAL
  48425. + nPathname + 4 + 2 /* zWal */
  48426. #endif
  48427. );
  48428. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  48429. if( !pPtr ){
  48430. sqlite3DbFree(0, zPathname);
  48431. return SQLITE_NOMEM_BKPT;
  48432. }
  48433. pPager = (Pager*)(pPtr);
  48434. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  48435. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  48436. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  48437. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  48438. pPager->zFilename = (char*)(pPtr += journalFileSize);
  48439. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  48440. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  48441. if( zPathname ){
  48442. assert( nPathname>0 );
  48443. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  48444. memcpy(pPager->zFilename, zPathname, nPathname);
  48445. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  48446. memcpy(pPager->zJournal, zPathname, nPathname);
  48447. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  48448. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  48449. #ifndef SQLITE_OMIT_WAL
  48450. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  48451. memcpy(pPager->zWal, zPathname, nPathname);
  48452. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  48453. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  48454. #endif
  48455. sqlite3DbFree(0, zPathname);
  48456. }
  48457. pPager->pVfs = pVfs;
  48458. pPager->vfsFlags = vfsFlags;
  48459. /* Open the pager file.
  48460. */
  48461. if( zFilename && zFilename[0] ){
  48462. int fout = 0; /* VFS flags returned by xOpen() */
  48463. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  48464. assert( !memDb );
  48465. readOnly = (fout&SQLITE_OPEN_READONLY);
  48466. /* If the file was successfully opened for read/write access,
  48467. ** choose a default page size in case we have to create the
  48468. ** database file. The default page size is the maximum of:
  48469. **
  48470. ** + SQLITE_DEFAULT_PAGE_SIZE,
  48471. ** + The value returned by sqlite3OsSectorSize()
  48472. ** + The largest page size that can be written atomically.
  48473. */
  48474. if( rc==SQLITE_OK ){
  48475. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  48476. if( !readOnly ){
  48477. setSectorSize(pPager);
  48478. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  48479. if( szPageDflt<pPager->sectorSize ){
  48480. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  48481. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  48482. }else{
  48483. szPageDflt = (u32)pPager->sectorSize;
  48484. }
  48485. }
  48486. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  48487. {
  48488. int ii;
  48489. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  48490. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  48491. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  48492. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  48493. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  48494. szPageDflt = ii;
  48495. }
  48496. }
  48497. }
  48498. #endif
  48499. }
  48500. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  48501. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  48502. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  48503. vfsFlags |= SQLITE_OPEN_READONLY;
  48504. goto act_like_temp_file;
  48505. }
  48506. }
  48507. }else{
  48508. /* If a temporary file is requested, it is not opened immediately.
  48509. ** In this case we accept the default page size and delay actually
  48510. ** opening the file until the first call to OsWrite().
  48511. **
  48512. ** This branch is also run for an in-memory database. An in-memory
  48513. ** database is the same as a temp-file that is never written out to
  48514. ** disk and uses an in-memory rollback journal.
  48515. **
  48516. ** This branch also runs for files marked as immutable.
  48517. */
  48518. act_like_temp_file:
  48519. tempFile = 1;
  48520. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  48521. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  48522. pPager->noLock = 1; /* Do no locking */
  48523. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  48524. }
  48525. /* The following call to PagerSetPagesize() serves to set the value of
  48526. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  48527. */
  48528. if( rc==SQLITE_OK ){
  48529. assert( pPager->memDb==0 );
  48530. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  48531. testcase( rc!=SQLITE_OK );
  48532. }
  48533. /* Initialize the PCache object. */
  48534. if( rc==SQLITE_OK ){
  48535. nExtra = ROUND8(nExtra);
  48536. assert( nExtra>=8 && nExtra<1000 );
  48537. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  48538. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  48539. }
  48540. /* If an error occurred above, free the Pager structure and close the file.
  48541. */
  48542. if( rc!=SQLITE_OK ){
  48543. sqlite3OsClose(pPager->fd);
  48544. sqlite3PageFree(pPager->pTmpSpace);
  48545. sqlite3_free(pPager);
  48546. return rc;
  48547. }
  48548. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  48549. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  48550. pPager->useJournal = (u8)useJournal;
  48551. /* pPager->stmtOpen = 0; */
  48552. /* pPager->stmtInUse = 0; */
  48553. /* pPager->nRef = 0; */
  48554. /* pPager->stmtSize = 0; */
  48555. /* pPager->stmtJSize = 0; */
  48556. /* pPager->nPage = 0; */
  48557. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  48558. /* pPager->state = PAGER_UNLOCK; */
  48559. /* pPager->errMask = 0; */
  48560. pPager->tempFile = (u8)tempFile;
  48561. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  48562. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  48563. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  48564. pPager->exclusiveMode = (u8)tempFile;
  48565. pPager->changeCountDone = pPager->tempFile;
  48566. pPager->memDb = (u8)memDb;
  48567. pPager->readOnly = (u8)readOnly;
  48568. assert( useJournal || pPager->tempFile );
  48569. pPager->noSync = pPager->tempFile;
  48570. if( pPager->noSync ){
  48571. assert( pPager->fullSync==0 );
  48572. assert( pPager->extraSync==0 );
  48573. assert( pPager->syncFlags==0 );
  48574. assert( pPager->walSyncFlags==0 );
  48575. assert( pPager->ckptSyncFlags==0 );
  48576. }else{
  48577. pPager->fullSync = 1;
  48578. pPager->extraSync = 0;
  48579. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  48580. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  48581. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  48582. }
  48583. /* pPager->pFirst = 0; */
  48584. /* pPager->pFirstSynced = 0; */
  48585. /* pPager->pLast = 0; */
  48586. pPager->nExtra = (u16)nExtra;
  48587. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  48588. assert( isOpen(pPager->fd) || tempFile );
  48589. setSectorSize(pPager);
  48590. if( !useJournal ){
  48591. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  48592. }else if( memDb ){
  48593. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  48594. }
  48595. /* pPager->xBusyHandler = 0; */
  48596. /* pPager->pBusyHandlerArg = 0; */
  48597. pPager->xReiniter = xReinit;
  48598. setGetterMethod(pPager);
  48599. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  48600. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  48601. *ppPager = pPager;
  48602. return SQLITE_OK;
  48603. }
  48604. /* Verify that the database file has not be deleted or renamed out from
  48605. ** under the pager. Return SQLITE_OK if the database is still were it ought
  48606. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  48607. ** code from sqlite3OsAccess()) if the database has gone missing.
  48608. */
  48609. static int databaseIsUnmoved(Pager *pPager){
  48610. int bHasMoved = 0;
  48611. int rc;
  48612. if( pPager->tempFile ) return SQLITE_OK;
  48613. if( pPager->dbSize==0 ) return SQLITE_OK;
  48614. assert( pPager->zFilename && pPager->zFilename[0] );
  48615. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  48616. if( rc==SQLITE_NOTFOUND ){
  48617. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  48618. ** has not been moved. That is the historical behavior of SQLite: prior to
  48619. ** version 3.8.3, it never checked */
  48620. rc = SQLITE_OK;
  48621. }else if( rc==SQLITE_OK && bHasMoved ){
  48622. rc = SQLITE_READONLY_DBMOVED;
  48623. }
  48624. return rc;
  48625. }
  48626. /*
  48627. ** This function is called after transitioning from PAGER_UNLOCK to
  48628. ** PAGER_SHARED state. It tests if there is a hot journal present in
  48629. ** the file-system for the given pager. A hot journal is one that
  48630. ** needs to be played back. According to this function, a hot-journal
  48631. ** file exists if the following criteria are met:
  48632. **
  48633. ** * The journal file exists in the file system, and
  48634. ** * No process holds a RESERVED or greater lock on the database file, and
  48635. ** * The database file itself is greater than 0 bytes in size, and
  48636. ** * The first byte of the journal file exists and is not 0x00.
  48637. **
  48638. ** If the current size of the database file is 0 but a journal file
  48639. ** exists, that is probably an old journal left over from a prior
  48640. ** database with the same name. In this case the journal file is
  48641. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  48642. ** is returned.
  48643. **
  48644. ** This routine does not check if there is a master journal filename
  48645. ** at the end of the file. If there is, and that master journal file
  48646. ** does not exist, then the journal file is not really hot. In this
  48647. ** case this routine will return a false-positive. The pager_playback()
  48648. ** routine will discover that the journal file is not really hot and
  48649. ** will not roll it back.
  48650. **
  48651. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  48652. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  48653. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  48654. ** to determine whether or not a hot-journal file exists, the IO error
  48655. ** code is returned and the value of *pExists is undefined.
  48656. */
  48657. static int hasHotJournal(Pager *pPager, int *pExists){
  48658. sqlite3_vfs * const pVfs = pPager->pVfs;
  48659. int rc = SQLITE_OK; /* Return code */
  48660. int exists = 1; /* True if a journal file is present */
  48661. int jrnlOpen = !!isOpen(pPager->jfd);
  48662. assert( pPager->useJournal );
  48663. assert( isOpen(pPager->fd) );
  48664. assert( pPager->eState==PAGER_OPEN );
  48665. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  48666. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  48667. ));
  48668. *pExists = 0;
  48669. if( !jrnlOpen ){
  48670. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  48671. }
  48672. if( rc==SQLITE_OK && exists ){
  48673. int locked = 0; /* True if some process holds a RESERVED lock */
  48674. /* Race condition here: Another process might have been holding the
  48675. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  48676. ** call above, but then delete the journal and drop the lock before
  48677. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  48678. ** is the case, this routine might think there is a hot journal when
  48679. ** in fact there is none. This results in a false-positive which will
  48680. ** be dealt with by the playback routine. Ticket #3883.
  48681. */
  48682. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  48683. if( rc==SQLITE_OK && !locked ){
  48684. Pgno nPage; /* Number of pages in database file */
  48685. assert( pPager->tempFile==0 );
  48686. rc = pagerPagecount(pPager, &nPage);
  48687. if( rc==SQLITE_OK ){
  48688. /* If the database is zero pages in size, that means that either (1) the
  48689. ** journal is a remnant from a prior database with the same name where
  48690. ** the database file but not the journal was deleted, or (2) the initial
  48691. ** transaction that populates a new database is being rolled back.
  48692. ** In either case, the journal file can be deleted. However, take care
  48693. ** not to delete the journal file if it is already open due to
  48694. ** journal_mode=PERSIST.
  48695. */
  48696. if( nPage==0 && !jrnlOpen ){
  48697. sqlite3BeginBenignMalloc();
  48698. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  48699. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  48700. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  48701. }
  48702. sqlite3EndBenignMalloc();
  48703. }else{
  48704. /* The journal file exists and no other connection has a reserved
  48705. ** or greater lock on the database file. Now check that there is
  48706. ** at least one non-zero bytes at the start of the journal file.
  48707. ** If there is, then we consider this journal to be hot. If not,
  48708. ** it can be ignored.
  48709. */
  48710. if( !jrnlOpen ){
  48711. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  48712. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  48713. }
  48714. if( rc==SQLITE_OK ){
  48715. u8 first = 0;
  48716. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  48717. if( rc==SQLITE_IOERR_SHORT_READ ){
  48718. rc = SQLITE_OK;
  48719. }
  48720. if( !jrnlOpen ){
  48721. sqlite3OsClose(pPager->jfd);
  48722. }
  48723. *pExists = (first!=0);
  48724. }else if( rc==SQLITE_CANTOPEN ){
  48725. /* If we cannot open the rollback journal file in order to see if
  48726. ** it has a zero header, that might be due to an I/O error, or
  48727. ** it might be due to the race condition described above and in
  48728. ** ticket #3883. Either way, assume that the journal is hot.
  48729. ** This might be a false positive. But if it is, then the
  48730. ** automatic journal playback and recovery mechanism will deal
  48731. ** with it under an EXCLUSIVE lock where we do not need to
  48732. ** worry so much with race conditions.
  48733. */
  48734. *pExists = 1;
  48735. rc = SQLITE_OK;
  48736. }
  48737. }
  48738. }
  48739. }
  48740. }
  48741. return rc;
  48742. }
  48743. /*
  48744. ** This function is called to obtain a shared lock on the database file.
  48745. ** It is illegal to call sqlite3PagerGet() until after this function
  48746. ** has been successfully called. If a shared-lock is already held when
  48747. ** this function is called, it is a no-op.
  48748. **
  48749. ** The following operations are also performed by this function.
  48750. **
  48751. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  48752. ** on the database file), then an attempt is made to obtain a
  48753. ** SHARED lock on the database file. Immediately after obtaining
  48754. ** the SHARED lock, the file-system is checked for a hot-journal,
  48755. ** which is played back if present. Following any hot-journal
  48756. ** rollback, the contents of the cache are validated by checking
  48757. ** the 'change-counter' field of the database file header and
  48758. ** discarded if they are found to be invalid.
  48759. **
  48760. ** 2) If the pager is running in exclusive-mode, and there are currently
  48761. ** no outstanding references to any pages, and is in the error state,
  48762. ** then an attempt is made to clear the error state by discarding
  48763. ** the contents of the page cache and rolling back any open journal
  48764. ** file.
  48765. **
  48766. ** If everything is successful, SQLITE_OK is returned. If an IO error
  48767. ** occurs while locking the database, checking for a hot-journal file or
  48768. ** rolling back a journal file, the IO error code is returned.
  48769. */
  48770. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  48771. int rc = SQLITE_OK; /* Return code */
  48772. /* This routine is only called from b-tree and only when there are no
  48773. ** outstanding pages. This implies that the pager state should either
  48774. ** be OPEN or READER. READER is only possible if the pager is or was in
  48775. ** exclusive access mode. */
  48776. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  48777. assert( assert_pager_state(pPager) );
  48778. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  48779. assert( pPager->errCode==SQLITE_OK );
  48780. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  48781. int bHotJournal = 1; /* True if there exists a hot journal-file */
  48782. assert( !MEMDB );
  48783. assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
  48784. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  48785. if( rc!=SQLITE_OK ){
  48786. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  48787. goto failed;
  48788. }
  48789. /* If a journal file exists, and there is no RESERVED lock on the
  48790. ** database file, then it either needs to be played back or deleted.
  48791. */
  48792. if( pPager->eLock<=SHARED_LOCK ){
  48793. rc = hasHotJournal(pPager, &bHotJournal);
  48794. }
  48795. if( rc!=SQLITE_OK ){
  48796. goto failed;
  48797. }
  48798. if( bHotJournal ){
  48799. if( pPager->readOnly ){
  48800. rc = SQLITE_READONLY_ROLLBACK;
  48801. goto failed;
  48802. }
  48803. /* Get an EXCLUSIVE lock on the database file. At this point it is
  48804. ** important that a RESERVED lock is not obtained on the way to the
  48805. ** EXCLUSIVE lock. If it were, another process might open the
  48806. ** database file, detect the RESERVED lock, and conclude that the
  48807. ** database is safe to read while this process is still rolling the
  48808. ** hot-journal back.
  48809. **
  48810. ** Because the intermediate RESERVED lock is not requested, any
  48811. ** other process attempting to access the database file will get to
  48812. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  48813. ** on the database file.
  48814. **
  48815. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  48816. ** downgraded to SHARED_LOCK before this function returns.
  48817. */
  48818. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  48819. if( rc!=SQLITE_OK ){
  48820. goto failed;
  48821. }
  48822. /* If it is not already open and the file exists on disk, open the
  48823. ** journal for read/write access. Write access is required because
  48824. ** in exclusive-access mode the file descriptor will be kept open
  48825. ** and possibly used for a transaction later on. Also, write-access
  48826. ** is usually required to finalize the journal in journal_mode=persist
  48827. ** mode (and also for journal_mode=truncate on some systems).
  48828. **
  48829. ** If the journal does not exist, it usually means that some
  48830. ** other connection managed to get in and roll it back before
  48831. ** this connection obtained the exclusive lock above. Or, it
  48832. ** may mean that the pager was in the error-state when this
  48833. ** function was called and the journal file does not exist.
  48834. */
  48835. if( !isOpen(pPager->jfd) ){
  48836. sqlite3_vfs * const pVfs = pPager->pVfs;
  48837. int bExists; /* True if journal file exists */
  48838. rc = sqlite3OsAccess(
  48839. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  48840. if( rc==SQLITE_OK && bExists ){
  48841. int fout = 0;
  48842. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  48843. assert( !pPager->tempFile );
  48844. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  48845. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  48846. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  48847. rc = SQLITE_CANTOPEN_BKPT;
  48848. sqlite3OsClose(pPager->jfd);
  48849. }
  48850. }
  48851. }
  48852. /* Playback and delete the journal. Drop the database write
  48853. ** lock and reacquire the read lock. Purge the cache before
  48854. ** playing back the hot-journal so that we don't end up with
  48855. ** an inconsistent cache. Sync the hot journal before playing
  48856. ** it back since the process that crashed and left the hot journal
  48857. ** probably did not sync it and we are required to always sync
  48858. ** the journal before playing it back.
  48859. */
  48860. if( isOpen(pPager->jfd) ){
  48861. assert( rc==SQLITE_OK );
  48862. rc = pagerSyncHotJournal(pPager);
  48863. if( rc==SQLITE_OK ){
  48864. rc = pager_playback(pPager, !pPager->tempFile);
  48865. pPager->eState = PAGER_OPEN;
  48866. }
  48867. }else if( !pPager->exclusiveMode ){
  48868. pagerUnlockDb(pPager, SHARED_LOCK);
  48869. }
  48870. if( rc!=SQLITE_OK ){
  48871. /* This branch is taken if an error occurs while trying to open
  48872. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  48873. ** pager_unlock() routine will be called before returning to unlock
  48874. ** the file. If the unlock attempt fails, then Pager.eLock must be
  48875. ** set to UNKNOWN_LOCK (see the comment above the #define for
  48876. ** UNKNOWN_LOCK above for an explanation).
  48877. **
  48878. ** In order to get pager_unlock() to do this, set Pager.eState to
  48879. ** PAGER_ERROR now. This is not actually counted as a transition
  48880. ** to ERROR state in the state diagram at the top of this file,
  48881. ** since we know that the same call to pager_unlock() will very
  48882. ** shortly transition the pager object to the OPEN state. Calling
  48883. ** assert_pager_state() would fail now, as it should not be possible
  48884. ** to be in ERROR state when there are zero outstanding page
  48885. ** references.
  48886. */
  48887. pager_error(pPager, rc);
  48888. goto failed;
  48889. }
  48890. assert( pPager->eState==PAGER_OPEN );
  48891. assert( (pPager->eLock==SHARED_LOCK)
  48892. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  48893. );
  48894. }
  48895. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  48896. /* The shared-lock has just been acquired then check to
  48897. ** see if the database has been modified. If the database has changed,
  48898. ** flush the cache. The hasHeldSharedLock flag prevents this from
  48899. ** occurring on the very first access to a file, in order to save a
  48900. ** single unnecessary sqlite3OsRead() call at the start-up.
  48901. **
  48902. ** Database changes are detected by looking at 15 bytes beginning
  48903. ** at offset 24 into the file. The first 4 of these 16 bytes are
  48904. ** a 32-bit counter that is incremented with each change. The
  48905. ** other bytes change randomly with each file change when
  48906. ** a codec is in use.
  48907. **
  48908. ** There is a vanishingly small chance that a change will not be
  48909. ** detected. The chance of an undetected change is so small that
  48910. ** it can be neglected.
  48911. */
  48912. Pgno nPage = 0;
  48913. char dbFileVers[sizeof(pPager->dbFileVers)];
  48914. rc = pagerPagecount(pPager, &nPage);
  48915. if( rc ) goto failed;
  48916. if( nPage>0 ){
  48917. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  48918. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  48919. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  48920. goto failed;
  48921. }
  48922. }else{
  48923. memset(dbFileVers, 0, sizeof(dbFileVers));
  48924. }
  48925. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  48926. pager_reset(pPager);
  48927. /* Unmap the database file. It is possible that external processes
  48928. ** may have truncated the database file and then extended it back
  48929. ** to its original size while this process was not holding a lock.
  48930. ** In this case there may exist a Pager.pMap mapping that appears
  48931. ** to be the right size but is not actually valid. Avoid this
  48932. ** possibility by unmapping the db here. */
  48933. if( USEFETCH(pPager) ){
  48934. sqlite3OsUnfetch(pPager->fd, 0, 0);
  48935. }
  48936. }
  48937. }
  48938. /* If there is a WAL file in the file-system, open this database in WAL
  48939. ** mode. Otherwise, the following function call is a no-op.
  48940. */
  48941. rc = pagerOpenWalIfPresent(pPager);
  48942. #ifndef SQLITE_OMIT_WAL
  48943. assert( pPager->pWal==0 || rc==SQLITE_OK );
  48944. #endif
  48945. }
  48946. if( pagerUseWal(pPager) ){
  48947. assert( rc==SQLITE_OK );
  48948. rc = pagerBeginReadTransaction(pPager);
  48949. }
  48950. if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  48951. rc = pagerPagecount(pPager, &pPager->dbSize);
  48952. }
  48953. failed:
  48954. if( rc!=SQLITE_OK ){
  48955. assert( !MEMDB );
  48956. pager_unlock(pPager);
  48957. assert( pPager->eState==PAGER_OPEN );
  48958. }else{
  48959. pPager->eState = PAGER_READER;
  48960. pPager->hasHeldSharedLock = 1;
  48961. }
  48962. return rc;
  48963. }
  48964. /*
  48965. ** If the reference count has reached zero, rollback any active
  48966. ** transaction and unlock the pager.
  48967. **
  48968. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  48969. ** the rollback journal, the unlock is not performed and there is
  48970. ** nothing to rollback, so this routine is a no-op.
  48971. */
  48972. static void pagerUnlockIfUnused(Pager *pPager){
  48973. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  48974. pagerUnlockAndRollback(pPager);
  48975. }
  48976. }
  48977. /*
  48978. ** The page getter methods each try to acquire a reference to a
  48979. ** page with page number pgno. If the requested reference is
  48980. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  48981. **
  48982. ** There are different implementations of the getter method depending
  48983. ** on the current state of the pager.
  48984. **
  48985. ** getPageNormal() -- The normal getter
  48986. ** getPageError() -- Used if the pager is in an error state
  48987. ** getPageMmap() -- Used if memory-mapped I/O is enabled
  48988. **
  48989. ** If the requested page is already in the cache, it is returned.
  48990. ** Otherwise, a new page object is allocated and populated with data
  48991. ** read from the database file. In some cases, the pcache module may
  48992. ** choose not to allocate a new page object and may reuse an existing
  48993. ** object with no outstanding references.
  48994. **
  48995. ** The extra data appended to a page is always initialized to zeros the
  48996. ** first time a page is loaded into memory. If the page requested is
  48997. ** already in the cache when this function is called, then the extra
  48998. ** data is left as it was when the page object was last used.
  48999. **
  49000. ** If the database image is smaller than the requested page or if
  49001. ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
  49002. ** requested page is not already stored in the cache, then no
  49003. ** actual disk read occurs. In this case the memory image of the
  49004. ** page is initialized to all zeros.
  49005. **
  49006. ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
  49007. ** the contents of the page. This occurs in two scenarios:
  49008. **
  49009. ** a) When reading a free-list leaf page from the database, and
  49010. **
  49011. ** b) When a savepoint is being rolled back and we need to load
  49012. ** a new page into the cache to be filled with the data read
  49013. ** from the savepoint journal.
  49014. **
  49015. ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
  49016. ** of being read from the database. Additionally, the bits corresponding
  49017. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  49018. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  49019. ** savepoints are set. This means if the page is made writable at any
  49020. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  49021. ** will not be journaled. This saves IO.
  49022. **
  49023. ** The acquisition might fail for several reasons. In all cases,
  49024. ** an appropriate error code is returned and *ppPage is set to NULL.
  49025. **
  49026. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  49027. ** to find a page in the in-memory cache first. If the page is not already
  49028. ** in memory, this routine goes to disk to read it in whereas Lookup()
  49029. ** just returns 0. This routine acquires a read-lock the first time it
  49030. ** has to go to disk, and could also playback an old journal if necessary.
  49031. ** Since Lookup() never goes to disk, it never has to deal with locks
  49032. ** or journal files.
  49033. */
  49034. static int getPageNormal(
  49035. Pager *pPager, /* The pager open on the database file */
  49036. Pgno pgno, /* Page number to fetch */
  49037. DbPage **ppPage, /* Write a pointer to the page here */
  49038. int flags /* PAGER_GET_XXX flags */
  49039. ){
  49040. int rc = SQLITE_OK;
  49041. PgHdr *pPg;
  49042. u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
  49043. sqlite3_pcache_page *pBase;
  49044. assert( pPager->errCode==SQLITE_OK );
  49045. assert( pPager->eState>=PAGER_READER );
  49046. assert( assert_pager_state(pPager) );
  49047. assert( pPager->hasHeldSharedLock==1 );
  49048. if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
  49049. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  49050. if( pBase==0 ){
  49051. pPg = 0;
  49052. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  49053. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  49054. if( pBase==0 ){
  49055. rc = SQLITE_NOMEM_BKPT;
  49056. goto pager_acquire_err;
  49057. }
  49058. }
  49059. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  49060. assert( pPg==(*ppPage) );
  49061. assert( pPg->pgno==pgno );
  49062. assert( pPg->pPager==pPager || pPg->pPager==0 );
  49063. noContent = (flags & PAGER_GET_NOCONTENT)!=0;
  49064. if( pPg->pPager && !noContent ){
  49065. /* In this case the pcache already contains an initialized copy of
  49066. ** the page. Return without further ado. */
  49067. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  49068. pPager->aStat[PAGER_STAT_HIT]++;
  49069. return SQLITE_OK;
  49070. }else{
  49071. /* The pager cache has created a new page. Its content needs to
  49072. ** be initialized. But first some error checks:
  49073. **
  49074. ** (1) The maximum page number is 2^31
  49075. ** (2) Never try to fetch the locking page
  49076. */
  49077. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  49078. rc = SQLITE_CORRUPT_BKPT;
  49079. goto pager_acquire_err;
  49080. }
  49081. pPg->pPager = pPager;
  49082. assert( !isOpen(pPager->fd) || !MEMDB );
  49083. if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
  49084. if( pgno>pPager->mxPgno ){
  49085. rc = SQLITE_FULL;
  49086. goto pager_acquire_err;
  49087. }
  49088. if( noContent ){
  49089. /* Failure to set the bits in the InJournal bit-vectors is benign.
  49090. ** It merely means that we might do some extra work to journal a
  49091. ** page that does not need to be journaled. Nevertheless, be sure
  49092. ** to test the case where a malloc error occurs while trying to set
  49093. ** a bit in a bit vector.
  49094. */
  49095. sqlite3BeginBenignMalloc();
  49096. if( pgno<=pPager->dbOrigSize ){
  49097. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  49098. testcase( rc==SQLITE_NOMEM );
  49099. }
  49100. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  49101. testcase( rc==SQLITE_NOMEM );
  49102. sqlite3EndBenignMalloc();
  49103. }
  49104. memset(pPg->pData, 0, pPager->pageSize);
  49105. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  49106. }else{
  49107. u32 iFrame = 0; /* Frame to read from WAL file */
  49108. if( pagerUseWal(pPager) ){
  49109. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  49110. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  49111. }
  49112. assert( pPg->pPager==pPager );
  49113. pPager->aStat[PAGER_STAT_MISS]++;
  49114. rc = readDbPage(pPg, iFrame);
  49115. if( rc!=SQLITE_OK ){
  49116. goto pager_acquire_err;
  49117. }
  49118. }
  49119. pager_set_pagehash(pPg);
  49120. }
  49121. return SQLITE_OK;
  49122. pager_acquire_err:
  49123. assert( rc!=SQLITE_OK );
  49124. if( pPg ){
  49125. sqlite3PcacheDrop(pPg);
  49126. }
  49127. pagerUnlockIfUnused(pPager);
  49128. *ppPage = 0;
  49129. return rc;
  49130. }
  49131. #if SQLITE_MAX_MMAP_SIZE>0
  49132. /* The page getter for when memory-mapped I/O is enabled */
  49133. static int getPageMMap(
  49134. Pager *pPager, /* The pager open on the database file */
  49135. Pgno pgno, /* Page number to fetch */
  49136. DbPage **ppPage, /* Write a pointer to the page here */
  49137. int flags /* PAGER_GET_XXX flags */
  49138. ){
  49139. int rc = SQLITE_OK;
  49140. PgHdr *pPg = 0;
  49141. u32 iFrame = 0; /* Frame to read from WAL file */
  49142. /* It is acceptable to use a read-only (mmap) page for any page except
  49143. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  49144. ** flag was specified by the caller. And so long as the db is not a
  49145. ** temporary or in-memory database. */
  49146. const int bMmapOk = (pgno>1
  49147. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  49148. );
  49149. assert( USEFETCH(pPager) );
  49150. #ifdef SQLITE_HAS_CODEC
  49151. assert( pPager->xCodec==0 );
  49152. #endif
  49153. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  49154. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  49155. ** test in the previous statement, and avoid testing pgno==0 in the
  49156. ** common case where pgno is large. */
  49157. if( pgno<=1 && pgno==0 ){
  49158. return SQLITE_CORRUPT_BKPT;
  49159. }
  49160. assert( pPager->eState>=PAGER_READER );
  49161. assert( assert_pager_state(pPager) );
  49162. assert( pPager->hasHeldSharedLock==1 );
  49163. assert( pPager->errCode==SQLITE_OK );
  49164. if( bMmapOk && pagerUseWal(pPager) ){
  49165. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  49166. if( rc!=SQLITE_OK ){
  49167. *ppPage = 0;
  49168. return rc;
  49169. }
  49170. }
  49171. if( bMmapOk && iFrame==0 ){
  49172. void *pData = 0;
  49173. rc = sqlite3OsFetch(pPager->fd,
  49174. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  49175. );
  49176. if( rc==SQLITE_OK && pData ){
  49177. if( pPager->eState>PAGER_READER || pPager->tempFile ){
  49178. pPg = sqlite3PagerLookup(pPager, pgno);
  49179. }
  49180. if( pPg==0 ){
  49181. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  49182. }else{
  49183. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  49184. }
  49185. if( pPg ){
  49186. assert( rc==SQLITE_OK );
  49187. *ppPage = pPg;
  49188. return SQLITE_OK;
  49189. }
  49190. }
  49191. if( rc!=SQLITE_OK ){
  49192. *ppPage = 0;
  49193. return rc;
  49194. }
  49195. }
  49196. return getPageNormal(pPager, pgno, ppPage, flags);
  49197. }
  49198. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  49199. /* The page getter method for when the pager is an error state */
  49200. static int getPageError(
  49201. Pager *pPager, /* The pager open on the database file */
  49202. Pgno pgno, /* Page number to fetch */
  49203. DbPage **ppPage, /* Write a pointer to the page here */
  49204. int flags /* PAGER_GET_XXX flags */
  49205. ){
  49206. UNUSED_PARAMETER(pgno);
  49207. UNUSED_PARAMETER(flags);
  49208. assert( pPager->errCode!=SQLITE_OK );
  49209. *ppPage = 0;
  49210. return pPager->errCode;
  49211. }
  49212. /* Dispatch all page fetch requests to the appropriate getter method.
  49213. */
  49214. SQLITE_PRIVATE int sqlite3PagerGet(
  49215. Pager *pPager, /* The pager open on the database file */
  49216. Pgno pgno, /* Page number to fetch */
  49217. DbPage **ppPage, /* Write a pointer to the page here */
  49218. int flags /* PAGER_GET_XXX flags */
  49219. ){
  49220. return pPager->xGet(pPager, pgno, ppPage, flags);
  49221. }
  49222. /*
  49223. ** Acquire a page if it is already in the in-memory cache. Do
  49224. ** not read the page from disk. Return a pointer to the page,
  49225. ** or 0 if the page is not in cache.
  49226. **
  49227. ** See also sqlite3PagerGet(). The difference between this routine
  49228. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  49229. ** in the page if the page is not already in cache. This routine
  49230. ** returns NULL if the page is not in cache or if a disk I/O error
  49231. ** has ever happened.
  49232. */
  49233. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  49234. sqlite3_pcache_page *pPage;
  49235. assert( pPager!=0 );
  49236. assert( pgno!=0 );
  49237. assert( pPager->pPCache!=0 );
  49238. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  49239. assert( pPage==0 || pPager->hasHeldSharedLock );
  49240. if( pPage==0 ) return 0;
  49241. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  49242. }
  49243. /*
  49244. ** Release a page reference.
  49245. **
  49246. ** If the number of references to the page drop to zero, then the
  49247. ** page is added to the LRU list. When all references to all pages
  49248. ** are released, a rollback occurs and the lock on the database is
  49249. ** removed.
  49250. */
  49251. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  49252. Pager *pPager;
  49253. assert( pPg!=0 );
  49254. pPager = pPg->pPager;
  49255. if( pPg->flags & PGHDR_MMAP ){
  49256. pagerReleaseMapPage(pPg);
  49257. }else{
  49258. sqlite3PcacheRelease(pPg);
  49259. }
  49260. pagerUnlockIfUnused(pPager);
  49261. }
  49262. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  49263. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  49264. }
  49265. /*
  49266. ** This function is called at the start of every write transaction.
  49267. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  49268. ** file when this routine is called.
  49269. **
  49270. ** Open the journal file for pager pPager and write a journal header
  49271. ** to the start of it. If there are active savepoints, open the sub-journal
  49272. ** as well. This function is only used when the journal file is being
  49273. ** opened to write a rollback log for a transaction. It is not used
  49274. ** when opening a hot journal file to roll it back.
  49275. **
  49276. ** If the journal file is already open (as it may be in exclusive mode),
  49277. ** then this function just writes a journal header to the start of the
  49278. ** already open file.
  49279. **
  49280. ** Whether or not the journal file is opened by this function, the
  49281. ** Pager.pInJournal bitvec structure is allocated.
  49282. **
  49283. ** Return SQLITE_OK if everything is successful. Otherwise, return
  49284. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  49285. ** an IO error code if opening or writing the journal file fails.
  49286. */
  49287. static int pager_open_journal(Pager *pPager){
  49288. int rc = SQLITE_OK; /* Return code */
  49289. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  49290. assert( pPager->eState==PAGER_WRITER_LOCKED );
  49291. assert( assert_pager_state(pPager) );
  49292. assert( pPager->pInJournal==0 );
  49293. /* If already in the error state, this function is a no-op. But on
  49294. ** the other hand, this routine is never called if we are already in
  49295. ** an error state. */
  49296. if( NEVER(pPager->errCode) ) return pPager->errCode;
  49297. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  49298. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  49299. if( pPager->pInJournal==0 ){
  49300. return SQLITE_NOMEM_BKPT;
  49301. }
  49302. /* Open the journal file if it is not already open. */
  49303. if( !isOpen(pPager->jfd) ){
  49304. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  49305. sqlite3MemJournalOpen(pPager->jfd);
  49306. }else{
  49307. int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  49308. int nSpill;
  49309. if( pPager->tempFile ){
  49310. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  49311. nSpill = sqlite3Config.nStmtSpill;
  49312. }else{
  49313. flags |= SQLITE_OPEN_MAIN_JOURNAL;
  49314. nSpill = jrnlBufferSize(pPager);
  49315. }
  49316. /* Verify that the database still has the same name as it did when
  49317. ** it was originally opened. */
  49318. rc = databaseIsUnmoved(pPager);
  49319. if( rc==SQLITE_OK ){
  49320. rc = sqlite3JournalOpen (
  49321. pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
  49322. );
  49323. }
  49324. }
  49325. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  49326. }
  49327. /* Write the first journal header to the journal file and open
  49328. ** the sub-journal if necessary.
  49329. */
  49330. if( rc==SQLITE_OK ){
  49331. /* TODO: Check if all of these are really required. */
  49332. pPager->nRec = 0;
  49333. pPager->journalOff = 0;
  49334. pPager->setMaster = 0;
  49335. pPager->journalHdr = 0;
  49336. rc = writeJournalHdr(pPager);
  49337. }
  49338. }
  49339. if( rc!=SQLITE_OK ){
  49340. sqlite3BitvecDestroy(pPager->pInJournal);
  49341. pPager->pInJournal = 0;
  49342. }else{
  49343. assert( pPager->eState==PAGER_WRITER_LOCKED );
  49344. pPager->eState = PAGER_WRITER_CACHEMOD;
  49345. }
  49346. return rc;
  49347. }
  49348. /*
  49349. ** Begin a write-transaction on the specified pager object. If a
  49350. ** write-transaction has already been opened, this function is a no-op.
  49351. **
  49352. ** If the exFlag argument is false, then acquire at least a RESERVED
  49353. ** lock on the database file. If exFlag is true, then acquire at least
  49354. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  49355. ** functions need be called.
  49356. **
  49357. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  49358. ** within this transaction will be opened as an in-memory file. This
  49359. ** has no effect if the sub-journal is already opened (as it may be when
  49360. ** running in exclusive mode) or if the transaction does not require a
  49361. ** sub-journal. If the subjInMemory argument is zero, then any required
  49362. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  49363. ** or using a temporary file otherwise.
  49364. */
  49365. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  49366. int rc = SQLITE_OK;
  49367. if( pPager->errCode ) return pPager->errCode;
  49368. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  49369. pPager->subjInMemory = (u8)subjInMemory;
  49370. if( ALWAYS(pPager->eState==PAGER_READER) ){
  49371. assert( pPager->pInJournal==0 );
  49372. if( pagerUseWal(pPager) ){
  49373. /* If the pager is configured to use locking_mode=exclusive, and an
  49374. ** exclusive lock on the database is not already held, obtain it now.
  49375. */
  49376. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  49377. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  49378. if( rc!=SQLITE_OK ){
  49379. return rc;
  49380. }
  49381. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  49382. }
  49383. /* Grab the write lock on the log file. If successful, upgrade to
  49384. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  49385. ** The busy-handler is not invoked if another connection already
  49386. ** holds the write-lock. If possible, the upper layer will call it.
  49387. */
  49388. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  49389. }else{
  49390. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  49391. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  49392. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  49393. ** lock, but not when obtaining the RESERVED lock.
  49394. */
  49395. rc = pagerLockDb(pPager, RESERVED_LOCK);
  49396. if( rc==SQLITE_OK && exFlag ){
  49397. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  49398. }
  49399. }
  49400. if( rc==SQLITE_OK ){
  49401. /* Change to WRITER_LOCKED state.
  49402. **
  49403. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  49404. ** when it has an open transaction, but never to DBMOD or FINISHED.
  49405. ** This is because in those states the code to roll back savepoint
  49406. ** transactions may copy data from the sub-journal into the database
  49407. ** file as well as into the page cache. Which would be incorrect in
  49408. ** WAL mode.
  49409. */
  49410. pPager->eState = PAGER_WRITER_LOCKED;
  49411. pPager->dbHintSize = pPager->dbSize;
  49412. pPager->dbFileSize = pPager->dbSize;
  49413. pPager->dbOrigSize = pPager->dbSize;
  49414. pPager->journalOff = 0;
  49415. }
  49416. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  49417. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  49418. assert( assert_pager_state(pPager) );
  49419. }
  49420. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  49421. return rc;
  49422. }
  49423. /*
  49424. ** Write page pPg onto the end of the rollback journal.
  49425. */
  49426. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  49427. Pager *pPager = pPg->pPager;
  49428. int rc;
  49429. u32 cksum;
  49430. char *pData2;
  49431. i64 iOff = pPager->journalOff;
  49432. /* We should never write to the journal file the page that
  49433. ** contains the database locks. The following assert verifies
  49434. ** that we do not. */
  49435. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  49436. assert( pPager->journalHdr<=pPager->journalOff );
  49437. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  49438. cksum = pager_cksum(pPager, (u8*)pData2);
  49439. /* Even if an IO or diskfull error occurs while journalling the
  49440. ** page in the block above, set the need-sync flag for the page.
  49441. ** Otherwise, when the transaction is rolled back, the logic in
  49442. ** playback_one_page() will think that the page needs to be restored
  49443. ** in the database file. And if an IO error occurs while doing so,
  49444. ** then corruption may follow.
  49445. */
  49446. pPg->flags |= PGHDR_NEED_SYNC;
  49447. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  49448. if( rc!=SQLITE_OK ) return rc;
  49449. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  49450. if( rc!=SQLITE_OK ) return rc;
  49451. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  49452. if( rc!=SQLITE_OK ) return rc;
  49453. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  49454. pPager->journalOff, pPager->pageSize));
  49455. PAGER_INCR(sqlite3_pager_writej_count);
  49456. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  49457. PAGERID(pPager), pPg->pgno,
  49458. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  49459. pPager->journalOff += 8 + pPager->pageSize;
  49460. pPager->nRec++;
  49461. assert( pPager->pInJournal!=0 );
  49462. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  49463. testcase( rc==SQLITE_NOMEM );
  49464. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  49465. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  49466. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  49467. return rc;
  49468. }
  49469. /*
  49470. ** Mark a single data page as writeable. The page is written into the
  49471. ** main journal or sub-journal as required. If the page is written into
  49472. ** one of the journals, the corresponding bit is set in the
  49473. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  49474. ** of any open savepoints as appropriate.
  49475. */
  49476. static int pager_write(PgHdr *pPg){
  49477. Pager *pPager = pPg->pPager;
  49478. int rc = SQLITE_OK;
  49479. /* This routine is not called unless a write-transaction has already
  49480. ** been started. The journal file may or may not be open at this point.
  49481. ** It is never called in the ERROR state.
  49482. */
  49483. assert( pPager->eState==PAGER_WRITER_LOCKED
  49484. || pPager->eState==PAGER_WRITER_CACHEMOD
  49485. || pPager->eState==PAGER_WRITER_DBMOD
  49486. );
  49487. assert( assert_pager_state(pPager) );
  49488. assert( pPager->errCode==0 );
  49489. assert( pPager->readOnly==0 );
  49490. CHECK_PAGE(pPg);
  49491. /* The journal file needs to be opened. Higher level routines have already
  49492. ** obtained the necessary locks to begin the write-transaction, but the
  49493. ** rollback journal might not yet be open. Open it now if this is the case.
  49494. **
  49495. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  49496. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  49497. ** an error might occur and the pager would end up in WRITER_LOCKED state
  49498. ** with pages marked as dirty in the cache.
  49499. */
  49500. if( pPager->eState==PAGER_WRITER_LOCKED ){
  49501. rc = pager_open_journal(pPager);
  49502. if( rc!=SQLITE_OK ) return rc;
  49503. }
  49504. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  49505. assert( assert_pager_state(pPager) );
  49506. /* Mark the page that is about to be modified as dirty. */
  49507. sqlite3PcacheMakeDirty(pPg);
  49508. /* If a rollback journal is in use, them make sure the page that is about
  49509. ** to change is in the rollback journal, or if the page is a new page off
  49510. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  49511. */
  49512. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  49513. if( pPager->pInJournal!=0
  49514. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  49515. ){
  49516. assert( pagerUseWal(pPager)==0 );
  49517. if( pPg->pgno<=pPager->dbOrigSize ){
  49518. rc = pagerAddPageToRollbackJournal(pPg);
  49519. if( rc!=SQLITE_OK ){
  49520. return rc;
  49521. }
  49522. }else{
  49523. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  49524. pPg->flags |= PGHDR_NEED_SYNC;
  49525. }
  49526. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  49527. PAGERID(pPager), pPg->pgno,
  49528. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  49529. }
  49530. }
  49531. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  49532. ** and before writing the page into the rollback journal. Wait until now,
  49533. ** after the page has been successfully journalled, before setting the
  49534. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  49535. */
  49536. pPg->flags |= PGHDR_WRITEABLE;
  49537. /* If the statement journal is open and the page is not in it,
  49538. ** then write the page into the statement journal.
  49539. */
  49540. if( pPager->nSavepoint>0 ){
  49541. rc = subjournalPageIfRequired(pPg);
  49542. }
  49543. /* Update the database size and return. */
  49544. if( pPager->dbSize<pPg->pgno ){
  49545. pPager->dbSize = pPg->pgno;
  49546. }
  49547. return rc;
  49548. }
  49549. /*
  49550. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  49551. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  49552. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  49553. ** a sector need to be journalled in case of a power loss in the middle of
  49554. ** a write.
  49555. **
  49556. ** Usually, the sector size is less than or equal to the page size, in which
  49557. ** case pages can be individually written. This routine only runs in the
  49558. ** exceptional case where the page size is smaller than the sector size.
  49559. */
  49560. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  49561. int rc = SQLITE_OK; /* Return code */
  49562. Pgno nPageCount; /* Total number of pages in database file */
  49563. Pgno pg1; /* First page of the sector pPg is located on. */
  49564. int nPage = 0; /* Number of pages starting at pg1 to journal */
  49565. int ii; /* Loop counter */
  49566. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  49567. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  49568. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  49569. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  49570. ** a journal header to be written between the pages journaled by
  49571. ** this function.
  49572. */
  49573. assert( !MEMDB );
  49574. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  49575. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  49576. /* This trick assumes that both the page-size and sector-size are
  49577. ** an integer power of 2. It sets variable pg1 to the identifier
  49578. ** of the first page of the sector pPg is located on.
  49579. */
  49580. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  49581. nPageCount = pPager->dbSize;
  49582. if( pPg->pgno>nPageCount ){
  49583. nPage = (pPg->pgno - pg1)+1;
  49584. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  49585. nPage = nPageCount+1-pg1;
  49586. }else{
  49587. nPage = nPagePerSector;
  49588. }
  49589. assert(nPage>0);
  49590. assert(pg1<=pPg->pgno);
  49591. assert((pg1+nPage)>pPg->pgno);
  49592. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  49593. Pgno pg = pg1+ii;
  49594. PgHdr *pPage;
  49595. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  49596. if( pg!=PAGER_MJ_PGNO(pPager) ){
  49597. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  49598. if( rc==SQLITE_OK ){
  49599. rc = pager_write(pPage);
  49600. if( pPage->flags&PGHDR_NEED_SYNC ){
  49601. needSync = 1;
  49602. }
  49603. sqlite3PagerUnrefNotNull(pPage);
  49604. }
  49605. }
  49606. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  49607. if( pPage->flags&PGHDR_NEED_SYNC ){
  49608. needSync = 1;
  49609. }
  49610. sqlite3PagerUnrefNotNull(pPage);
  49611. }
  49612. }
  49613. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  49614. ** starting at pg1, then it needs to be set for all of them. Because
  49615. ** writing to any of these nPage pages may damage the others, the
  49616. ** journal file must contain sync()ed copies of all of them
  49617. ** before any of them can be written out to the database file.
  49618. */
  49619. if( rc==SQLITE_OK && needSync ){
  49620. assert( !MEMDB );
  49621. for(ii=0; ii<nPage; ii++){
  49622. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  49623. if( pPage ){
  49624. pPage->flags |= PGHDR_NEED_SYNC;
  49625. sqlite3PagerUnrefNotNull(pPage);
  49626. }
  49627. }
  49628. }
  49629. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  49630. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  49631. return rc;
  49632. }
  49633. /*
  49634. ** Mark a data page as writeable. This routine must be called before
  49635. ** making changes to a page. The caller must check the return value
  49636. ** of this function and be careful not to change any page data unless
  49637. ** this routine returns SQLITE_OK.
  49638. **
  49639. ** The difference between this function and pager_write() is that this
  49640. ** function also deals with the special case where 2 or more pages
  49641. ** fit on a single disk sector. In this case all co-resident pages
  49642. ** must have been written to the journal file before returning.
  49643. **
  49644. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  49645. ** as appropriate. Otherwise, SQLITE_OK.
  49646. */
  49647. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  49648. Pager *pPager = pPg->pPager;
  49649. assert( (pPg->flags & PGHDR_MMAP)==0 );
  49650. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  49651. assert( assert_pager_state(pPager) );
  49652. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  49653. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  49654. return SQLITE_OK;
  49655. }else if( pPager->errCode ){
  49656. return pPager->errCode;
  49657. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  49658. assert( pPager->tempFile==0 );
  49659. return pagerWriteLargeSector(pPg);
  49660. }else{
  49661. return pager_write(pPg);
  49662. }
  49663. }
  49664. /*
  49665. ** Return TRUE if the page given in the argument was previously passed
  49666. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  49667. ** to change the content of the page.
  49668. */
  49669. #ifndef NDEBUG
  49670. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  49671. return pPg->flags & PGHDR_WRITEABLE;
  49672. }
  49673. #endif
  49674. /*
  49675. ** A call to this routine tells the pager that it is not necessary to
  49676. ** write the information on page pPg back to the disk, even though
  49677. ** that page might be marked as dirty. This happens, for example, when
  49678. ** the page has been added as a leaf of the freelist and so its
  49679. ** content no longer matters.
  49680. **
  49681. ** The overlying software layer calls this routine when all of the data
  49682. ** on the given page is unused. The pager marks the page as clean so
  49683. ** that it does not get written to disk.
  49684. **
  49685. ** Tests show that this optimization can quadruple the speed of large
  49686. ** DELETE operations.
  49687. **
  49688. ** This optimization cannot be used with a temp-file, as the page may
  49689. ** have been dirty at the start of the transaction. In that case, if
  49690. ** memory pressure forces page pPg out of the cache, the data does need
  49691. ** to be written out to disk so that it may be read back in if the
  49692. ** current transaction is rolled back.
  49693. */
  49694. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  49695. Pager *pPager = pPg->pPager;
  49696. if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  49697. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  49698. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  49699. pPg->flags |= PGHDR_DONT_WRITE;
  49700. pPg->flags &= ~PGHDR_WRITEABLE;
  49701. testcase( pPg->flags & PGHDR_NEED_SYNC );
  49702. pager_set_pagehash(pPg);
  49703. }
  49704. }
  49705. /*
  49706. ** This routine is called to increment the value of the database file
  49707. ** change-counter, stored as a 4-byte big-endian integer starting at
  49708. ** byte offset 24 of the pager file. The secondary change counter at
  49709. ** 92 is also updated, as is the SQLite version number at offset 96.
  49710. **
  49711. ** But this only happens if the pPager->changeCountDone flag is false.
  49712. ** To avoid excess churning of page 1, the update only happens once.
  49713. ** See also the pager_write_changecounter() routine that does an
  49714. ** unconditional update of the change counters.
  49715. **
  49716. ** If the isDirectMode flag is zero, then this is done by calling
  49717. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  49718. ** page data. In this case the file will be updated when the current
  49719. ** transaction is committed.
  49720. **
  49721. ** The isDirectMode flag may only be non-zero if the library was compiled
  49722. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  49723. ** if isDirect is non-zero, then the database file is updated directly
  49724. ** by writing an updated version of page 1 using a call to the
  49725. ** sqlite3OsWrite() function.
  49726. */
  49727. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  49728. int rc = SQLITE_OK;
  49729. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  49730. || pPager->eState==PAGER_WRITER_DBMOD
  49731. );
  49732. assert( assert_pager_state(pPager) );
  49733. /* Declare and initialize constant integer 'isDirect'. If the
  49734. ** atomic-write optimization is enabled in this build, then isDirect
  49735. ** is initialized to the value passed as the isDirectMode parameter
  49736. ** to this function. Otherwise, it is always set to zero.
  49737. **
  49738. ** The idea is that if the atomic-write optimization is not
  49739. ** enabled at compile time, the compiler can omit the tests of
  49740. ** 'isDirect' below, as well as the block enclosed in the
  49741. ** "if( isDirect )" condition.
  49742. */
  49743. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  49744. # define DIRECT_MODE 0
  49745. assert( isDirectMode==0 );
  49746. UNUSED_PARAMETER(isDirectMode);
  49747. #else
  49748. # define DIRECT_MODE isDirectMode
  49749. #endif
  49750. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  49751. PgHdr *pPgHdr; /* Reference to page 1 */
  49752. assert( !pPager->tempFile && isOpen(pPager->fd) );
  49753. /* Open page 1 of the file for writing. */
  49754. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  49755. assert( pPgHdr==0 || rc==SQLITE_OK );
  49756. /* If page one was fetched successfully, and this function is not
  49757. ** operating in direct-mode, make page 1 writable. When not in
  49758. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  49759. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  49760. */
  49761. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  49762. rc = sqlite3PagerWrite(pPgHdr);
  49763. }
  49764. if( rc==SQLITE_OK ){
  49765. /* Actually do the update of the change counter */
  49766. pager_write_changecounter(pPgHdr);
  49767. /* If running in direct mode, write the contents of page 1 to the file. */
  49768. if( DIRECT_MODE ){
  49769. const void *zBuf;
  49770. assert( pPager->dbFileSize>0 );
  49771. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
  49772. if( rc==SQLITE_OK ){
  49773. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  49774. pPager->aStat[PAGER_STAT_WRITE]++;
  49775. }
  49776. if( rc==SQLITE_OK ){
  49777. /* Update the pager's copy of the change-counter. Otherwise, the
  49778. ** next time a read transaction is opened the cache will be
  49779. ** flushed (as the change-counter values will not match). */
  49780. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  49781. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  49782. pPager->changeCountDone = 1;
  49783. }
  49784. }else{
  49785. pPager->changeCountDone = 1;
  49786. }
  49787. }
  49788. /* Release the page reference. */
  49789. sqlite3PagerUnref(pPgHdr);
  49790. }
  49791. return rc;
  49792. }
  49793. /*
  49794. ** Sync the database file to disk. This is a no-op for in-memory databases
  49795. ** or pages with the Pager.noSync flag set.
  49796. **
  49797. ** If successful, or if called on a pager for which it is a no-op, this
  49798. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  49799. */
  49800. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  49801. int rc = SQLITE_OK;
  49802. if( isOpen(pPager->fd) ){
  49803. void *pArg = (void*)zMaster;
  49804. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  49805. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  49806. }
  49807. if( rc==SQLITE_OK && !pPager->noSync ){
  49808. assert( !MEMDB );
  49809. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  49810. }
  49811. return rc;
  49812. }
  49813. /*
  49814. ** This function may only be called while a write-transaction is active in
  49815. ** rollback. If the connection is in WAL mode, this call is a no-op.
  49816. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  49817. ** the database file, an attempt is made to obtain one.
  49818. **
  49819. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  49820. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  49821. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  49822. ** returned.
  49823. */
  49824. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  49825. int rc = pPager->errCode;
  49826. assert( assert_pager_state(pPager) );
  49827. if( rc==SQLITE_OK ){
  49828. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  49829. || pPager->eState==PAGER_WRITER_DBMOD
  49830. || pPager->eState==PAGER_WRITER_LOCKED
  49831. );
  49832. assert( assert_pager_state(pPager) );
  49833. if( 0==pagerUseWal(pPager) ){
  49834. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  49835. }
  49836. }
  49837. return rc;
  49838. }
  49839. /*
  49840. ** Sync the database file for the pager pPager. zMaster points to the name
  49841. ** of a master journal file that should be written into the individual
  49842. ** journal file. zMaster may be NULL, which is interpreted as no master
  49843. ** journal (a single database transaction).
  49844. **
  49845. ** This routine ensures that:
  49846. **
  49847. ** * The database file change-counter is updated,
  49848. ** * the journal is synced (unless the atomic-write optimization is used),
  49849. ** * all dirty pages are written to the database file,
  49850. ** * the database file is truncated (if required), and
  49851. ** * the database file synced.
  49852. **
  49853. ** The only thing that remains to commit the transaction is to finalize
  49854. ** (delete, truncate or zero the first part of) the journal file (or
  49855. ** delete the master journal file if specified).
  49856. **
  49857. ** Note that if zMaster==NULL, this does not overwrite a previous value
  49858. ** passed to an sqlite3PagerCommitPhaseOne() call.
  49859. **
  49860. ** If the final parameter - noSync - is true, then the database file itself
  49861. ** is not synced. The caller must call sqlite3PagerSync() directly to
  49862. ** sync the database file before calling CommitPhaseTwo() to delete the
  49863. ** journal file in this case.
  49864. */
  49865. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  49866. Pager *pPager, /* Pager object */
  49867. const char *zMaster, /* If not NULL, the master journal name */
  49868. int noSync /* True to omit the xSync on the db file */
  49869. ){
  49870. int rc = SQLITE_OK; /* Return code */
  49871. assert( pPager->eState==PAGER_WRITER_LOCKED
  49872. || pPager->eState==PAGER_WRITER_CACHEMOD
  49873. || pPager->eState==PAGER_WRITER_DBMOD
  49874. || pPager->eState==PAGER_ERROR
  49875. );
  49876. assert( assert_pager_state(pPager) );
  49877. /* If a prior error occurred, report that error again. */
  49878. if( NEVER(pPager->errCode) ) return pPager->errCode;
  49879. /* Provide the ability to easily simulate an I/O error during testing */
  49880. if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
  49881. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  49882. pPager->zFilename, zMaster, pPager->dbSize));
  49883. /* If no database changes have been made, return early. */
  49884. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  49885. assert( MEMDB==0 || pPager->tempFile );
  49886. assert( isOpen(pPager->fd) || pPager->tempFile );
  49887. if( 0==pagerFlushOnCommit(pPager, 1) ){
  49888. /* If this is an in-memory db, or no pages have been written to, or this
  49889. ** function has already been called, it is mostly a no-op. However, any
  49890. ** backup in progress needs to be restarted. */
  49891. sqlite3BackupRestart(pPager->pBackup);
  49892. }else{
  49893. if( pagerUseWal(pPager) ){
  49894. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  49895. PgHdr *pPageOne = 0;
  49896. if( pList==0 ){
  49897. /* Must have at least one page for the WAL commit flag.
  49898. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  49899. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  49900. pList = pPageOne;
  49901. pList->pDirty = 0;
  49902. }
  49903. assert( rc==SQLITE_OK );
  49904. if( ALWAYS(pList) ){
  49905. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  49906. }
  49907. sqlite3PagerUnref(pPageOne);
  49908. if( rc==SQLITE_OK ){
  49909. sqlite3PcacheCleanAll(pPager->pPCache);
  49910. }
  49911. }else{
  49912. /* The following block updates the change-counter. Exactly how it
  49913. ** does this depends on whether or not the atomic-update optimization
  49914. ** was enabled at compile time, and if this transaction meets the
  49915. ** runtime criteria to use the operation:
  49916. **
  49917. ** * The file-system supports the atomic-write property for
  49918. ** blocks of size page-size, and
  49919. ** * This commit is not part of a multi-file transaction, and
  49920. ** * Exactly one page has been modified and store in the journal file.
  49921. **
  49922. ** If the optimization was not enabled at compile time, then the
  49923. ** pager_incr_changecounter() function is called to update the change
  49924. ** counter in 'indirect-mode'. If the optimization is compiled in but
  49925. ** is not applicable to this transaction, call sqlite3JournalCreate()
  49926. ** to make sure the journal file has actually been created, then call
  49927. ** pager_incr_changecounter() to update the change-counter in indirect
  49928. ** mode.
  49929. **
  49930. ** Otherwise, if the optimization is both enabled and applicable,
  49931. ** then call pager_incr_changecounter() to update the change-counter
  49932. ** in 'direct' mode. In this case the journal file will never be
  49933. ** created for this transaction.
  49934. */
  49935. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  49936. PgHdr *pPg;
  49937. assert( isOpen(pPager->jfd)
  49938. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  49939. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  49940. );
  49941. if( !zMaster && isOpen(pPager->jfd)
  49942. && pPager->journalOff==jrnlBufferSize(pPager)
  49943. && pPager->dbSize>=pPager->dbOrigSize
  49944. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  49945. ){
  49946. /* Update the db file change counter via the direct-write method. The
  49947. ** following call will modify the in-memory representation of page 1
  49948. ** to include the updated change counter and then write page 1
  49949. ** directly to the database file. Because of the atomic-write
  49950. ** property of the host file-system, this is safe.
  49951. */
  49952. rc = pager_incr_changecounter(pPager, 1);
  49953. }else{
  49954. rc = sqlite3JournalCreate(pPager->jfd);
  49955. if( rc==SQLITE_OK ){
  49956. rc = pager_incr_changecounter(pPager, 0);
  49957. }
  49958. }
  49959. #else
  49960. rc = pager_incr_changecounter(pPager, 0);
  49961. #endif
  49962. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  49963. /* Write the master journal name into the journal file. If a master
  49964. ** journal file name has already been written to the journal file,
  49965. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  49966. */
  49967. rc = writeMasterJournal(pPager, zMaster);
  49968. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  49969. /* Sync the journal file and write all dirty pages to the database.
  49970. ** If the atomic-update optimization is being used, this sync will not
  49971. ** create the journal file or perform any real IO.
  49972. **
  49973. ** Because the change-counter page was just modified, unless the
  49974. ** atomic-update optimization is used it is almost certain that the
  49975. ** journal requires a sync here. However, in locking_mode=exclusive
  49976. ** on a system under memory pressure it is just possible that this is
  49977. ** not the case. In this case it is likely enough that the redundant
  49978. ** xSync() call will be changed to a no-op by the OS anyhow.
  49979. */
  49980. rc = syncJournal(pPager, 0);
  49981. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  49982. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  49983. if( rc!=SQLITE_OK ){
  49984. assert( rc!=SQLITE_IOERR_BLOCKED );
  49985. goto commit_phase_one_exit;
  49986. }
  49987. sqlite3PcacheCleanAll(pPager->pPCache);
  49988. /* If the file on disk is smaller than the database image, use
  49989. ** pager_truncate to grow the file here. This can happen if the database
  49990. ** image was extended as part of the current transaction and then the
  49991. ** last page in the db image moved to the free-list. In this case the
  49992. ** last page is never written out to disk, leaving the database file
  49993. ** undersized. Fix this now if it is the case. */
  49994. if( pPager->dbSize>pPager->dbFileSize ){
  49995. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  49996. assert( pPager->eState==PAGER_WRITER_DBMOD );
  49997. rc = pager_truncate(pPager, nNew);
  49998. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  49999. }
  50000. /* Finally, sync the database file. */
  50001. if( !noSync ){
  50002. rc = sqlite3PagerSync(pPager, zMaster);
  50003. }
  50004. IOTRACE(("DBSYNC %p\n", pPager))
  50005. }
  50006. }
  50007. commit_phase_one_exit:
  50008. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  50009. pPager->eState = PAGER_WRITER_FINISHED;
  50010. }
  50011. return rc;
  50012. }
  50013. /*
  50014. ** When this function is called, the database file has been completely
  50015. ** updated to reflect the changes made by the current transaction and
  50016. ** synced to disk. The journal file still exists in the file-system
  50017. ** though, and if a failure occurs at this point it will eventually
  50018. ** be used as a hot-journal and the current transaction rolled back.
  50019. **
  50020. ** This function finalizes the journal file, either by deleting,
  50021. ** truncating or partially zeroing it, so that it cannot be used
  50022. ** for hot-journal rollback. Once this is done the transaction is
  50023. ** irrevocably committed.
  50024. **
  50025. ** If an error occurs, an IO error code is returned and the pager
  50026. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  50027. */
  50028. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  50029. int rc = SQLITE_OK; /* Return code */
  50030. /* This routine should not be called if a prior error has occurred.
  50031. ** But if (due to a coding error elsewhere in the system) it does get
  50032. ** called, just return the same error code without doing anything. */
  50033. if( NEVER(pPager->errCode) ) return pPager->errCode;
  50034. assert( pPager->eState==PAGER_WRITER_LOCKED
  50035. || pPager->eState==PAGER_WRITER_FINISHED
  50036. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  50037. );
  50038. assert( assert_pager_state(pPager) );
  50039. /* An optimization. If the database was not actually modified during
  50040. ** this transaction, the pager is running in exclusive-mode and is
  50041. ** using persistent journals, then this function is a no-op.
  50042. **
  50043. ** The start of the journal file currently contains a single journal
  50044. ** header with the nRec field set to 0. If such a journal is used as
  50045. ** a hot-journal during hot-journal rollback, 0 changes will be made
  50046. ** to the database file. So there is no need to zero the journal
  50047. ** header. Since the pager is in exclusive mode, there is no need
  50048. ** to drop any locks either.
  50049. */
  50050. if( pPager->eState==PAGER_WRITER_LOCKED
  50051. && pPager->exclusiveMode
  50052. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  50053. ){
  50054. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  50055. pPager->eState = PAGER_READER;
  50056. return SQLITE_OK;
  50057. }
  50058. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  50059. pPager->iDataVersion++;
  50060. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  50061. return pager_error(pPager, rc);
  50062. }
  50063. /*
  50064. ** If a write transaction is open, then all changes made within the
  50065. ** transaction are reverted and the current write-transaction is closed.
  50066. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  50067. ** state if an error occurs.
  50068. **
  50069. ** If the pager is already in PAGER_ERROR state when this function is called,
  50070. ** it returns Pager.errCode immediately. No work is performed in this case.
  50071. **
  50072. ** Otherwise, in rollback mode, this function performs two functions:
  50073. **
  50074. ** 1) It rolls back the journal file, restoring all database file and
  50075. ** in-memory cache pages to the state they were in when the transaction
  50076. ** was opened, and
  50077. **
  50078. ** 2) It finalizes the journal file, so that it is not used for hot
  50079. ** rollback at any point in the future.
  50080. **
  50081. ** Finalization of the journal file (task 2) is only performed if the
  50082. ** rollback is successful.
  50083. **
  50084. ** In WAL mode, all cache-entries containing data modified within the
  50085. ** current transaction are either expelled from the cache or reverted to
  50086. ** their pre-transaction state by re-reading data from the database or
  50087. ** WAL files. The WAL transaction is then closed.
  50088. */
  50089. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  50090. int rc = SQLITE_OK; /* Return code */
  50091. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  50092. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  50093. ** the pager is already in the ERROR state, the rollback is not
  50094. ** attempted here. Instead, the error code is returned to the caller.
  50095. */
  50096. assert( assert_pager_state(pPager) );
  50097. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  50098. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  50099. if( pagerUseWal(pPager) ){
  50100. int rc2;
  50101. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  50102. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  50103. if( rc==SQLITE_OK ) rc = rc2;
  50104. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  50105. int eState = pPager->eState;
  50106. rc = pager_end_transaction(pPager, 0, 0);
  50107. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  50108. /* This can happen using journal_mode=off. Move the pager to the error
  50109. ** state to indicate that the contents of the cache may not be trusted.
  50110. ** Any active readers will get SQLITE_ABORT.
  50111. */
  50112. pPager->errCode = SQLITE_ABORT;
  50113. pPager->eState = PAGER_ERROR;
  50114. setGetterMethod(pPager);
  50115. return rc;
  50116. }
  50117. }else{
  50118. rc = pager_playback(pPager, 0);
  50119. }
  50120. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  50121. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  50122. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  50123. || rc==SQLITE_CANTOPEN
  50124. );
  50125. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  50126. ** cache. So call pager_error() on the way out to make any error persistent.
  50127. */
  50128. return pager_error(pPager, rc);
  50129. }
  50130. /*
  50131. ** Return TRUE if the database file is opened read-only. Return FALSE
  50132. ** if the database is (in theory) writable.
  50133. */
  50134. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  50135. return pPager->readOnly;
  50136. }
  50137. #ifdef SQLITE_DEBUG
  50138. /*
  50139. ** Return the sum of the reference counts for all pages held by pPager.
  50140. */
  50141. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  50142. return sqlite3PcacheRefCount(pPager->pPCache);
  50143. }
  50144. #endif
  50145. /*
  50146. ** Return the approximate number of bytes of memory currently
  50147. ** used by the pager and its associated cache.
  50148. */
  50149. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  50150. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  50151. + 5*sizeof(void*);
  50152. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  50153. + sqlite3MallocSize(pPager)
  50154. + pPager->pageSize;
  50155. }
  50156. /*
  50157. ** Return the number of references to the specified page.
  50158. */
  50159. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  50160. return sqlite3PcachePageRefcount(pPage);
  50161. }
  50162. #ifdef SQLITE_TEST
  50163. /*
  50164. ** This routine is used for testing and analysis only.
  50165. */
  50166. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  50167. static int a[11];
  50168. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  50169. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  50170. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  50171. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  50172. a[4] = pPager->eState;
  50173. a[5] = pPager->errCode;
  50174. a[6] = pPager->aStat[PAGER_STAT_HIT];
  50175. a[7] = pPager->aStat[PAGER_STAT_MISS];
  50176. a[8] = 0; /* Used to be pPager->nOvfl */
  50177. a[9] = pPager->nRead;
  50178. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  50179. return a;
  50180. }
  50181. #endif
  50182. /*
  50183. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  50184. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  50185. ** current cache hit or miss count, according to the value of eStat. If the
  50186. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  50187. ** returning.
  50188. */
  50189. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  50190. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  50191. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  50192. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  50193. );
  50194. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  50195. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  50196. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  50197. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  50198. if( reset ){
  50199. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  50200. }
  50201. }
  50202. /*
  50203. ** Return true if this is an in-memory or temp-file backed pager.
  50204. */
  50205. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  50206. return pPager->tempFile;
  50207. }
  50208. /*
  50209. ** Check that there are at least nSavepoint savepoints open. If there are
  50210. ** currently less than nSavepoints open, then open one or more savepoints
  50211. ** to make up the difference. If the number of savepoints is already
  50212. ** equal to nSavepoint, then this function is a no-op.
  50213. **
  50214. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  50215. ** occurs while opening the sub-journal file, then an IO error code is
  50216. ** returned. Otherwise, SQLITE_OK.
  50217. */
  50218. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  50219. int rc = SQLITE_OK; /* Return code */
  50220. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  50221. int ii; /* Iterator variable */
  50222. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  50223. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50224. assert( assert_pager_state(pPager) );
  50225. assert( nSavepoint>nCurrent && pPager->useJournal );
  50226. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  50227. ** if the allocation fails. Otherwise, zero the new portion in case a
  50228. ** malloc failure occurs while populating it in the for(...) loop below.
  50229. */
  50230. aNew = (PagerSavepoint *)sqlite3Realloc(
  50231. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  50232. );
  50233. if( !aNew ){
  50234. return SQLITE_NOMEM_BKPT;
  50235. }
  50236. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  50237. pPager->aSavepoint = aNew;
  50238. /* Populate the PagerSavepoint structures just allocated. */
  50239. for(ii=nCurrent; ii<nSavepoint; ii++){
  50240. aNew[ii].nOrig = pPager->dbSize;
  50241. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  50242. aNew[ii].iOffset = pPager->journalOff;
  50243. }else{
  50244. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  50245. }
  50246. aNew[ii].iSubRec = pPager->nSubRec;
  50247. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  50248. if( !aNew[ii].pInSavepoint ){
  50249. return SQLITE_NOMEM_BKPT;
  50250. }
  50251. if( pagerUseWal(pPager) ){
  50252. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  50253. }
  50254. pPager->nSavepoint = ii+1;
  50255. }
  50256. assert( pPager->nSavepoint==nSavepoint );
  50257. assertTruncateConstraint(pPager);
  50258. return rc;
  50259. }
  50260. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  50261. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50262. assert( assert_pager_state(pPager) );
  50263. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  50264. return pagerOpenSavepoint(pPager, nSavepoint);
  50265. }else{
  50266. return SQLITE_OK;
  50267. }
  50268. }
  50269. /*
  50270. ** This function is called to rollback or release (commit) a savepoint.
  50271. ** The savepoint to release or rollback need not be the most recently
  50272. ** created savepoint.
  50273. **
  50274. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  50275. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  50276. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  50277. ** that have occurred since the specified savepoint was created.
  50278. **
  50279. ** The savepoint to rollback or release is identified by parameter
  50280. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  50281. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  50282. ** on the most recently created savepoint. If iSavepoint is greater than
  50283. ** (Pager.nSavepoint-1), then this function is a no-op.
  50284. **
  50285. ** If a negative value is passed to this function, then the current
  50286. ** transaction is rolled back. This is different to calling
  50287. ** sqlite3PagerRollback() because this function does not terminate
  50288. ** the transaction or unlock the database, it just restores the
  50289. ** contents of the database to its original state.
  50290. **
  50291. ** In any case, all savepoints with an index greater than iSavepoint
  50292. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  50293. ** then savepoint iSavepoint is also destroyed.
  50294. **
  50295. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  50296. ** or an IO error code if an IO error occurs while rolling back a
  50297. ** savepoint. If no errors occur, SQLITE_OK is returned.
  50298. */
  50299. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  50300. int rc = pPager->errCode;
  50301. #ifdef SQLITE_ENABLE_ZIPVFS
  50302. if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
  50303. #endif
  50304. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  50305. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  50306. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  50307. int ii; /* Iterator variable */
  50308. int nNew; /* Number of remaining savepoints after this op. */
  50309. /* Figure out how many savepoints will still be active after this
  50310. ** operation. Store this value in nNew. Then free resources associated
  50311. ** with any savepoints that are destroyed by this operation.
  50312. */
  50313. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  50314. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  50315. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  50316. }
  50317. pPager->nSavepoint = nNew;
  50318. /* If this is a release of the outermost savepoint, truncate
  50319. ** the sub-journal to zero bytes in size. */
  50320. if( op==SAVEPOINT_RELEASE ){
  50321. if( nNew==0 && isOpen(pPager->sjfd) ){
  50322. /* Only truncate if it is an in-memory sub-journal. */
  50323. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  50324. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  50325. assert( rc==SQLITE_OK );
  50326. }
  50327. pPager->nSubRec = 0;
  50328. }
  50329. }
  50330. /* Else this is a rollback operation, playback the specified savepoint.
  50331. ** If this is a temp-file, it is possible that the journal file has
  50332. ** not yet been opened. In this case there have been no changes to
  50333. ** the database file, so the playback operation can be skipped.
  50334. */
  50335. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  50336. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  50337. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  50338. assert(rc!=SQLITE_DONE);
  50339. }
  50340. #ifdef SQLITE_ENABLE_ZIPVFS
  50341. /* If the cache has been modified but the savepoint cannot be rolled
  50342. ** back journal_mode=off, put the pager in the error state. This way,
  50343. ** if the VFS used by this pager includes ZipVFS, the entire transaction
  50344. ** can be rolled back at the ZipVFS level. */
  50345. else if(
  50346. pPager->journalMode==PAGER_JOURNALMODE_OFF
  50347. && pPager->eState>=PAGER_WRITER_CACHEMOD
  50348. ){
  50349. pPager->errCode = SQLITE_ABORT;
  50350. pPager->eState = PAGER_ERROR;
  50351. setGetterMethod(pPager);
  50352. }
  50353. #endif
  50354. }
  50355. return rc;
  50356. }
  50357. /*
  50358. ** Return the full pathname of the database file.
  50359. **
  50360. ** Except, if the pager is in-memory only, then return an empty string if
  50361. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  50362. ** used to report the filename to the user, for compatibility with legacy
  50363. ** behavior. But when the Btree needs to know the filename for matching to
  50364. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  50365. ** participate in shared-cache.
  50366. */
  50367. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  50368. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  50369. }
  50370. /*
  50371. ** Return the VFS structure for the pager.
  50372. */
  50373. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  50374. return pPager->pVfs;
  50375. }
  50376. /*
  50377. ** Return the file handle for the database file associated
  50378. ** with the pager. This might return NULL if the file has
  50379. ** not yet been opened.
  50380. */
  50381. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  50382. return pPager->fd;
  50383. }
  50384. /*
  50385. ** Return the file handle for the journal file (if it exists).
  50386. ** This will be either the rollback journal or the WAL file.
  50387. */
  50388. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  50389. #if SQLITE_OMIT_WAL
  50390. return pPager->jfd;
  50391. #else
  50392. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  50393. #endif
  50394. }
  50395. /*
  50396. ** Return the full pathname of the journal file.
  50397. */
  50398. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  50399. return pPager->zJournal;
  50400. }
  50401. #ifdef SQLITE_HAS_CODEC
  50402. /*
  50403. ** Set or retrieve the codec for this pager
  50404. */
  50405. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  50406. Pager *pPager,
  50407. void *(*xCodec)(void*,void*,Pgno,int),
  50408. void (*xCodecSizeChng)(void*,int,int),
  50409. void (*xCodecFree)(void*),
  50410. void *pCodec
  50411. ){
  50412. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  50413. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  50414. pPager->xCodecSizeChng = xCodecSizeChng;
  50415. pPager->xCodecFree = xCodecFree;
  50416. pPager->pCodec = pCodec;
  50417. setGetterMethod(pPager);
  50418. pagerReportSize(pPager);
  50419. }
  50420. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  50421. return pPager->pCodec;
  50422. }
  50423. /*
  50424. ** This function is called by the wal module when writing page content
  50425. ** into the log file.
  50426. **
  50427. ** This function returns a pointer to a buffer containing the encrypted
  50428. ** page content. If a malloc fails, this function may return NULL.
  50429. */
  50430. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  50431. void *aData = 0;
  50432. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  50433. return aData;
  50434. }
  50435. /*
  50436. ** Return the current pager state
  50437. */
  50438. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  50439. return pPager->eState;
  50440. }
  50441. #endif /* SQLITE_HAS_CODEC */
  50442. #ifndef SQLITE_OMIT_AUTOVACUUM
  50443. /*
  50444. ** Move the page pPg to location pgno in the file.
  50445. **
  50446. ** There must be no references to the page previously located at
  50447. ** pgno (which we call pPgOld) though that page is allowed to be
  50448. ** in cache. If the page previously located at pgno is not already
  50449. ** in the rollback journal, it is not put there by by this routine.
  50450. **
  50451. ** References to the page pPg remain valid. Updating any
  50452. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  50453. ** allocated along with the page) is the responsibility of the caller.
  50454. **
  50455. ** A transaction must be active when this routine is called. It used to be
  50456. ** required that a statement transaction was not active, but this restriction
  50457. ** has been removed (CREATE INDEX needs to move a page when a statement
  50458. ** transaction is active).
  50459. **
  50460. ** If the fourth argument, isCommit, is non-zero, then this page is being
  50461. ** moved as part of a database reorganization just before the transaction
  50462. ** is being committed. In this case, it is guaranteed that the database page
  50463. ** pPg refers to will not be written to again within this transaction.
  50464. **
  50465. ** This function may return SQLITE_NOMEM or an IO error code if an error
  50466. ** occurs. Otherwise, it returns SQLITE_OK.
  50467. */
  50468. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  50469. PgHdr *pPgOld; /* The page being overwritten. */
  50470. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  50471. int rc; /* Return code */
  50472. Pgno origPgno; /* The original page number */
  50473. assert( pPg->nRef>0 );
  50474. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  50475. || pPager->eState==PAGER_WRITER_DBMOD
  50476. );
  50477. assert( assert_pager_state(pPager) );
  50478. /* In order to be able to rollback, an in-memory database must journal
  50479. ** the page we are moving from.
  50480. */
  50481. assert( pPager->tempFile || !MEMDB );
  50482. if( pPager->tempFile ){
  50483. rc = sqlite3PagerWrite(pPg);
  50484. if( rc ) return rc;
  50485. }
  50486. /* If the page being moved is dirty and has not been saved by the latest
  50487. ** savepoint, then save the current contents of the page into the
  50488. ** sub-journal now. This is required to handle the following scenario:
  50489. **
  50490. ** BEGIN;
  50491. ** <journal page X, then modify it in memory>
  50492. ** SAVEPOINT one;
  50493. ** <Move page X to location Y>
  50494. ** ROLLBACK TO one;
  50495. **
  50496. ** If page X were not written to the sub-journal here, it would not
  50497. ** be possible to restore its contents when the "ROLLBACK TO one"
  50498. ** statement were is processed.
  50499. **
  50500. ** subjournalPage() may need to allocate space to store pPg->pgno into
  50501. ** one or more savepoint bitvecs. This is the reason this function
  50502. ** may return SQLITE_NOMEM.
  50503. */
  50504. if( (pPg->flags & PGHDR_DIRTY)!=0
  50505. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  50506. ){
  50507. return rc;
  50508. }
  50509. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  50510. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  50511. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  50512. /* If the journal needs to be sync()ed before page pPg->pgno can
  50513. ** be written to, store pPg->pgno in local variable needSyncPgno.
  50514. **
  50515. ** If the isCommit flag is set, there is no need to remember that
  50516. ** the journal needs to be sync()ed before database page pPg->pgno
  50517. ** can be written to. The caller has already promised not to write to it.
  50518. */
  50519. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  50520. needSyncPgno = pPg->pgno;
  50521. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  50522. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  50523. assert( pPg->flags&PGHDR_DIRTY );
  50524. }
  50525. /* If the cache contains a page with page-number pgno, remove it
  50526. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  50527. ** page pgno before the 'move' operation, it needs to be retained
  50528. ** for the page moved there.
  50529. */
  50530. pPg->flags &= ~PGHDR_NEED_SYNC;
  50531. pPgOld = sqlite3PagerLookup(pPager, pgno);
  50532. assert( !pPgOld || pPgOld->nRef==1 );
  50533. if( pPgOld ){
  50534. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  50535. if( pPager->tempFile ){
  50536. /* Do not discard pages from an in-memory database since we might
  50537. ** need to rollback later. Just move the page out of the way. */
  50538. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  50539. }else{
  50540. sqlite3PcacheDrop(pPgOld);
  50541. }
  50542. }
  50543. origPgno = pPg->pgno;
  50544. sqlite3PcacheMove(pPg, pgno);
  50545. sqlite3PcacheMakeDirty(pPg);
  50546. /* For an in-memory database, make sure the original page continues
  50547. ** to exist, in case the transaction needs to roll back. Use pPgOld
  50548. ** as the original page since it has already been allocated.
  50549. */
  50550. if( pPager->tempFile && pPgOld ){
  50551. sqlite3PcacheMove(pPgOld, origPgno);
  50552. sqlite3PagerUnrefNotNull(pPgOld);
  50553. }
  50554. if( needSyncPgno ){
  50555. /* If needSyncPgno is non-zero, then the journal file needs to be
  50556. ** sync()ed before any data is written to database file page needSyncPgno.
  50557. ** Currently, no such page exists in the page-cache and the
  50558. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  50559. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  50560. ** flag.
  50561. **
  50562. ** If the attempt to load the page into the page-cache fails, (due
  50563. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  50564. ** array. Otherwise, if the page is loaded and written again in
  50565. ** this transaction, it may be written to the database file before
  50566. ** it is synced into the journal file. This way, it may end up in
  50567. ** the journal file twice, but that is not a problem.
  50568. */
  50569. PgHdr *pPgHdr;
  50570. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  50571. if( rc!=SQLITE_OK ){
  50572. if( needSyncPgno<=pPager->dbOrigSize ){
  50573. assert( pPager->pTmpSpace!=0 );
  50574. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  50575. }
  50576. return rc;
  50577. }
  50578. pPgHdr->flags |= PGHDR_NEED_SYNC;
  50579. sqlite3PcacheMakeDirty(pPgHdr);
  50580. sqlite3PagerUnrefNotNull(pPgHdr);
  50581. }
  50582. return SQLITE_OK;
  50583. }
  50584. #endif
  50585. /*
  50586. ** The page handle passed as the first argument refers to a dirty page
  50587. ** with a page number other than iNew. This function changes the page's
  50588. ** page number to iNew and sets the value of the PgHdr.flags field to
  50589. ** the value passed as the third parameter.
  50590. */
  50591. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  50592. assert( pPg->pgno!=iNew );
  50593. pPg->flags = flags;
  50594. sqlite3PcacheMove(pPg, iNew);
  50595. }
  50596. /*
  50597. ** Return a pointer to the data for the specified page.
  50598. */
  50599. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  50600. assert( pPg->nRef>0 || pPg->pPager->memDb );
  50601. return pPg->pData;
  50602. }
  50603. /*
  50604. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  50605. ** allocated along with the specified page.
  50606. */
  50607. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  50608. return pPg->pExtra;
  50609. }
  50610. /*
  50611. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  50612. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  50613. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  50614. ** the locking-mode is set to the value specified.
  50615. **
  50616. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  50617. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  50618. ** locking-mode.
  50619. */
  50620. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  50621. assert( eMode==PAGER_LOCKINGMODE_QUERY
  50622. || eMode==PAGER_LOCKINGMODE_NORMAL
  50623. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  50624. assert( PAGER_LOCKINGMODE_QUERY<0 );
  50625. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  50626. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  50627. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  50628. pPager->exclusiveMode = (u8)eMode;
  50629. }
  50630. return (int)pPager->exclusiveMode;
  50631. }
  50632. /*
  50633. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  50634. **
  50635. ** PAGER_JOURNALMODE_DELETE
  50636. ** PAGER_JOURNALMODE_TRUNCATE
  50637. ** PAGER_JOURNALMODE_PERSIST
  50638. ** PAGER_JOURNALMODE_OFF
  50639. ** PAGER_JOURNALMODE_MEMORY
  50640. ** PAGER_JOURNALMODE_WAL
  50641. **
  50642. ** The journalmode is set to the value specified if the change is allowed.
  50643. ** The change may be disallowed for the following reasons:
  50644. **
  50645. ** * An in-memory database can only have its journal_mode set to _OFF
  50646. ** or _MEMORY.
  50647. **
  50648. ** * Temporary databases cannot have _WAL journalmode.
  50649. **
  50650. ** The returned indicate the current (possibly updated) journal-mode.
  50651. */
  50652. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  50653. u8 eOld = pPager->journalMode; /* Prior journalmode */
  50654. #ifdef SQLITE_DEBUG
  50655. /* The print_pager_state() routine is intended to be used by the debugger
  50656. ** only. We invoke it once here to suppress a compiler warning. */
  50657. print_pager_state(pPager);
  50658. #endif
  50659. /* The eMode parameter is always valid */
  50660. assert( eMode==PAGER_JOURNALMODE_DELETE
  50661. || eMode==PAGER_JOURNALMODE_TRUNCATE
  50662. || eMode==PAGER_JOURNALMODE_PERSIST
  50663. || eMode==PAGER_JOURNALMODE_OFF
  50664. || eMode==PAGER_JOURNALMODE_WAL
  50665. || eMode==PAGER_JOURNALMODE_MEMORY );
  50666. /* This routine is only called from the OP_JournalMode opcode, and
  50667. ** the logic there will never allow a temporary file to be changed
  50668. ** to WAL mode.
  50669. */
  50670. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  50671. /* Do allow the journalmode of an in-memory database to be set to
  50672. ** anything other than MEMORY or OFF
  50673. */
  50674. if( MEMDB ){
  50675. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  50676. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  50677. eMode = eOld;
  50678. }
  50679. }
  50680. if( eMode!=eOld ){
  50681. /* Change the journal mode. */
  50682. assert( pPager->eState!=PAGER_ERROR );
  50683. pPager->journalMode = (u8)eMode;
  50684. /* When transistioning from TRUNCATE or PERSIST to any other journal
  50685. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  50686. ** delete the journal file.
  50687. */
  50688. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  50689. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  50690. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  50691. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  50692. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  50693. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  50694. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  50695. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  50696. /* In this case we would like to delete the journal file. If it is
  50697. ** not possible, then that is not a problem. Deleting the journal file
  50698. ** here is an optimization only.
  50699. **
  50700. ** Before deleting the journal file, obtain a RESERVED lock on the
  50701. ** database file. This ensures that the journal file is not deleted
  50702. ** while it is in use by some other client.
  50703. */
  50704. sqlite3OsClose(pPager->jfd);
  50705. if( pPager->eLock>=RESERVED_LOCK ){
  50706. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  50707. }else{
  50708. int rc = SQLITE_OK;
  50709. int state = pPager->eState;
  50710. assert( state==PAGER_OPEN || state==PAGER_READER );
  50711. if( state==PAGER_OPEN ){
  50712. rc = sqlite3PagerSharedLock(pPager);
  50713. }
  50714. if( pPager->eState==PAGER_READER ){
  50715. assert( rc==SQLITE_OK );
  50716. rc = pagerLockDb(pPager, RESERVED_LOCK);
  50717. }
  50718. if( rc==SQLITE_OK ){
  50719. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  50720. }
  50721. if( rc==SQLITE_OK && state==PAGER_READER ){
  50722. pagerUnlockDb(pPager, SHARED_LOCK);
  50723. }else if( state==PAGER_OPEN ){
  50724. pager_unlock(pPager);
  50725. }
  50726. assert( state==pPager->eState );
  50727. }
  50728. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  50729. sqlite3OsClose(pPager->jfd);
  50730. }
  50731. }
  50732. /* Return the new journal mode */
  50733. return (int)pPager->journalMode;
  50734. }
  50735. /*
  50736. ** Return the current journal mode.
  50737. */
  50738. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  50739. return (int)pPager->journalMode;
  50740. }
  50741. /*
  50742. ** Return TRUE if the pager is in a state where it is OK to change the
  50743. ** journalmode. Journalmode changes can only happen when the database
  50744. ** is unmodified.
  50745. */
  50746. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  50747. assert( assert_pager_state(pPager) );
  50748. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  50749. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  50750. return 1;
  50751. }
  50752. /*
  50753. ** Get/set the size-limit used for persistent journal files.
  50754. **
  50755. ** Setting the size limit to -1 means no limit is enforced.
  50756. ** An attempt to set a limit smaller than -1 is a no-op.
  50757. */
  50758. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  50759. if( iLimit>=-1 ){
  50760. pPager->journalSizeLimit = iLimit;
  50761. sqlite3WalLimit(pPager->pWal, iLimit);
  50762. }
  50763. return pPager->journalSizeLimit;
  50764. }
  50765. /*
  50766. ** Return a pointer to the pPager->pBackup variable. The backup module
  50767. ** in backup.c maintains the content of this variable. This module
  50768. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  50769. ** sqlite3BackupUpdate() only.
  50770. */
  50771. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  50772. return &pPager->pBackup;
  50773. }
  50774. #ifndef SQLITE_OMIT_VACUUM
  50775. /*
  50776. ** Unless this is an in-memory or temporary database, clear the pager cache.
  50777. */
  50778. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  50779. assert( MEMDB==0 || pPager->tempFile );
  50780. if( pPager->tempFile==0 ) pager_reset(pPager);
  50781. }
  50782. #endif
  50783. #ifndef SQLITE_OMIT_WAL
  50784. /*
  50785. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  50786. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  50787. ** or wal_blocking_checkpoint() API functions.
  50788. **
  50789. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  50790. */
  50791. SQLITE_PRIVATE int sqlite3PagerCheckpoint(
  50792. Pager *pPager, /* Checkpoint on this pager */
  50793. sqlite3 *db, /* Db handle used to check for interrupts */
  50794. int eMode, /* Type of checkpoint */
  50795. int *pnLog, /* OUT: Final number of frames in log */
  50796. int *pnCkpt /* OUT: Final number of checkpointed frames */
  50797. ){
  50798. int rc = SQLITE_OK;
  50799. if( pPager->pWal ){
  50800. rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
  50801. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  50802. pPager->pBusyHandlerArg,
  50803. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  50804. pnLog, pnCkpt
  50805. );
  50806. }
  50807. return rc;
  50808. }
  50809. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  50810. return sqlite3WalCallback(pPager->pWal);
  50811. }
  50812. /*
  50813. ** Return true if the underlying VFS for the given pager supports the
  50814. ** primitives necessary for write-ahead logging.
  50815. */
  50816. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  50817. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  50818. if( pPager->noLock ) return 0;
  50819. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  50820. }
  50821. /*
  50822. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  50823. ** is obtained instead, immediately release it.
  50824. */
  50825. static int pagerExclusiveLock(Pager *pPager){
  50826. int rc; /* Return code */
  50827. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  50828. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  50829. if( rc!=SQLITE_OK ){
  50830. /* If the attempt to grab the exclusive lock failed, release the
  50831. ** pending lock that may have been obtained instead. */
  50832. pagerUnlockDb(pPager, SHARED_LOCK);
  50833. }
  50834. return rc;
  50835. }
  50836. /*
  50837. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  50838. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  50839. ** lock on the database file and use heap-memory to store the wal-index
  50840. ** in. Otherwise, use the normal shared-memory.
  50841. */
  50842. static int pagerOpenWal(Pager *pPager){
  50843. int rc = SQLITE_OK;
  50844. assert( pPager->pWal==0 && pPager->tempFile==0 );
  50845. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  50846. /* If the pager is already in exclusive-mode, the WAL module will use
  50847. ** heap-memory for the wal-index instead of the VFS shared-memory
  50848. ** implementation. Take the exclusive lock now, before opening the WAL
  50849. ** file, to make sure this is safe.
  50850. */
  50851. if( pPager->exclusiveMode ){
  50852. rc = pagerExclusiveLock(pPager);
  50853. }
  50854. /* Open the connection to the log file. If this operation fails,
  50855. ** (e.g. due to malloc() failure), return an error code.
  50856. */
  50857. if( rc==SQLITE_OK ){
  50858. rc = sqlite3WalOpen(pPager->pVfs,
  50859. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  50860. pPager->journalSizeLimit, &pPager->pWal
  50861. );
  50862. }
  50863. pagerFixMaplimit(pPager);
  50864. return rc;
  50865. }
  50866. /*
  50867. ** The caller must be holding a SHARED lock on the database file to call
  50868. ** this function.
  50869. **
  50870. ** If the pager passed as the first argument is open on a real database
  50871. ** file (not a temp file or an in-memory database), and the WAL file
  50872. ** is not already open, make an attempt to open it now. If successful,
  50873. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  50874. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  50875. ** not modified in either case.
  50876. **
  50877. ** If the pager is open on a temp-file (or in-memory database), or if
  50878. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  50879. ** without doing anything.
  50880. */
  50881. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  50882. Pager *pPager, /* Pager object */
  50883. int *pbOpen /* OUT: Set to true if call is a no-op */
  50884. ){
  50885. int rc = SQLITE_OK; /* Return code */
  50886. assert( assert_pager_state(pPager) );
  50887. assert( pPager->eState==PAGER_OPEN || pbOpen );
  50888. assert( pPager->eState==PAGER_READER || !pbOpen );
  50889. assert( pbOpen==0 || *pbOpen==0 );
  50890. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  50891. if( !pPager->tempFile && !pPager->pWal ){
  50892. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  50893. /* Close any rollback journal previously open */
  50894. sqlite3OsClose(pPager->jfd);
  50895. rc = pagerOpenWal(pPager);
  50896. if( rc==SQLITE_OK ){
  50897. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  50898. pPager->eState = PAGER_OPEN;
  50899. }
  50900. }else{
  50901. *pbOpen = 1;
  50902. }
  50903. return rc;
  50904. }
  50905. /*
  50906. ** This function is called to close the connection to the log file prior
  50907. ** to switching from WAL to rollback mode.
  50908. **
  50909. ** Before closing the log file, this function attempts to take an
  50910. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  50911. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  50912. ** If successful, the EXCLUSIVE lock is not released before returning.
  50913. */
  50914. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  50915. int rc = SQLITE_OK;
  50916. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  50917. /* If the log file is not already open, but does exist in the file-system,
  50918. ** it may need to be checkpointed before the connection can switch to
  50919. ** rollback mode. Open it now so this can happen.
  50920. */
  50921. if( !pPager->pWal ){
  50922. int logexists = 0;
  50923. rc = pagerLockDb(pPager, SHARED_LOCK);
  50924. if( rc==SQLITE_OK ){
  50925. rc = sqlite3OsAccess(
  50926. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  50927. );
  50928. }
  50929. if( rc==SQLITE_OK && logexists ){
  50930. rc = pagerOpenWal(pPager);
  50931. }
  50932. }
  50933. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  50934. ** the database file, the log and log-summary files will be deleted.
  50935. */
  50936. if( rc==SQLITE_OK && pPager->pWal ){
  50937. rc = pagerExclusiveLock(pPager);
  50938. if( rc==SQLITE_OK ){
  50939. rc = sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags,
  50940. pPager->pageSize, (u8*)pPager->pTmpSpace);
  50941. pPager->pWal = 0;
  50942. pagerFixMaplimit(pPager);
  50943. if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  50944. }
  50945. }
  50946. return rc;
  50947. }
  50948. #ifdef SQLITE_ENABLE_SNAPSHOT
  50949. /*
  50950. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  50951. ** currently open. Otherwise, return an error.
  50952. */
  50953. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  50954. int rc = SQLITE_ERROR;
  50955. if( pPager->pWal ){
  50956. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  50957. }
  50958. return rc;
  50959. }
  50960. /*
  50961. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  50962. ** read transaction is opened, attempt to read from the snapshot it
  50963. ** identifies. If this is not a WAL database, return an error.
  50964. */
  50965. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  50966. int rc = SQLITE_OK;
  50967. if( pPager->pWal ){
  50968. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  50969. }else{
  50970. rc = SQLITE_ERROR;
  50971. }
  50972. return rc;
  50973. }
  50974. /*
  50975. ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
  50976. ** is not a WAL database, return an error.
  50977. */
  50978. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
  50979. int rc;
  50980. if( pPager->pWal ){
  50981. rc = sqlite3WalSnapshotRecover(pPager->pWal);
  50982. }else{
  50983. rc = SQLITE_ERROR;
  50984. }
  50985. return rc;
  50986. }
  50987. #endif /* SQLITE_ENABLE_SNAPSHOT */
  50988. #endif /* !SQLITE_OMIT_WAL */
  50989. #ifdef SQLITE_ENABLE_ZIPVFS
  50990. /*
  50991. ** A read-lock must be held on the pager when this function is called. If
  50992. ** the pager is in WAL mode and the WAL file currently contains one or more
  50993. ** frames, return the size in bytes of the page images stored within the
  50994. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  50995. ** is empty, return 0.
  50996. */
  50997. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  50998. assert( pPager->eState>=PAGER_READER );
  50999. return sqlite3WalFramesize(pPager->pWal);
  51000. }
  51001. #endif
  51002. #endif /* SQLITE_OMIT_DISKIO */
  51003. /************** End of pager.c ***********************************************/
  51004. /************** Begin file wal.c *********************************************/
  51005. /*
  51006. ** 2010 February 1
  51007. **
  51008. ** The author disclaims copyright to this source code. In place of
  51009. ** a legal notice, here is a blessing:
  51010. **
  51011. ** May you do good and not evil.
  51012. ** May you find forgiveness for yourself and forgive others.
  51013. ** May you share freely, never taking more than you give.
  51014. **
  51015. *************************************************************************
  51016. **
  51017. ** This file contains the implementation of a write-ahead log (WAL) used in
  51018. ** "journal_mode=WAL" mode.
  51019. **
  51020. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  51021. **
  51022. ** A WAL file consists of a header followed by zero or more "frames".
  51023. ** Each frame records the revised content of a single page from the
  51024. ** database file. All changes to the database are recorded by writing
  51025. ** frames into the WAL. Transactions commit when a frame is written that
  51026. ** contains a commit marker. A single WAL can and usually does record
  51027. ** multiple transactions. Periodically, the content of the WAL is
  51028. ** transferred back into the database file in an operation called a
  51029. ** "checkpoint".
  51030. **
  51031. ** A single WAL file can be used multiple times. In other words, the
  51032. ** WAL can fill up with frames and then be checkpointed and then new
  51033. ** frames can overwrite the old ones. A WAL always grows from beginning
  51034. ** toward the end. Checksums and counters attached to each frame are
  51035. ** used to determine which frames within the WAL are valid and which
  51036. ** are leftovers from prior checkpoints.
  51037. **
  51038. ** The WAL header is 32 bytes in size and consists of the following eight
  51039. ** big-endian 32-bit unsigned integer values:
  51040. **
  51041. ** 0: Magic number. 0x377f0682 or 0x377f0683
  51042. ** 4: File format version. Currently 3007000
  51043. ** 8: Database page size. Example: 1024
  51044. ** 12: Checkpoint sequence number
  51045. ** 16: Salt-1, random integer incremented with each checkpoint
  51046. ** 20: Salt-2, a different random integer changing with each ckpt
  51047. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  51048. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  51049. **
  51050. ** Immediately following the wal-header are zero or more frames. Each
  51051. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  51052. ** of page data. The frame-header is six big-endian 32-bit unsigned
  51053. ** integer values, as follows:
  51054. **
  51055. ** 0: Page number.
  51056. ** 4: For commit records, the size of the database image in pages
  51057. ** after the commit. For all other records, zero.
  51058. ** 8: Salt-1 (copied from the header)
  51059. ** 12: Salt-2 (copied from the header)
  51060. ** 16: Checksum-1.
  51061. ** 20: Checksum-2.
  51062. **
  51063. ** A frame is considered valid if and only if the following conditions are
  51064. ** true:
  51065. **
  51066. ** (1) The salt-1 and salt-2 values in the frame-header match
  51067. ** salt values in the wal-header
  51068. **
  51069. ** (2) The checksum values in the final 8 bytes of the frame-header
  51070. ** exactly match the checksum computed consecutively on the
  51071. ** WAL header and the first 8 bytes and the content of all frames
  51072. ** up to and including the current frame.
  51073. **
  51074. ** The checksum is computed using 32-bit big-endian integers if the
  51075. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  51076. ** is computed using little-endian if the magic number is 0x377f0682.
  51077. ** The checksum values are always stored in the frame header in a
  51078. ** big-endian format regardless of which byte order is used to compute
  51079. ** the checksum. The checksum is computed by interpreting the input as
  51080. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  51081. ** algorithm used for the checksum is as follows:
  51082. **
  51083. ** for i from 0 to n-1 step 2:
  51084. ** s0 += x[i] + s1;
  51085. ** s1 += x[i+1] + s0;
  51086. ** endfor
  51087. **
  51088. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  51089. ** in reverse order (the largest fibonacci weight occurs on the first element
  51090. ** of the sequence being summed.) The s1 value spans all 32-bit
  51091. ** terms of the sequence whereas s0 omits the final term.
  51092. **
  51093. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  51094. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  51095. ** The VFS.xSync operations serve as write barriers - all writes launched
  51096. ** before the xSync must complete before any write that launches after the
  51097. ** xSync begins.
  51098. **
  51099. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  51100. ** value is randomized. This prevents old and new frames in the WAL from
  51101. ** being considered valid at the same time and being checkpointing together
  51102. ** following a crash.
  51103. **
  51104. ** READER ALGORITHM
  51105. **
  51106. ** To read a page from the database (call it page number P), a reader
  51107. ** first checks the WAL to see if it contains page P. If so, then the
  51108. ** last valid instance of page P that is a followed by a commit frame
  51109. ** or is a commit frame itself becomes the value read. If the WAL
  51110. ** contains no copies of page P that are valid and which are a commit
  51111. ** frame or are followed by a commit frame, then page P is read from
  51112. ** the database file.
  51113. **
  51114. ** To start a read transaction, the reader records the index of the last
  51115. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  51116. ** for all subsequent read operations. New transactions can be appended
  51117. ** to the WAL, but as long as the reader uses its original mxFrame value
  51118. ** and ignores the newly appended content, it will see a consistent snapshot
  51119. ** of the database from a single point in time. This technique allows
  51120. ** multiple concurrent readers to view different versions of the database
  51121. ** content simultaneously.
  51122. **
  51123. ** The reader algorithm in the previous paragraphs works correctly, but
  51124. ** because frames for page P can appear anywhere within the WAL, the
  51125. ** reader has to scan the entire WAL looking for page P frames. If the
  51126. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  51127. ** and read performance suffers. To overcome this problem, a separate
  51128. ** data structure called the wal-index is maintained to expedite the
  51129. ** search for frames of a particular page.
  51130. **
  51131. ** WAL-INDEX FORMAT
  51132. **
  51133. ** Conceptually, the wal-index is shared memory, though VFS implementations
  51134. ** might choose to implement the wal-index using a mmapped file. Because
  51135. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  51136. ** on a network filesystem. All users of the database must be able to
  51137. ** share memory.
  51138. **
  51139. ** The wal-index is transient. After a crash, the wal-index can (and should
  51140. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  51141. ** to either truncate or zero the header of the wal-index when the last
  51142. ** connection to it closes. Because the wal-index is transient, it can
  51143. ** use an architecture-specific format; it does not have to be cross-platform.
  51144. ** Hence, unlike the database and WAL file formats which store all values
  51145. ** as big endian, the wal-index can store multi-byte values in the native
  51146. ** byte order of the host computer.
  51147. **
  51148. ** The purpose of the wal-index is to answer this question quickly: Given
  51149. ** a page number P and a maximum frame index M, return the index of the
  51150. ** last frame in the wal before frame M for page P in the WAL, or return
  51151. ** NULL if there are no frames for page P in the WAL prior to M.
  51152. **
  51153. ** The wal-index consists of a header region, followed by an one or
  51154. ** more index blocks.
  51155. **
  51156. ** The wal-index header contains the total number of frames within the WAL
  51157. ** in the mxFrame field.
  51158. **
  51159. ** Each index block except for the first contains information on
  51160. ** HASHTABLE_NPAGE frames. The first index block contains information on
  51161. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  51162. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  51163. ** first index block are the same size as all other index blocks in the
  51164. ** wal-index.
  51165. **
  51166. ** Each index block contains two sections, a page-mapping that contains the
  51167. ** database page number associated with each wal frame, and a hash-table
  51168. ** that allows readers to query an index block for a specific page number.
  51169. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  51170. ** for the first index block) 32-bit page numbers. The first entry in the
  51171. ** first index-block contains the database page number corresponding to the
  51172. ** first frame in the WAL file. The first entry in the second index block
  51173. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  51174. ** the log, and so on.
  51175. **
  51176. ** The last index block in a wal-index usually contains less than the full
  51177. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  51178. ** depending on the contents of the WAL file. This does not change the
  51179. ** allocated size of the page-mapping array - the page-mapping array merely
  51180. ** contains unused entries.
  51181. **
  51182. ** Even without using the hash table, the last frame for page P
  51183. ** can be found by scanning the page-mapping sections of each index block
  51184. ** starting with the last index block and moving toward the first, and
  51185. ** within each index block, starting at the end and moving toward the
  51186. ** beginning. The first entry that equals P corresponds to the frame
  51187. ** holding the content for that page.
  51188. **
  51189. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  51190. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  51191. ** hash table for each page number in the mapping section, so the hash
  51192. ** table is never more than half full. The expected number of collisions
  51193. ** prior to finding a match is 1. Each entry of the hash table is an
  51194. ** 1-based index of an entry in the mapping section of the same
  51195. ** index block. Let K be the 1-based index of the largest entry in
  51196. ** the mapping section. (For index blocks other than the last, K will
  51197. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  51198. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  51199. ** contain a value of 0.
  51200. **
  51201. ** To look for page P in the hash table, first compute a hash iKey on
  51202. ** P as follows:
  51203. **
  51204. ** iKey = (P * 383) % HASHTABLE_NSLOT
  51205. **
  51206. ** Then start scanning entries of the hash table, starting with iKey
  51207. ** (wrapping around to the beginning when the end of the hash table is
  51208. ** reached) until an unused hash slot is found. Let the first unused slot
  51209. ** be at index iUnused. (iUnused might be less than iKey if there was
  51210. ** wrap-around.) Because the hash table is never more than half full,
  51211. ** the search is guaranteed to eventually hit an unused entry. Let
  51212. ** iMax be the value between iKey and iUnused, closest to iUnused,
  51213. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  51214. ** no hash slot such that aHash[i]==p) then page P is not in the
  51215. ** current index block. Otherwise the iMax-th mapping entry of the
  51216. ** current index block corresponds to the last entry that references
  51217. ** page P.
  51218. **
  51219. ** A hash search begins with the last index block and moves toward the
  51220. ** first index block, looking for entries corresponding to page P. On
  51221. ** average, only two or three slots in each index block need to be
  51222. ** examined in order to either find the last entry for page P, or to
  51223. ** establish that no such entry exists in the block. Each index block
  51224. ** holds over 4000 entries. So two or three index blocks are sufficient
  51225. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  51226. ** comparisons (on average) suffice to either locate a frame in the
  51227. ** WAL or to establish that the frame does not exist in the WAL. This
  51228. ** is much faster than scanning the entire 10MB WAL.
  51229. **
  51230. ** Note that entries are added in order of increasing K. Hence, one
  51231. ** reader might be using some value K0 and a second reader that started
  51232. ** at a later time (after additional transactions were added to the WAL
  51233. ** and to the wal-index) might be using a different value K1, where K1>K0.
  51234. ** Both readers can use the same hash table and mapping section to get
  51235. ** the correct result. There may be entries in the hash table with
  51236. ** K>K0 but to the first reader, those entries will appear to be unused
  51237. ** slots in the hash table and so the first reader will get an answer as
  51238. ** if no values greater than K0 had ever been inserted into the hash table
  51239. ** in the first place - which is what reader one wants. Meanwhile, the
  51240. ** second reader using K1 will see additional values that were inserted
  51241. ** later, which is exactly what reader two wants.
  51242. **
  51243. ** When a rollback occurs, the value of K is decreased. Hash table entries
  51244. ** that correspond to frames greater than the new K value are removed
  51245. ** from the hash table at this point.
  51246. */
  51247. #ifndef SQLITE_OMIT_WAL
  51248. /* #include "wal.h" */
  51249. /*
  51250. ** Trace output macros
  51251. */
  51252. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  51253. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  51254. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  51255. #else
  51256. # define WALTRACE(X)
  51257. #endif
  51258. /*
  51259. ** The maximum (and only) versions of the wal and wal-index formats
  51260. ** that may be interpreted by this version of SQLite.
  51261. **
  51262. ** If a client begins recovering a WAL file and finds that (a) the checksum
  51263. ** values in the wal-header are correct and (b) the version field is not
  51264. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  51265. **
  51266. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  51267. ** checksum test is successful) and finds that the version field is not
  51268. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  51269. ** returns SQLITE_CANTOPEN.
  51270. */
  51271. #define WAL_MAX_VERSION 3007000
  51272. #define WALINDEX_MAX_VERSION 3007000
  51273. /*
  51274. ** Indices of various locking bytes. WAL_NREADER is the number
  51275. ** of available reader locks and should be at least 3. The default
  51276. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  51277. */
  51278. #define WAL_WRITE_LOCK 0
  51279. #define WAL_ALL_BUT_WRITE 1
  51280. #define WAL_CKPT_LOCK 1
  51281. #define WAL_RECOVER_LOCK 2
  51282. #define WAL_READ_LOCK(I) (3+(I))
  51283. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  51284. /* Object declarations */
  51285. typedef struct WalIndexHdr WalIndexHdr;
  51286. typedef struct WalIterator WalIterator;
  51287. typedef struct WalCkptInfo WalCkptInfo;
  51288. /*
  51289. ** The following object holds a copy of the wal-index header content.
  51290. **
  51291. ** The actual header in the wal-index consists of two copies of this
  51292. ** object followed by one instance of the WalCkptInfo object.
  51293. ** For all versions of SQLite through 3.10.0 and probably beyond,
  51294. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  51295. ** the total header size is 136 bytes.
  51296. **
  51297. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  51298. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  51299. ** added in 3.7.1 when support for 64K pages was added.
  51300. */
  51301. struct WalIndexHdr {
  51302. u32 iVersion; /* Wal-index version */
  51303. u32 unused; /* Unused (padding) field */
  51304. u32 iChange; /* Counter incremented each transaction */
  51305. u8 isInit; /* 1 when initialized */
  51306. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  51307. u16 szPage; /* Database page size in bytes. 1==64K */
  51308. u32 mxFrame; /* Index of last valid frame in the WAL */
  51309. u32 nPage; /* Size of database in pages */
  51310. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  51311. u32 aSalt[2]; /* Two salt values copied from WAL header */
  51312. u32 aCksum[2]; /* Checksum over all prior fields */
  51313. };
  51314. /*
  51315. ** A copy of the following object occurs in the wal-index immediately
  51316. ** following the second copy of the WalIndexHdr. This object stores
  51317. ** information used by checkpoint.
  51318. **
  51319. ** nBackfill is the number of frames in the WAL that have been written
  51320. ** back into the database. (We call the act of moving content from WAL to
  51321. ** database "backfilling".) The nBackfill number is never greater than
  51322. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  51323. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  51324. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  51325. ** mxFrame back to zero when the WAL is reset.
  51326. **
  51327. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  51328. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  51329. ** the nBackfillAttempted is set before any backfilling is done and the
  51330. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  51331. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  51332. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  51333. **
  51334. ** The aLock[] field is a set of bytes used for locking. These bytes should
  51335. ** never be read or written.
  51336. **
  51337. ** There is one entry in aReadMark[] for each reader lock. If a reader
  51338. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  51339. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  51340. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  51341. ** a special case; its value is never used and it exists as a place-holder
  51342. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  51343. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  51344. ** directly from the database.
  51345. **
  51346. ** The value of aReadMark[K] may only be changed by a thread that
  51347. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  51348. ** aReadMark[K] cannot changed while there is a reader is using that mark
  51349. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  51350. **
  51351. ** The checkpointer may only transfer frames from WAL to database where
  51352. ** the frame numbers are less than or equal to every aReadMark[] that is
  51353. ** in use (that is, every aReadMark[j] for which there is a corresponding
  51354. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  51355. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  51356. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  51357. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  51358. ** in the WAL has been backfilled into the database) then new readers
  51359. ** will choose aReadMark[0] which has value 0 and hence such reader will
  51360. ** get all their all content directly from the database file and ignore
  51361. ** the WAL.
  51362. **
  51363. ** Writers normally append new frames to the end of the WAL. However,
  51364. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  51365. ** written back into the database) and if no readers are using the WAL
  51366. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  51367. ** the writer will first "reset" the WAL back to the beginning and start
  51368. ** writing new content beginning at frame 1.
  51369. **
  51370. ** We assume that 32-bit loads are atomic and so no locks are needed in
  51371. ** order to read from any aReadMark[] entries.
  51372. */
  51373. struct WalCkptInfo {
  51374. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  51375. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  51376. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  51377. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  51378. u32 notUsed0; /* Available for future enhancements */
  51379. };
  51380. #define READMARK_NOT_USED 0xffffffff
  51381. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  51382. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  51383. ** only support mandatory file-locks, we do not read or write data
  51384. ** from the region of the file on which locks are applied.
  51385. */
  51386. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  51387. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  51388. /* Size of header before each frame in wal */
  51389. #define WAL_FRAME_HDRSIZE 24
  51390. /* Size of write ahead log header, including checksum. */
  51391. /* #define WAL_HDRSIZE 24 */
  51392. #define WAL_HDRSIZE 32
  51393. /* WAL magic value. Either this value, or the same value with the least
  51394. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  51395. ** big-endian format in the first 4 bytes of a WAL file.
  51396. **
  51397. ** If the LSB is set, then the checksums for each frame within the WAL
  51398. ** file are calculated by treating all data as an array of 32-bit
  51399. ** big-endian words. Otherwise, they are calculated by interpreting
  51400. ** all data as 32-bit little-endian words.
  51401. */
  51402. #define WAL_MAGIC 0x377f0682
  51403. /*
  51404. ** Return the offset of frame iFrame in the write-ahead log file,
  51405. ** assuming a database page size of szPage bytes. The offset returned
  51406. ** is to the start of the write-ahead log frame-header.
  51407. */
  51408. #define walFrameOffset(iFrame, szPage) ( \
  51409. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  51410. )
  51411. /*
  51412. ** An open write-ahead log file is represented by an instance of the
  51413. ** following object.
  51414. */
  51415. struct Wal {
  51416. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  51417. sqlite3_file *pDbFd; /* File handle for the database file */
  51418. sqlite3_file *pWalFd; /* File handle for WAL file */
  51419. u32 iCallback; /* Value to pass to log callback (or 0) */
  51420. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  51421. int nWiData; /* Size of array apWiData */
  51422. int szFirstBlock; /* Size of first block written to WAL file */
  51423. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  51424. u32 szPage; /* Database page size */
  51425. i16 readLock; /* Which read lock is being held. -1 for none */
  51426. u8 syncFlags; /* Flags to use to sync header writes */
  51427. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  51428. u8 writeLock; /* True if in a write transaction */
  51429. u8 ckptLock; /* True if holding a checkpoint lock */
  51430. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  51431. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  51432. u8 syncHeader; /* Fsync the WAL header if true */
  51433. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  51434. WalIndexHdr hdr; /* Wal-index header for current transaction */
  51435. u32 minFrame; /* Ignore wal frames before this one */
  51436. u32 iReCksum; /* On commit, recalculate checksums from here */
  51437. const char *zWalName; /* Name of WAL file */
  51438. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  51439. #ifdef SQLITE_DEBUG
  51440. u8 lockError; /* True if a locking error has occurred */
  51441. #endif
  51442. #ifdef SQLITE_ENABLE_SNAPSHOT
  51443. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  51444. #endif
  51445. };
  51446. /*
  51447. ** Candidate values for Wal.exclusiveMode.
  51448. */
  51449. #define WAL_NORMAL_MODE 0
  51450. #define WAL_EXCLUSIVE_MODE 1
  51451. #define WAL_HEAPMEMORY_MODE 2
  51452. /*
  51453. ** Possible values for WAL.readOnly
  51454. */
  51455. #define WAL_RDWR 0 /* Normal read/write connection */
  51456. #define WAL_RDONLY 1 /* The WAL file is readonly */
  51457. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  51458. /*
  51459. ** Each page of the wal-index mapping contains a hash-table made up of
  51460. ** an array of HASHTABLE_NSLOT elements of the following type.
  51461. */
  51462. typedef u16 ht_slot;
  51463. /*
  51464. ** This structure is used to implement an iterator that loops through
  51465. ** all frames in the WAL in database page order. Where two or more frames
  51466. ** correspond to the same database page, the iterator visits only the
  51467. ** frame most recently written to the WAL (in other words, the frame with
  51468. ** the largest index).
  51469. **
  51470. ** The internals of this structure are only accessed by:
  51471. **
  51472. ** walIteratorInit() - Create a new iterator,
  51473. ** walIteratorNext() - Step an iterator,
  51474. ** walIteratorFree() - Free an iterator.
  51475. **
  51476. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  51477. */
  51478. struct WalIterator {
  51479. int iPrior; /* Last result returned from the iterator */
  51480. int nSegment; /* Number of entries in aSegment[] */
  51481. struct WalSegment {
  51482. int iNext; /* Next slot in aIndex[] not yet returned */
  51483. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  51484. u32 *aPgno; /* Array of page numbers. */
  51485. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  51486. int iZero; /* Frame number associated with aPgno[0] */
  51487. } aSegment[1]; /* One for every 32KB page in the wal-index */
  51488. };
  51489. /*
  51490. ** Define the parameters of the hash tables in the wal-index file. There
  51491. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  51492. ** wal-index.
  51493. **
  51494. ** Changing any of these constants will alter the wal-index format and
  51495. ** create incompatibilities.
  51496. */
  51497. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  51498. #define HASHTABLE_HASH_1 383 /* Should be prime */
  51499. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  51500. /*
  51501. ** The block of page numbers associated with the first hash-table in a
  51502. ** wal-index is smaller than usual. This is so that there is a complete
  51503. ** hash-table on each aligned 32KB page of the wal-index.
  51504. */
  51505. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  51506. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  51507. #define WALINDEX_PGSZ ( \
  51508. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  51509. )
  51510. /*
  51511. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  51512. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  51513. ** numbered from zero.
  51514. **
  51515. ** If this call is successful, *ppPage is set to point to the wal-index
  51516. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  51517. ** then an SQLite error code is returned and *ppPage is set to 0.
  51518. */
  51519. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  51520. int rc = SQLITE_OK;
  51521. /* Enlarge the pWal->apWiData[] array if required */
  51522. if( pWal->nWiData<=iPage ){
  51523. int nByte = sizeof(u32*)*(iPage+1);
  51524. volatile u32 **apNew;
  51525. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  51526. if( !apNew ){
  51527. *ppPage = 0;
  51528. return SQLITE_NOMEM_BKPT;
  51529. }
  51530. memset((void*)&apNew[pWal->nWiData], 0,
  51531. sizeof(u32*)*(iPage+1-pWal->nWiData));
  51532. pWal->apWiData = apNew;
  51533. pWal->nWiData = iPage+1;
  51534. }
  51535. /* Request a pointer to the required page from the VFS */
  51536. if( pWal->apWiData[iPage]==0 ){
  51537. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  51538. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  51539. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  51540. }else{
  51541. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  51542. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  51543. );
  51544. if( rc==SQLITE_READONLY ){
  51545. pWal->readOnly |= WAL_SHM_RDONLY;
  51546. rc = SQLITE_OK;
  51547. }
  51548. }
  51549. }
  51550. *ppPage = pWal->apWiData[iPage];
  51551. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  51552. return rc;
  51553. }
  51554. /*
  51555. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  51556. */
  51557. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  51558. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  51559. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  51560. }
  51561. /*
  51562. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  51563. */
  51564. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  51565. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  51566. return (volatile WalIndexHdr*)pWal->apWiData[0];
  51567. }
  51568. /*
  51569. ** The argument to this macro must be of type u32. On a little-endian
  51570. ** architecture, it returns the u32 value that results from interpreting
  51571. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  51572. ** returns the value that would be produced by interpreting the 4 bytes
  51573. ** of the input value as a little-endian integer.
  51574. */
  51575. #define BYTESWAP32(x) ( \
  51576. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  51577. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  51578. )
  51579. /*
  51580. ** Generate or extend an 8 byte checksum based on the data in
  51581. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  51582. ** initial values of 0 and 0 if aIn==NULL).
  51583. **
  51584. ** The checksum is written back into aOut[] before returning.
  51585. **
  51586. ** nByte must be a positive multiple of 8.
  51587. */
  51588. static void walChecksumBytes(
  51589. int nativeCksum, /* True for native byte-order, false for non-native */
  51590. u8 *a, /* Content to be checksummed */
  51591. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  51592. const u32 *aIn, /* Initial checksum value input */
  51593. u32 *aOut /* OUT: Final checksum value output */
  51594. ){
  51595. u32 s1, s2;
  51596. u32 *aData = (u32 *)a;
  51597. u32 *aEnd = (u32 *)&a[nByte];
  51598. if( aIn ){
  51599. s1 = aIn[0];
  51600. s2 = aIn[1];
  51601. }else{
  51602. s1 = s2 = 0;
  51603. }
  51604. assert( nByte>=8 );
  51605. assert( (nByte&0x00000007)==0 );
  51606. if( nativeCksum ){
  51607. do {
  51608. s1 += *aData++ + s2;
  51609. s2 += *aData++ + s1;
  51610. }while( aData<aEnd );
  51611. }else{
  51612. do {
  51613. s1 += BYTESWAP32(aData[0]) + s2;
  51614. s2 += BYTESWAP32(aData[1]) + s1;
  51615. aData += 2;
  51616. }while( aData<aEnd );
  51617. }
  51618. aOut[0] = s1;
  51619. aOut[1] = s2;
  51620. }
  51621. static void walShmBarrier(Wal *pWal){
  51622. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  51623. sqlite3OsShmBarrier(pWal->pDbFd);
  51624. }
  51625. }
  51626. /*
  51627. ** Write the header information in pWal->hdr into the wal-index.
  51628. **
  51629. ** The checksum on pWal->hdr is updated before it is written.
  51630. */
  51631. static void walIndexWriteHdr(Wal *pWal){
  51632. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  51633. const int nCksum = offsetof(WalIndexHdr, aCksum);
  51634. assert( pWal->writeLock );
  51635. pWal->hdr.isInit = 1;
  51636. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  51637. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  51638. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  51639. walShmBarrier(pWal);
  51640. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  51641. }
  51642. /*
  51643. ** This function encodes a single frame header and writes it to a buffer
  51644. ** supplied by the caller. A frame-header is made up of a series of
  51645. ** 4-byte big-endian integers, as follows:
  51646. **
  51647. ** 0: Page number.
  51648. ** 4: For commit records, the size of the database image in pages
  51649. ** after the commit. For all other records, zero.
  51650. ** 8: Salt-1 (copied from the wal-header)
  51651. ** 12: Salt-2 (copied from the wal-header)
  51652. ** 16: Checksum-1.
  51653. ** 20: Checksum-2.
  51654. */
  51655. static void walEncodeFrame(
  51656. Wal *pWal, /* The write-ahead log */
  51657. u32 iPage, /* Database page number for frame */
  51658. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  51659. u8 *aData, /* Pointer to page data */
  51660. u8 *aFrame /* OUT: Write encoded frame here */
  51661. ){
  51662. int nativeCksum; /* True for native byte-order checksums */
  51663. u32 *aCksum = pWal->hdr.aFrameCksum;
  51664. assert( WAL_FRAME_HDRSIZE==24 );
  51665. sqlite3Put4byte(&aFrame[0], iPage);
  51666. sqlite3Put4byte(&aFrame[4], nTruncate);
  51667. if( pWal->iReCksum==0 ){
  51668. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  51669. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  51670. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  51671. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  51672. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  51673. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  51674. }else{
  51675. memset(&aFrame[8], 0, 16);
  51676. }
  51677. }
  51678. /*
  51679. ** Check to see if the frame with header in aFrame[] and content
  51680. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  51681. ** *pnTruncate and return true. Return if the frame is not valid.
  51682. */
  51683. static int walDecodeFrame(
  51684. Wal *pWal, /* The write-ahead log */
  51685. u32 *piPage, /* OUT: Database page number for frame */
  51686. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  51687. u8 *aData, /* Pointer to page data (for checksum) */
  51688. u8 *aFrame /* Frame data */
  51689. ){
  51690. int nativeCksum; /* True for native byte-order checksums */
  51691. u32 *aCksum = pWal->hdr.aFrameCksum;
  51692. u32 pgno; /* Page number of the frame */
  51693. assert( WAL_FRAME_HDRSIZE==24 );
  51694. /* A frame is only valid if the salt values in the frame-header
  51695. ** match the salt values in the wal-header.
  51696. */
  51697. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  51698. return 0;
  51699. }
  51700. /* A frame is only valid if the page number is creater than zero.
  51701. */
  51702. pgno = sqlite3Get4byte(&aFrame[0]);
  51703. if( pgno==0 ){
  51704. return 0;
  51705. }
  51706. /* A frame is only valid if a checksum of the WAL header,
  51707. ** all prior frams, the first 16 bytes of this frame-header,
  51708. ** and the frame-data matches the checksum in the last 8
  51709. ** bytes of this frame-header.
  51710. */
  51711. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  51712. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  51713. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  51714. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  51715. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  51716. ){
  51717. /* Checksum failed. */
  51718. return 0;
  51719. }
  51720. /* If we reach this point, the frame is valid. Return the page number
  51721. ** and the new database size.
  51722. */
  51723. *piPage = pgno;
  51724. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  51725. return 1;
  51726. }
  51727. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  51728. /*
  51729. ** Names of locks. This routine is used to provide debugging output and is not
  51730. ** a part of an ordinary build.
  51731. */
  51732. static const char *walLockName(int lockIdx){
  51733. if( lockIdx==WAL_WRITE_LOCK ){
  51734. return "WRITE-LOCK";
  51735. }else if( lockIdx==WAL_CKPT_LOCK ){
  51736. return "CKPT-LOCK";
  51737. }else if( lockIdx==WAL_RECOVER_LOCK ){
  51738. return "RECOVER-LOCK";
  51739. }else{
  51740. static char zName[15];
  51741. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  51742. lockIdx-WAL_READ_LOCK(0));
  51743. return zName;
  51744. }
  51745. }
  51746. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  51747. /*
  51748. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  51749. ** A lock cannot be moved directly between shared and exclusive - it must go
  51750. ** through the unlocked state first.
  51751. **
  51752. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  51753. */
  51754. static int walLockShared(Wal *pWal, int lockIdx){
  51755. int rc;
  51756. if( pWal->exclusiveMode ) return SQLITE_OK;
  51757. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  51758. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  51759. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  51760. walLockName(lockIdx), rc ? "failed" : "ok"));
  51761. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  51762. return rc;
  51763. }
  51764. static void walUnlockShared(Wal *pWal, int lockIdx){
  51765. if( pWal->exclusiveMode ) return;
  51766. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  51767. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  51768. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  51769. }
  51770. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  51771. int rc;
  51772. if( pWal->exclusiveMode ) return SQLITE_OK;
  51773. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  51774. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  51775. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  51776. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  51777. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  51778. return rc;
  51779. }
  51780. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  51781. if( pWal->exclusiveMode ) return;
  51782. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  51783. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  51784. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  51785. walLockName(lockIdx), n));
  51786. }
  51787. /*
  51788. ** Compute a hash on a page number. The resulting hash value must land
  51789. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  51790. ** the hash to the next value in the event of a collision.
  51791. */
  51792. static int walHash(u32 iPage){
  51793. assert( iPage>0 );
  51794. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  51795. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  51796. }
  51797. static int walNextHash(int iPriorHash){
  51798. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  51799. }
  51800. /*
  51801. ** Return pointers to the hash table and page number array stored on
  51802. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  51803. ** numbered starting from 0.
  51804. **
  51805. ** Set output variable *paHash to point to the start of the hash table
  51806. ** in the wal-index file. Set *piZero to one less than the frame
  51807. ** number of the first frame indexed by this hash table. If a
  51808. ** slot in the hash table is set to N, it refers to frame number
  51809. ** (*piZero+N) in the log.
  51810. **
  51811. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  51812. ** first frame indexed by the hash table, frame (*piZero+1).
  51813. */
  51814. static int walHashGet(
  51815. Wal *pWal, /* WAL handle */
  51816. int iHash, /* Find the iHash'th table */
  51817. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  51818. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  51819. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  51820. ){
  51821. int rc; /* Return code */
  51822. volatile u32 *aPgno;
  51823. rc = walIndexPage(pWal, iHash, &aPgno);
  51824. assert( rc==SQLITE_OK || iHash>0 );
  51825. if( rc==SQLITE_OK ){
  51826. u32 iZero;
  51827. volatile ht_slot *aHash;
  51828. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  51829. if( iHash==0 ){
  51830. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  51831. iZero = 0;
  51832. }else{
  51833. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  51834. }
  51835. *paPgno = &aPgno[-1];
  51836. *paHash = aHash;
  51837. *piZero = iZero;
  51838. }
  51839. return rc;
  51840. }
  51841. /*
  51842. ** Return the number of the wal-index page that contains the hash-table
  51843. ** and page-number array that contain entries corresponding to WAL frame
  51844. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  51845. ** are numbered starting from 0.
  51846. */
  51847. static int walFramePage(u32 iFrame){
  51848. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  51849. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  51850. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  51851. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  51852. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  51853. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  51854. );
  51855. return iHash;
  51856. }
  51857. /*
  51858. ** Return the page number associated with frame iFrame in this WAL.
  51859. */
  51860. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  51861. int iHash = walFramePage(iFrame);
  51862. if( iHash==0 ){
  51863. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  51864. }
  51865. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  51866. }
  51867. /*
  51868. ** Remove entries from the hash table that point to WAL slots greater
  51869. ** than pWal->hdr.mxFrame.
  51870. **
  51871. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  51872. ** to a rollback or savepoint.
  51873. **
  51874. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  51875. ** updated. Any later hash tables will be automatically cleared when
  51876. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  51877. ** actually needed.
  51878. */
  51879. static void walCleanupHash(Wal *pWal){
  51880. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  51881. volatile u32 *aPgno = 0; /* Page number array for hash table */
  51882. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  51883. int iLimit = 0; /* Zero values greater than this */
  51884. int nByte; /* Number of bytes to zero in aPgno[] */
  51885. int i; /* Used to iterate through aHash[] */
  51886. assert( pWal->writeLock );
  51887. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  51888. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  51889. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  51890. if( pWal->hdr.mxFrame==0 ) return;
  51891. /* Obtain pointers to the hash-table and page-number array containing
  51892. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  51893. ** that the page said hash-table and array reside on is already mapped.
  51894. */
  51895. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  51896. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  51897. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  51898. /* Zero all hash-table entries that correspond to frame numbers greater
  51899. ** than pWal->hdr.mxFrame.
  51900. */
  51901. iLimit = pWal->hdr.mxFrame - iZero;
  51902. assert( iLimit>0 );
  51903. for(i=0; i<HASHTABLE_NSLOT; i++){
  51904. if( aHash[i]>iLimit ){
  51905. aHash[i] = 0;
  51906. }
  51907. }
  51908. /* Zero the entries in the aPgno array that correspond to frames with
  51909. ** frame numbers greater than pWal->hdr.mxFrame.
  51910. */
  51911. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  51912. memset((void *)&aPgno[iLimit+1], 0, nByte);
  51913. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  51914. /* Verify that the every entry in the mapping region is still reachable
  51915. ** via the hash table even after the cleanup.
  51916. */
  51917. if( iLimit ){
  51918. int j; /* Loop counter */
  51919. int iKey; /* Hash key */
  51920. for(j=1; j<=iLimit; j++){
  51921. for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
  51922. if( aHash[iKey]==j ) break;
  51923. }
  51924. assert( aHash[iKey]==j );
  51925. }
  51926. }
  51927. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  51928. }
  51929. /*
  51930. ** Set an entry in the wal-index that will map database page number
  51931. ** pPage into WAL frame iFrame.
  51932. */
  51933. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  51934. int rc; /* Return code */
  51935. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  51936. volatile u32 *aPgno = 0; /* Page number array */
  51937. volatile ht_slot *aHash = 0; /* Hash table */
  51938. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  51939. /* Assuming the wal-index file was successfully mapped, populate the
  51940. ** page number array and hash table entry.
  51941. */
  51942. if( rc==SQLITE_OK ){
  51943. int iKey; /* Hash table key */
  51944. int idx; /* Value to write to hash-table slot */
  51945. int nCollide; /* Number of hash collisions */
  51946. idx = iFrame - iZero;
  51947. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  51948. /* If this is the first entry to be added to this hash-table, zero the
  51949. ** entire hash table and aPgno[] array before proceeding.
  51950. */
  51951. if( idx==1 ){
  51952. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  51953. memset((void*)&aPgno[1], 0, nByte);
  51954. }
  51955. /* If the entry in aPgno[] is already set, then the previous writer
  51956. ** must have exited unexpectedly in the middle of a transaction (after
  51957. ** writing one or more dirty pages to the WAL to free up memory).
  51958. ** Remove the remnants of that writers uncommitted transaction from
  51959. ** the hash-table before writing any new entries.
  51960. */
  51961. if( aPgno[idx] ){
  51962. walCleanupHash(pWal);
  51963. assert( !aPgno[idx] );
  51964. }
  51965. /* Write the aPgno[] array entry and the hash-table slot. */
  51966. nCollide = idx;
  51967. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  51968. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  51969. }
  51970. aPgno[idx] = iPage;
  51971. aHash[iKey] = (ht_slot)idx;
  51972. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  51973. /* Verify that the number of entries in the hash table exactly equals
  51974. ** the number of entries in the mapping region.
  51975. */
  51976. {
  51977. int i; /* Loop counter */
  51978. int nEntry = 0; /* Number of entries in the hash table */
  51979. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  51980. assert( nEntry==idx );
  51981. }
  51982. /* Verify that the every entry in the mapping region is reachable
  51983. ** via the hash table. This turns out to be a really, really expensive
  51984. ** thing to check, so only do this occasionally - not on every
  51985. ** iteration.
  51986. */
  51987. if( (idx&0x3ff)==0 ){
  51988. int i; /* Loop counter */
  51989. for(i=1; i<=idx; i++){
  51990. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  51991. if( aHash[iKey]==i ) break;
  51992. }
  51993. assert( aHash[iKey]==i );
  51994. }
  51995. }
  51996. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  51997. }
  51998. return rc;
  51999. }
  52000. /*
  52001. ** Recover the wal-index by reading the write-ahead log file.
  52002. **
  52003. ** This routine first tries to establish an exclusive lock on the
  52004. ** wal-index to prevent other threads/processes from doing anything
  52005. ** with the WAL or wal-index while recovery is running. The
  52006. ** WAL_RECOVER_LOCK is also held so that other threads will know
  52007. ** that this thread is running recovery. If unable to establish
  52008. ** the necessary locks, this routine returns SQLITE_BUSY.
  52009. */
  52010. static int walIndexRecover(Wal *pWal){
  52011. int rc; /* Return Code */
  52012. i64 nSize; /* Size of log file */
  52013. u32 aFrameCksum[2] = {0, 0};
  52014. int iLock; /* Lock offset to lock for checkpoint */
  52015. int nLock; /* Number of locks to hold */
  52016. /* Obtain an exclusive lock on all byte in the locking range not already
  52017. ** locked by the caller. The caller is guaranteed to have locked the
  52018. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  52019. ** If successful, the same bytes that are locked here are unlocked before
  52020. ** this function returns.
  52021. */
  52022. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  52023. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  52024. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  52025. assert( pWal->writeLock );
  52026. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  52027. nLock = SQLITE_SHM_NLOCK - iLock;
  52028. rc = walLockExclusive(pWal, iLock, nLock);
  52029. if( rc ){
  52030. return rc;
  52031. }
  52032. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  52033. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  52034. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  52035. if( rc!=SQLITE_OK ){
  52036. goto recovery_error;
  52037. }
  52038. if( nSize>WAL_HDRSIZE ){
  52039. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  52040. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  52041. int szFrame; /* Number of bytes in buffer aFrame[] */
  52042. u8 *aData; /* Pointer to data part of aFrame buffer */
  52043. int iFrame; /* Index of last frame read */
  52044. i64 iOffset; /* Next offset to read from log file */
  52045. int szPage; /* Page size according to the log */
  52046. u32 magic; /* Magic value read from WAL header */
  52047. u32 version; /* Magic value read from WAL header */
  52048. int isValid; /* True if this frame is valid */
  52049. /* Read in the WAL header. */
  52050. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  52051. if( rc!=SQLITE_OK ){
  52052. goto recovery_error;
  52053. }
  52054. /* If the database page size is not a power of two, or is greater than
  52055. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  52056. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  52057. ** WAL file.
  52058. */
  52059. magic = sqlite3Get4byte(&aBuf[0]);
  52060. szPage = sqlite3Get4byte(&aBuf[8]);
  52061. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  52062. || szPage&(szPage-1)
  52063. || szPage>SQLITE_MAX_PAGE_SIZE
  52064. || szPage<512
  52065. ){
  52066. goto finished;
  52067. }
  52068. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  52069. pWal->szPage = szPage;
  52070. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  52071. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  52072. /* Verify that the WAL header checksum is correct */
  52073. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  52074. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  52075. );
  52076. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  52077. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  52078. ){
  52079. goto finished;
  52080. }
  52081. /* Verify that the version number on the WAL format is one that
  52082. ** are able to understand */
  52083. version = sqlite3Get4byte(&aBuf[4]);
  52084. if( version!=WAL_MAX_VERSION ){
  52085. rc = SQLITE_CANTOPEN_BKPT;
  52086. goto finished;
  52087. }
  52088. /* Malloc a buffer to read frames into. */
  52089. szFrame = szPage + WAL_FRAME_HDRSIZE;
  52090. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  52091. if( !aFrame ){
  52092. rc = SQLITE_NOMEM_BKPT;
  52093. goto recovery_error;
  52094. }
  52095. aData = &aFrame[WAL_FRAME_HDRSIZE];
  52096. /* Read all frames from the log file. */
  52097. iFrame = 0;
  52098. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  52099. u32 pgno; /* Database page number for frame */
  52100. u32 nTruncate; /* dbsize field from frame header */
  52101. /* Read and decode the next log frame. */
  52102. iFrame++;
  52103. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  52104. if( rc!=SQLITE_OK ) break;
  52105. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  52106. if( !isValid ) break;
  52107. rc = walIndexAppend(pWal, iFrame, pgno);
  52108. if( rc!=SQLITE_OK ) break;
  52109. /* If nTruncate is non-zero, this is a commit record. */
  52110. if( nTruncate ){
  52111. pWal->hdr.mxFrame = iFrame;
  52112. pWal->hdr.nPage = nTruncate;
  52113. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  52114. testcase( szPage<=32768 );
  52115. testcase( szPage>=65536 );
  52116. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  52117. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  52118. }
  52119. }
  52120. sqlite3_free(aFrame);
  52121. }
  52122. finished:
  52123. if( rc==SQLITE_OK ){
  52124. volatile WalCkptInfo *pInfo;
  52125. int i;
  52126. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  52127. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  52128. walIndexWriteHdr(pWal);
  52129. /* Reset the checkpoint-header. This is safe because this thread is
  52130. ** currently holding locks that exclude all other readers, writers and
  52131. ** checkpointers.
  52132. */
  52133. pInfo = walCkptInfo(pWal);
  52134. pInfo->nBackfill = 0;
  52135. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  52136. pInfo->aReadMark[0] = 0;
  52137. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  52138. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  52139. /* If more than one frame was recovered from the log file, report an
  52140. ** event via sqlite3_log(). This is to help with identifying performance
  52141. ** problems caused by applications routinely shutting down without
  52142. ** checkpointing the log file.
  52143. */
  52144. if( pWal->hdr.nPage ){
  52145. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  52146. "recovered %d frames from WAL file %s",
  52147. pWal->hdr.mxFrame, pWal->zWalName
  52148. );
  52149. }
  52150. }
  52151. recovery_error:
  52152. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  52153. walUnlockExclusive(pWal, iLock, nLock);
  52154. return rc;
  52155. }
  52156. /*
  52157. ** Close an open wal-index.
  52158. */
  52159. static void walIndexClose(Wal *pWal, int isDelete){
  52160. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  52161. int i;
  52162. for(i=0; i<pWal->nWiData; i++){
  52163. sqlite3_free((void *)pWal->apWiData[i]);
  52164. pWal->apWiData[i] = 0;
  52165. }
  52166. }else{
  52167. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  52168. }
  52169. }
  52170. /*
  52171. ** Open a connection to the WAL file zWalName. The database file must
  52172. ** already be opened on connection pDbFd. The buffer that zWalName points
  52173. ** to must remain valid for the lifetime of the returned Wal* handle.
  52174. **
  52175. ** A SHARED lock should be held on the database file when this function
  52176. ** is called. The purpose of this SHARED lock is to prevent any other
  52177. ** client from unlinking the WAL or wal-index file. If another process
  52178. ** were to do this just after this client opened one of these files, the
  52179. ** system would be badly broken.
  52180. **
  52181. ** If the log file is successfully opened, SQLITE_OK is returned and
  52182. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  52183. ** an SQLite error code is returned and *ppWal is left unmodified.
  52184. */
  52185. SQLITE_PRIVATE int sqlite3WalOpen(
  52186. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  52187. sqlite3_file *pDbFd, /* The open database file */
  52188. const char *zWalName, /* Name of the WAL file */
  52189. int bNoShm, /* True to run in heap-memory mode */
  52190. i64 mxWalSize, /* Truncate WAL to this size on reset */
  52191. Wal **ppWal /* OUT: Allocated Wal handle */
  52192. ){
  52193. int rc; /* Return Code */
  52194. Wal *pRet; /* Object to allocate and return */
  52195. int flags; /* Flags passed to OsOpen() */
  52196. assert( zWalName && zWalName[0] );
  52197. assert( pDbFd );
  52198. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  52199. ** this source file. Verify that the #defines of the locking byte offsets
  52200. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  52201. ** For that matter, if the lock offset ever changes from its initial design
  52202. ** value of 120, we need to know that so there is an assert() to check it.
  52203. */
  52204. assert( 120==WALINDEX_LOCK_OFFSET );
  52205. assert( 136==WALINDEX_HDR_SIZE );
  52206. #ifdef WIN_SHM_BASE
  52207. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  52208. #endif
  52209. #ifdef UNIX_SHM_BASE
  52210. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  52211. #endif
  52212. /* Allocate an instance of struct Wal to return. */
  52213. *ppWal = 0;
  52214. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  52215. if( !pRet ){
  52216. return SQLITE_NOMEM_BKPT;
  52217. }
  52218. pRet->pVfs = pVfs;
  52219. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  52220. pRet->pDbFd = pDbFd;
  52221. pRet->readLock = -1;
  52222. pRet->mxWalSize = mxWalSize;
  52223. pRet->zWalName = zWalName;
  52224. pRet->syncHeader = 1;
  52225. pRet->padToSectorBoundary = 1;
  52226. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  52227. /* Open file handle on the write-ahead log file. */
  52228. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  52229. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  52230. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  52231. pRet->readOnly = WAL_RDONLY;
  52232. }
  52233. if( rc!=SQLITE_OK ){
  52234. walIndexClose(pRet, 0);
  52235. sqlite3OsClose(pRet->pWalFd);
  52236. sqlite3_free(pRet);
  52237. }else{
  52238. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  52239. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  52240. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  52241. pRet->padToSectorBoundary = 0;
  52242. }
  52243. *ppWal = pRet;
  52244. WALTRACE(("WAL%d: opened\n", pRet));
  52245. }
  52246. return rc;
  52247. }
  52248. /*
  52249. ** Change the size to which the WAL file is trucated on each reset.
  52250. */
  52251. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  52252. if( pWal ) pWal->mxWalSize = iLimit;
  52253. }
  52254. /*
  52255. ** Find the smallest page number out of all pages held in the WAL that
  52256. ** has not been returned by any prior invocation of this method on the
  52257. ** same WalIterator object. Write into *piFrame the frame index where
  52258. ** that page was last written into the WAL. Write into *piPage the page
  52259. ** number.
  52260. **
  52261. ** Return 0 on success. If there are no pages in the WAL with a page
  52262. ** number larger than *piPage, then return 1.
  52263. */
  52264. static int walIteratorNext(
  52265. WalIterator *p, /* Iterator */
  52266. u32 *piPage, /* OUT: The page number of the next page */
  52267. u32 *piFrame /* OUT: Wal frame index of next page */
  52268. ){
  52269. u32 iMin; /* Result pgno must be greater than iMin */
  52270. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  52271. int i; /* For looping through segments */
  52272. iMin = p->iPrior;
  52273. assert( iMin<0xffffffff );
  52274. for(i=p->nSegment-1; i>=0; i--){
  52275. struct WalSegment *pSegment = &p->aSegment[i];
  52276. while( pSegment->iNext<pSegment->nEntry ){
  52277. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  52278. if( iPg>iMin ){
  52279. if( iPg<iRet ){
  52280. iRet = iPg;
  52281. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  52282. }
  52283. break;
  52284. }
  52285. pSegment->iNext++;
  52286. }
  52287. }
  52288. *piPage = p->iPrior = iRet;
  52289. return (iRet==0xFFFFFFFF);
  52290. }
  52291. /*
  52292. ** This function merges two sorted lists into a single sorted list.
  52293. **
  52294. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  52295. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  52296. ** is guaranteed for all J<K:
  52297. **
  52298. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  52299. ** aContent[aRight[J]] < aContent[aRight[K]]
  52300. **
  52301. ** This routine overwrites aRight[] with a new (probably longer) sequence
  52302. ** of indices such that the aRight[] contains every index that appears in
  52303. ** either aLeft[] or the old aRight[] and such that the second condition
  52304. ** above is still met.
  52305. **
  52306. ** The aContent[aLeft[X]] values will be unique for all X. And the
  52307. ** aContent[aRight[X]] values will be unique too. But there might be
  52308. ** one or more combinations of X and Y such that
  52309. **
  52310. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  52311. **
  52312. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  52313. */
  52314. static void walMerge(
  52315. const u32 *aContent, /* Pages in wal - keys for the sort */
  52316. ht_slot *aLeft, /* IN: Left hand input list */
  52317. int nLeft, /* IN: Elements in array *paLeft */
  52318. ht_slot **paRight, /* IN/OUT: Right hand input list */
  52319. int *pnRight, /* IN/OUT: Elements in *paRight */
  52320. ht_slot *aTmp /* Temporary buffer */
  52321. ){
  52322. int iLeft = 0; /* Current index in aLeft */
  52323. int iRight = 0; /* Current index in aRight */
  52324. int iOut = 0; /* Current index in output buffer */
  52325. int nRight = *pnRight;
  52326. ht_slot *aRight = *paRight;
  52327. assert( nLeft>0 && nRight>0 );
  52328. while( iRight<nRight || iLeft<nLeft ){
  52329. ht_slot logpage;
  52330. Pgno dbpage;
  52331. if( (iLeft<nLeft)
  52332. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  52333. ){
  52334. logpage = aLeft[iLeft++];
  52335. }else{
  52336. logpage = aRight[iRight++];
  52337. }
  52338. dbpage = aContent[logpage];
  52339. aTmp[iOut++] = logpage;
  52340. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  52341. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  52342. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  52343. }
  52344. *paRight = aLeft;
  52345. *pnRight = iOut;
  52346. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  52347. }
  52348. /*
  52349. ** Sort the elements in list aList using aContent[] as the sort key.
  52350. ** Remove elements with duplicate keys, preferring to keep the
  52351. ** larger aList[] values.
  52352. **
  52353. ** The aList[] entries are indices into aContent[]. The values in
  52354. ** aList[] are to be sorted so that for all J<K:
  52355. **
  52356. ** aContent[aList[J]] < aContent[aList[K]]
  52357. **
  52358. ** For any X and Y such that
  52359. **
  52360. ** aContent[aList[X]] == aContent[aList[Y]]
  52361. **
  52362. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  52363. ** the smaller.
  52364. */
  52365. static void walMergesort(
  52366. const u32 *aContent, /* Pages in wal */
  52367. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  52368. ht_slot *aList, /* IN/OUT: List to sort */
  52369. int *pnList /* IN/OUT: Number of elements in aList[] */
  52370. ){
  52371. struct Sublist {
  52372. int nList; /* Number of elements in aList */
  52373. ht_slot *aList; /* Pointer to sub-list content */
  52374. };
  52375. const int nList = *pnList; /* Size of input list */
  52376. int nMerge = 0; /* Number of elements in list aMerge */
  52377. ht_slot *aMerge = 0; /* List to be merged */
  52378. int iList; /* Index into input list */
  52379. u32 iSub = 0; /* Index into aSub array */
  52380. struct Sublist aSub[13]; /* Array of sub-lists */
  52381. memset(aSub, 0, sizeof(aSub));
  52382. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  52383. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  52384. for(iList=0; iList<nList; iList++){
  52385. nMerge = 1;
  52386. aMerge = &aList[iList];
  52387. for(iSub=0; iList & (1<<iSub); iSub++){
  52388. struct Sublist *p;
  52389. assert( iSub<ArraySize(aSub) );
  52390. p = &aSub[iSub];
  52391. assert( p->aList && p->nList<=(1<<iSub) );
  52392. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  52393. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  52394. }
  52395. aSub[iSub].aList = aMerge;
  52396. aSub[iSub].nList = nMerge;
  52397. }
  52398. for(iSub++; iSub<ArraySize(aSub); iSub++){
  52399. if( nList & (1<<iSub) ){
  52400. struct Sublist *p;
  52401. assert( iSub<ArraySize(aSub) );
  52402. p = &aSub[iSub];
  52403. assert( p->nList<=(1<<iSub) );
  52404. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  52405. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  52406. }
  52407. }
  52408. assert( aMerge==aList );
  52409. *pnList = nMerge;
  52410. #ifdef SQLITE_DEBUG
  52411. {
  52412. int i;
  52413. for(i=1; i<*pnList; i++){
  52414. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  52415. }
  52416. }
  52417. #endif
  52418. }
  52419. /*
  52420. ** Free an iterator allocated by walIteratorInit().
  52421. */
  52422. static void walIteratorFree(WalIterator *p){
  52423. sqlite3_free(p);
  52424. }
  52425. /*
  52426. ** Construct a WalInterator object that can be used to loop over all
  52427. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  52428. ** lock.
  52429. **
  52430. ** On success, make *pp point to the newly allocated WalInterator object
  52431. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  52432. ** returns an error, the value of *pp is undefined.
  52433. **
  52434. ** The calling routine should invoke walIteratorFree() to destroy the
  52435. ** WalIterator object when it has finished with it.
  52436. */
  52437. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  52438. WalIterator *p; /* Return value */
  52439. int nSegment; /* Number of segments to merge */
  52440. u32 iLast; /* Last frame in log */
  52441. int nByte; /* Number of bytes to allocate */
  52442. int i; /* Iterator variable */
  52443. ht_slot *aTmp; /* Temp space used by merge-sort */
  52444. int rc = SQLITE_OK; /* Return Code */
  52445. /* This routine only runs while holding the checkpoint lock. And
  52446. ** it only runs if there is actually content in the log (mxFrame>0).
  52447. */
  52448. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  52449. iLast = pWal->hdr.mxFrame;
  52450. /* Allocate space for the WalIterator object. */
  52451. nSegment = walFramePage(iLast) + 1;
  52452. nByte = sizeof(WalIterator)
  52453. + (nSegment-1)*sizeof(struct WalSegment)
  52454. + iLast*sizeof(ht_slot);
  52455. p = (WalIterator *)sqlite3_malloc64(nByte);
  52456. if( !p ){
  52457. return SQLITE_NOMEM_BKPT;
  52458. }
  52459. memset(p, 0, nByte);
  52460. p->nSegment = nSegment;
  52461. /* Allocate temporary space used by the merge-sort routine. This block
  52462. ** of memory will be freed before this function returns.
  52463. */
  52464. aTmp = (ht_slot *)sqlite3_malloc64(
  52465. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  52466. );
  52467. if( !aTmp ){
  52468. rc = SQLITE_NOMEM_BKPT;
  52469. }
  52470. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  52471. volatile ht_slot *aHash;
  52472. u32 iZero;
  52473. volatile u32 *aPgno;
  52474. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  52475. if( rc==SQLITE_OK ){
  52476. int j; /* Counter variable */
  52477. int nEntry; /* Number of entries in this segment */
  52478. ht_slot *aIndex; /* Sorted index for this segment */
  52479. aPgno++;
  52480. if( (i+1)==nSegment ){
  52481. nEntry = (int)(iLast - iZero);
  52482. }else{
  52483. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  52484. }
  52485. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  52486. iZero++;
  52487. for(j=0; j<nEntry; j++){
  52488. aIndex[j] = (ht_slot)j;
  52489. }
  52490. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  52491. p->aSegment[i].iZero = iZero;
  52492. p->aSegment[i].nEntry = nEntry;
  52493. p->aSegment[i].aIndex = aIndex;
  52494. p->aSegment[i].aPgno = (u32 *)aPgno;
  52495. }
  52496. }
  52497. sqlite3_free(aTmp);
  52498. if( rc!=SQLITE_OK ){
  52499. walIteratorFree(p);
  52500. }
  52501. *pp = p;
  52502. return rc;
  52503. }
  52504. /*
  52505. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  52506. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  52507. ** busy-handler function. Invoke it and retry the lock until either the
  52508. ** lock is successfully obtained or the busy-handler returns 0.
  52509. */
  52510. static int walBusyLock(
  52511. Wal *pWal, /* WAL connection */
  52512. int (*xBusy)(void*), /* Function to call when busy */
  52513. void *pBusyArg, /* Context argument for xBusyHandler */
  52514. int lockIdx, /* Offset of first byte to lock */
  52515. int n /* Number of bytes to lock */
  52516. ){
  52517. int rc;
  52518. do {
  52519. rc = walLockExclusive(pWal, lockIdx, n);
  52520. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  52521. return rc;
  52522. }
  52523. /*
  52524. ** The cache of the wal-index header must be valid to call this function.
  52525. ** Return the page-size in bytes used by the database.
  52526. */
  52527. static int walPagesize(Wal *pWal){
  52528. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  52529. }
  52530. /*
  52531. ** The following is guaranteed when this function is called:
  52532. **
  52533. ** a) the WRITER lock is held,
  52534. ** b) the entire log file has been checkpointed, and
  52535. ** c) any existing readers are reading exclusively from the database
  52536. ** file - there are no readers that may attempt to read a frame from
  52537. ** the log file.
  52538. **
  52539. ** This function updates the shared-memory structures so that the next
  52540. ** client to write to the database (which may be this one) does so by
  52541. ** writing frames into the start of the log file.
  52542. **
  52543. ** The value of parameter salt1 is used as the aSalt[1] value in the
  52544. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  52545. ** one obtained from sqlite3_randomness()).
  52546. */
  52547. static void walRestartHdr(Wal *pWal, u32 salt1){
  52548. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  52549. int i; /* Loop counter */
  52550. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  52551. pWal->nCkpt++;
  52552. pWal->hdr.mxFrame = 0;
  52553. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  52554. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  52555. walIndexWriteHdr(pWal);
  52556. pInfo->nBackfill = 0;
  52557. pInfo->nBackfillAttempted = 0;
  52558. pInfo->aReadMark[1] = 0;
  52559. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  52560. assert( pInfo->aReadMark[0]==0 );
  52561. }
  52562. /*
  52563. ** Copy as much content as we can from the WAL back into the database file
  52564. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  52565. **
  52566. ** The amount of information copies from WAL to database might be limited
  52567. ** by active readers. This routine will never overwrite a database page
  52568. ** that a concurrent reader might be using.
  52569. **
  52570. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  52571. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  52572. ** checkpoints are always run by a background thread or background
  52573. ** process, foreground threads will never block on a lengthy fsync call.
  52574. **
  52575. ** Fsync is called on the WAL before writing content out of the WAL and
  52576. ** into the database. This ensures that if the new content is persistent
  52577. ** in the WAL and can be recovered following a power-loss or hard reset.
  52578. **
  52579. ** Fsync is also called on the database file if (and only if) the entire
  52580. ** WAL content is copied into the database file. This second fsync makes
  52581. ** it safe to delete the WAL since the new content will persist in the
  52582. ** database file.
  52583. **
  52584. ** This routine uses and updates the nBackfill field of the wal-index header.
  52585. ** This is the only routine that will increase the value of nBackfill.
  52586. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  52587. ** its value.)
  52588. **
  52589. ** The caller must be holding sufficient locks to ensure that no other
  52590. ** checkpoint is running (in any other thread or process) at the same
  52591. ** time.
  52592. */
  52593. static int walCheckpoint(
  52594. Wal *pWal, /* Wal connection */
  52595. sqlite3 *db, /* Check for interrupts on this handle */
  52596. int eMode, /* One of PASSIVE, FULL or RESTART */
  52597. int (*xBusy)(void*), /* Function to call when busy */
  52598. void *pBusyArg, /* Context argument for xBusyHandler */
  52599. int sync_flags, /* Flags for OsSync() (or 0) */
  52600. u8 *zBuf /* Temporary buffer to use */
  52601. ){
  52602. int rc = SQLITE_OK; /* Return code */
  52603. int szPage; /* Database page-size */
  52604. WalIterator *pIter = 0; /* Wal iterator context */
  52605. u32 iDbpage = 0; /* Next database page to write */
  52606. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  52607. u32 mxSafeFrame; /* Max frame that can be backfilled */
  52608. u32 mxPage; /* Max database page to write */
  52609. int i; /* Loop counter */
  52610. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  52611. szPage = walPagesize(pWal);
  52612. testcase( szPage<=32768 );
  52613. testcase( szPage>=65536 );
  52614. pInfo = walCkptInfo(pWal);
  52615. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  52616. /* Allocate the iterator */
  52617. rc = walIteratorInit(pWal, &pIter);
  52618. if( rc!=SQLITE_OK ){
  52619. return rc;
  52620. }
  52621. assert( pIter );
  52622. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  52623. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  52624. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  52625. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  52626. ** safe to write into the database. Frames beyond mxSafeFrame might
  52627. ** overwrite database pages that are in use by active readers and thus
  52628. ** cannot be backfilled from the WAL.
  52629. */
  52630. mxSafeFrame = pWal->hdr.mxFrame;
  52631. mxPage = pWal->hdr.nPage;
  52632. for(i=1; i<WAL_NREADER; i++){
  52633. /* Thread-sanitizer reports that the following is an unsafe read,
  52634. ** as some other thread may be in the process of updating the value
  52635. ** of the aReadMark[] slot. The assumption here is that if that is
  52636. ** happening, the other client may only be increasing the value,
  52637. ** not decreasing it. So assuming either that either the "old" or
  52638. ** "new" version of the value is read, and not some arbitrary value
  52639. ** that would never be written by a real client, things are still
  52640. ** safe. */
  52641. u32 y = pInfo->aReadMark[i];
  52642. if( mxSafeFrame>y ){
  52643. assert( y<=pWal->hdr.mxFrame );
  52644. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  52645. if( rc==SQLITE_OK ){
  52646. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  52647. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  52648. }else if( rc==SQLITE_BUSY ){
  52649. mxSafeFrame = y;
  52650. xBusy = 0;
  52651. }else{
  52652. goto walcheckpoint_out;
  52653. }
  52654. }
  52655. }
  52656. if( pInfo->nBackfill<mxSafeFrame
  52657. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  52658. ){
  52659. i64 nSize; /* Current size of database file */
  52660. u32 nBackfill = pInfo->nBackfill;
  52661. pInfo->nBackfillAttempted = mxSafeFrame;
  52662. /* Sync the WAL to disk */
  52663. if( sync_flags ){
  52664. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  52665. }
  52666. /* If the database may grow as a result of this checkpoint, hint
  52667. ** about the eventual size of the db file to the VFS layer.
  52668. */
  52669. if( rc==SQLITE_OK ){
  52670. i64 nReq = ((i64)mxPage * szPage);
  52671. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  52672. if( rc==SQLITE_OK && nSize<nReq ){
  52673. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  52674. }
  52675. }
  52676. /* Iterate through the contents of the WAL, copying data to the db file */
  52677. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  52678. i64 iOffset;
  52679. assert( walFramePgno(pWal, iFrame)==iDbpage );
  52680. if( db->u1.isInterrupted ){
  52681. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  52682. break;
  52683. }
  52684. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  52685. continue;
  52686. }
  52687. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  52688. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  52689. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  52690. if( rc!=SQLITE_OK ) break;
  52691. iOffset = (iDbpage-1)*(i64)szPage;
  52692. testcase( IS_BIG_INT(iOffset) );
  52693. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  52694. if( rc!=SQLITE_OK ) break;
  52695. }
  52696. /* If work was actually accomplished... */
  52697. if( rc==SQLITE_OK ){
  52698. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  52699. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  52700. testcase( IS_BIG_INT(szDb) );
  52701. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  52702. if( rc==SQLITE_OK && sync_flags ){
  52703. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  52704. }
  52705. }
  52706. if( rc==SQLITE_OK ){
  52707. pInfo->nBackfill = mxSafeFrame;
  52708. }
  52709. }
  52710. /* Release the reader lock held while backfilling */
  52711. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  52712. }
  52713. if( rc==SQLITE_BUSY ){
  52714. /* Reset the return code so as not to report a checkpoint failure
  52715. ** just because there are active readers. */
  52716. rc = SQLITE_OK;
  52717. }
  52718. }
  52719. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  52720. ** entire wal file has been copied into the database file, then block
  52721. ** until all readers have finished using the wal file. This ensures that
  52722. ** the next process to write to the database restarts the wal file.
  52723. */
  52724. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  52725. assert( pWal->writeLock );
  52726. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  52727. rc = SQLITE_BUSY;
  52728. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  52729. u32 salt1;
  52730. sqlite3_randomness(4, &salt1);
  52731. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  52732. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  52733. if( rc==SQLITE_OK ){
  52734. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  52735. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  52736. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  52737. ** truncates the log file to zero bytes just prior to a
  52738. ** successful return.
  52739. **
  52740. ** In theory, it might be safe to do this without updating the
  52741. ** wal-index header in shared memory, as all subsequent reader or
  52742. ** writer clients should see that the entire log file has been
  52743. ** checkpointed and behave accordingly. This seems unsafe though,
  52744. ** as it would leave the system in a state where the contents of
  52745. ** the wal-index header do not match the contents of the
  52746. ** file-system. To avoid this, update the wal-index header to
  52747. ** indicate that the log file contains zero valid frames. */
  52748. walRestartHdr(pWal, salt1);
  52749. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  52750. }
  52751. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  52752. }
  52753. }
  52754. }
  52755. walcheckpoint_out:
  52756. walIteratorFree(pIter);
  52757. return rc;
  52758. }
  52759. /*
  52760. ** If the WAL file is currently larger than nMax bytes in size, truncate
  52761. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  52762. */
  52763. static void walLimitSize(Wal *pWal, i64 nMax){
  52764. i64 sz;
  52765. int rx;
  52766. sqlite3BeginBenignMalloc();
  52767. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  52768. if( rx==SQLITE_OK && (sz > nMax ) ){
  52769. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  52770. }
  52771. sqlite3EndBenignMalloc();
  52772. if( rx ){
  52773. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  52774. }
  52775. }
  52776. /*
  52777. ** Close a connection to a log file.
  52778. */
  52779. SQLITE_PRIVATE int sqlite3WalClose(
  52780. Wal *pWal, /* Wal to close */
  52781. sqlite3 *db, /* For interrupt flag */
  52782. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  52783. int nBuf,
  52784. u8 *zBuf /* Buffer of at least nBuf bytes */
  52785. ){
  52786. int rc = SQLITE_OK;
  52787. if( pWal ){
  52788. int isDelete = 0; /* True to unlink wal and wal-index files */
  52789. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  52790. ** ordinary, rollback-mode locking methods, this guarantees that the
  52791. ** connection associated with this log file is the only connection to
  52792. ** the database. In this case checkpoint the database and unlink both
  52793. ** the wal and wal-index files.
  52794. **
  52795. ** The EXCLUSIVE lock is not released before returning.
  52796. */
  52797. if( zBuf!=0
  52798. && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
  52799. ){
  52800. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  52801. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  52802. }
  52803. rc = sqlite3WalCheckpoint(pWal, db,
  52804. SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  52805. );
  52806. if( rc==SQLITE_OK ){
  52807. int bPersist = -1;
  52808. sqlite3OsFileControlHint(
  52809. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  52810. );
  52811. if( bPersist!=1 ){
  52812. /* Try to delete the WAL file if the checkpoint completed and
  52813. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  52814. ** mode (!bPersist) */
  52815. isDelete = 1;
  52816. }else if( pWal->mxWalSize>=0 ){
  52817. /* Try to truncate the WAL file to zero bytes if the checkpoint
  52818. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  52819. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  52820. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  52821. ** to zero bytes as truncating to the journal_size_limit might
  52822. ** leave a corrupt WAL file on disk. */
  52823. walLimitSize(pWal, 0);
  52824. }
  52825. }
  52826. }
  52827. walIndexClose(pWal, isDelete);
  52828. sqlite3OsClose(pWal->pWalFd);
  52829. if( isDelete ){
  52830. sqlite3BeginBenignMalloc();
  52831. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  52832. sqlite3EndBenignMalloc();
  52833. }
  52834. WALTRACE(("WAL%p: closed\n", pWal));
  52835. sqlite3_free((void *)pWal->apWiData);
  52836. sqlite3_free(pWal);
  52837. }
  52838. return rc;
  52839. }
  52840. /*
  52841. ** Try to read the wal-index header. Return 0 on success and 1 if
  52842. ** there is a problem.
  52843. **
  52844. ** The wal-index is in shared memory. Another thread or process might
  52845. ** be writing the header at the same time this procedure is trying to
  52846. ** read it, which might result in inconsistency. A dirty read is detected
  52847. ** by verifying that both copies of the header are the same and also by
  52848. ** a checksum on the header.
  52849. **
  52850. ** If and only if the read is consistent and the header is different from
  52851. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  52852. ** and *pChanged is set to 1.
  52853. **
  52854. ** If the checksum cannot be verified return non-zero. If the header
  52855. ** is read successfully and the checksum verified, return zero.
  52856. */
  52857. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  52858. u32 aCksum[2]; /* Checksum on the header content */
  52859. WalIndexHdr h1, h2; /* Two copies of the header content */
  52860. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  52861. /* The first page of the wal-index must be mapped at this point. */
  52862. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  52863. /* Read the header. This might happen concurrently with a write to the
  52864. ** same area of shared memory on a different CPU in a SMP,
  52865. ** meaning it is possible that an inconsistent snapshot is read
  52866. ** from the file. If this happens, return non-zero.
  52867. **
  52868. ** There are two copies of the header at the beginning of the wal-index.
  52869. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  52870. ** Memory barriers are used to prevent the compiler or the hardware from
  52871. ** reordering the reads and writes.
  52872. */
  52873. aHdr = walIndexHdr(pWal);
  52874. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  52875. walShmBarrier(pWal);
  52876. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  52877. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  52878. return 1; /* Dirty read */
  52879. }
  52880. if( h1.isInit==0 ){
  52881. return 1; /* Malformed header - probably all zeros */
  52882. }
  52883. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  52884. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  52885. return 1; /* Checksum does not match */
  52886. }
  52887. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  52888. *pChanged = 1;
  52889. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  52890. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  52891. testcase( pWal->szPage<=32768 );
  52892. testcase( pWal->szPage>=65536 );
  52893. }
  52894. /* The header was successfully read. Return zero. */
  52895. return 0;
  52896. }
  52897. /*
  52898. ** Read the wal-index header from the wal-index and into pWal->hdr.
  52899. ** If the wal-header appears to be corrupt, try to reconstruct the
  52900. ** wal-index from the WAL before returning.
  52901. **
  52902. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  52903. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  52904. ** to 0.
  52905. **
  52906. ** If the wal-index header is successfully read, return SQLITE_OK.
  52907. ** Otherwise an SQLite error code.
  52908. */
  52909. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  52910. int rc; /* Return code */
  52911. int badHdr; /* True if a header read failed */
  52912. volatile u32 *page0; /* Chunk of wal-index containing header */
  52913. /* Ensure that page 0 of the wal-index (the page that contains the
  52914. ** wal-index header) is mapped. Return early if an error occurs here.
  52915. */
  52916. assert( pChanged );
  52917. rc = walIndexPage(pWal, 0, &page0);
  52918. if( rc!=SQLITE_OK ){
  52919. return rc;
  52920. };
  52921. assert( page0 || pWal->writeLock==0 );
  52922. /* If the first page of the wal-index has been mapped, try to read the
  52923. ** wal-index header immediately, without holding any lock. This usually
  52924. ** works, but may fail if the wal-index header is corrupt or currently
  52925. ** being modified by another thread or process.
  52926. */
  52927. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  52928. /* If the first attempt failed, it might have been due to a race
  52929. ** with a writer. So get a WRITE lock and try again.
  52930. */
  52931. assert( badHdr==0 || pWal->writeLock==0 );
  52932. if( badHdr ){
  52933. if( pWal->readOnly & WAL_SHM_RDONLY ){
  52934. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  52935. walUnlockShared(pWal, WAL_WRITE_LOCK);
  52936. rc = SQLITE_READONLY_RECOVERY;
  52937. }
  52938. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  52939. pWal->writeLock = 1;
  52940. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  52941. badHdr = walIndexTryHdr(pWal, pChanged);
  52942. if( badHdr ){
  52943. /* If the wal-index header is still malformed even while holding
  52944. ** a WRITE lock, it can only mean that the header is corrupted and
  52945. ** needs to be reconstructed. So run recovery to do exactly that.
  52946. */
  52947. rc = walIndexRecover(pWal);
  52948. *pChanged = 1;
  52949. }
  52950. }
  52951. pWal->writeLock = 0;
  52952. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  52953. }
  52954. }
  52955. /* If the header is read successfully, check the version number to make
  52956. ** sure the wal-index was not constructed with some future format that
  52957. ** this version of SQLite cannot understand.
  52958. */
  52959. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  52960. rc = SQLITE_CANTOPEN_BKPT;
  52961. }
  52962. return rc;
  52963. }
  52964. /*
  52965. ** This is the value that walTryBeginRead returns when it needs to
  52966. ** be retried.
  52967. */
  52968. #define WAL_RETRY (-1)
  52969. /*
  52970. ** Attempt to start a read transaction. This might fail due to a race or
  52971. ** other transient condition. When that happens, it returns WAL_RETRY to
  52972. ** indicate to the caller that it is safe to retry immediately.
  52973. **
  52974. ** On success return SQLITE_OK. On a permanent failure (such an
  52975. ** I/O error or an SQLITE_BUSY because another process is running
  52976. ** recovery) return a positive error code.
  52977. **
  52978. ** The useWal parameter is true to force the use of the WAL and disable
  52979. ** the case where the WAL is bypassed because it has been completely
  52980. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  52981. ** to make a copy of the wal-index header into pWal->hdr. If the
  52982. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  52983. ** to the caller that the local paget cache is obsolete and needs to be
  52984. ** flushed.) When useWal==1, the wal-index header is assumed to already
  52985. ** be loaded and the pChanged parameter is unused.
  52986. **
  52987. ** The caller must set the cnt parameter to the number of prior calls to
  52988. ** this routine during the current read attempt that returned WAL_RETRY.
  52989. ** This routine will start taking more aggressive measures to clear the
  52990. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  52991. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  52992. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  52993. ** and is not honoring the locking protocol. There is a vanishingly small
  52994. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  52995. ** bad luck when there is lots of contention for the wal-index, but that
  52996. ** possibility is so small that it can be safely neglected, we believe.
  52997. **
  52998. ** On success, this routine obtains a read lock on
  52999. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  53000. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  53001. ** that means the Wal does not hold any read lock. The reader must not
  53002. ** access any database page that is modified by a WAL frame up to and
  53003. ** including frame number aReadMark[pWal->readLock]. The reader will
  53004. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  53005. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  53006. ** completely and get all content directly from the database file.
  53007. ** If the useWal parameter is 1 then the WAL will never be ignored and
  53008. ** this routine will always set pWal->readLock>0 on success.
  53009. ** When the read transaction is completed, the caller must release the
  53010. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  53011. **
  53012. ** This routine uses the nBackfill and aReadMark[] fields of the header
  53013. ** to select a particular WAL_READ_LOCK() that strives to let the
  53014. ** checkpoint process do as much work as possible. This routine might
  53015. ** update values of the aReadMark[] array in the header, but if it does
  53016. ** so it takes care to hold an exclusive lock on the corresponding
  53017. ** WAL_READ_LOCK() while changing values.
  53018. */
  53019. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  53020. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  53021. u32 mxReadMark; /* Largest aReadMark[] value */
  53022. int mxI; /* Index of largest aReadMark[] value */
  53023. int i; /* Loop counter */
  53024. int rc = SQLITE_OK; /* Return code */
  53025. u32 mxFrame; /* Wal frame to lock to */
  53026. assert( pWal->readLock<0 ); /* Not currently locked */
  53027. /* Take steps to avoid spinning forever if there is a protocol error.
  53028. **
  53029. ** Circumstances that cause a RETRY should only last for the briefest
  53030. ** instances of time. No I/O or other system calls are done while the
  53031. ** locks are held, so the locks should not be held for very long. But
  53032. ** if we are unlucky, another process that is holding a lock might get
  53033. ** paged out or take a page-fault that is time-consuming to resolve,
  53034. ** during the few nanoseconds that it is holding the lock. In that case,
  53035. ** it might take longer than normal for the lock to free.
  53036. **
  53037. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  53038. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  53039. ** is more of a scheduler yield than an actual delay. But on the 10th
  53040. ** an subsequent retries, the delays start becoming longer and longer,
  53041. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  53042. ** The total delay time before giving up is less than 10 seconds.
  53043. */
  53044. if( cnt>5 ){
  53045. int nDelay = 1; /* Pause time in microseconds */
  53046. if( cnt>100 ){
  53047. VVA_ONLY( pWal->lockError = 1; )
  53048. return SQLITE_PROTOCOL;
  53049. }
  53050. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  53051. sqlite3OsSleep(pWal->pVfs, nDelay);
  53052. }
  53053. if( !useWal ){
  53054. rc = walIndexReadHdr(pWal, pChanged);
  53055. if( rc==SQLITE_BUSY ){
  53056. /* If there is not a recovery running in another thread or process
  53057. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  53058. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  53059. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  53060. ** would be technically correct. But the race is benign since with
  53061. ** WAL_RETRY this routine will be called again and will probably be
  53062. ** right on the second iteration.
  53063. */
  53064. if( pWal->apWiData[0]==0 ){
  53065. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  53066. ** We assume this is a transient condition, so return WAL_RETRY. The
  53067. ** xShmMap() implementation used by the default unix and win32 VFS
  53068. ** modules may return SQLITE_BUSY due to a race condition in the
  53069. ** code that determines whether or not the shared-memory region
  53070. ** must be zeroed before the requested page is returned.
  53071. */
  53072. rc = WAL_RETRY;
  53073. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  53074. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  53075. rc = WAL_RETRY;
  53076. }else if( rc==SQLITE_BUSY ){
  53077. rc = SQLITE_BUSY_RECOVERY;
  53078. }
  53079. }
  53080. if( rc!=SQLITE_OK ){
  53081. return rc;
  53082. }
  53083. }
  53084. pInfo = walCkptInfo(pWal);
  53085. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  53086. #ifdef SQLITE_ENABLE_SNAPSHOT
  53087. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
  53088. || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
  53089. #endif
  53090. ){
  53091. /* The WAL has been completely backfilled (or it is empty).
  53092. ** and can be safely ignored.
  53093. */
  53094. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  53095. walShmBarrier(pWal);
  53096. if( rc==SQLITE_OK ){
  53097. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  53098. /* It is not safe to allow the reader to continue here if frames
  53099. ** may have been appended to the log before READ_LOCK(0) was obtained.
  53100. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  53101. ** which implies that the database file contains a trustworthy
  53102. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  53103. ** happening, this is usually correct.
  53104. **
  53105. ** However, if frames have been appended to the log (or if the log
  53106. ** is wrapped and written for that matter) before the READ_LOCK(0)
  53107. ** is obtained, that is not necessarily true. A checkpointer may
  53108. ** have started to backfill the appended frames but crashed before
  53109. ** it finished. Leaving a corrupt image in the database file.
  53110. */
  53111. walUnlockShared(pWal, WAL_READ_LOCK(0));
  53112. return WAL_RETRY;
  53113. }
  53114. pWal->readLock = 0;
  53115. return SQLITE_OK;
  53116. }else if( rc!=SQLITE_BUSY ){
  53117. return rc;
  53118. }
  53119. }
  53120. /* If we get this far, it means that the reader will want to use
  53121. ** the WAL to get at content from recent commits. The job now is
  53122. ** to select one of the aReadMark[] entries that is closest to
  53123. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  53124. */
  53125. mxReadMark = 0;
  53126. mxI = 0;
  53127. mxFrame = pWal->hdr.mxFrame;
  53128. #ifdef SQLITE_ENABLE_SNAPSHOT
  53129. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  53130. mxFrame = pWal->pSnapshot->mxFrame;
  53131. }
  53132. #endif
  53133. for(i=1; i<WAL_NREADER; i++){
  53134. u32 thisMark = pInfo->aReadMark[i];
  53135. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  53136. assert( thisMark!=READMARK_NOT_USED );
  53137. mxReadMark = thisMark;
  53138. mxI = i;
  53139. }
  53140. }
  53141. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  53142. && (mxReadMark<mxFrame || mxI==0)
  53143. ){
  53144. for(i=1; i<WAL_NREADER; i++){
  53145. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  53146. if( rc==SQLITE_OK ){
  53147. mxReadMark = pInfo->aReadMark[i] = mxFrame;
  53148. mxI = i;
  53149. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  53150. break;
  53151. }else if( rc!=SQLITE_BUSY ){
  53152. return rc;
  53153. }
  53154. }
  53155. }
  53156. if( mxI==0 ){
  53157. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  53158. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  53159. }
  53160. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  53161. if( rc ){
  53162. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  53163. }
  53164. /* Now that the read-lock has been obtained, check that neither the
  53165. ** value in the aReadMark[] array or the contents of the wal-index
  53166. ** header have changed.
  53167. **
  53168. ** It is necessary to check that the wal-index header did not change
  53169. ** between the time it was read and when the shared-lock was obtained
  53170. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  53171. ** that the log file may have been wrapped by a writer, or that frames
  53172. ** that occur later in the log than pWal->hdr.mxFrame may have been
  53173. ** copied into the database by a checkpointer. If either of these things
  53174. ** happened, then reading the database with the current value of
  53175. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  53176. ** instead.
  53177. **
  53178. ** Before checking that the live wal-index header has not changed
  53179. ** since it was read, set Wal.minFrame to the first frame in the wal
  53180. ** file that has not yet been checkpointed. This client will not need
  53181. ** to read any frames earlier than minFrame from the wal file - they
  53182. ** can be safely read directly from the database file.
  53183. **
  53184. ** Because a ShmBarrier() call is made between taking the copy of
  53185. ** nBackfill and checking that the wal-header in shared-memory still
  53186. ** matches the one cached in pWal->hdr, it is guaranteed that the
  53187. ** checkpointer that set nBackfill was not working with a wal-index
  53188. ** header newer than that cached in pWal->hdr. If it were, that could
  53189. ** cause a problem. The checkpointer could omit to checkpoint
  53190. ** a version of page X that lies before pWal->minFrame (call that version
  53191. ** A) on the basis that there is a newer version (version B) of the same
  53192. ** page later in the wal file. But if version B happens to like past
  53193. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  53194. ** that it can read version A from the database file. However, since
  53195. ** we can guarantee that the checkpointer that set nBackfill could not
  53196. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  53197. */
  53198. pWal->minFrame = pInfo->nBackfill+1;
  53199. walShmBarrier(pWal);
  53200. if( pInfo->aReadMark[mxI]!=mxReadMark
  53201. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  53202. ){
  53203. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  53204. return WAL_RETRY;
  53205. }else{
  53206. assert( mxReadMark<=pWal->hdr.mxFrame );
  53207. pWal->readLock = (i16)mxI;
  53208. }
  53209. return rc;
  53210. }
  53211. #ifdef SQLITE_ENABLE_SNAPSHOT
  53212. /*
  53213. ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
  53214. ** variable so that older snapshots can be accessed. To do this, loop
  53215. ** through all wal frames from nBackfillAttempted to (nBackfill+1),
  53216. ** comparing their content to the corresponding page with the database
  53217. ** file, if any. Set nBackfillAttempted to the frame number of the
  53218. ** first frame for which the wal file content matches the db file.
  53219. **
  53220. ** This is only really safe if the file-system is such that any page
  53221. ** writes made by earlier checkpointers were atomic operations, which
  53222. ** is not always true. It is also possible that nBackfillAttempted
  53223. ** may be left set to a value larger than expected, if a wal frame
  53224. ** contains content that duplicate of an earlier version of the same
  53225. ** page.
  53226. **
  53227. ** SQLITE_OK is returned if successful, or an SQLite error code if an
  53228. ** error occurs. It is not an error if nBackfillAttempted cannot be
  53229. ** decreased at all.
  53230. */
  53231. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
  53232. int rc;
  53233. assert( pWal->readLock>=0 );
  53234. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  53235. if( rc==SQLITE_OK ){
  53236. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  53237. int szPage = (int)pWal->szPage;
  53238. i64 szDb; /* Size of db file in bytes */
  53239. rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
  53240. if( rc==SQLITE_OK ){
  53241. void *pBuf1 = sqlite3_malloc(szPage);
  53242. void *pBuf2 = sqlite3_malloc(szPage);
  53243. if( pBuf1==0 || pBuf2==0 ){
  53244. rc = SQLITE_NOMEM;
  53245. }else{
  53246. u32 i = pInfo->nBackfillAttempted;
  53247. for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
  53248. volatile ht_slot *dummy;
  53249. volatile u32 *aPgno; /* Array of page numbers */
  53250. u32 iZero; /* Frame corresponding to aPgno[0] */
  53251. u32 pgno; /* Page number in db file */
  53252. i64 iDbOff; /* Offset of db file entry */
  53253. i64 iWalOff; /* Offset of wal file entry */
  53254. rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
  53255. if( rc!=SQLITE_OK ) break;
  53256. pgno = aPgno[i-iZero];
  53257. iDbOff = (i64)(pgno-1) * szPage;
  53258. if( iDbOff+szPage<=szDb ){
  53259. iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
  53260. rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
  53261. if( rc==SQLITE_OK ){
  53262. rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
  53263. }
  53264. if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
  53265. break;
  53266. }
  53267. }
  53268. pInfo->nBackfillAttempted = i-1;
  53269. }
  53270. }
  53271. sqlite3_free(pBuf1);
  53272. sqlite3_free(pBuf2);
  53273. }
  53274. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  53275. }
  53276. return rc;
  53277. }
  53278. #endif /* SQLITE_ENABLE_SNAPSHOT */
  53279. /*
  53280. ** Begin a read transaction on the database.
  53281. **
  53282. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  53283. ** it takes a snapshot of the state of the WAL and wal-index for the current
  53284. ** instant in time. The current thread will continue to use this snapshot.
  53285. ** Other threads might append new content to the WAL and wal-index but
  53286. ** that extra content is ignored by the current thread.
  53287. **
  53288. ** If the database contents have changes since the previous read
  53289. ** transaction, then *pChanged is set to 1 before returning. The
  53290. ** Pager layer will use this to know that is cache is stale and
  53291. ** needs to be flushed.
  53292. */
  53293. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  53294. int rc; /* Return code */
  53295. int cnt = 0; /* Number of TryBeginRead attempts */
  53296. #ifdef SQLITE_ENABLE_SNAPSHOT
  53297. int bChanged = 0;
  53298. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  53299. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  53300. bChanged = 1;
  53301. }
  53302. #endif
  53303. do{
  53304. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  53305. }while( rc==WAL_RETRY );
  53306. testcase( (rc&0xff)==SQLITE_BUSY );
  53307. testcase( (rc&0xff)==SQLITE_IOERR );
  53308. testcase( rc==SQLITE_PROTOCOL );
  53309. testcase( rc==SQLITE_OK );
  53310. #ifdef SQLITE_ENABLE_SNAPSHOT
  53311. if( rc==SQLITE_OK ){
  53312. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  53313. /* At this point the client has a lock on an aReadMark[] slot holding
  53314. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  53315. ** is populated with the wal-index header corresponding to the head
  53316. ** of the wal file. Verify that pSnapshot is still valid before
  53317. ** continuing. Reasons why pSnapshot might no longer be valid:
  53318. **
  53319. ** (1) The WAL file has been reset since the snapshot was taken.
  53320. ** In this case, the salt will have changed.
  53321. **
  53322. ** (2) A checkpoint as been attempted that wrote frames past
  53323. ** pSnapshot->mxFrame into the database file. Note that the
  53324. ** checkpoint need not have completed for this to cause problems.
  53325. */
  53326. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  53327. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  53328. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  53329. /* It is possible that there is a checkpointer thread running
  53330. ** concurrent with this code. If this is the case, it may be that the
  53331. ** checkpointer has already determined that it will checkpoint
  53332. ** snapshot X, where X is later in the wal file than pSnapshot, but
  53333. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  53334. ** its intent. To avoid the race condition this leads to, ensure that
  53335. ** there is no checkpointer process by taking a shared CKPT lock
  53336. ** before checking pInfo->nBackfillAttempted.
  53337. **
  53338. ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
  53339. ** this already?
  53340. */
  53341. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  53342. if( rc==SQLITE_OK ){
  53343. /* Check that the wal file has not been wrapped. Assuming that it has
  53344. ** not, also check that no checkpointer has attempted to checkpoint any
  53345. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  53346. ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
  53347. ** with *pSnapshot and set *pChanged as appropriate for opening the
  53348. ** snapshot. */
  53349. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  53350. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  53351. ){
  53352. assert( pWal->readLock>0 );
  53353. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  53354. *pChanged = bChanged;
  53355. }else{
  53356. rc = SQLITE_BUSY_SNAPSHOT;
  53357. }
  53358. /* Release the shared CKPT lock obtained above. */
  53359. walUnlockShared(pWal, WAL_CKPT_LOCK);
  53360. }
  53361. if( rc!=SQLITE_OK ){
  53362. sqlite3WalEndReadTransaction(pWal);
  53363. }
  53364. }
  53365. }
  53366. #endif
  53367. return rc;
  53368. }
  53369. /*
  53370. ** Finish with a read transaction. All this does is release the
  53371. ** read-lock.
  53372. */
  53373. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  53374. sqlite3WalEndWriteTransaction(pWal);
  53375. if( pWal->readLock>=0 ){
  53376. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  53377. pWal->readLock = -1;
  53378. }
  53379. }
  53380. /*
  53381. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  53382. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  53383. ** to zero.
  53384. **
  53385. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  53386. ** error does occur, the final value of *piRead is undefined.
  53387. */
  53388. SQLITE_PRIVATE int sqlite3WalFindFrame(
  53389. Wal *pWal, /* WAL handle */
  53390. Pgno pgno, /* Database page number to read data for */
  53391. u32 *piRead /* OUT: Frame number (or zero) */
  53392. ){
  53393. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  53394. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  53395. int iHash; /* Used to loop through N hash tables */
  53396. int iMinHash;
  53397. /* This routine is only be called from within a read transaction. */
  53398. assert( pWal->readLock>=0 || pWal->lockError );
  53399. /* If the "last page" field of the wal-index header snapshot is 0, then
  53400. ** no data will be read from the wal under any circumstances. Return early
  53401. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  53402. ** then the WAL is ignored by the reader so return early, as if the
  53403. ** WAL were empty.
  53404. */
  53405. if( iLast==0 || pWal->readLock==0 ){
  53406. *piRead = 0;
  53407. return SQLITE_OK;
  53408. }
  53409. /* Search the hash table or tables for an entry matching page number
  53410. ** pgno. Each iteration of the following for() loop searches one
  53411. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  53412. **
  53413. ** This code might run concurrently to the code in walIndexAppend()
  53414. ** that adds entries to the wal-index (and possibly to this hash
  53415. ** table). This means the value just read from the hash
  53416. ** slot (aHash[iKey]) may have been added before or after the
  53417. ** current read transaction was opened. Values added after the
  53418. ** read transaction was opened may have been written incorrectly -
  53419. ** i.e. these slots may contain garbage data. However, we assume
  53420. ** that any slots written before the current read transaction was
  53421. ** opened remain unmodified.
  53422. **
  53423. ** For the reasons above, the if(...) condition featured in the inner
  53424. ** loop of the following block is more stringent that would be required
  53425. ** if we had exclusive access to the hash-table:
  53426. **
  53427. ** (aPgno[iFrame]==pgno):
  53428. ** This condition filters out normal hash-table collisions.
  53429. **
  53430. ** (iFrame<=iLast):
  53431. ** This condition filters out entries that were added to the hash
  53432. ** table after the current read-transaction had started.
  53433. */
  53434. iMinHash = walFramePage(pWal->minFrame);
  53435. for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
  53436. volatile ht_slot *aHash; /* Pointer to hash table */
  53437. volatile u32 *aPgno; /* Pointer to array of page numbers */
  53438. u32 iZero; /* Frame number corresponding to aPgno[0] */
  53439. int iKey; /* Hash slot index */
  53440. int nCollide; /* Number of hash collisions remaining */
  53441. int rc; /* Error code */
  53442. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  53443. if( rc!=SQLITE_OK ){
  53444. return rc;
  53445. }
  53446. nCollide = HASHTABLE_NSLOT;
  53447. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  53448. u32 iFrame = aHash[iKey] + iZero;
  53449. if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
  53450. assert( iFrame>iRead || CORRUPT_DB );
  53451. iRead = iFrame;
  53452. }
  53453. if( (nCollide--)==0 ){
  53454. return SQLITE_CORRUPT_BKPT;
  53455. }
  53456. }
  53457. }
  53458. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  53459. /* If expensive assert() statements are available, do a linear search
  53460. ** of the wal-index file content. Make sure the results agree with the
  53461. ** result obtained using the hash indexes above. */
  53462. {
  53463. u32 iRead2 = 0;
  53464. u32 iTest;
  53465. assert( pWal->minFrame>0 );
  53466. for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
  53467. if( walFramePgno(pWal, iTest)==pgno ){
  53468. iRead2 = iTest;
  53469. break;
  53470. }
  53471. }
  53472. assert( iRead==iRead2 );
  53473. }
  53474. #endif
  53475. *piRead = iRead;
  53476. return SQLITE_OK;
  53477. }
  53478. /*
  53479. ** Read the contents of frame iRead from the wal file into buffer pOut
  53480. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  53481. ** error code otherwise.
  53482. */
  53483. SQLITE_PRIVATE int sqlite3WalReadFrame(
  53484. Wal *pWal, /* WAL handle */
  53485. u32 iRead, /* Frame to read */
  53486. int nOut, /* Size of buffer pOut in bytes */
  53487. u8 *pOut /* Buffer to write page data to */
  53488. ){
  53489. int sz;
  53490. i64 iOffset;
  53491. sz = pWal->hdr.szPage;
  53492. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  53493. testcase( sz<=32768 );
  53494. testcase( sz>=65536 );
  53495. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  53496. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  53497. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  53498. }
  53499. /*
  53500. ** Return the size of the database in pages (or zero, if unknown).
  53501. */
  53502. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  53503. if( pWal && ALWAYS(pWal->readLock>=0) ){
  53504. return pWal->hdr.nPage;
  53505. }
  53506. return 0;
  53507. }
  53508. /*
  53509. ** This function starts a write transaction on the WAL.
  53510. **
  53511. ** A read transaction must have already been started by a prior call
  53512. ** to sqlite3WalBeginReadTransaction().
  53513. **
  53514. ** If another thread or process has written into the database since
  53515. ** the read transaction was started, then it is not possible for this
  53516. ** thread to write as doing so would cause a fork. So this routine
  53517. ** returns SQLITE_BUSY in that case and no write transaction is started.
  53518. **
  53519. ** There can only be a single writer active at a time.
  53520. */
  53521. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  53522. int rc;
  53523. /* Cannot start a write transaction without first holding a read
  53524. ** transaction. */
  53525. assert( pWal->readLock>=0 );
  53526. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  53527. if( pWal->readOnly ){
  53528. return SQLITE_READONLY;
  53529. }
  53530. /* Only one writer allowed at a time. Get the write lock. Return
  53531. ** SQLITE_BUSY if unable.
  53532. */
  53533. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  53534. if( rc ){
  53535. return rc;
  53536. }
  53537. pWal->writeLock = 1;
  53538. /* If another connection has written to the database file since the
  53539. ** time the read transaction on this connection was started, then
  53540. ** the write is disallowed.
  53541. */
  53542. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  53543. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  53544. pWal->writeLock = 0;
  53545. rc = SQLITE_BUSY_SNAPSHOT;
  53546. }
  53547. return rc;
  53548. }
  53549. /*
  53550. ** End a write transaction. The commit has already been done. This
  53551. ** routine merely releases the lock.
  53552. */
  53553. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  53554. if( pWal->writeLock ){
  53555. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  53556. pWal->writeLock = 0;
  53557. pWal->iReCksum = 0;
  53558. pWal->truncateOnCommit = 0;
  53559. }
  53560. return SQLITE_OK;
  53561. }
  53562. /*
  53563. ** If any data has been written (but not committed) to the log file, this
  53564. ** function moves the write-pointer back to the start of the transaction.
  53565. **
  53566. ** Additionally, the callback function is invoked for each frame written
  53567. ** to the WAL since the start of the transaction. If the callback returns
  53568. ** other than SQLITE_OK, it is not invoked again and the error code is
  53569. ** returned to the caller.
  53570. **
  53571. ** Otherwise, if the callback function does not return an error, this
  53572. ** function returns SQLITE_OK.
  53573. */
  53574. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  53575. int rc = SQLITE_OK;
  53576. if( ALWAYS(pWal->writeLock) ){
  53577. Pgno iMax = pWal->hdr.mxFrame;
  53578. Pgno iFrame;
  53579. /* Restore the clients cache of the wal-index header to the state it
  53580. ** was in before the client began writing to the database.
  53581. */
  53582. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  53583. for(iFrame=pWal->hdr.mxFrame+1;
  53584. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  53585. iFrame++
  53586. ){
  53587. /* This call cannot fail. Unless the page for which the page number
  53588. ** is passed as the second argument is (a) in the cache and
  53589. ** (b) has an outstanding reference, then xUndo is either a no-op
  53590. ** (if (a) is false) or simply expels the page from the cache (if (b)
  53591. ** is false).
  53592. **
  53593. ** If the upper layer is doing a rollback, it is guaranteed that there
  53594. ** are no outstanding references to any page other than page 1. And
  53595. ** page 1 is never written to the log until the transaction is
  53596. ** committed. As a result, the call to xUndo may not fail.
  53597. */
  53598. assert( walFramePgno(pWal, iFrame)!=1 );
  53599. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  53600. }
  53601. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  53602. }
  53603. return rc;
  53604. }
  53605. /*
  53606. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  53607. ** values. This function populates the array with values required to
  53608. ** "rollback" the write position of the WAL handle back to the current
  53609. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  53610. */
  53611. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  53612. assert( pWal->writeLock );
  53613. aWalData[0] = pWal->hdr.mxFrame;
  53614. aWalData[1] = pWal->hdr.aFrameCksum[0];
  53615. aWalData[2] = pWal->hdr.aFrameCksum[1];
  53616. aWalData[3] = pWal->nCkpt;
  53617. }
  53618. /*
  53619. ** Move the write position of the WAL back to the point identified by
  53620. ** the values in the aWalData[] array. aWalData must point to an array
  53621. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  53622. ** by a call to WalSavepoint().
  53623. */
  53624. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  53625. int rc = SQLITE_OK;
  53626. assert( pWal->writeLock );
  53627. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  53628. if( aWalData[3]!=pWal->nCkpt ){
  53629. /* This savepoint was opened immediately after the write-transaction
  53630. ** was started. Right after that, the writer decided to wrap around
  53631. ** to the start of the log. Update the savepoint values to match.
  53632. */
  53633. aWalData[0] = 0;
  53634. aWalData[3] = pWal->nCkpt;
  53635. }
  53636. if( aWalData[0]<pWal->hdr.mxFrame ){
  53637. pWal->hdr.mxFrame = aWalData[0];
  53638. pWal->hdr.aFrameCksum[0] = aWalData[1];
  53639. pWal->hdr.aFrameCksum[1] = aWalData[2];
  53640. walCleanupHash(pWal);
  53641. }
  53642. return rc;
  53643. }
  53644. /*
  53645. ** This function is called just before writing a set of frames to the log
  53646. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  53647. ** to the current log file, it is possible to overwrite the start of the
  53648. ** existing log file with the new frames (i.e. "reset" the log). If so,
  53649. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  53650. ** unchanged.
  53651. **
  53652. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  53653. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  53654. ** if an error occurs.
  53655. */
  53656. static int walRestartLog(Wal *pWal){
  53657. int rc = SQLITE_OK;
  53658. int cnt;
  53659. if( pWal->readLock==0 ){
  53660. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  53661. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  53662. if( pInfo->nBackfill>0 ){
  53663. u32 salt1;
  53664. sqlite3_randomness(4, &salt1);
  53665. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  53666. if( rc==SQLITE_OK ){
  53667. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  53668. ** readers are currently using the WAL), then the transactions
  53669. ** frames will overwrite the start of the existing log. Update the
  53670. ** wal-index header to reflect this.
  53671. **
  53672. ** In theory it would be Ok to update the cache of the header only
  53673. ** at this point. But updating the actual wal-index header is also
  53674. ** safe and means there is no special case for sqlite3WalUndo()
  53675. ** to handle if this transaction is rolled back. */
  53676. walRestartHdr(pWal, salt1);
  53677. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  53678. }else if( rc!=SQLITE_BUSY ){
  53679. return rc;
  53680. }
  53681. }
  53682. walUnlockShared(pWal, WAL_READ_LOCK(0));
  53683. pWal->readLock = -1;
  53684. cnt = 0;
  53685. do{
  53686. int notUsed;
  53687. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  53688. }while( rc==WAL_RETRY );
  53689. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  53690. testcase( (rc&0xff)==SQLITE_IOERR );
  53691. testcase( rc==SQLITE_PROTOCOL );
  53692. testcase( rc==SQLITE_OK );
  53693. }
  53694. return rc;
  53695. }
  53696. /*
  53697. ** Information about the current state of the WAL file and where
  53698. ** the next fsync should occur - passed from sqlite3WalFrames() into
  53699. ** walWriteToLog().
  53700. */
  53701. typedef struct WalWriter {
  53702. Wal *pWal; /* The complete WAL information */
  53703. sqlite3_file *pFd; /* The WAL file to which we write */
  53704. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  53705. int syncFlags; /* Flags for the fsync */
  53706. int szPage; /* Size of one page */
  53707. } WalWriter;
  53708. /*
  53709. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  53710. ** Do a sync when crossing the p->iSyncPoint boundary.
  53711. **
  53712. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  53713. ** first write the part before iSyncPoint, then sync, then write the
  53714. ** rest.
  53715. */
  53716. static int walWriteToLog(
  53717. WalWriter *p, /* WAL to write to */
  53718. void *pContent, /* Content to be written */
  53719. int iAmt, /* Number of bytes to write */
  53720. sqlite3_int64 iOffset /* Start writing at this offset */
  53721. ){
  53722. int rc;
  53723. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  53724. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  53725. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  53726. if( rc ) return rc;
  53727. iOffset += iFirstAmt;
  53728. iAmt -= iFirstAmt;
  53729. pContent = (void*)(iFirstAmt + (char*)pContent);
  53730. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  53731. rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  53732. if( iAmt==0 || rc ) return rc;
  53733. }
  53734. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  53735. return rc;
  53736. }
  53737. /*
  53738. ** Write out a single frame of the WAL
  53739. */
  53740. static int walWriteOneFrame(
  53741. WalWriter *p, /* Where to write the frame */
  53742. PgHdr *pPage, /* The page of the frame to be written */
  53743. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  53744. sqlite3_int64 iOffset /* Byte offset at which to write */
  53745. ){
  53746. int rc; /* Result code from subfunctions */
  53747. void *pData; /* Data actually written */
  53748. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  53749. #if defined(SQLITE_HAS_CODEC)
  53750. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
  53751. #else
  53752. pData = pPage->pData;
  53753. #endif
  53754. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  53755. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  53756. if( rc ) return rc;
  53757. /* Write the page data */
  53758. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  53759. return rc;
  53760. }
  53761. /*
  53762. ** This function is called as part of committing a transaction within which
  53763. ** one or more frames have been overwritten. It updates the checksums for
  53764. ** all frames written to the wal file by the current transaction starting
  53765. ** with the earliest to have been overwritten.
  53766. **
  53767. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  53768. */
  53769. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  53770. const int szPage = pWal->szPage;/* Database page size */
  53771. int rc = SQLITE_OK; /* Return code */
  53772. u8 *aBuf; /* Buffer to load data from wal file into */
  53773. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  53774. u32 iRead; /* Next frame to read from wal file */
  53775. i64 iCksumOff;
  53776. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  53777. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  53778. /* Find the checksum values to use as input for the recalculating the
  53779. ** first checksum. If the first frame is frame 1 (implying that the current
  53780. ** transaction restarted the wal file), these values must be read from the
  53781. ** wal-file header. Otherwise, read them from the frame header of the
  53782. ** previous frame. */
  53783. assert( pWal->iReCksum>0 );
  53784. if( pWal->iReCksum==1 ){
  53785. iCksumOff = 24;
  53786. }else{
  53787. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  53788. }
  53789. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  53790. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  53791. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  53792. iRead = pWal->iReCksum;
  53793. pWal->iReCksum = 0;
  53794. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  53795. i64 iOff = walFrameOffset(iRead, szPage);
  53796. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  53797. if( rc==SQLITE_OK ){
  53798. u32 iPgno, nDbSize;
  53799. iPgno = sqlite3Get4byte(aBuf);
  53800. nDbSize = sqlite3Get4byte(&aBuf[4]);
  53801. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  53802. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  53803. }
  53804. }
  53805. sqlite3_free(aBuf);
  53806. return rc;
  53807. }
  53808. /*
  53809. ** Write a set of frames to the log. The caller must hold the write-lock
  53810. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  53811. */
  53812. SQLITE_PRIVATE int sqlite3WalFrames(
  53813. Wal *pWal, /* Wal handle to write to */
  53814. int szPage, /* Database page-size in bytes */
  53815. PgHdr *pList, /* List of dirty pages to write */
  53816. Pgno nTruncate, /* Database size after this commit */
  53817. int isCommit, /* True if this is a commit */
  53818. int sync_flags /* Flags to pass to OsSync() (or 0) */
  53819. ){
  53820. int rc; /* Used to catch return codes */
  53821. u32 iFrame; /* Next frame address */
  53822. PgHdr *p; /* Iterator to run through pList with. */
  53823. PgHdr *pLast = 0; /* Last frame in list */
  53824. int nExtra = 0; /* Number of extra copies of last page */
  53825. int szFrame; /* The size of a single frame */
  53826. i64 iOffset; /* Next byte to write in WAL file */
  53827. WalWriter w; /* The writer */
  53828. u32 iFirst = 0; /* First frame that may be overwritten */
  53829. WalIndexHdr *pLive; /* Pointer to shared header */
  53830. assert( pList );
  53831. assert( pWal->writeLock );
  53832. /* If this frame set completes a transaction, then nTruncate>0. If
  53833. ** nTruncate==0 then this frame set does not complete the transaction. */
  53834. assert( (isCommit!=0)==(nTruncate!=0) );
  53835. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  53836. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  53837. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  53838. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  53839. }
  53840. #endif
  53841. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  53842. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  53843. iFirst = pLive->mxFrame+1;
  53844. }
  53845. /* See if it is possible to write these frames into the start of the
  53846. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  53847. */
  53848. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  53849. return rc;
  53850. }
  53851. /* If this is the first frame written into the log, write the WAL
  53852. ** header to the start of the WAL file. See comments at the top of
  53853. ** this source file for a description of the WAL header format.
  53854. */
  53855. iFrame = pWal->hdr.mxFrame;
  53856. if( iFrame==0 ){
  53857. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  53858. u32 aCksum[2]; /* Checksum for wal-header */
  53859. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  53860. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  53861. sqlite3Put4byte(&aWalHdr[8], szPage);
  53862. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  53863. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  53864. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  53865. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  53866. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  53867. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  53868. pWal->szPage = szPage;
  53869. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  53870. pWal->hdr.aFrameCksum[0] = aCksum[0];
  53871. pWal->hdr.aFrameCksum[1] = aCksum[1];
  53872. pWal->truncateOnCommit = 1;
  53873. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  53874. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  53875. if( rc!=SQLITE_OK ){
  53876. return rc;
  53877. }
  53878. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  53879. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  53880. ** an out-of-order write following a WAL restart could result in
  53881. ** database corruption. See the ticket:
  53882. **
  53883. ** http://localhost:591/sqlite/info/ff5be73dee
  53884. */
  53885. if( pWal->syncHeader && sync_flags ){
  53886. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  53887. if( rc ) return rc;
  53888. }
  53889. }
  53890. assert( (int)pWal->szPage==szPage );
  53891. /* Setup information needed to write frames into the WAL */
  53892. w.pWal = pWal;
  53893. w.pFd = pWal->pWalFd;
  53894. w.iSyncPoint = 0;
  53895. w.syncFlags = sync_flags;
  53896. w.szPage = szPage;
  53897. iOffset = walFrameOffset(iFrame+1, szPage);
  53898. szFrame = szPage + WAL_FRAME_HDRSIZE;
  53899. /* Write all frames into the log file exactly once */
  53900. for(p=pList; p; p=p->pDirty){
  53901. int nDbSize; /* 0 normally. Positive == commit flag */
  53902. /* Check if this page has already been written into the wal file by
  53903. ** the current transaction. If so, overwrite the existing frame and
  53904. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  53905. ** checksums must be recomputed when the transaction is committed. */
  53906. if( iFirst && (p->pDirty || isCommit==0) ){
  53907. u32 iWrite = 0;
  53908. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  53909. assert( rc==SQLITE_OK || iWrite==0 );
  53910. if( iWrite>=iFirst ){
  53911. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  53912. void *pData;
  53913. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  53914. pWal->iReCksum = iWrite;
  53915. }
  53916. #if defined(SQLITE_HAS_CODEC)
  53917. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  53918. #else
  53919. pData = p->pData;
  53920. #endif
  53921. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  53922. if( rc ) return rc;
  53923. p->flags &= ~PGHDR_WAL_APPEND;
  53924. continue;
  53925. }
  53926. }
  53927. iFrame++;
  53928. assert( iOffset==walFrameOffset(iFrame, szPage) );
  53929. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  53930. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  53931. if( rc ) return rc;
  53932. pLast = p;
  53933. iOffset += szFrame;
  53934. p->flags |= PGHDR_WAL_APPEND;
  53935. }
  53936. /* Recalculate checksums within the wal file if required. */
  53937. if( isCommit && pWal->iReCksum ){
  53938. rc = walRewriteChecksums(pWal, iFrame);
  53939. if( rc ) return rc;
  53940. }
  53941. /* If this is the end of a transaction, then we might need to pad
  53942. ** the transaction and/or sync the WAL file.
  53943. **
  53944. ** Padding and syncing only occur if this set of frames complete a
  53945. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  53946. ** or synchronous==OFF, then no padding or syncing are needed.
  53947. **
  53948. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  53949. ** needed and only the sync is done. If padding is needed, then the
  53950. ** final frame is repeated (with its commit mark) until the next sector
  53951. ** boundary is crossed. Only the part of the WAL prior to the last
  53952. ** sector boundary is synced; the part of the last frame that extends
  53953. ** past the sector boundary is written after the sync.
  53954. */
  53955. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  53956. int bSync = 1;
  53957. if( pWal->padToSectorBoundary ){
  53958. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  53959. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  53960. bSync = (w.iSyncPoint==iOffset);
  53961. testcase( bSync );
  53962. while( iOffset<w.iSyncPoint ){
  53963. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  53964. if( rc ) return rc;
  53965. iOffset += szFrame;
  53966. nExtra++;
  53967. }
  53968. }
  53969. if( bSync ){
  53970. assert( rc==SQLITE_OK );
  53971. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  53972. }
  53973. }
  53974. /* If this frame set completes the first transaction in the WAL and
  53975. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  53976. ** journal size limit, if possible.
  53977. */
  53978. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  53979. i64 sz = pWal->mxWalSize;
  53980. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  53981. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  53982. }
  53983. walLimitSize(pWal, sz);
  53984. pWal->truncateOnCommit = 0;
  53985. }
  53986. /* Append data to the wal-index. It is not necessary to lock the
  53987. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  53988. ** guarantees that there are no other writers, and no data that may
  53989. ** be in use by existing readers is being overwritten.
  53990. */
  53991. iFrame = pWal->hdr.mxFrame;
  53992. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  53993. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  53994. iFrame++;
  53995. rc = walIndexAppend(pWal, iFrame, p->pgno);
  53996. }
  53997. while( rc==SQLITE_OK && nExtra>0 ){
  53998. iFrame++;
  53999. nExtra--;
  54000. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  54001. }
  54002. if( rc==SQLITE_OK ){
  54003. /* Update the private copy of the header. */
  54004. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  54005. testcase( szPage<=32768 );
  54006. testcase( szPage>=65536 );
  54007. pWal->hdr.mxFrame = iFrame;
  54008. if( isCommit ){
  54009. pWal->hdr.iChange++;
  54010. pWal->hdr.nPage = nTruncate;
  54011. }
  54012. /* If this is a commit, update the wal-index header too. */
  54013. if( isCommit ){
  54014. walIndexWriteHdr(pWal);
  54015. pWal->iCallback = iFrame;
  54016. }
  54017. }
  54018. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  54019. return rc;
  54020. }
  54021. /*
  54022. ** This routine is called to implement sqlite3_wal_checkpoint() and
  54023. ** related interfaces.
  54024. **
  54025. ** Obtain a CHECKPOINT lock and then backfill as much information as
  54026. ** we can from WAL into the database.
  54027. **
  54028. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  54029. ** callback. In this case this function runs a blocking checkpoint.
  54030. */
  54031. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  54032. Wal *pWal, /* Wal connection */
  54033. sqlite3 *db, /* Check this handle's interrupt flag */
  54034. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  54035. int (*xBusy)(void*), /* Function to call when busy */
  54036. void *pBusyArg, /* Context argument for xBusyHandler */
  54037. int sync_flags, /* Flags to sync db file with (or 0) */
  54038. int nBuf, /* Size of temporary buffer */
  54039. u8 *zBuf, /* Temporary buffer to use */
  54040. int *pnLog, /* OUT: Number of frames in WAL */
  54041. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  54042. ){
  54043. int rc; /* Return code */
  54044. int isChanged = 0; /* True if a new wal-index header is loaded */
  54045. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  54046. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  54047. assert( pWal->ckptLock==0 );
  54048. assert( pWal->writeLock==0 );
  54049. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  54050. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  54051. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  54052. if( pWal->readOnly ) return SQLITE_READONLY;
  54053. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  54054. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  54055. ** "checkpoint" lock on the database file. */
  54056. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  54057. if( rc ){
  54058. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  54059. ** checkpoint operation at the same time, the lock cannot be obtained and
  54060. ** SQLITE_BUSY is returned.
  54061. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  54062. ** it will not be invoked in this case.
  54063. */
  54064. testcase( rc==SQLITE_BUSY );
  54065. testcase( xBusy!=0 );
  54066. return rc;
  54067. }
  54068. pWal->ckptLock = 1;
  54069. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  54070. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  54071. ** file.
  54072. **
  54073. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  54074. ** immediately, and a busy-handler is configured, it is invoked and the
  54075. ** writer lock retried until either the busy-handler returns 0 or the
  54076. ** lock is successfully obtained.
  54077. */
  54078. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  54079. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  54080. if( rc==SQLITE_OK ){
  54081. pWal->writeLock = 1;
  54082. }else if( rc==SQLITE_BUSY ){
  54083. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  54084. xBusy2 = 0;
  54085. rc = SQLITE_OK;
  54086. }
  54087. }
  54088. /* Read the wal-index header. */
  54089. if( rc==SQLITE_OK ){
  54090. rc = walIndexReadHdr(pWal, &isChanged);
  54091. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  54092. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  54093. }
  54094. }
  54095. /* Copy data from the log to the database file. */
  54096. if( rc==SQLITE_OK ){
  54097. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  54098. rc = SQLITE_CORRUPT_BKPT;
  54099. }else{
  54100. rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  54101. }
  54102. /* If no error occurred, set the output variables. */
  54103. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  54104. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  54105. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  54106. }
  54107. }
  54108. if( isChanged ){
  54109. /* If a new wal-index header was loaded before the checkpoint was
  54110. ** performed, then the pager-cache associated with pWal is now
  54111. ** out of date. So zero the cached wal-index header to ensure that
  54112. ** next time the pager opens a snapshot on this database it knows that
  54113. ** the cache needs to be reset.
  54114. */
  54115. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  54116. }
  54117. /* Release the locks. */
  54118. sqlite3WalEndWriteTransaction(pWal);
  54119. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  54120. pWal->ckptLock = 0;
  54121. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  54122. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  54123. }
  54124. /* Return the value to pass to a sqlite3_wal_hook callback, the
  54125. ** number of frames in the WAL at the point of the last commit since
  54126. ** sqlite3WalCallback() was called. If no commits have occurred since
  54127. ** the last call, then return 0.
  54128. */
  54129. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  54130. u32 ret = 0;
  54131. if( pWal ){
  54132. ret = pWal->iCallback;
  54133. pWal->iCallback = 0;
  54134. }
  54135. return (int)ret;
  54136. }
  54137. /*
  54138. ** This function is called to change the WAL subsystem into or out
  54139. ** of locking_mode=EXCLUSIVE.
  54140. **
  54141. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  54142. ** into locking_mode=NORMAL. This means that we must acquire a lock
  54143. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  54144. ** or if the acquisition of the lock fails, then return 0. If the
  54145. ** transition out of exclusive-mode is successful, return 1. This
  54146. ** operation must occur while the pager is still holding the exclusive
  54147. ** lock on the main database file.
  54148. **
  54149. ** If op is one, then change from locking_mode=NORMAL into
  54150. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  54151. ** be released. Return 1 if the transition is made and 0 if the
  54152. ** WAL is already in exclusive-locking mode - meaning that this
  54153. ** routine is a no-op. The pager must already hold the exclusive lock
  54154. ** on the main database file before invoking this operation.
  54155. **
  54156. ** If op is negative, then do a dry-run of the op==1 case but do
  54157. ** not actually change anything. The pager uses this to see if it
  54158. ** should acquire the database exclusive lock prior to invoking
  54159. ** the op==1 case.
  54160. */
  54161. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  54162. int rc;
  54163. assert( pWal->writeLock==0 );
  54164. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  54165. /* pWal->readLock is usually set, but might be -1 if there was a
  54166. ** prior error while attempting to acquire are read-lock. This cannot
  54167. ** happen if the connection is actually in exclusive mode (as no xShmLock
  54168. ** locks are taken in this case). Nor should the pager attempt to
  54169. ** upgrade to exclusive-mode following such an error.
  54170. */
  54171. assert( pWal->readLock>=0 || pWal->lockError );
  54172. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  54173. if( op==0 ){
  54174. if( pWal->exclusiveMode ){
  54175. pWal->exclusiveMode = 0;
  54176. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  54177. pWal->exclusiveMode = 1;
  54178. }
  54179. rc = pWal->exclusiveMode==0;
  54180. }else{
  54181. /* Already in locking_mode=NORMAL */
  54182. rc = 0;
  54183. }
  54184. }else if( op>0 ){
  54185. assert( pWal->exclusiveMode==0 );
  54186. assert( pWal->readLock>=0 );
  54187. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  54188. pWal->exclusiveMode = 1;
  54189. rc = 1;
  54190. }else{
  54191. rc = pWal->exclusiveMode==0;
  54192. }
  54193. return rc;
  54194. }
  54195. /*
  54196. ** Return true if the argument is non-NULL and the WAL module is using
  54197. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  54198. ** WAL module is using shared-memory, return false.
  54199. */
  54200. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  54201. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  54202. }
  54203. #ifdef SQLITE_ENABLE_SNAPSHOT
  54204. /* Create a snapshot object. The content of a snapshot is opaque to
  54205. ** every other subsystem, so the WAL module can put whatever it needs
  54206. ** in the object.
  54207. */
  54208. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  54209. int rc = SQLITE_OK;
  54210. WalIndexHdr *pRet;
  54211. static const u32 aZero[4] = { 0, 0, 0, 0 };
  54212. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  54213. if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  54214. *ppSnapshot = 0;
  54215. return SQLITE_ERROR;
  54216. }
  54217. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  54218. if( pRet==0 ){
  54219. rc = SQLITE_NOMEM_BKPT;
  54220. }else{
  54221. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  54222. *ppSnapshot = (sqlite3_snapshot*)pRet;
  54223. }
  54224. return rc;
  54225. }
  54226. /* Try to open on pSnapshot when the next read-transaction starts
  54227. */
  54228. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  54229. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  54230. }
  54231. /*
  54232. ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
  54233. ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
  54234. */
  54235. SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
  54236. WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
  54237. WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
  54238. /* aSalt[0] is a copy of the value stored in the wal file header. It
  54239. ** is incremented each time the wal file is restarted. */
  54240. if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
  54241. if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
  54242. if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
  54243. if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
  54244. return 0;
  54245. }
  54246. #endif /* SQLITE_ENABLE_SNAPSHOT */
  54247. #ifdef SQLITE_ENABLE_ZIPVFS
  54248. /*
  54249. ** If the argument is not NULL, it points to a Wal object that holds a
  54250. ** read-lock. This function returns the database page-size if it is known,
  54251. ** or zero if it is not (or if pWal is NULL).
  54252. */
  54253. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  54254. assert( pWal==0 || pWal->readLock>=0 );
  54255. return (pWal ? pWal->szPage : 0);
  54256. }
  54257. #endif
  54258. /* Return the sqlite3_file object for the WAL file
  54259. */
  54260. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  54261. return pWal->pWalFd;
  54262. }
  54263. #endif /* #ifndef SQLITE_OMIT_WAL */
  54264. /************** End of wal.c *************************************************/
  54265. /************** Begin file btmutex.c *****************************************/
  54266. /*
  54267. ** 2007 August 27
  54268. **
  54269. ** The author disclaims copyright to this source code. In place of
  54270. ** a legal notice, here is a blessing:
  54271. **
  54272. ** May you do good and not evil.
  54273. ** May you find forgiveness for yourself and forgive others.
  54274. ** May you share freely, never taking more than you give.
  54275. **
  54276. *************************************************************************
  54277. **
  54278. ** This file contains code used to implement mutexes on Btree objects.
  54279. ** This code really belongs in btree.c. But btree.c is getting too
  54280. ** big and we want to break it down some. This packaged seemed like
  54281. ** a good breakout.
  54282. */
  54283. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  54284. /************** Begin file btreeInt.h ****************************************/
  54285. /*
  54286. ** 2004 April 6
  54287. **
  54288. ** The author disclaims copyright to this source code. In place of
  54289. ** a legal notice, here is a blessing:
  54290. **
  54291. ** May you do good and not evil.
  54292. ** May you find forgiveness for yourself and forgive others.
  54293. ** May you share freely, never taking more than you give.
  54294. **
  54295. *************************************************************************
  54296. ** This file implements an external (disk-based) database using BTrees.
  54297. ** For a detailed discussion of BTrees, refer to
  54298. **
  54299. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  54300. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  54301. ** Publishing Company, Reading, Massachusetts.
  54302. **
  54303. ** The basic idea is that each page of the file contains N database
  54304. ** entries and N+1 pointers to subpages.
  54305. **
  54306. ** ----------------------------------------------------------------
  54307. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  54308. ** ----------------------------------------------------------------
  54309. **
  54310. ** All of the keys on the page that Ptr(0) points to have values less
  54311. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  54312. ** values greater than Key(0) and less than Key(1). All of the keys
  54313. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  54314. ** so forth.
  54315. **
  54316. ** Finding a particular key requires reading O(log(M)) pages from the
  54317. ** disk where M is the number of entries in the tree.
  54318. **
  54319. ** In this implementation, a single file can hold one or more separate
  54320. ** BTrees. Each BTree is identified by the index of its root page. The
  54321. ** key and data for any entry are combined to form the "payload". A
  54322. ** fixed amount of payload can be carried directly on the database
  54323. ** page. If the payload is larger than the preset amount then surplus
  54324. ** bytes are stored on overflow pages. The payload for an entry
  54325. ** and the preceding pointer are combined to form a "Cell". Each
  54326. ** page has a small header which contains the Ptr(N) pointer and other
  54327. ** information such as the size of key and data.
  54328. **
  54329. ** FORMAT DETAILS
  54330. **
  54331. ** The file is divided into pages. The first page is called page 1,
  54332. ** the second is page 2, and so forth. A page number of zero indicates
  54333. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  54334. ** Each page can be either a btree page, a freelist page, an overflow
  54335. ** page, or a pointer-map page.
  54336. **
  54337. ** The first page is always a btree page. The first 100 bytes of the first
  54338. ** page contain a special header (the "file header") that describes the file.
  54339. ** The format of the file header is as follows:
  54340. **
  54341. ** OFFSET SIZE DESCRIPTION
  54342. ** 0 16 Header string: "SQLite format 3\000"
  54343. ** 16 2 Page size in bytes. (1 means 65536)
  54344. ** 18 1 File format write version
  54345. ** 19 1 File format read version
  54346. ** 20 1 Bytes of unused space at the end of each page
  54347. ** 21 1 Max embedded payload fraction (must be 64)
  54348. ** 22 1 Min embedded payload fraction (must be 32)
  54349. ** 23 1 Min leaf payload fraction (must be 32)
  54350. ** 24 4 File change counter
  54351. ** 28 4 Reserved for future use
  54352. ** 32 4 First freelist page
  54353. ** 36 4 Number of freelist pages in the file
  54354. ** 40 60 15 4-byte meta values passed to higher layers
  54355. **
  54356. ** 40 4 Schema cookie
  54357. ** 44 4 File format of schema layer
  54358. ** 48 4 Size of page cache
  54359. ** 52 4 Largest root-page (auto/incr_vacuum)
  54360. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  54361. ** 60 4 User version
  54362. ** 64 4 Incremental vacuum mode
  54363. ** 68 4 Application-ID
  54364. ** 72 20 unused
  54365. ** 92 4 The version-valid-for number
  54366. ** 96 4 SQLITE_VERSION_NUMBER
  54367. **
  54368. ** All of the integer values are big-endian (most significant byte first).
  54369. **
  54370. ** The file change counter is incremented when the database is changed
  54371. ** This counter allows other processes to know when the file has changed
  54372. ** and thus when they need to flush their cache.
  54373. **
  54374. ** The max embedded payload fraction is the amount of the total usable
  54375. ** space in a page that can be consumed by a single cell for standard
  54376. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  54377. ** is to limit the maximum cell size so that at least 4 cells will fit
  54378. ** on one page. Thus the default max embedded payload fraction is 64.
  54379. **
  54380. ** If the payload for a cell is larger than the max payload, then extra
  54381. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  54382. ** as many bytes as possible are moved into the overflow pages without letting
  54383. ** the cell size drop below the min embedded payload fraction.
  54384. **
  54385. ** The min leaf payload fraction is like the min embedded payload fraction
  54386. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  54387. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  54388. ** not specified in the header.
  54389. **
  54390. ** Each btree pages is divided into three sections: The header, the
  54391. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  54392. ** file header that occurs before the page header.
  54393. **
  54394. ** |----------------|
  54395. ** | file header | 100 bytes. Page 1 only.
  54396. ** |----------------|
  54397. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  54398. ** |----------------|
  54399. ** | cell pointer | | 2 bytes per cell. Sorted order.
  54400. ** | array | | Grows downward
  54401. ** | | v
  54402. ** |----------------|
  54403. ** | unallocated |
  54404. ** | space |
  54405. ** |----------------| ^ Grows upwards
  54406. ** | cell content | | Arbitrary order interspersed with freeblocks.
  54407. ** | area | | and free space fragments.
  54408. ** |----------------|
  54409. **
  54410. ** The page headers looks like this:
  54411. **
  54412. ** OFFSET SIZE DESCRIPTION
  54413. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  54414. ** 1 2 byte offset to the first freeblock
  54415. ** 3 2 number of cells on this page
  54416. ** 5 2 first byte of the cell content area
  54417. ** 7 1 number of fragmented free bytes
  54418. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  54419. **
  54420. ** The flags define the format of this btree page. The leaf flag means that
  54421. ** this page has no children. The zerodata flag means that this page carries
  54422. ** only keys and no data. The intkey flag means that the key is an integer
  54423. ** which is stored in the key size entry of the cell header rather than in
  54424. ** the payload area.
  54425. **
  54426. ** The cell pointer array begins on the first byte after the page header.
  54427. ** The cell pointer array contains zero or more 2-byte numbers which are
  54428. ** offsets from the beginning of the page to the cell content in the cell
  54429. ** content area. The cell pointers occur in sorted order. The system strives
  54430. ** to keep free space after the last cell pointer so that new cells can
  54431. ** be easily added without having to defragment the page.
  54432. **
  54433. ** Cell content is stored at the very end of the page and grows toward the
  54434. ** beginning of the page.
  54435. **
  54436. ** Unused space within the cell content area is collected into a linked list of
  54437. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  54438. ** to the first freeblock is given in the header. Freeblocks occur in
  54439. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  54440. ** any group of 3 or fewer unused bytes in the cell content area cannot
  54441. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  54442. ** a fragment. The total number of bytes in all fragments is recorded.
  54443. ** in the page header at offset 7.
  54444. **
  54445. ** SIZE DESCRIPTION
  54446. ** 2 Byte offset of the next freeblock
  54447. ** 2 Bytes in this freeblock
  54448. **
  54449. ** Cells are of variable length. Cells are stored in the cell content area at
  54450. ** the end of the page. Pointers to the cells are in the cell pointer array
  54451. ** that immediately follows the page header. Cells is not necessarily
  54452. ** contiguous or in order, but cell pointers are contiguous and in order.
  54453. **
  54454. ** Cell content makes use of variable length integers. A variable
  54455. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  54456. ** byte are used. The integer consists of all bytes that have bit 8 set and
  54457. ** the first byte with bit 8 clear. The most significant byte of the integer
  54458. ** appears first. A variable-length integer may not be more than 9 bytes long.
  54459. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  54460. ** allows a 64-bit integer to be encoded in 9 bytes.
  54461. **
  54462. ** 0x00 becomes 0x00000000
  54463. ** 0x7f becomes 0x0000007f
  54464. ** 0x81 0x00 becomes 0x00000080
  54465. ** 0x82 0x00 becomes 0x00000100
  54466. ** 0x80 0x7f becomes 0x0000007f
  54467. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  54468. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  54469. **
  54470. ** Variable length integers are used for rowids and to hold the number of
  54471. ** bytes of key and data in a btree cell.
  54472. **
  54473. ** The content of a cell looks like this:
  54474. **
  54475. ** SIZE DESCRIPTION
  54476. ** 4 Page number of the left child. Omitted if leaf flag is set.
  54477. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  54478. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  54479. ** * Payload
  54480. ** 4 First page of the overflow chain. Omitted if no overflow
  54481. **
  54482. ** Overflow pages form a linked list. Each page except the last is completely
  54483. ** filled with data (pagesize - 4 bytes). The last page can have as little
  54484. ** as 1 byte of data.
  54485. **
  54486. ** SIZE DESCRIPTION
  54487. ** 4 Page number of next overflow page
  54488. ** * Data
  54489. **
  54490. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  54491. ** file header points to the first in a linked list of trunk page. Each trunk
  54492. ** page points to multiple leaf pages. The content of a leaf page is
  54493. ** unspecified. A trunk page looks like this:
  54494. **
  54495. ** SIZE DESCRIPTION
  54496. ** 4 Page number of next trunk page
  54497. ** 4 Number of leaf pointers on this page
  54498. ** * zero or more pages numbers of leaves
  54499. */
  54500. /* #include "sqliteInt.h" */
  54501. /* The following value is the maximum cell size assuming a maximum page
  54502. ** size give above.
  54503. */
  54504. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  54505. /* The maximum number of cells on a single page of the database. This
  54506. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  54507. ** plus 2 bytes for the index to the cell in the page header). Such
  54508. ** small cells will be rare, but they are possible.
  54509. */
  54510. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  54511. /* Forward declarations */
  54512. typedef struct MemPage MemPage;
  54513. typedef struct BtLock BtLock;
  54514. typedef struct CellInfo CellInfo;
  54515. /*
  54516. ** This is a magic string that appears at the beginning of every
  54517. ** SQLite database in order to identify the file as a real database.
  54518. **
  54519. ** You can change this value at compile-time by specifying a
  54520. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  54521. ** header must be exactly 16 bytes including the zero-terminator so
  54522. ** the string itself should be 15 characters long. If you change
  54523. ** the header, then your custom library will not be able to read
  54524. ** databases generated by the standard tools and the standard tools
  54525. ** will not be able to read databases created by your custom library.
  54526. */
  54527. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  54528. # define SQLITE_FILE_HEADER "SQLite format 3"
  54529. #endif
  54530. /*
  54531. ** Page type flags. An ORed combination of these flags appear as the
  54532. ** first byte of on-disk image of every BTree page.
  54533. */
  54534. #define PTF_INTKEY 0x01
  54535. #define PTF_ZERODATA 0x02
  54536. #define PTF_LEAFDATA 0x04
  54537. #define PTF_LEAF 0x08
  54538. /*
  54539. ** An instance of this object stores information about each a single database
  54540. ** page that has been loaded into memory. The information in this object
  54541. ** is derived from the raw on-disk page content.
  54542. **
  54543. ** As each database page is loaded into memory, the pager allocats an
  54544. ** instance of this object and zeros the first 8 bytes. (This is the
  54545. ** "extra" information associated with each page of the pager.)
  54546. **
  54547. ** Access to all fields of this structure is controlled by the mutex
  54548. ** stored in MemPage.pBt->mutex.
  54549. */
  54550. struct MemPage {
  54551. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  54552. u8 bBusy; /* Prevent endless loops on corrupt database files */
  54553. u8 intKey; /* True if table b-trees. False for index b-trees */
  54554. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  54555. Pgno pgno; /* Page number for this page */
  54556. /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
  54557. ** is allocated. All fields that follow must be initialized before use */
  54558. u8 leaf; /* True if a leaf page */
  54559. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  54560. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  54561. u8 max1bytePayload; /* min(maxLocal,127) */
  54562. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  54563. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  54564. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  54565. u16 cellOffset; /* Index in aData of first cell pointer */
  54566. u16 nFree; /* Number of free bytes on the page */
  54567. u16 nCell; /* Number of cells on this page, local and ovfl */
  54568. u16 maskPage; /* Mask for page offset */
  54569. u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
  54570. ** non-overflow cell */
  54571. u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
  54572. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  54573. u8 *aData; /* Pointer to disk image of the page data */
  54574. u8 *aDataEnd; /* One byte past the end of usable data */
  54575. u8 *aCellIdx; /* The cell index area */
  54576. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  54577. DbPage *pDbPage; /* Pager page handle */
  54578. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  54579. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  54580. };
  54581. /*
  54582. ** A linked list of the following structures is stored at BtShared.pLock.
  54583. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  54584. ** is opened on the table with root page BtShared.iTable. Locks are removed
  54585. ** from this list when a transaction is committed or rolled back, or when
  54586. ** a btree handle is closed.
  54587. */
  54588. struct BtLock {
  54589. Btree *pBtree; /* Btree handle holding this lock */
  54590. Pgno iTable; /* Root page of table */
  54591. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  54592. BtLock *pNext; /* Next in BtShared.pLock list */
  54593. };
  54594. /* Candidate values for BtLock.eLock */
  54595. #define READ_LOCK 1
  54596. #define WRITE_LOCK 2
  54597. /* A Btree handle
  54598. **
  54599. ** A database connection contains a pointer to an instance of
  54600. ** this object for every database file that it has open. This structure
  54601. ** is opaque to the database connection. The database connection cannot
  54602. ** see the internals of this structure and only deals with pointers to
  54603. ** this structure.
  54604. **
  54605. ** For some database files, the same underlying database cache might be
  54606. ** shared between multiple connections. In that case, each connection
  54607. ** has it own instance of this object. But each instance of this object
  54608. ** points to the same BtShared object. The database cache and the
  54609. ** schema associated with the database file are all contained within
  54610. ** the BtShared object.
  54611. **
  54612. ** All fields in this structure are accessed under sqlite3.mutex.
  54613. ** The pBt pointer itself may not be changed while there exists cursors
  54614. ** in the referenced BtShared that point back to this Btree since those
  54615. ** cursors have to go through this Btree to find their BtShared and
  54616. ** they often do so without holding sqlite3.mutex.
  54617. */
  54618. struct Btree {
  54619. sqlite3 *db; /* The database connection holding this btree */
  54620. BtShared *pBt; /* Sharable content of this btree */
  54621. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  54622. u8 sharable; /* True if we can share pBt with another db */
  54623. u8 locked; /* True if db currently has pBt locked */
  54624. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  54625. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  54626. int nBackup; /* Number of backup operations reading this btree */
  54627. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  54628. Btree *pNext; /* List of other sharable Btrees from the same db */
  54629. Btree *pPrev; /* Back pointer of the same list */
  54630. #ifndef SQLITE_OMIT_SHARED_CACHE
  54631. BtLock lock; /* Object used to lock page 1 */
  54632. #endif
  54633. };
  54634. /*
  54635. ** Btree.inTrans may take one of the following values.
  54636. **
  54637. ** If the shared-data extension is enabled, there may be multiple users
  54638. ** of the Btree structure. At most one of these may open a write transaction,
  54639. ** but any number may have active read transactions.
  54640. */
  54641. #define TRANS_NONE 0
  54642. #define TRANS_READ 1
  54643. #define TRANS_WRITE 2
  54644. /*
  54645. ** An instance of this object represents a single database file.
  54646. **
  54647. ** A single database file can be in use at the same time by two
  54648. ** or more database connections. When two or more connections are
  54649. ** sharing the same database file, each connection has it own
  54650. ** private Btree object for the file and each of those Btrees points
  54651. ** to this one BtShared object. BtShared.nRef is the number of
  54652. ** connections currently sharing this database file.
  54653. **
  54654. ** Fields in this structure are accessed under the BtShared.mutex
  54655. ** mutex, except for nRef and pNext which are accessed under the
  54656. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  54657. ** may not be modified once it is initially set as long as nRef>0.
  54658. ** The pSchema field may be set once under BtShared.mutex and
  54659. ** thereafter is unchanged as long as nRef>0.
  54660. **
  54661. ** isPending:
  54662. **
  54663. ** If a BtShared client fails to obtain a write-lock on a database
  54664. ** table (because there exists one or more read-locks on the table),
  54665. ** the shared-cache enters 'pending-lock' state and isPending is
  54666. ** set to true.
  54667. **
  54668. ** The shared-cache leaves the 'pending lock' state when either of
  54669. ** the following occur:
  54670. **
  54671. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  54672. ** 2) The number of locks held by other connections drops to zero.
  54673. **
  54674. ** while in the 'pending-lock' state, no connection may start a new
  54675. ** transaction.
  54676. **
  54677. ** This feature is included to help prevent writer-starvation.
  54678. */
  54679. struct BtShared {
  54680. Pager *pPager; /* The page cache */
  54681. sqlite3 *db; /* Database connection currently using this Btree */
  54682. BtCursor *pCursor; /* A list of all open cursors */
  54683. MemPage *pPage1; /* First page of the database */
  54684. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  54685. #ifndef SQLITE_OMIT_AUTOVACUUM
  54686. u8 autoVacuum; /* True if auto-vacuum is enabled */
  54687. u8 incrVacuum; /* True if incr-vacuum is enabled */
  54688. u8 bDoTruncate; /* True to truncate db on commit */
  54689. #endif
  54690. u8 inTransaction; /* Transaction state */
  54691. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  54692. #ifdef SQLITE_HAS_CODEC
  54693. u8 optimalReserve; /* Desired amount of reserved space per page */
  54694. #endif
  54695. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  54696. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  54697. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  54698. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  54699. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  54700. u32 pageSize; /* Total number of bytes on a page */
  54701. u32 usableSize; /* Number of usable bytes on each page */
  54702. int nTransaction; /* Number of open transactions (read + write) */
  54703. u32 nPage; /* Number of pages in the database */
  54704. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  54705. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  54706. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  54707. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  54708. #ifndef SQLITE_OMIT_SHARED_CACHE
  54709. int nRef; /* Number of references to this structure */
  54710. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  54711. BtLock *pLock; /* List of locks held on this shared-btree struct */
  54712. Btree *pWriter; /* Btree with currently open write transaction */
  54713. #endif
  54714. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  54715. };
  54716. /*
  54717. ** Allowed values for BtShared.btsFlags
  54718. */
  54719. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  54720. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  54721. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  54722. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  54723. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  54724. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  54725. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  54726. /*
  54727. ** An instance of the following structure is used to hold information
  54728. ** about a cell. The parseCellPtr() function fills in this structure
  54729. ** based on information extract from the raw disk page.
  54730. */
  54731. struct CellInfo {
  54732. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  54733. u8 *pPayload; /* Pointer to the start of payload */
  54734. u32 nPayload; /* Bytes of payload */
  54735. u16 nLocal; /* Amount of payload held locally, not on overflow */
  54736. u16 nSize; /* Size of the cell content on the main b-tree page */
  54737. };
  54738. /*
  54739. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  54740. ** this will be declared corrupt. This value is calculated based on a
  54741. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  54742. ** root-node and 3 for all other internal nodes.
  54743. **
  54744. ** If a tree that appears to be taller than this is encountered, it is
  54745. ** assumed that the database is corrupt.
  54746. */
  54747. #define BTCURSOR_MAX_DEPTH 20
  54748. /*
  54749. ** A cursor is a pointer to a particular entry within a particular
  54750. ** b-tree within a database file.
  54751. **
  54752. ** The entry is identified by its MemPage and the index in
  54753. ** MemPage.aCell[] of the entry.
  54754. **
  54755. ** A single database file can be shared by two more database connections,
  54756. ** but cursors cannot be shared. Each cursor is associated with a
  54757. ** particular database connection identified BtCursor.pBtree.db.
  54758. **
  54759. ** Fields in this structure are accessed under the BtShared.mutex
  54760. ** found at self->pBt->mutex.
  54761. **
  54762. ** skipNext meaning:
  54763. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  54764. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  54765. ** eState==FAULT: Cursor fault with skipNext as error code.
  54766. */
  54767. struct BtCursor {
  54768. Btree *pBtree; /* The Btree to which this cursor belongs */
  54769. BtShared *pBt; /* The BtShared this cursor points to */
  54770. BtCursor *pNext; /* Forms a linked list of all cursors */
  54771. Pgno *aOverflow; /* Cache of overflow page locations */
  54772. CellInfo info; /* A parse of the cell we are pointing at */
  54773. i64 nKey; /* Size of pKey, or last integer key */
  54774. void *pKey; /* Saved key that was cursor last known position */
  54775. Pgno pgnoRoot; /* The root page of this tree */
  54776. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  54777. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  54778. ** Error code if eState==CURSOR_FAULT */
  54779. u8 curFlags; /* zero or more BTCF_* flags defined below */
  54780. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  54781. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  54782. u8 hints; /* As configured by CursorSetHints() */
  54783. /* All fields above are zeroed when the cursor is allocated. See
  54784. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  54785. ** initialized. */
  54786. i8 iPage; /* Index of current page in apPage */
  54787. u8 curIntKey; /* Value of apPage[0]->intKey */
  54788. u16 ix; /* Current index for apPage[iPage] */
  54789. u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
  54790. struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
  54791. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  54792. };
  54793. /*
  54794. ** Legal values for BtCursor.curFlags
  54795. */
  54796. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  54797. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  54798. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  54799. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  54800. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  54801. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  54802. /*
  54803. ** Potential values for BtCursor.eState.
  54804. **
  54805. ** CURSOR_INVALID:
  54806. ** Cursor does not point to a valid entry. This can happen (for example)
  54807. ** because the table is empty or because BtreeCursorFirst() has not been
  54808. ** called.
  54809. **
  54810. ** CURSOR_VALID:
  54811. ** Cursor points to a valid entry. getPayload() etc. may be called.
  54812. **
  54813. ** CURSOR_SKIPNEXT:
  54814. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  54815. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  54816. ** operation should be a no-op.
  54817. **
  54818. ** CURSOR_REQUIRESEEK:
  54819. ** The table that this cursor was opened on still exists, but has been
  54820. ** modified since the cursor was last used. The cursor position is saved
  54821. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  54822. ** this state, restoreCursorPosition() can be called to attempt to
  54823. ** seek the cursor to the saved position.
  54824. **
  54825. ** CURSOR_FAULT:
  54826. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  54827. ** on a different connection that shares the BtShared cache with this
  54828. ** cursor. The error has left the cache in an inconsistent state.
  54829. ** Do nothing else with this cursor. Any attempt to use the cursor
  54830. ** should return the error code stored in BtCursor.skipNext
  54831. */
  54832. #define CURSOR_INVALID 0
  54833. #define CURSOR_VALID 1
  54834. #define CURSOR_SKIPNEXT 2
  54835. #define CURSOR_REQUIRESEEK 3
  54836. #define CURSOR_FAULT 4
  54837. /*
  54838. ** The database page the PENDING_BYTE occupies. This page is never used.
  54839. */
  54840. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  54841. /*
  54842. ** These macros define the location of the pointer-map entry for a
  54843. ** database page. The first argument to each is the number of usable
  54844. ** bytes on each page of the database (often 1024). The second is the
  54845. ** page number to look up in the pointer map.
  54846. **
  54847. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  54848. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  54849. ** the offset of the requested map entry.
  54850. **
  54851. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  54852. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  54853. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  54854. ** this test.
  54855. */
  54856. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  54857. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  54858. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  54859. /*
  54860. ** The pointer map is a lookup table that identifies the parent page for
  54861. ** each child page in the database file. The parent page is the page that
  54862. ** contains a pointer to the child. Every page in the database contains
  54863. ** 0 or 1 parent pages. (In this context 'database page' refers
  54864. ** to any page that is not part of the pointer map itself.) Each pointer map
  54865. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  54866. ** The PTRMAP_XXX identifiers below are the valid types.
  54867. **
  54868. ** The purpose of the pointer map is to facility moving pages from one
  54869. ** position in the file to another as part of autovacuum. When a page
  54870. ** is moved, the pointer in its parent must be updated to point to the
  54871. ** new location. The pointer map is used to locate the parent page quickly.
  54872. **
  54873. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  54874. ** used in this case.
  54875. **
  54876. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  54877. ** is not used in this case.
  54878. **
  54879. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  54880. ** overflow pages. The page number identifies the page that
  54881. ** contains the cell with a pointer to this overflow page.
  54882. **
  54883. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  54884. ** overflow pages. The page-number identifies the previous
  54885. ** page in the overflow page list.
  54886. **
  54887. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  54888. ** identifies the parent page in the btree.
  54889. */
  54890. #define PTRMAP_ROOTPAGE 1
  54891. #define PTRMAP_FREEPAGE 2
  54892. #define PTRMAP_OVERFLOW1 3
  54893. #define PTRMAP_OVERFLOW2 4
  54894. #define PTRMAP_BTREE 5
  54895. /* A bunch of assert() statements to check the transaction state variables
  54896. ** of handle p (type Btree*) are internally consistent.
  54897. */
  54898. #define btreeIntegrity(p) \
  54899. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  54900. assert( p->pBt->inTransaction>=p->inTrans );
  54901. /*
  54902. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  54903. ** if the database supports auto-vacuum or not. Because it is used
  54904. ** within an expression that is an argument to another macro
  54905. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  54906. ** So, this macro is defined instead.
  54907. */
  54908. #ifndef SQLITE_OMIT_AUTOVACUUM
  54909. #define ISAUTOVACUUM (pBt->autoVacuum)
  54910. #else
  54911. #define ISAUTOVACUUM 0
  54912. #endif
  54913. /*
  54914. ** This structure is passed around through all the sanity checking routines
  54915. ** in order to keep track of some global state information.
  54916. **
  54917. ** The aRef[] array is allocated so that there is 1 bit for each page in
  54918. ** the database. As the integrity-check proceeds, for each page used in
  54919. ** the database the corresponding bit is set. This allows integrity-check to
  54920. ** detect pages that are used twice and orphaned pages (both of which
  54921. ** indicate corruption).
  54922. */
  54923. typedef struct IntegrityCk IntegrityCk;
  54924. struct IntegrityCk {
  54925. BtShared *pBt; /* The tree being checked out */
  54926. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  54927. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  54928. Pgno nPage; /* Number of pages in the database */
  54929. int mxErr; /* Stop accumulating errors when this reaches zero */
  54930. int nErr; /* Number of messages written to zErrMsg so far */
  54931. int mallocFailed; /* A memory allocation error has occurred */
  54932. const char *zPfx; /* Error message prefix */
  54933. int v1, v2; /* Values for up to two %d fields in zPfx */
  54934. StrAccum errMsg; /* Accumulate the error message text here */
  54935. u32 *heap; /* Min-heap used for analyzing cell coverage */
  54936. };
  54937. /*
  54938. ** Routines to read or write a two- and four-byte big-endian integer values.
  54939. */
  54940. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  54941. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  54942. #define get4byte sqlite3Get4byte
  54943. #define put4byte sqlite3Put4byte
  54944. /*
  54945. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  54946. ** two-byte aligned address. get2bytea() is only used for accessing the
  54947. ** cell addresses in a btree header.
  54948. */
  54949. #if SQLITE_BYTEORDER==4321
  54950. # define get2byteAligned(x) (*(u16*)(x))
  54951. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  54952. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  54953. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  54954. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  54955. #else
  54956. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  54957. #endif
  54958. /************** End of btreeInt.h ********************************************/
  54959. /************** Continuing where we left off in btmutex.c ********************/
  54960. #ifndef SQLITE_OMIT_SHARED_CACHE
  54961. #if SQLITE_THREADSAFE
  54962. /*
  54963. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  54964. ** set BtShared.db to the database handle associated with p and the
  54965. ** p->locked boolean to true.
  54966. */
  54967. static void lockBtreeMutex(Btree *p){
  54968. assert( p->locked==0 );
  54969. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  54970. assert( sqlite3_mutex_held(p->db->mutex) );
  54971. sqlite3_mutex_enter(p->pBt->mutex);
  54972. p->pBt->db = p->db;
  54973. p->locked = 1;
  54974. }
  54975. /*
  54976. ** Release the BtShared mutex associated with B-Tree handle p and
  54977. ** clear the p->locked boolean.
  54978. */
  54979. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  54980. BtShared *pBt = p->pBt;
  54981. assert( p->locked==1 );
  54982. assert( sqlite3_mutex_held(pBt->mutex) );
  54983. assert( sqlite3_mutex_held(p->db->mutex) );
  54984. assert( p->db==pBt->db );
  54985. sqlite3_mutex_leave(pBt->mutex);
  54986. p->locked = 0;
  54987. }
  54988. /* Forward reference */
  54989. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  54990. /*
  54991. ** Enter a mutex on the given BTree object.
  54992. **
  54993. ** If the object is not sharable, then no mutex is ever required
  54994. ** and this routine is a no-op. The underlying mutex is non-recursive.
  54995. ** But we keep a reference count in Btree.wantToLock so the behavior
  54996. ** of this interface is recursive.
  54997. **
  54998. ** To avoid deadlocks, multiple Btrees are locked in the same order
  54999. ** by all database connections. The p->pNext is a list of other
  55000. ** Btrees belonging to the same database connection as the p Btree
  55001. ** which need to be locked after p. If we cannot get a lock on
  55002. ** p, then first unlock all of the others on p->pNext, then wait
  55003. ** for the lock to become available on p, then relock all of the
  55004. ** subsequent Btrees that desire a lock.
  55005. */
  55006. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  55007. /* Some basic sanity checking on the Btree. The list of Btrees
  55008. ** connected by pNext and pPrev should be in sorted order by
  55009. ** Btree.pBt value. All elements of the list should belong to
  55010. ** the same connection. Only shared Btrees are on the list. */
  55011. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  55012. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  55013. assert( p->pNext==0 || p->pNext->db==p->db );
  55014. assert( p->pPrev==0 || p->pPrev->db==p->db );
  55015. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  55016. /* Check for locking consistency */
  55017. assert( !p->locked || p->wantToLock>0 );
  55018. assert( p->sharable || p->wantToLock==0 );
  55019. /* We should already hold a lock on the database connection */
  55020. assert( sqlite3_mutex_held(p->db->mutex) );
  55021. /* Unless the database is sharable and unlocked, then BtShared.db
  55022. ** should already be set correctly. */
  55023. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  55024. if( !p->sharable ) return;
  55025. p->wantToLock++;
  55026. if( p->locked ) return;
  55027. btreeLockCarefully(p);
  55028. }
  55029. /* This is a helper function for sqlite3BtreeLock(). By moving
  55030. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  55031. ** into this routine, we avoid unnecessary stack pointer changes
  55032. ** and thus help the sqlite3BtreeLock() routine to run much faster
  55033. ** in the common case.
  55034. */
  55035. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  55036. Btree *pLater;
  55037. /* In most cases, we should be able to acquire the lock we
  55038. ** want without having to go through the ascending lock
  55039. ** procedure that follows. Just be sure not to block.
  55040. */
  55041. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  55042. p->pBt->db = p->db;
  55043. p->locked = 1;
  55044. return;
  55045. }
  55046. /* To avoid deadlock, first release all locks with a larger
  55047. ** BtShared address. Then acquire our lock. Then reacquire
  55048. ** the other BtShared locks that we used to hold in ascending
  55049. ** order.
  55050. */
  55051. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  55052. assert( pLater->sharable );
  55053. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  55054. assert( !pLater->locked || pLater->wantToLock>0 );
  55055. if( pLater->locked ){
  55056. unlockBtreeMutex(pLater);
  55057. }
  55058. }
  55059. lockBtreeMutex(p);
  55060. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  55061. if( pLater->wantToLock ){
  55062. lockBtreeMutex(pLater);
  55063. }
  55064. }
  55065. }
  55066. /*
  55067. ** Exit the recursive mutex on a Btree.
  55068. */
  55069. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  55070. assert( sqlite3_mutex_held(p->db->mutex) );
  55071. if( p->sharable ){
  55072. assert( p->wantToLock>0 );
  55073. p->wantToLock--;
  55074. if( p->wantToLock==0 ){
  55075. unlockBtreeMutex(p);
  55076. }
  55077. }
  55078. }
  55079. #ifndef NDEBUG
  55080. /*
  55081. ** Return true if the BtShared mutex is held on the btree, or if the
  55082. ** B-Tree is not marked as sharable.
  55083. **
  55084. ** This routine is used only from within assert() statements.
  55085. */
  55086. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  55087. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  55088. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  55089. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  55090. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  55091. return (p->sharable==0 || p->locked);
  55092. }
  55093. #endif
  55094. /*
  55095. ** Enter the mutex on every Btree associated with a database
  55096. ** connection. This is needed (for example) prior to parsing
  55097. ** a statement since we will be comparing table and column names
  55098. ** against all schemas and we do not want those schemas being
  55099. ** reset out from under us.
  55100. **
  55101. ** There is a corresponding leave-all procedures.
  55102. **
  55103. ** Enter the mutexes in accending order by BtShared pointer address
  55104. ** to avoid the possibility of deadlock when two threads with
  55105. ** two or more btrees in common both try to lock all their btrees
  55106. ** at the same instant.
  55107. */
  55108. static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
  55109. int i;
  55110. int skipOk = 1;
  55111. Btree *p;
  55112. assert( sqlite3_mutex_held(db->mutex) );
  55113. for(i=0; i<db->nDb; i++){
  55114. p = db->aDb[i].pBt;
  55115. if( p && p->sharable ){
  55116. sqlite3BtreeEnter(p);
  55117. skipOk = 0;
  55118. }
  55119. }
  55120. db->skipBtreeMutex = skipOk;
  55121. }
  55122. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  55123. if( db->skipBtreeMutex==0 ) btreeEnterAll(db);
  55124. }
  55125. static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
  55126. int i;
  55127. Btree *p;
  55128. assert( sqlite3_mutex_held(db->mutex) );
  55129. for(i=0; i<db->nDb; i++){
  55130. p = db->aDb[i].pBt;
  55131. if( p ) sqlite3BtreeLeave(p);
  55132. }
  55133. }
  55134. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  55135. if( db->skipBtreeMutex==0 ) btreeLeaveAll(db);
  55136. }
  55137. #ifndef NDEBUG
  55138. /*
  55139. ** Return true if the current thread holds the database connection
  55140. ** mutex and all required BtShared mutexes.
  55141. **
  55142. ** This routine is used inside assert() statements only.
  55143. */
  55144. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  55145. int i;
  55146. if( !sqlite3_mutex_held(db->mutex) ){
  55147. return 0;
  55148. }
  55149. for(i=0; i<db->nDb; i++){
  55150. Btree *p;
  55151. p = db->aDb[i].pBt;
  55152. if( p && p->sharable &&
  55153. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  55154. return 0;
  55155. }
  55156. }
  55157. return 1;
  55158. }
  55159. #endif /* NDEBUG */
  55160. #ifndef NDEBUG
  55161. /*
  55162. ** Return true if the correct mutexes are held for accessing the
  55163. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  55164. ** access are:
  55165. **
  55166. ** (1) The mutex on db
  55167. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  55168. **
  55169. ** If pSchema is not NULL, then iDb is computed from pSchema and
  55170. ** db using sqlite3SchemaToIndex().
  55171. */
  55172. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  55173. Btree *p;
  55174. assert( db!=0 );
  55175. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  55176. assert( iDb>=0 && iDb<db->nDb );
  55177. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  55178. if( iDb==1 ) return 1;
  55179. p = db->aDb[iDb].pBt;
  55180. assert( p!=0 );
  55181. return p->sharable==0 || p->locked==1;
  55182. }
  55183. #endif /* NDEBUG */
  55184. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  55185. /*
  55186. ** The following are special cases for mutex enter routines for use
  55187. ** in single threaded applications that use shared cache. Except for
  55188. ** these two routines, all mutex operations are no-ops in that case and
  55189. ** are null #defines in btree.h.
  55190. **
  55191. ** If shared cache is disabled, then all btree mutex routines, including
  55192. ** the ones below, are no-ops and are null #defines in btree.h.
  55193. */
  55194. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  55195. p->pBt->db = p->db;
  55196. }
  55197. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  55198. int i;
  55199. for(i=0; i<db->nDb; i++){
  55200. Btree *p = db->aDb[i].pBt;
  55201. if( p ){
  55202. p->pBt->db = p->db;
  55203. }
  55204. }
  55205. }
  55206. #endif /* if SQLITE_THREADSAFE */
  55207. #ifndef SQLITE_OMIT_INCRBLOB
  55208. /*
  55209. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  55210. **
  55211. ** These entry points are used by incremental I/O only. Enter() is required
  55212. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  55213. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  55214. */
  55215. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  55216. sqlite3BtreeEnter(pCur->pBtree);
  55217. }
  55218. # if SQLITE_THREADSAFE
  55219. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  55220. sqlite3BtreeLeave(pCur->pBtree);
  55221. }
  55222. # endif
  55223. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  55224. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  55225. /************** End of btmutex.c *********************************************/
  55226. /************** Begin file btree.c *******************************************/
  55227. /*
  55228. ** 2004 April 6
  55229. **
  55230. ** The author disclaims copyright to this source code. In place of
  55231. ** a legal notice, here is a blessing:
  55232. **
  55233. ** May you do good and not evil.
  55234. ** May you find forgiveness for yourself and forgive others.
  55235. ** May you share freely, never taking more than you give.
  55236. **
  55237. *************************************************************************
  55238. ** This file implements an external (disk-based) database using BTrees.
  55239. ** See the header comment on "btreeInt.h" for additional information.
  55240. ** Including a description of file format and an overview of operation.
  55241. */
  55242. /* #include "btreeInt.h" */
  55243. /*
  55244. ** The header string that appears at the beginning of every
  55245. ** SQLite database.
  55246. */
  55247. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  55248. /*
  55249. ** Set this global variable to 1 to enable tracing using the TRACE
  55250. ** macro.
  55251. */
  55252. #if 0
  55253. int sqlite3BtreeTrace=1; /* True to enable tracing */
  55254. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  55255. #else
  55256. # define TRACE(X)
  55257. #endif
  55258. /*
  55259. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  55260. ** But if the value is zero, make it 65536.
  55261. **
  55262. ** This routine is used to extract the "offset to cell content area" value
  55263. ** from the header of a btree page. If the page size is 65536 and the page
  55264. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  55265. ** This routine makes the necessary adjustment to 65536.
  55266. */
  55267. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  55268. /*
  55269. ** Values passed as the 5th argument to allocateBtreePage()
  55270. */
  55271. #define BTALLOC_ANY 0 /* Allocate any page */
  55272. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  55273. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  55274. /*
  55275. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  55276. ** defined, or 0 if it is. For example:
  55277. **
  55278. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  55279. */
  55280. #ifndef SQLITE_OMIT_AUTOVACUUM
  55281. #define IfNotOmitAV(expr) (expr)
  55282. #else
  55283. #define IfNotOmitAV(expr) 0
  55284. #endif
  55285. #ifndef SQLITE_OMIT_SHARED_CACHE
  55286. /*
  55287. ** A list of BtShared objects that are eligible for participation
  55288. ** in shared cache. This variable has file scope during normal builds,
  55289. ** but the test harness needs to access it so we make it global for
  55290. ** test builds.
  55291. **
  55292. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  55293. */
  55294. #ifdef SQLITE_TEST
  55295. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  55296. #else
  55297. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  55298. #endif
  55299. #endif /* SQLITE_OMIT_SHARED_CACHE */
  55300. #ifndef SQLITE_OMIT_SHARED_CACHE
  55301. /*
  55302. ** Enable or disable the shared pager and schema features.
  55303. **
  55304. ** This routine has no effect on existing database connections.
  55305. ** The shared cache setting effects only future calls to
  55306. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  55307. */
  55308. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  55309. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  55310. return SQLITE_OK;
  55311. }
  55312. #endif
  55313. #ifdef SQLITE_OMIT_SHARED_CACHE
  55314. /*
  55315. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  55316. ** and clearAllSharedCacheTableLocks()
  55317. ** manipulate entries in the BtShared.pLock linked list used to store
  55318. ** shared-cache table level locks. If the library is compiled with the
  55319. ** shared-cache feature disabled, then there is only ever one user
  55320. ** of each BtShared structure and so this locking is not necessary.
  55321. ** So define the lock related functions as no-ops.
  55322. */
  55323. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  55324. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  55325. #define clearAllSharedCacheTableLocks(a)
  55326. #define downgradeAllSharedCacheTableLocks(a)
  55327. #define hasSharedCacheTableLock(a,b,c,d) 1
  55328. #define hasReadConflicts(a, b) 0
  55329. #endif
  55330. #ifndef SQLITE_OMIT_SHARED_CACHE
  55331. #ifdef SQLITE_DEBUG
  55332. /*
  55333. **** This function is only used as part of an assert() statement. ***
  55334. **
  55335. ** Check to see if pBtree holds the required locks to read or write to the
  55336. ** table with root page iRoot. Return 1 if it does and 0 if not.
  55337. **
  55338. ** For example, when writing to a table with root-page iRoot via
  55339. ** Btree connection pBtree:
  55340. **
  55341. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  55342. **
  55343. ** When writing to an index that resides in a sharable database, the
  55344. ** caller should have first obtained a lock specifying the root page of
  55345. ** the corresponding table. This makes things a bit more complicated,
  55346. ** as this module treats each table as a separate structure. To determine
  55347. ** the table corresponding to the index being written, this
  55348. ** function has to search through the database schema.
  55349. **
  55350. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  55351. ** hold a write-lock on the schema table (root page 1). This is also
  55352. ** acceptable.
  55353. */
  55354. static int hasSharedCacheTableLock(
  55355. Btree *pBtree, /* Handle that must hold lock */
  55356. Pgno iRoot, /* Root page of b-tree */
  55357. int isIndex, /* True if iRoot is the root of an index b-tree */
  55358. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  55359. ){
  55360. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  55361. Pgno iTab = 0;
  55362. BtLock *pLock;
  55363. /* If this database is not shareable, or if the client is reading
  55364. ** and has the read-uncommitted flag set, then no lock is required.
  55365. ** Return true immediately.
  55366. */
  55367. if( (pBtree->sharable==0)
  55368. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  55369. ){
  55370. return 1;
  55371. }
  55372. /* If the client is reading or writing an index and the schema is
  55373. ** not loaded, then it is too difficult to actually check to see if
  55374. ** the correct locks are held. So do not bother - just return true.
  55375. ** This case does not come up very often anyhow.
  55376. */
  55377. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  55378. return 1;
  55379. }
  55380. /* Figure out the root-page that the lock should be held on. For table
  55381. ** b-trees, this is just the root page of the b-tree being read or
  55382. ** written. For index b-trees, it is the root page of the associated
  55383. ** table. */
  55384. if( isIndex ){
  55385. HashElem *p;
  55386. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  55387. Index *pIdx = (Index *)sqliteHashData(p);
  55388. if( pIdx->tnum==(int)iRoot ){
  55389. if( iTab ){
  55390. /* Two or more indexes share the same root page. There must
  55391. ** be imposter tables. So just return true. The assert is not
  55392. ** useful in that case. */
  55393. return 1;
  55394. }
  55395. iTab = pIdx->pTable->tnum;
  55396. }
  55397. }
  55398. }else{
  55399. iTab = iRoot;
  55400. }
  55401. /* Search for the required lock. Either a write-lock on root-page iTab, a
  55402. ** write-lock on the schema table, or (if the client is reading) a
  55403. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  55404. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  55405. if( pLock->pBtree==pBtree
  55406. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  55407. && pLock->eLock>=eLockType
  55408. ){
  55409. return 1;
  55410. }
  55411. }
  55412. /* Failed to find the required lock. */
  55413. return 0;
  55414. }
  55415. #endif /* SQLITE_DEBUG */
  55416. #ifdef SQLITE_DEBUG
  55417. /*
  55418. **** This function may be used as part of assert() statements only. ****
  55419. **
  55420. ** Return true if it would be illegal for pBtree to write into the
  55421. ** table or index rooted at iRoot because other shared connections are
  55422. ** simultaneously reading that same table or index.
  55423. **
  55424. ** It is illegal for pBtree to write if some other Btree object that
  55425. ** shares the same BtShared object is currently reading or writing
  55426. ** the iRoot table. Except, if the other Btree object has the
  55427. ** read-uncommitted flag set, then it is OK for the other object to
  55428. ** have a read cursor.
  55429. **
  55430. ** For example, before writing to any part of the table or index
  55431. ** rooted at page iRoot, one should call:
  55432. **
  55433. ** assert( !hasReadConflicts(pBtree, iRoot) );
  55434. */
  55435. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  55436. BtCursor *p;
  55437. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  55438. if( p->pgnoRoot==iRoot
  55439. && p->pBtree!=pBtree
  55440. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  55441. ){
  55442. return 1;
  55443. }
  55444. }
  55445. return 0;
  55446. }
  55447. #endif /* #ifdef SQLITE_DEBUG */
  55448. /*
  55449. ** Query to see if Btree handle p may obtain a lock of type eLock
  55450. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  55451. ** SQLITE_OK if the lock may be obtained (by calling
  55452. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  55453. */
  55454. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  55455. BtShared *pBt = p->pBt;
  55456. BtLock *pIter;
  55457. assert( sqlite3BtreeHoldsMutex(p) );
  55458. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  55459. assert( p->db!=0 );
  55460. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  55461. /* If requesting a write-lock, then the Btree must have an open write
  55462. ** transaction on this file. And, obviously, for this to be so there
  55463. ** must be an open write transaction on the file itself.
  55464. */
  55465. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  55466. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  55467. /* This routine is a no-op if the shared-cache is not enabled */
  55468. if( !p->sharable ){
  55469. return SQLITE_OK;
  55470. }
  55471. /* If some other connection is holding an exclusive lock, the
  55472. ** requested lock may not be obtained.
  55473. */
  55474. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  55475. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  55476. return SQLITE_LOCKED_SHAREDCACHE;
  55477. }
  55478. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  55479. /* The condition (pIter->eLock!=eLock) in the following if(...)
  55480. ** statement is a simplification of:
  55481. **
  55482. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  55483. **
  55484. ** since we know that if eLock==WRITE_LOCK, then no other connection
  55485. ** may hold a WRITE_LOCK on any table in this file (since there can
  55486. ** only be a single writer).
  55487. */
  55488. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  55489. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  55490. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  55491. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  55492. if( eLock==WRITE_LOCK ){
  55493. assert( p==pBt->pWriter );
  55494. pBt->btsFlags |= BTS_PENDING;
  55495. }
  55496. return SQLITE_LOCKED_SHAREDCACHE;
  55497. }
  55498. }
  55499. return SQLITE_OK;
  55500. }
  55501. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  55502. #ifndef SQLITE_OMIT_SHARED_CACHE
  55503. /*
  55504. ** Add a lock on the table with root-page iTable to the shared-btree used
  55505. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  55506. ** WRITE_LOCK.
  55507. **
  55508. ** This function assumes the following:
  55509. **
  55510. ** (a) The specified Btree object p is connected to a sharable
  55511. ** database (one with the BtShared.sharable flag set), and
  55512. **
  55513. ** (b) No other Btree objects hold a lock that conflicts
  55514. ** with the requested lock (i.e. querySharedCacheTableLock() has
  55515. ** already been called and returned SQLITE_OK).
  55516. **
  55517. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  55518. ** is returned if a malloc attempt fails.
  55519. */
  55520. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  55521. BtShared *pBt = p->pBt;
  55522. BtLock *pLock = 0;
  55523. BtLock *pIter;
  55524. assert( sqlite3BtreeHoldsMutex(p) );
  55525. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  55526. assert( p->db!=0 );
  55527. /* A connection with the read-uncommitted flag set will never try to
  55528. ** obtain a read-lock using this function. The only read-lock obtained
  55529. ** by a connection in read-uncommitted mode is on the sqlite_master
  55530. ** table, and that lock is obtained in BtreeBeginTrans(). */
  55531. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  55532. /* This function should only be called on a sharable b-tree after it
  55533. ** has been determined that no other b-tree holds a conflicting lock. */
  55534. assert( p->sharable );
  55535. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  55536. /* First search the list for an existing lock on this table. */
  55537. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  55538. if( pIter->iTable==iTable && pIter->pBtree==p ){
  55539. pLock = pIter;
  55540. break;
  55541. }
  55542. }
  55543. /* If the above search did not find a BtLock struct associating Btree p
  55544. ** with table iTable, allocate one and link it into the list.
  55545. */
  55546. if( !pLock ){
  55547. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  55548. if( !pLock ){
  55549. return SQLITE_NOMEM_BKPT;
  55550. }
  55551. pLock->iTable = iTable;
  55552. pLock->pBtree = p;
  55553. pLock->pNext = pBt->pLock;
  55554. pBt->pLock = pLock;
  55555. }
  55556. /* Set the BtLock.eLock variable to the maximum of the current lock
  55557. ** and the requested lock. This means if a write-lock was already held
  55558. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  55559. */
  55560. assert( WRITE_LOCK>READ_LOCK );
  55561. if( eLock>pLock->eLock ){
  55562. pLock->eLock = eLock;
  55563. }
  55564. return SQLITE_OK;
  55565. }
  55566. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  55567. #ifndef SQLITE_OMIT_SHARED_CACHE
  55568. /*
  55569. ** Release all the table locks (locks obtained via calls to
  55570. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  55571. **
  55572. ** This function assumes that Btree p has an open read or write
  55573. ** transaction. If it does not, then the BTS_PENDING flag
  55574. ** may be incorrectly cleared.
  55575. */
  55576. static void clearAllSharedCacheTableLocks(Btree *p){
  55577. BtShared *pBt = p->pBt;
  55578. BtLock **ppIter = &pBt->pLock;
  55579. assert( sqlite3BtreeHoldsMutex(p) );
  55580. assert( p->sharable || 0==*ppIter );
  55581. assert( p->inTrans>0 );
  55582. while( *ppIter ){
  55583. BtLock *pLock = *ppIter;
  55584. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  55585. assert( pLock->pBtree->inTrans>=pLock->eLock );
  55586. if( pLock->pBtree==p ){
  55587. *ppIter = pLock->pNext;
  55588. assert( pLock->iTable!=1 || pLock==&p->lock );
  55589. if( pLock->iTable!=1 ){
  55590. sqlite3_free(pLock);
  55591. }
  55592. }else{
  55593. ppIter = &pLock->pNext;
  55594. }
  55595. }
  55596. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  55597. if( pBt->pWriter==p ){
  55598. pBt->pWriter = 0;
  55599. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  55600. }else if( pBt->nTransaction==2 ){
  55601. /* This function is called when Btree p is concluding its
  55602. ** transaction. If there currently exists a writer, and p is not
  55603. ** that writer, then the number of locks held by connections other
  55604. ** than the writer must be about to drop to zero. In this case
  55605. ** set the BTS_PENDING flag to 0.
  55606. **
  55607. ** If there is not currently a writer, then BTS_PENDING must
  55608. ** be zero already. So this next line is harmless in that case.
  55609. */
  55610. pBt->btsFlags &= ~BTS_PENDING;
  55611. }
  55612. }
  55613. /*
  55614. ** This function changes all write-locks held by Btree p into read-locks.
  55615. */
  55616. static void downgradeAllSharedCacheTableLocks(Btree *p){
  55617. BtShared *pBt = p->pBt;
  55618. if( pBt->pWriter==p ){
  55619. BtLock *pLock;
  55620. pBt->pWriter = 0;
  55621. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  55622. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  55623. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  55624. pLock->eLock = READ_LOCK;
  55625. }
  55626. }
  55627. }
  55628. #endif /* SQLITE_OMIT_SHARED_CACHE */
  55629. static void releasePage(MemPage *pPage); /* Forward reference */
  55630. /*
  55631. ***** This routine is used inside of assert() only ****
  55632. **
  55633. ** Verify that the cursor holds the mutex on its BtShared
  55634. */
  55635. #ifdef SQLITE_DEBUG
  55636. static int cursorHoldsMutex(BtCursor *p){
  55637. return sqlite3_mutex_held(p->pBt->mutex);
  55638. }
  55639. /* Verify that the cursor and the BtShared agree about what is the current
  55640. ** database connetion. This is important in shared-cache mode. If the database
  55641. ** connection pointers get out-of-sync, it is possible for routines like
  55642. ** btreeInitPage() to reference an stale connection pointer that references a
  55643. ** a connection that has already closed. This routine is used inside assert()
  55644. ** statements only and for the purpose of double-checking that the btree code
  55645. ** does keep the database connection pointers up-to-date.
  55646. */
  55647. static int cursorOwnsBtShared(BtCursor *p){
  55648. assert( cursorHoldsMutex(p) );
  55649. return (p->pBtree->db==p->pBt->db);
  55650. }
  55651. #endif
  55652. /*
  55653. ** Invalidate the overflow cache of the cursor passed as the first argument.
  55654. ** on the shared btree structure pBt.
  55655. */
  55656. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  55657. /*
  55658. ** Invalidate the overflow page-list cache for all cursors opened
  55659. ** on the shared btree structure pBt.
  55660. */
  55661. static void invalidateAllOverflowCache(BtShared *pBt){
  55662. BtCursor *p;
  55663. assert( sqlite3_mutex_held(pBt->mutex) );
  55664. for(p=pBt->pCursor; p; p=p->pNext){
  55665. invalidateOverflowCache(p);
  55666. }
  55667. }
  55668. #ifndef SQLITE_OMIT_INCRBLOB
  55669. /*
  55670. ** This function is called before modifying the contents of a table
  55671. ** to invalidate any incrblob cursors that are open on the
  55672. ** row or one of the rows being modified.
  55673. **
  55674. ** If argument isClearTable is true, then the entire contents of the
  55675. ** table is about to be deleted. In this case invalidate all incrblob
  55676. ** cursors open on any row within the table with root-page pgnoRoot.
  55677. **
  55678. ** Otherwise, if argument isClearTable is false, then the row with
  55679. ** rowid iRow is being replaced or deleted. In this case invalidate
  55680. ** only those incrblob cursors open on that specific row.
  55681. */
  55682. static void invalidateIncrblobCursors(
  55683. Btree *pBtree, /* The database file to check */
  55684. Pgno pgnoRoot, /* The table that might be changing */
  55685. i64 iRow, /* The rowid that might be changing */
  55686. int isClearTable /* True if all rows are being deleted */
  55687. ){
  55688. BtCursor *p;
  55689. if( pBtree->hasIncrblobCur==0 ) return;
  55690. assert( sqlite3BtreeHoldsMutex(pBtree) );
  55691. pBtree->hasIncrblobCur = 0;
  55692. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  55693. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  55694. pBtree->hasIncrblobCur = 1;
  55695. if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
  55696. p->eState = CURSOR_INVALID;
  55697. }
  55698. }
  55699. }
  55700. }
  55701. #else
  55702. /* Stub function when INCRBLOB is omitted */
  55703. #define invalidateIncrblobCursors(w,x,y,z)
  55704. #endif /* SQLITE_OMIT_INCRBLOB */
  55705. /*
  55706. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  55707. ** when a page that previously contained data becomes a free-list leaf
  55708. ** page.
  55709. **
  55710. ** The BtShared.pHasContent bitvec exists to work around an obscure
  55711. ** bug caused by the interaction of two useful IO optimizations surrounding
  55712. ** free-list leaf pages:
  55713. **
  55714. ** 1) When all data is deleted from a page and the page becomes
  55715. ** a free-list leaf page, the page is not written to the database
  55716. ** (as free-list leaf pages contain no meaningful data). Sometimes
  55717. ** such a page is not even journalled (as it will not be modified,
  55718. ** why bother journalling it?).
  55719. **
  55720. ** 2) When a free-list leaf page is reused, its content is not read
  55721. ** from the database or written to the journal file (why should it
  55722. ** be, if it is not at all meaningful?).
  55723. **
  55724. ** By themselves, these optimizations work fine and provide a handy
  55725. ** performance boost to bulk delete or insert operations. However, if
  55726. ** a page is moved to the free-list and then reused within the same
  55727. ** transaction, a problem comes up. If the page is not journalled when
  55728. ** it is moved to the free-list and it is also not journalled when it
  55729. ** is extracted from the free-list and reused, then the original data
  55730. ** may be lost. In the event of a rollback, it may not be possible
  55731. ** to restore the database to its original configuration.
  55732. **
  55733. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  55734. ** moved to become a free-list leaf page, the corresponding bit is
  55735. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  55736. ** optimization 2 above is omitted if the corresponding bit is already
  55737. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  55738. ** at the end of every transaction.
  55739. */
  55740. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  55741. int rc = SQLITE_OK;
  55742. if( !pBt->pHasContent ){
  55743. assert( pgno<=pBt->nPage );
  55744. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  55745. if( !pBt->pHasContent ){
  55746. rc = SQLITE_NOMEM_BKPT;
  55747. }
  55748. }
  55749. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  55750. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  55751. }
  55752. return rc;
  55753. }
  55754. /*
  55755. ** Query the BtShared.pHasContent vector.
  55756. **
  55757. ** This function is called when a free-list leaf page is removed from the
  55758. ** free-list for reuse. It returns false if it is safe to retrieve the
  55759. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  55760. */
  55761. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  55762. Bitvec *p = pBt->pHasContent;
  55763. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  55764. }
  55765. /*
  55766. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  55767. ** invoked at the conclusion of each write-transaction.
  55768. */
  55769. static void btreeClearHasContent(BtShared *pBt){
  55770. sqlite3BitvecDestroy(pBt->pHasContent);
  55771. pBt->pHasContent = 0;
  55772. }
  55773. /*
  55774. ** Release all of the apPage[] pages for a cursor.
  55775. */
  55776. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  55777. int i;
  55778. for(i=0; i<=pCur->iPage; i++){
  55779. releasePage(pCur->apPage[i]);
  55780. pCur->apPage[i] = 0;
  55781. }
  55782. pCur->iPage = -1;
  55783. }
  55784. /*
  55785. ** The cursor passed as the only argument must point to a valid entry
  55786. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  55787. ** function saves the current cursor key in variables pCur->nKey and
  55788. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  55789. ** code otherwise.
  55790. **
  55791. ** If the cursor is open on an intkey table, then the integer key
  55792. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  55793. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  55794. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  55795. ** the key.
  55796. */
  55797. static int saveCursorKey(BtCursor *pCur){
  55798. int rc = SQLITE_OK;
  55799. assert( CURSOR_VALID==pCur->eState );
  55800. assert( 0==pCur->pKey );
  55801. assert( cursorHoldsMutex(pCur) );
  55802. if( pCur->curIntKey ){
  55803. /* Only the rowid is required for a table btree */
  55804. pCur->nKey = sqlite3BtreeIntegerKey(pCur);
  55805. }else{
  55806. /* For an index btree, save the complete key content */
  55807. void *pKey;
  55808. pCur->nKey = sqlite3BtreePayloadSize(pCur);
  55809. pKey = sqlite3Malloc( pCur->nKey );
  55810. if( pKey ){
  55811. rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
  55812. if( rc==SQLITE_OK ){
  55813. pCur->pKey = pKey;
  55814. }else{
  55815. sqlite3_free(pKey);
  55816. }
  55817. }else{
  55818. rc = SQLITE_NOMEM_BKPT;
  55819. }
  55820. }
  55821. assert( !pCur->curIntKey || !pCur->pKey );
  55822. return rc;
  55823. }
  55824. /*
  55825. ** Save the current cursor position in the variables BtCursor.nKey
  55826. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  55827. **
  55828. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  55829. ** prior to calling this routine.
  55830. */
  55831. static int saveCursorPosition(BtCursor *pCur){
  55832. int rc;
  55833. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  55834. assert( 0==pCur->pKey );
  55835. assert( cursorHoldsMutex(pCur) );
  55836. if( pCur->eState==CURSOR_SKIPNEXT ){
  55837. pCur->eState = CURSOR_VALID;
  55838. }else{
  55839. pCur->skipNext = 0;
  55840. }
  55841. rc = saveCursorKey(pCur);
  55842. if( rc==SQLITE_OK ){
  55843. btreeReleaseAllCursorPages(pCur);
  55844. pCur->eState = CURSOR_REQUIRESEEK;
  55845. }
  55846. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  55847. return rc;
  55848. }
  55849. /* Forward reference */
  55850. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  55851. /*
  55852. ** Save the positions of all cursors (except pExcept) that are open on
  55853. ** the table with root-page iRoot. "Saving the cursor position" means that
  55854. ** the location in the btree is remembered in such a way that it can be
  55855. ** moved back to the same spot after the btree has been modified. This
  55856. ** routine is called just before cursor pExcept is used to modify the
  55857. ** table, for example in BtreeDelete() or BtreeInsert().
  55858. **
  55859. ** If there are two or more cursors on the same btree, then all such
  55860. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  55861. ** routine enforces that rule. This routine only needs to be called in
  55862. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  55863. **
  55864. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  55865. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  55866. ** pointless call to this routine.
  55867. **
  55868. ** Implementation note: This routine merely checks to see if any cursors
  55869. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  55870. ** event that cursors are in need to being saved.
  55871. */
  55872. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  55873. BtCursor *p;
  55874. assert( sqlite3_mutex_held(pBt->mutex) );
  55875. assert( pExcept==0 || pExcept->pBt==pBt );
  55876. for(p=pBt->pCursor; p; p=p->pNext){
  55877. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  55878. }
  55879. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  55880. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  55881. return SQLITE_OK;
  55882. }
  55883. /* This helper routine to saveAllCursors does the actual work of saving
  55884. ** the cursors if and when a cursor is found that actually requires saving.
  55885. ** The common case is that no cursors need to be saved, so this routine is
  55886. ** broken out from its caller to avoid unnecessary stack pointer movement.
  55887. */
  55888. static int SQLITE_NOINLINE saveCursorsOnList(
  55889. BtCursor *p, /* The first cursor that needs saving */
  55890. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  55891. BtCursor *pExcept /* Do not save this cursor */
  55892. ){
  55893. do{
  55894. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  55895. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  55896. int rc = saveCursorPosition(p);
  55897. if( SQLITE_OK!=rc ){
  55898. return rc;
  55899. }
  55900. }else{
  55901. testcase( p->iPage>0 );
  55902. btreeReleaseAllCursorPages(p);
  55903. }
  55904. }
  55905. p = p->pNext;
  55906. }while( p );
  55907. return SQLITE_OK;
  55908. }
  55909. /*
  55910. ** Clear the current cursor position.
  55911. */
  55912. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  55913. assert( cursorHoldsMutex(pCur) );
  55914. sqlite3_free(pCur->pKey);
  55915. pCur->pKey = 0;
  55916. pCur->eState = CURSOR_INVALID;
  55917. }
  55918. /*
  55919. ** In this version of BtreeMoveto, pKey is a packed index record
  55920. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  55921. ** record and then call BtreeMovetoUnpacked() to do the work.
  55922. */
  55923. static int btreeMoveto(
  55924. BtCursor *pCur, /* Cursor open on the btree to be searched */
  55925. const void *pKey, /* Packed key if the btree is an index */
  55926. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  55927. int bias, /* Bias search to the high end */
  55928. int *pRes /* Write search results here */
  55929. ){
  55930. int rc; /* Status code */
  55931. UnpackedRecord *pIdxKey; /* Unpacked index key */
  55932. if( pKey ){
  55933. assert( nKey==(i64)(int)nKey );
  55934. pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
  55935. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  55936. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  55937. if( pIdxKey->nField==0 ){
  55938. rc = SQLITE_CORRUPT_BKPT;
  55939. goto moveto_done;
  55940. }
  55941. }else{
  55942. pIdxKey = 0;
  55943. }
  55944. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  55945. moveto_done:
  55946. if( pIdxKey ){
  55947. sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
  55948. }
  55949. return rc;
  55950. }
  55951. /*
  55952. ** Restore the cursor to the position it was in (or as close to as possible)
  55953. ** when saveCursorPosition() was called. Note that this call deletes the
  55954. ** saved position info stored by saveCursorPosition(), so there can be
  55955. ** at most one effective restoreCursorPosition() call after each
  55956. ** saveCursorPosition().
  55957. */
  55958. static int btreeRestoreCursorPosition(BtCursor *pCur){
  55959. int rc;
  55960. int skipNext;
  55961. assert( cursorOwnsBtShared(pCur) );
  55962. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  55963. if( pCur->eState==CURSOR_FAULT ){
  55964. return pCur->skipNext;
  55965. }
  55966. pCur->eState = CURSOR_INVALID;
  55967. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  55968. if( rc==SQLITE_OK ){
  55969. sqlite3_free(pCur->pKey);
  55970. pCur->pKey = 0;
  55971. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  55972. pCur->skipNext |= skipNext;
  55973. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  55974. pCur->eState = CURSOR_SKIPNEXT;
  55975. }
  55976. }
  55977. return rc;
  55978. }
  55979. #define restoreCursorPosition(p) \
  55980. (p->eState>=CURSOR_REQUIRESEEK ? \
  55981. btreeRestoreCursorPosition(p) : \
  55982. SQLITE_OK)
  55983. /*
  55984. ** Determine whether or not a cursor has moved from the position where
  55985. ** it was last placed, or has been invalidated for any other reason.
  55986. ** Cursors can move when the row they are pointing at is deleted out
  55987. ** from under them, for example. Cursor might also move if a btree
  55988. ** is rebalanced.
  55989. **
  55990. ** Calling this routine with a NULL cursor pointer returns false.
  55991. **
  55992. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  55993. ** back to where it ought to be if this routine returns true.
  55994. */
  55995. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  55996. return pCur->eState!=CURSOR_VALID;
  55997. }
  55998. /*
  55999. ** This routine restores a cursor back to its original position after it
  56000. ** has been moved by some outside activity (such as a btree rebalance or
  56001. ** a row having been deleted out from under the cursor).
  56002. **
  56003. ** On success, the *pDifferentRow parameter is false if the cursor is left
  56004. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  56005. ** was pointing to has been deleted, forcing the cursor to point to some
  56006. ** nearby row.
  56007. **
  56008. ** This routine should only be called for a cursor that just returned
  56009. ** TRUE from sqlite3BtreeCursorHasMoved().
  56010. */
  56011. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  56012. int rc;
  56013. assert( pCur!=0 );
  56014. assert( pCur->eState!=CURSOR_VALID );
  56015. rc = restoreCursorPosition(pCur);
  56016. if( rc ){
  56017. *pDifferentRow = 1;
  56018. return rc;
  56019. }
  56020. if( pCur->eState!=CURSOR_VALID ){
  56021. *pDifferentRow = 1;
  56022. }else{
  56023. assert( pCur->skipNext==0 );
  56024. *pDifferentRow = 0;
  56025. }
  56026. return SQLITE_OK;
  56027. }
  56028. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  56029. /*
  56030. ** Provide hints to the cursor. The particular hint given (and the type
  56031. ** and number of the varargs parameters) is determined by the eHintType
  56032. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  56033. */
  56034. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  56035. /* Used only by system that substitute their own storage engine */
  56036. }
  56037. #endif
  56038. /*
  56039. ** Provide flag hints to the cursor.
  56040. */
  56041. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  56042. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  56043. pCur->hints = x;
  56044. }
  56045. #ifndef SQLITE_OMIT_AUTOVACUUM
  56046. /*
  56047. ** Given a page number of a regular database page, return the page
  56048. ** number for the pointer-map page that contains the entry for the
  56049. ** input page number.
  56050. **
  56051. ** Return 0 (not a valid page) for pgno==1 since there is
  56052. ** no pointer map associated with page 1. The integrity_check logic
  56053. ** requires that ptrmapPageno(*,1)!=1.
  56054. */
  56055. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  56056. int nPagesPerMapPage;
  56057. Pgno iPtrMap, ret;
  56058. assert( sqlite3_mutex_held(pBt->mutex) );
  56059. if( pgno<2 ) return 0;
  56060. nPagesPerMapPage = (pBt->usableSize/5)+1;
  56061. iPtrMap = (pgno-2)/nPagesPerMapPage;
  56062. ret = (iPtrMap*nPagesPerMapPage) + 2;
  56063. if( ret==PENDING_BYTE_PAGE(pBt) ){
  56064. ret++;
  56065. }
  56066. return ret;
  56067. }
  56068. /*
  56069. ** Write an entry into the pointer map.
  56070. **
  56071. ** This routine updates the pointer map entry for page number 'key'
  56072. ** so that it maps to type 'eType' and parent page number 'pgno'.
  56073. **
  56074. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  56075. ** a no-op. If an error occurs, the appropriate error code is written
  56076. ** into *pRC.
  56077. */
  56078. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  56079. DbPage *pDbPage; /* The pointer map page */
  56080. u8 *pPtrmap; /* The pointer map data */
  56081. Pgno iPtrmap; /* The pointer map page number */
  56082. int offset; /* Offset in pointer map page */
  56083. int rc; /* Return code from subfunctions */
  56084. if( *pRC ) return;
  56085. assert( sqlite3_mutex_held(pBt->mutex) );
  56086. /* The master-journal page number must never be used as a pointer map page */
  56087. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  56088. assert( pBt->autoVacuum );
  56089. if( key==0 ){
  56090. *pRC = SQLITE_CORRUPT_BKPT;
  56091. return;
  56092. }
  56093. iPtrmap = PTRMAP_PAGENO(pBt, key);
  56094. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  56095. if( rc!=SQLITE_OK ){
  56096. *pRC = rc;
  56097. return;
  56098. }
  56099. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  56100. if( offset<0 ){
  56101. *pRC = SQLITE_CORRUPT_BKPT;
  56102. goto ptrmap_exit;
  56103. }
  56104. assert( offset <= (int)pBt->usableSize-5 );
  56105. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  56106. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  56107. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  56108. *pRC= rc = sqlite3PagerWrite(pDbPage);
  56109. if( rc==SQLITE_OK ){
  56110. pPtrmap[offset] = eType;
  56111. put4byte(&pPtrmap[offset+1], parent);
  56112. }
  56113. }
  56114. ptrmap_exit:
  56115. sqlite3PagerUnref(pDbPage);
  56116. }
  56117. /*
  56118. ** Read an entry from the pointer map.
  56119. **
  56120. ** This routine retrieves the pointer map entry for page 'key', writing
  56121. ** the type and parent page number to *pEType and *pPgno respectively.
  56122. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  56123. */
  56124. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  56125. DbPage *pDbPage; /* The pointer map page */
  56126. int iPtrmap; /* Pointer map page index */
  56127. u8 *pPtrmap; /* Pointer map page data */
  56128. int offset; /* Offset of entry in pointer map */
  56129. int rc;
  56130. assert( sqlite3_mutex_held(pBt->mutex) );
  56131. iPtrmap = PTRMAP_PAGENO(pBt, key);
  56132. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  56133. if( rc!=0 ){
  56134. return rc;
  56135. }
  56136. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  56137. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  56138. if( offset<0 ){
  56139. sqlite3PagerUnref(pDbPage);
  56140. return SQLITE_CORRUPT_BKPT;
  56141. }
  56142. assert( offset <= (int)pBt->usableSize-5 );
  56143. assert( pEType!=0 );
  56144. *pEType = pPtrmap[offset];
  56145. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  56146. sqlite3PagerUnref(pDbPage);
  56147. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  56148. return SQLITE_OK;
  56149. }
  56150. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  56151. #define ptrmapPut(w,x,y,z,rc)
  56152. #define ptrmapGet(w,x,y,z) SQLITE_OK
  56153. #define ptrmapPutOvflPtr(x, y, rc)
  56154. #endif
  56155. /*
  56156. ** Given a btree page and a cell index (0 means the first cell on
  56157. ** the page, 1 means the second cell, and so forth) return a pointer
  56158. ** to the cell content.
  56159. **
  56160. ** findCellPastPtr() does the same except it skips past the initial
  56161. ** 4-byte child pointer found on interior pages, if there is one.
  56162. **
  56163. ** This routine works only for pages that do not contain overflow cells.
  56164. */
  56165. #define findCell(P,I) \
  56166. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  56167. #define findCellPastPtr(P,I) \
  56168. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  56169. /*
  56170. ** This is common tail processing for btreeParseCellPtr() and
  56171. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  56172. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  56173. ** structure.
  56174. */
  56175. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  56176. MemPage *pPage, /* Page containing the cell */
  56177. u8 *pCell, /* Pointer to the cell text. */
  56178. CellInfo *pInfo /* Fill in this structure */
  56179. ){
  56180. /* If the payload will not fit completely on the local page, we have
  56181. ** to decide how much to store locally and how much to spill onto
  56182. ** overflow pages. The strategy is to minimize the amount of unused
  56183. ** space on overflow pages while keeping the amount of local storage
  56184. ** in between minLocal and maxLocal.
  56185. **
  56186. ** Warning: changing the way overflow payload is distributed in any
  56187. ** way will result in an incompatible file format.
  56188. */
  56189. int minLocal; /* Minimum amount of payload held locally */
  56190. int maxLocal; /* Maximum amount of payload held locally */
  56191. int surplus; /* Overflow payload available for local storage */
  56192. minLocal = pPage->minLocal;
  56193. maxLocal = pPage->maxLocal;
  56194. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  56195. testcase( surplus==maxLocal );
  56196. testcase( surplus==maxLocal+1 );
  56197. if( surplus <= maxLocal ){
  56198. pInfo->nLocal = (u16)surplus;
  56199. }else{
  56200. pInfo->nLocal = (u16)minLocal;
  56201. }
  56202. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  56203. }
  56204. /*
  56205. ** The following routines are implementations of the MemPage.xParseCell()
  56206. ** method.
  56207. **
  56208. ** Parse a cell content block and fill in the CellInfo structure.
  56209. **
  56210. ** btreeParseCellPtr() => table btree leaf nodes
  56211. ** btreeParseCellNoPayload() => table btree internal nodes
  56212. ** btreeParseCellPtrIndex() => index btree nodes
  56213. **
  56214. ** There is also a wrapper function btreeParseCell() that works for
  56215. ** all MemPage types and that references the cell by index rather than
  56216. ** by pointer.
  56217. */
  56218. static void btreeParseCellPtrNoPayload(
  56219. MemPage *pPage, /* Page containing the cell */
  56220. u8 *pCell, /* Pointer to the cell text. */
  56221. CellInfo *pInfo /* Fill in this structure */
  56222. ){
  56223. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56224. assert( pPage->leaf==0 );
  56225. assert( pPage->childPtrSize==4 );
  56226. #ifndef SQLITE_DEBUG
  56227. UNUSED_PARAMETER(pPage);
  56228. #endif
  56229. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  56230. pInfo->nPayload = 0;
  56231. pInfo->nLocal = 0;
  56232. pInfo->pPayload = 0;
  56233. return;
  56234. }
  56235. static void btreeParseCellPtr(
  56236. MemPage *pPage, /* Page containing the cell */
  56237. u8 *pCell, /* Pointer to the cell text. */
  56238. CellInfo *pInfo /* Fill in this structure */
  56239. ){
  56240. u8 *pIter; /* For scanning through pCell */
  56241. u32 nPayload; /* Number of bytes of cell payload */
  56242. u64 iKey; /* Extracted Key value */
  56243. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56244. assert( pPage->leaf==0 || pPage->leaf==1 );
  56245. assert( pPage->intKeyLeaf );
  56246. assert( pPage->childPtrSize==0 );
  56247. pIter = pCell;
  56248. /* The next block of code is equivalent to:
  56249. **
  56250. ** pIter += getVarint32(pIter, nPayload);
  56251. **
  56252. ** The code is inlined to avoid a function call.
  56253. */
  56254. nPayload = *pIter;
  56255. if( nPayload>=0x80 ){
  56256. u8 *pEnd = &pIter[8];
  56257. nPayload &= 0x7f;
  56258. do{
  56259. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  56260. }while( (*pIter)>=0x80 && pIter<pEnd );
  56261. }
  56262. pIter++;
  56263. /* The next block of code is equivalent to:
  56264. **
  56265. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  56266. **
  56267. ** The code is inlined to avoid a function call.
  56268. */
  56269. iKey = *pIter;
  56270. if( iKey>=0x80 ){
  56271. u8 *pEnd = &pIter[7];
  56272. iKey &= 0x7f;
  56273. while(1){
  56274. iKey = (iKey<<7) | (*++pIter & 0x7f);
  56275. if( (*pIter)<0x80 ) break;
  56276. if( pIter>=pEnd ){
  56277. iKey = (iKey<<8) | *++pIter;
  56278. break;
  56279. }
  56280. }
  56281. }
  56282. pIter++;
  56283. pInfo->nKey = *(i64*)&iKey;
  56284. pInfo->nPayload = nPayload;
  56285. pInfo->pPayload = pIter;
  56286. testcase( nPayload==pPage->maxLocal );
  56287. testcase( nPayload==pPage->maxLocal+1 );
  56288. if( nPayload<=pPage->maxLocal ){
  56289. /* This is the (easy) common case where the entire payload fits
  56290. ** on the local page. No overflow is required.
  56291. */
  56292. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  56293. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  56294. pInfo->nLocal = (u16)nPayload;
  56295. }else{
  56296. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  56297. }
  56298. }
  56299. static void btreeParseCellPtrIndex(
  56300. MemPage *pPage, /* Page containing the cell */
  56301. u8 *pCell, /* Pointer to the cell text. */
  56302. CellInfo *pInfo /* Fill in this structure */
  56303. ){
  56304. u8 *pIter; /* For scanning through pCell */
  56305. u32 nPayload; /* Number of bytes of cell payload */
  56306. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56307. assert( pPage->leaf==0 || pPage->leaf==1 );
  56308. assert( pPage->intKeyLeaf==0 );
  56309. pIter = pCell + pPage->childPtrSize;
  56310. nPayload = *pIter;
  56311. if( nPayload>=0x80 ){
  56312. u8 *pEnd = &pIter[8];
  56313. nPayload &= 0x7f;
  56314. do{
  56315. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  56316. }while( *(pIter)>=0x80 && pIter<pEnd );
  56317. }
  56318. pIter++;
  56319. pInfo->nKey = nPayload;
  56320. pInfo->nPayload = nPayload;
  56321. pInfo->pPayload = pIter;
  56322. testcase( nPayload==pPage->maxLocal );
  56323. testcase( nPayload==pPage->maxLocal+1 );
  56324. if( nPayload<=pPage->maxLocal ){
  56325. /* This is the (easy) common case where the entire payload fits
  56326. ** on the local page. No overflow is required.
  56327. */
  56328. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  56329. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  56330. pInfo->nLocal = (u16)nPayload;
  56331. }else{
  56332. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  56333. }
  56334. }
  56335. static void btreeParseCell(
  56336. MemPage *pPage, /* Page containing the cell */
  56337. int iCell, /* The cell index. First cell is 0 */
  56338. CellInfo *pInfo /* Fill in this structure */
  56339. ){
  56340. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  56341. }
  56342. /*
  56343. ** The following routines are implementations of the MemPage.xCellSize
  56344. ** method.
  56345. **
  56346. ** Compute the total number of bytes that a Cell needs in the cell
  56347. ** data area of the btree-page. The return number includes the cell
  56348. ** data header and the local payload, but not any overflow page or
  56349. ** the space used by the cell pointer.
  56350. **
  56351. ** cellSizePtrNoPayload() => table internal nodes
  56352. ** cellSizePtr() => all index nodes & table leaf nodes
  56353. */
  56354. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  56355. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  56356. u8 *pEnd; /* End mark for a varint */
  56357. u32 nSize; /* Size value to return */
  56358. #ifdef SQLITE_DEBUG
  56359. /* The value returned by this function should always be the same as
  56360. ** the (CellInfo.nSize) value found by doing a full parse of the
  56361. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  56362. ** this function verifies that this invariant is not violated. */
  56363. CellInfo debuginfo;
  56364. pPage->xParseCell(pPage, pCell, &debuginfo);
  56365. #endif
  56366. nSize = *pIter;
  56367. if( nSize>=0x80 ){
  56368. pEnd = &pIter[8];
  56369. nSize &= 0x7f;
  56370. do{
  56371. nSize = (nSize<<7) | (*++pIter & 0x7f);
  56372. }while( *(pIter)>=0x80 && pIter<pEnd );
  56373. }
  56374. pIter++;
  56375. if( pPage->intKey ){
  56376. /* pIter now points at the 64-bit integer key value, a variable length
  56377. ** integer. The following block moves pIter to point at the first byte
  56378. ** past the end of the key value. */
  56379. pEnd = &pIter[9];
  56380. while( (*pIter++)&0x80 && pIter<pEnd );
  56381. }
  56382. testcase( nSize==pPage->maxLocal );
  56383. testcase( nSize==pPage->maxLocal+1 );
  56384. if( nSize<=pPage->maxLocal ){
  56385. nSize += (u32)(pIter - pCell);
  56386. if( nSize<4 ) nSize = 4;
  56387. }else{
  56388. int minLocal = pPage->minLocal;
  56389. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  56390. testcase( nSize==pPage->maxLocal );
  56391. testcase( nSize==pPage->maxLocal+1 );
  56392. if( nSize>pPage->maxLocal ){
  56393. nSize = minLocal;
  56394. }
  56395. nSize += 4 + (u16)(pIter - pCell);
  56396. }
  56397. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  56398. return (u16)nSize;
  56399. }
  56400. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  56401. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  56402. u8 *pEnd; /* End mark for a varint */
  56403. #ifdef SQLITE_DEBUG
  56404. /* The value returned by this function should always be the same as
  56405. ** the (CellInfo.nSize) value found by doing a full parse of the
  56406. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  56407. ** this function verifies that this invariant is not violated. */
  56408. CellInfo debuginfo;
  56409. pPage->xParseCell(pPage, pCell, &debuginfo);
  56410. #else
  56411. UNUSED_PARAMETER(pPage);
  56412. #endif
  56413. assert( pPage->childPtrSize==4 );
  56414. pEnd = pIter + 9;
  56415. while( (*pIter++)&0x80 && pIter<pEnd );
  56416. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  56417. return (u16)(pIter - pCell);
  56418. }
  56419. #ifdef SQLITE_DEBUG
  56420. /* This variation on cellSizePtr() is used inside of assert() statements
  56421. ** only. */
  56422. static u16 cellSize(MemPage *pPage, int iCell){
  56423. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  56424. }
  56425. #endif
  56426. #ifndef SQLITE_OMIT_AUTOVACUUM
  56427. /*
  56428. ** If the cell pCell, part of page pPage contains a pointer
  56429. ** to an overflow page, insert an entry into the pointer-map
  56430. ** for the overflow page.
  56431. */
  56432. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  56433. CellInfo info;
  56434. if( *pRC ) return;
  56435. assert( pCell!=0 );
  56436. pPage->xParseCell(pPage, pCell, &info);
  56437. if( info.nLocal<info.nPayload ){
  56438. Pgno ovfl = get4byte(&pCell[info.nSize-4]);
  56439. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  56440. }
  56441. }
  56442. #endif
  56443. /*
  56444. ** Defragment the page given. This routine reorganizes cells within the
  56445. ** page so that there are no free-blocks on the free-block list.
  56446. **
  56447. ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
  56448. ** present in the page after this routine returns.
  56449. **
  56450. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  56451. ** b-tree page so that there are no freeblocks or fragment bytes, all
  56452. ** unused bytes are contained in the unallocated space region, and all
  56453. ** cells are packed tightly at the end of the page.
  56454. */
  56455. static int defragmentPage(MemPage *pPage, int nMaxFrag){
  56456. int i; /* Loop counter */
  56457. int pc; /* Address of the i-th cell */
  56458. int hdr; /* Offset to the page header */
  56459. int size; /* Size of a cell */
  56460. int usableSize; /* Number of usable bytes on a page */
  56461. int cellOffset; /* Offset to the cell pointer array */
  56462. int cbrk; /* Offset to the cell content area */
  56463. int nCell; /* Number of cells on the page */
  56464. unsigned char *data; /* The page data */
  56465. unsigned char *temp; /* Temp area for cell content */
  56466. unsigned char *src; /* Source of content */
  56467. int iCellFirst; /* First allowable cell index */
  56468. int iCellLast; /* Last possible cell index */
  56469. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56470. assert( pPage->pBt!=0 );
  56471. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  56472. assert( pPage->nOverflow==0 );
  56473. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56474. temp = 0;
  56475. src = data = pPage->aData;
  56476. hdr = pPage->hdrOffset;
  56477. cellOffset = pPage->cellOffset;
  56478. nCell = pPage->nCell;
  56479. assert( nCell==get2byte(&data[hdr+3]) );
  56480. iCellFirst = cellOffset + 2*nCell;
  56481. usableSize = pPage->pBt->usableSize;
  56482. /* This block handles pages with two or fewer free blocks and nMaxFrag
  56483. ** or fewer fragmented bytes. In this case it is faster to move the
  56484. ** two (or one) blocks of cells using memmove() and add the required
  56485. ** offsets to each pointer in the cell-pointer array than it is to
  56486. ** reconstruct the entire page. */
  56487. if( (int)data[hdr+7]<=nMaxFrag ){
  56488. int iFree = get2byte(&data[hdr+1]);
  56489. if( iFree ){
  56490. int iFree2 = get2byte(&data[iFree]);
  56491. /* pageFindSlot() has already verified that free blocks are sorted
  56492. ** in order of offset within the page, and that no block extends
  56493. ** past the end of the page. Provided the two free slots do not
  56494. ** overlap, this guarantees that the memmove() calls below will not
  56495. ** overwrite the usableSize byte buffer, even if the database page
  56496. ** is corrupt. */
  56497. assert( iFree2==0 || iFree2>iFree );
  56498. assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
  56499. assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
  56500. if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
  56501. u8 *pEnd = &data[cellOffset + nCell*2];
  56502. u8 *pAddr;
  56503. int sz2 = 0;
  56504. int sz = get2byte(&data[iFree+2]);
  56505. int top = get2byte(&data[hdr+5]);
  56506. if( iFree2 ){
  56507. if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_BKPT;
  56508. sz2 = get2byte(&data[iFree2+2]);
  56509. assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
  56510. memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
  56511. sz += sz2;
  56512. }
  56513. cbrk = top+sz;
  56514. assert( cbrk+(iFree-top) <= usableSize );
  56515. memmove(&data[cbrk], &data[top], iFree-top);
  56516. for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
  56517. pc = get2byte(pAddr);
  56518. if( pc<iFree ){ put2byte(pAddr, pc+sz); }
  56519. else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
  56520. }
  56521. goto defragment_out;
  56522. }
  56523. }
  56524. }
  56525. cbrk = usableSize;
  56526. iCellLast = usableSize - 4;
  56527. for(i=0; i<nCell; i++){
  56528. u8 *pAddr; /* The i-th cell pointer */
  56529. pAddr = &data[cellOffset + i*2];
  56530. pc = get2byte(pAddr);
  56531. testcase( pc==iCellFirst );
  56532. testcase( pc==iCellLast );
  56533. /* These conditions have already been verified in btreeInitPage()
  56534. ** if PRAGMA cell_size_check=ON.
  56535. */
  56536. if( pc<iCellFirst || pc>iCellLast ){
  56537. return SQLITE_CORRUPT_BKPT;
  56538. }
  56539. assert( pc>=iCellFirst && pc<=iCellLast );
  56540. size = pPage->xCellSize(pPage, &src[pc]);
  56541. cbrk -= size;
  56542. if( cbrk<iCellFirst || pc+size>usableSize ){
  56543. return SQLITE_CORRUPT_BKPT;
  56544. }
  56545. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  56546. testcase( cbrk+size==usableSize );
  56547. testcase( pc+size==usableSize );
  56548. put2byte(pAddr, cbrk);
  56549. if( temp==0 ){
  56550. int x;
  56551. if( cbrk==pc ) continue;
  56552. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  56553. x = get2byte(&data[hdr+5]);
  56554. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  56555. src = temp;
  56556. }
  56557. memcpy(&data[cbrk], &src[pc], size);
  56558. }
  56559. data[hdr+7] = 0;
  56560. defragment_out:
  56561. if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
  56562. return SQLITE_CORRUPT_BKPT;
  56563. }
  56564. assert( cbrk>=iCellFirst );
  56565. put2byte(&data[hdr+5], cbrk);
  56566. data[hdr+1] = 0;
  56567. data[hdr+2] = 0;
  56568. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  56569. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56570. return SQLITE_OK;
  56571. }
  56572. /*
  56573. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  56574. ** size. If one can be found, return a pointer to the space and remove it
  56575. ** from the free-list.
  56576. **
  56577. ** If no suitable space can be found on the free-list, return NULL.
  56578. **
  56579. ** This function may detect corruption within pPg. If corruption is
  56580. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  56581. **
  56582. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  56583. ** will be ignored if adding the extra space to the fragmentation count
  56584. ** causes the fragmentation count to exceed 60.
  56585. */
  56586. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  56587. const int hdr = pPg->hdrOffset;
  56588. u8 * const aData = pPg->aData;
  56589. int iAddr = hdr + 1;
  56590. int pc = get2byte(&aData[iAddr]);
  56591. int x;
  56592. int usableSize = pPg->pBt->usableSize;
  56593. assert( pc>0 );
  56594. do{
  56595. int size; /* Size of the free slot */
  56596. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  56597. ** increasing offset. */
  56598. if( pc>usableSize-4 || pc<iAddr+4 ){
  56599. *pRc = SQLITE_CORRUPT_BKPT;
  56600. return 0;
  56601. }
  56602. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  56603. ** freeblock form a big-endian integer which is the size of the freeblock
  56604. ** in bytes, including the 4-byte header. */
  56605. size = get2byte(&aData[pc+2]);
  56606. if( (x = size - nByte)>=0 ){
  56607. testcase( x==4 );
  56608. testcase( x==3 );
  56609. if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
  56610. *pRc = SQLITE_CORRUPT_BKPT;
  56611. return 0;
  56612. }else if( x<4 ){
  56613. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  56614. ** number of bytes in fragments may not exceed 60. */
  56615. if( aData[hdr+7]>57 ) return 0;
  56616. /* Remove the slot from the free-list. Update the number of
  56617. ** fragmented bytes within the page. */
  56618. memcpy(&aData[iAddr], &aData[pc], 2);
  56619. aData[hdr+7] += (u8)x;
  56620. }else{
  56621. /* The slot remains on the free-list. Reduce its size to account
  56622. ** for the portion used by the new allocation. */
  56623. put2byte(&aData[pc+2], x);
  56624. }
  56625. return &aData[pc + x];
  56626. }
  56627. iAddr = pc;
  56628. pc = get2byte(&aData[pc]);
  56629. }while( pc );
  56630. return 0;
  56631. }
  56632. /*
  56633. ** Allocate nByte bytes of space from within the B-Tree page passed
  56634. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  56635. ** of the first byte of allocated space. Return either SQLITE_OK or
  56636. ** an error code (usually SQLITE_CORRUPT).
  56637. **
  56638. ** The caller guarantees that there is sufficient space to make the
  56639. ** allocation. This routine might need to defragment in order to bring
  56640. ** all the space together, however. This routine will avoid using
  56641. ** the first two bytes past the cell pointer area since presumably this
  56642. ** allocation is being made in order to insert a new cell, so we will
  56643. ** also end up needing a new cell pointer.
  56644. */
  56645. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  56646. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  56647. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  56648. int top; /* First byte of cell content area */
  56649. int rc = SQLITE_OK; /* Integer return code */
  56650. int gap; /* First byte of gap between cell pointers and cell content */
  56651. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56652. assert( pPage->pBt );
  56653. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56654. assert( nByte>=0 ); /* Minimum cell size is 4 */
  56655. assert( pPage->nFree>=nByte );
  56656. assert( pPage->nOverflow==0 );
  56657. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  56658. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  56659. gap = pPage->cellOffset + 2*pPage->nCell;
  56660. assert( gap<=65536 );
  56661. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  56662. ** and the reserved space is zero (the usual value for reserved space)
  56663. ** then the cell content offset of an empty page wants to be 65536.
  56664. ** However, that integer is too large to be stored in a 2-byte unsigned
  56665. ** integer, so a value of 0 is used in its place. */
  56666. top = get2byte(&data[hdr+5]);
  56667. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  56668. if( gap>top ){
  56669. if( top==0 && pPage->pBt->usableSize==65536 ){
  56670. top = 65536;
  56671. }else{
  56672. return SQLITE_CORRUPT_BKPT;
  56673. }
  56674. }
  56675. /* If there is enough space between gap and top for one more cell pointer
  56676. ** array entry offset, and if the freelist is not empty, then search the
  56677. ** freelist looking for a free slot big enough to satisfy the request.
  56678. */
  56679. testcase( gap+2==top );
  56680. testcase( gap+1==top );
  56681. testcase( gap==top );
  56682. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  56683. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  56684. if( pSpace ){
  56685. assert( pSpace>=data && (pSpace - data)<65536 );
  56686. *pIdx = (int)(pSpace - data);
  56687. return SQLITE_OK;
  56688. }else if( rc ){
  56689. return rc;
  56690. }
  56691. }
  56692. /* The request could not be fulfilled using a freelist slot. Check
  56693. ** to see if defragmentation is necessary.
  56694. */
  56695. testcase( gap+2+nByte==top );
  56696. if( gap+2+nByte>top ){
  56697. assert( pPage->nCell>0 || CORRUPT_DB );
  56698. rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
  56699. if( rc ) return rc;
  56700. top = get2byteNotZero(&data[hdr+5]);
  56701. assert( gap+2+nByte<=top );
  56702. }
  56703. /* Allocate memory from the gap in between the cell pointer array
  56704. ** and the cell content area. The btreeInitPage() call has already
  56705. ** validated the freelist. Given that the freelist is valid, there
  56706. ** is no way that the allocation can extend off the end of the page.
  56707. ** The assert() below verifies the previous sentence.
  56708. */
  56709. top -= nByte;
  56710. put2byte(&data[hdr+5], top);
  56711. assert( top+nByte <= (int)pPage->pBt->usableSize );
  56712. *pIdx = top;
  56713. return SQLITE_OK;
  56714. }
  56715. /*
  56716. ** Return a section of the pPage->aData to the freelist.
  56717. ** The first byte of the new free block is pPage->aData[iStart]
  56718. ** and the size of the block is iSize bytes.
  56719. **
  56720. ** Adjacent freeblocks are coalesced.
  56721. **
  56722. ** Note that even though the freeblock list was checked by btreeInitPage(),
  56723. ** that routine will not detect overlap between cells or freeblocks. Nor
  56724. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  56725. ** at the end of the page. So do additional corruption checks inside this
  56726. ** routine and return SQLITE_CORRUPT if any problems are found.
  56727. */
  56728. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  56729. u16 iPtr; /* Address of ptr to next freeblock */
  56730. u16 iFreeBlk; /* Address of the next freeblock */
  56731. u8 hdr; /* Page header size. 0 or 100 */
  56732. u8 nFrag = 0; /* Reduction in fragmentation */
  56733. u16 iOrigSize = iSize; /* Original value of iSize */
  56734. u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  56735. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  56736. unsigned char *data = pPage->aData; /* Page content */
  56737. assert( pPage->pBt!=0 );
  56738. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56739. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  56740. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  56741. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56742. assert( iSize>=4 ); /* Minimum cell size is 4 */
  56743. assert( iStart<=iLast );
  56744. /* Overwrite deleted information with zeros when the secure_delete
  56745. ** option is enabled */
  56746. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  56747. memset(&data[iStart], 0, iSize);
  56748. }
  56749. /* The list of freeblocks must be in ascending order. Find the
  56750. ** spot on the list where iStart should be inserted.
  56751. */
  56752. hdr = pPage->hdrOffset;
  56753. iPtr = hdr + 1;
  56754. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  56755. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  56756. }else{
  56757. while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
  56758. if( iFreeBlk<iPtr+4 ){
  56759. if( iFreeBlk==0 ) break;
  56760. return SQLITE_CORRUPT_BKPT;
  56761. }
  56762. iPtr = iFreeBlk;
  56763. }
  56764. if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
  56765. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  56766. /* At this point:
  56767. ** iFreeBlk: First freeblock after iStart, or zero if none
  56768. ** iPtr: The address of a pointer to iFreeBlk
  56769. **
  56770. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  56771. */
  56772. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  56773. nFrag = iFreeBlk - iEnd;
  56774. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  56775. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  56776. if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
  56777. iSize = iEnd - iStart;
  56778. iFreeBlk = get2byte(&data[iFreeBlk]);
  56779. }
  56780. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  56781. ** pointer in the page header) then check to see if iStart should be
  56782. ** coalesced onto the end of iPtr.
  56783. */
  56784. if( iPtr>hdr+1 ){
  56785. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  56786. if( iPtrEnd+3>=iStart ){
  56787. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  56788. nFrag += iStart - iPtrEnd;
  56789. iSize = iEnd - iPtr;
  56790. iStart = iPtr;
  56791. }
  56792. }
  56793. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
  56794. data[hdr+7] -= nFrag;
  56795. }
  56796. if( iStart==get2byte(&data[hdr+5]) ){
  56797. /* The new freeblock is at the beginning of the cell content area,
  56798. ** so just extend the cell content area rather than create another
  56799. ** freelist entry */
  56800. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
  56801. put2byte(&data[hdr+1], iFreeBlk);
  56802. put2byte(&data[hdr+5], iEnd);
  56803. }else{
  56804. /* Insert the new freeblock into the freelist */
  56805. put2byte(&data[iPtr], iStart);
  56806. put2byte(&data[iStart], iFreeBlk);
  56807. put2byte(&data[iStart+2], iSize);
  56808. }
  56809. pPage->nFree += iOrigSize;
  56810. return SQLITE_OK;
  56811. }
  56812. /*
  56813. ** Decode the flags byte (the first byte of the header) for a page
  56814. ** and initialize fields of the MemPage structure accordingly.
  56815. **
  56816. ** Only the following combinations are supported. Anything different
  56817. ** indicates a corrupt database files:
  56818. **
  56819. ** PTF_ZERODATA
  56820. ** PTF_ZERODATA | PTF_LEAF
  56821. ** PTF_LEAFDATA | PTF_INTKEY
  56822. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  56823. */
  56824. static int decodeFlags(MemPage *pPage, int flagByte){
  56825. BtShared *pBt; /* A copy of pPage->pBt */
  56826. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  56827. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56828. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  56829. flagByte &= ~PTF_LEAF;
  56830. pPage->childPtrSize = 4-4*pPage->leaf;
  56831. pPage->xCellSize = cellSizePtr;
  56832. pBt = pPage->pBt;
  56833. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  56834. /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
  56835. ** interior table b-tree page. */
  56836. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  56837. /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
  56838. ** leaf table b-tree page. */
  56839. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  56840. pPage->intKey = 1;
  56841. if( pPage->leaf ){
  56842. pPage->intKeyLeaf = 1;
  56843. pPage->xParseCell = btreeParseCellPtr;
  56844. }else{
  56845. pPage->intKeyLeaf = 0;
  56846. pPage->xCellSize = cellSizePtrNoPayload;
  56847. pPage->xParseCell = btreeParseCellPtrNoPayload;
  56848. }
  56849. pPage->maxLocal = pBt->maxLeaf;
  56850. pPage->minLocal = pBt->minLeaf;
  56851. }else if( flagByte==PTF_ZERODATA ){
  56852. /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
  56853. ** interior index b-tree page. */
  56854. assert( (PTF_ZERODATA)==2 );
  56855. /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
  56856. ** leaf index b-tree page. */
  56857. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  56858. pPage->intKey = 0;
  56859. pPage->intKeyLeaf = 0;
  56860. pPage->xParseCell = btreeParseCellPtrIndex;
  56861. pPage->maxLocal = pBt->maxLocal;
  56862. pPage->minLocal = pBt->minLocal;
  56863. }else{
  56864. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  56865. ** an error. */
  56866. return SQLITE_CORRUPT_BKPT;
  56867. }
  56868. pPage->max1bytePayload = pBt->max1bytePayload;
  56869. return SQLITE_OK;
  56870. }
  56871. /*
  56872. ** Initialize the auxiliary information for a disk block.
  56873. **
  56874. ** Return SQLITE_OK on success. If we see that the page does
  56875. ** not contain a well-formed database page, then return
  56876. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  56877. ** guarantee that the page is well-formed. It only shows that
  56878. ** we failed to detect any corruption.
  56879. */
  56880. static int btreeInitPage(MemPage *pPage){
  56881. assert( pPage->pBt!=0 );
  56882. assert( pPage->pBt->db!=0 );
  56883. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56884. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  56885. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  56886. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  56887. if( !pPage->isInit ){
  56888. int pc; /* Address of a freeblock within pPage->aData[] */
  56889. u8 hdr; /* Offset to beginning of page header */
  56890. u8 *data; /* Equal to pPage->aData */
  56891. BtShared *pBt; /* The main btree structure */
  56892. int usableSize; /* Amount of usable space on each page */
  56893. u16 cellOffset; /* Offset from start of page to first cell pointer */
  56894. int nFree; /* Number of unused bytes on the page */
  56895. int top; /* First byte of the cell content area */
  56896. int iCellFirst; /* First allowable cell or freeblock offset */
  56897. int iCellLast; /* Last possible cell or freeblock offset */
  56898. pBt = pPage->pBt;
  56899. hdr = pPage->hdrOffset;
  56900. data = pPage->aData;
  56901. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  56902. ** the b-tree page type. */
  56903. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  56904. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  56905. pPage->maskPage = (u16)(pBt->pageSize - 1);
  56906. pPage->nOverflow = 0;
  56907. usableSize = pBt->usableSize;
  56908. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  56909. pPage->aDataEnd = &data[usableSize];
  56910. pPage->aCellIdx = &data[cellOffset];
  56911. pPage->aDataOfst = &data[pPage->childPtrSize];
  56912. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  56913. ** the start of the cell content area. A zero value for this integer is
  56914. ** interpreted as 65536. */
  56915. top = get2byteNotZero(&data[hdr+5]);
  56916. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  56917. ** number of cells on the page. */
  56918. pPage->nCell = get2byte(&data[hdr+3]);
  56919. if( pPage->nCell>MX_CELL(pBt) ){
  56920. /* To many cells for a single page. The page must be corrupt */
  56921. return SQLITE_CORRUPT_BKPT;
  56922. }
  56923. testcase( pPage->nCell==MX_CELL(pBt) );
  56924. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  56925. ** possible for a root page of a table that contains no rows) then the
  56926. ** offset to the cell content area will equal the page size minus the
  56927. ** bytes of reserved space. */
  56928. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  56929. /* A malformed database page might cause us to read past the end
  56930. ** of page when parsing a cell.
  56931. **
  56932. ** The following block of code checks early to see if a cell extends
  56933. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  56934. ** returned if it does.
  56935. */
  56936. iCellFirst = cellOffset + 2*pPage->nCell;
  56937. iCellLast = usableSize - 4;
  56938. if( pBt->db->flags & SQLITE_CellSizeCk ){
  56939. int i; /* Index into the cell pointer array */
  56940. int sz; /* Size of a cell */
  56941. if( !pPage->leaf ) iCellLast--;
  56942. for(i=0; i<pPage->nCell; i++){
  56943. pc = get2byteAligned(&data[cellOffset+i*2]);
  56944. testcase( pc==iCellFirst );
  56945. testcase( pc==iCellLast );
  56946. if( pc<iCellFirst || pc>iCellLast ){
  56947. return SQLITE_CORRUPT_BKPT;
  56948. }
  56949. sz = pPage->xCellSize(pPage, &data[pc]);
  56950. testcase( pc+sz==usableSize );
  56951. if( pc+sz>usableSize ){
  56952. return SQLITE_CORRUPT_BKPT;
  56953. }
  56954. }
  56955. if( !pPage->leaf ) iCellLast++;
  56956. }
  56957. /* Compute the total free space on the page
  56958. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  56959. ** start of the first freeblock on the page, or is zero if there are no
  56960. ** freeblocks. */
  56961. pc = get2byte(&data[hdr+1]);
  56962. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  56963. if( pc>0 ){
  56964. u32 next, size;
  56965. if( pc<iCellFirst ){
  56966. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  56967. ** always be at least one cell before the first freeblock.
  56968. */
  56969. return SQLITE_CORRUPT_BKPT;
  56970. }
  56971. while( 1 ){
  56972. if( pc>iCellLast ){
  56973. return SQLITE_CORRUPT_BKPT; /* Freeblock off the end of the page */
  56974. }
  56975. next = get2byte(&data[pc]);
  56976. size = get2byte(&data[pc+2]);
  56977. nFree = nFree + size;
  56978. if( next<=pc+size+3 ) break;
  56979. pc = next;
  56980. }
  56981. if( next>0 ){
  56982. return SQLITE_CORRUPT_BKPT; /* Freeblock not in ascending order */
  56983. }
  56984. if( pc+size>(unsigned int)usableSize ){
  56985. return SQLITE_CORRUPT_BKPT; /* Last freeblock extends past page end */
  56986. }
  56987. }
  56988. /* At this point, nFree contains the sum of the offset to the start
  56989. ** of the cell-content area plus the number of free bytes within
  56990. ** the cell-content area. If this is greater than the usable-size
  56991. ** of the page, then the page must be corrupted. This check also
  56992. ** serves to verify that the offset to the start of the cell-content
  56993. ** area, according to the page header, lies within the page.
  56994. */
  56995. if( nFree>usableSize ){
  56996. return SQLITE_CORRUPT_BKPT;
  56997. }
  56998. pPage->nFree = (u16)(nFree - iCellFirst);
  56999. pPage->isInit = 1;
  57000. }
  57001. return SQLITE_OK;
  57002. }
  57003. /*
  57004. ** Set up a raw page so that it looks like a database page holding
  57005. ** no entries.
  57006. */
  57007. static void zeroPage(MemPage *pPage, int flags){
  57008. unsigned char *data = pPage->aData;
  57009. BtShared *pBt = pPage->pBt;
  57010. u8 hdr = pPage->hdrOffset;
  57011. u16 first;
  57012. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  57013. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  57014. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  57015. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57016. assert( sqlite3_mutex_held(pBt->mutex) );
  57017. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  57018. memset(&data[hdr], 0, pBt->usableSize - hdr);
  57019. }
  57020. data[hdr] = (char)flags;
  57021. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  57022. memset(&data[hdr+1], 0, 4);
  57023. data[hdr+7] = 0;
  57024. put2byte(&data[hdr+5], pBt->usableSize);
  57025. pPage->nFree = (u16)(pBt->usableSize - first);
  57026. decodeFlags(pPage, flags);
  57027. pPage->cellOffset = first;
  57028. pPage->aDataEnd = &data[pBt->usableSize];
  57029. pPage->aCellIdx = &data[first];
  57030. pPage->aDataOfst = &data[pPage->childPtrSize];
  57031. pPage->nOverflow = 0;
  57032. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  57033. pPage->maskPage = (u16)(pBt->pageSize - 1);
  57034. pPage->nCell = 0;
  57035. pPage->isInit = 1;
  57036. }
  57037. /*
  57038. ** Convert a DbPage obtained from the pager into a MemPage used by
  57039. ** the btree layer.
  57040. */
  57041. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  57042. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  57043. if( pgno!=pPage->pgno ){
  57044. pPage->aData = sqlite3PagerGetData(pDbPage);
  57045. pPage->pDbPage = pDbPage;
  57046. pPage->pBt = pBt;
  57047. pPage->pgno = pgno;
  57048. pPage->hdrOffset = pgno==1 ? 100 : 0;
  57049. }
  57050. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  57051. return pPage;
  57052. }
  57053. /*
  57054. ** Get a page from the pager. Initialize the MemPage.pBt and
  57055. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  57056. **
  57057. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  57058. ** about the content of the page at this time. So do not go to the disk
  57059. ** to fetch the content. Just fill in the content with zeros for now.
  57060. ** If in the future we call sqlite3PagerWrite() on this page, that
  57061. ** means we have started to be concerned about content and the disk
  57062. ** read should occur at that point.
  57063. */
  57064. static int btreeGetPage(
  57065. BtShared *pBt, /* The btree */
  57066. Pgno pgno, /* Number of the page to fetch */
  57067. MemPage **ppPage, /* Return the page in this parameter */
  57068. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  57069. ){
  57070. int rc;
  57071. DbPage *pDbPage;
  57072. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  57073. assert( sqlite3_mutex_held(pBt->mutex) );
  57074. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  57075. if( rc ) return rc;
  57076. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  57077. return SQLITE_OK;
  57078. }
  57079. /*
  57080. ** Retrieve a page from the pager cache. If the requested page is not
  57081. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  57082. ** MemPage.aData elements if needed.
  57083. */
  57084. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  57085. DbPage *pDbPage;
  57086. assert( sqlite3_mutex_held(pBt->mutex) );
  57087. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  57088. if( pDbPage ){
  57089. return btreePageFromDbPage(pDbPage, pgno, pBt);
  57090. }
  57091. return 0;
  57092. }
  57093. /*
  57094. ** Return the size of the database file in pages. If there is any kind of
  57095. ** error, return ((unsigned int)-1).
  57096. */
  57097. static Pgno btreePagecount(BtShared *pBt){
  57098. return pBt->nPage;
  57099. }
  57100. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  57101. assert( sqlite3BtreeHoldsMutex(p) );
  57102. assert( ((p->pBt->nPage)&0x8000000)==0 );
  57103. return btreePagecount(p->pBt);
  57104. }
  57105. /*
  57106. ** Get a page from the pager and initialize it.
  57107. **
  57108. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  57109. ** call. Do additional sanity checking on the page in this case.
  57110. ** And if the fetch fails, this routine must decrement pCur->iPage.
  57111. **
  57112. ** The page is fetched as read-write unless pCur is not NULL and is
  57113. ** a read-only cursor.
  57114. **
  57115. ** If an error occurs, then *ppPage is undefined. It
  57116. ** may remain unchanged, or it may be set to an invalid value.
  57117. */
  57118. static int getAndInitPage(
  57119. BtShared *pBt, /* The database file */
  57120. Pgno pgno, /* Number of the page to get */
  57121. MemPage **ppPage, /* Write the page pointer here */
  57122. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  57123. int bReadOnly /* True for a read-only page */
  57124. ){
  57125. int rc;
  57126. DbPage *pDbPage;
  57127. assert( sqlite3_mutex_held(pBt->mutex) );
  57128. assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
  57129. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  57130. assert( pCur==0 || pCur->iPage>0 );
  57131. if( pgno>btreePagecount(pBt) ){
  57132. rc = SQLITE_CORRUPT_BKPT;
  57133. goto getAndInitPage_error;
  57134. }
  57135. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  57136. if( rc ){
  57137. goto getAndInitPage_error;
  57138. }
  57139. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  57140. if( (*ppPage)->isInit==0 ){
  57141. btreePageFromDbPage(pDbPage, pgno, pBt);
  57142. rc = btreeInitPage(*ppPage);
  57143. if( rc!=SQLITE_OK ){
  57144. releasePage(*ppPage);
  57145. goto getAndInitPage_error;
  57146. }
  57147. }
  57148. assert( (*ppPage)->pgno==pgno );
  57149. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  57150. /* If obtaining a child page for a cursor, we must verify that the page is
  57151. ** compatible with the root page. */
  57152. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  57153. rc = SQLITE_CORRUPT_BKPT;
  57154. releasePage(*ppPage);
  57155. goto getAndInitPage_error;
  57156. }
  57157. return SQLITE_OK;
  57158. getAndInitPage_error:
  57159. if( pCur ) pCur->iPage--;
  57160. testcase( pgno==0 );
  57161. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  57162. return rc;
  57163. }
  57164. /*
  57165. ** Release a MemPage. This should be called once for each prior
  57166. ** call to btreeGetPage.
  57167. */
  57168. static void releasePageNotNull(MemPage *pPage){
  57169. assert( pPage->aData );
  57170. assert( pPage->pBt );
  57171. assert( pPage->pDbPage!=0 );
  57172. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  57173. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  57174. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57175. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  57176. }
  57177. static void releasePage(MemPage *pPage){
  57178. if( pPage ) releasePageNotNull(pPage);
  57179. }
  57180. /*
  57181. ** Get an unused page.
  57182. **
  57183. ** This works just like btreeGetPage() with the addition:
  57184. **
  57185. ** * If the page is already in use for some other purpose, immediately
  57186. ** release it and return an SQLITE_CURRUPT error.
  57187. ** * Make sure the isInit flag is clear
  57188. */
  57189. static int btreeGetUnusedPage(
  57190. BtShared *pBt, /* The btree */
  57191. Pgno pgno, /* Number of the page to fetch */
  57192. MemPage **ppPage, /* Return the page in this parameter */
  57193. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  57194. ){
  57195. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  57196. if( rc==SQLITE_OK ){
  57197. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  57198. releasePage(*ppPage);
  57199. *ppPage = 0;
  57200. return SQLITE_CORRUPT_BKPT;
  57201. }
  57202. (*ppPage)->isInit = 0;
  57203. }else{
  57204. *ppPage = 0;
  57205. }
  57206. return rc;
  57207. }
  57208. /*
  57209. ** During a rollback, when the pager reloads information into the cache
  57210. ** so that the cache is restored to its original state at the start of
  57211. ** the transaction, for each page restored this routine is called.
  57212. **
  57213. ** This routine needs to reset the extra data section at the end of the
  57214. ** page to agree with the restored data.
  57215. */
  57216. static void pageReinit(DbPage *pData){
  57217. MemPage *pPage;
  57218. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  57219. assert( sqlite3PagerPageRefcount(pData)>0 );
  57220. if( pPage->isInit ){
  57221. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57222. pPage->isInit = 0;
  57223. if( sqlite3PagerPageRefcount(pData)>1 ){
  57224. /* pPage might not be a btree page; it might be an overflow page
  57225. ** or ptrmap page or a free page. In those cases, the following
  57226. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  57227. ** But no harm is done by this. And it is very important that
  57228. ** btreeInitPage() be called on every btree page so we make
  57229. ** the call for every page that comes in for re-initing. */
  57230. btreeInitPage(pPage);
  57231. }
  57232. }
  57233. }
  57234. /*
  57235. ** Invoke the busy handler for a btree.
  57236. */
  57237. static int btreeInvokeBusyHandler(void *pArg){
  57238. BtShared *pBt = (BtShared*)pArg;
  57239. assert( pBt->db );
  57240. assert( sqlite3_mutex_held(pBt->db->mutex) );
  57241. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  57242. }
  57243. /*
  57244. ** Open a database file.
  57245. **
  57246. ** zFilename is the name of the database file. If zFilename is NULL
  57247. ** then an ephemeral database is created. The ephemeral database might
  57248. ** be exclusively in memory, or it might use a disk-based memory cache.
  57249. ** Either way, the ephemeral database will be automatically deleted
  57250. ** when sqlite3BtreeClose() is called.
  57251. **
  57252. ** If zFilename is ":memory:" then an in-memory database is created
  57253. ** that is automatically destroyed when it is closed.
  57254. **
  57255. ** The "flags" parameter is a bitmask that might contain bits like
  57256. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  57257. **
  57258. ** If the database is already opened in the same database connection
  57259. ** and we are in shared cache mode, then the open will fail with an
  57260. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  57261. ** objects in the same database connection since doing so will lead
  57262. ** to problems with locking.
  57263. */
  57264. SQLITE_PRIVATE int sqlite3BtreeOpen(
  57265. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  57266. const char *zFilename, /* Name of the file containing the BTree database */
  57267. sqlite3 *db, /* Associated database handle */
  57268. Btree **ppBtree, /* Pointer to new Btree object written here */
  57269. int flags, /* Options */
  57270. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  57271. ){
  57272. BtShared *pBt = 0; /* Shared part of btree structure */
  57273. Btree *p; /* Handle to return */
  57274. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  57275. int rc = SQLITE_OK; /* Result code from this function */
  57276. u8 nReserve; /* Byte of unused space on each page */
  57277. unsigned char zDbHeader[100]; /* Database header content */
  57278. /* True if opening an ephemeral, temporary database */
  57279. const int isTempDb = zFilename==0 || zFilename[0]==0;
  57280. /* Set the variable isMemdb to true for an in-memory database, or
  57281. ** false for a file-based database.
  57282. */
  57283. #ifdef SQLITE_OMIT_MEMORYDB
  57284. const int isMemdb = 0;
  57285. #else
  57286. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  57287. || (isTempDb && sqlite3TempInMemory(db))
  57288. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  57289. #endif
  57290. assert( db!=0 );
  57291. assert( pVfs!=0 );
  57292. assert( sqlite3_mutex_held(db->mutex) );
  57293. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  57294. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  57295. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  57296. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  57297. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  57298. if( isMemdb ){
  57299. flags |= BTREE_MEMORY;
  57300. }
  57301. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  57302. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  57303. }
  57304. p = sqlite3MallocZero(sizeof(Btree));
  57305. if( !p ){
  57306. return SQLITE_NOMEM_BKPT;
  57307. }
  57308. p->inTrans = TRANS_NONE;
  57309. p->db = db;
  57310. #ifndef SQLITE_OMIT_SHARED_CACHE
  57311. p->lock.pBtree = p;
  57312. p->lock.iTable = 1;
  57313. #endif
  57314. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  57315. /*
  57316. ** If this Btree is a candidate for shared cache, try to find an
  57317. ** existing BtShared object that we can share with
  57318. */
  57319. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  57320. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  57321. int nFilename = sqlite3Strlen30(zFilename)+1;
  57322. int nFullPathname = pVfs->mxPathname+1;
  57323. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  57324. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  57325. p->sharable = 1;
  57326. if( !zFullPathname ){
  57327. sqlite3_free(p);
  57328. return SQLITE_NOMEM_BKPT;
  57329. }
  57330. if( isMemdb ){
  57331. memcpy(zFullPathname, zFilename, nFilename);
  57332. }else{
  57333. rc = sqlite3OsFullPathname(pVfs, zFilename,
  57334. nFullPathname, zFullPathname);
  57335. if( rc ){
  57336. sqlite3_free(zFullPathname);
  57337. sqlite3_free(p);
  57338. return rc;
  57339. }
  57340. }
  57341. #if SQLITE_THREADSAFE
  57342. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  57343. sqlite3_mutex_enter(mutexOpen);
  57344. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  57345. sqlite3_mutex_enter(mutexShared);
  57346. #endif
  57347. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  57348. assert( pBt->nRef>0 );
  57349. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  57350. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  57351. int iDb;
  57352. for(iDb=db->nDb-1; iDb>=0; iDb--){
  57353. Btree *pExisting = db->aDb[iDb].pBt;
  57354. if( pExisting && pExisting->pBt==pBt ){
  57355. sqlite3_mutex_leave(mutexShared);
  57356. sqlite3_mutex_leave(mutexOpen);
  57357. sqlite3_free(zFullPathname);
  57358. sqlite3_free(p);
  57359. return SQLITE_CONSTRAINT;
  57360. }
  57361. }
  57362. p->pBt = pBt;
  57363. pBt->nRef++;
  57364. break;
  57365. }
  57366. }
  57367. sqlite3_mutex_leave(mutexShared);
  57368. sqlite3_free(zFullPathname);
  57369. }
  57370. #ifdef SQLITE_DEBUG
  57371. else{
  57372. /* In debug mode, we mark all persistent databases as sharable
  57373. ** even when they are not. This exercises the locking code and
  57374. ** gives more opportunity for asserts(sqlite3_mutex_held())
  57375. ** statements to find locking problems.
  57376. */
  57377. p->sharable = 1;
  57378. }
  57379. #endif
  57380. }
  57381. #endif
  57382. if( pBt==0 ){
  57383. /*
  57384. ** The following asserts make sure that structures used by the btree are
  57385. ** the right size. This is to guard against size changes that result
  57386. ** when compiling on a different architecture.
  57387. */
  57388. assert( sizeof(i64)==8 );
  57389. assert( sizeof(u64)==8 );
  57390. assert( sizeof(u32)==4 );
  57391. assert( sizeof(u16)==2 );
  57392. assert( sizeof(Pgno)==4 );
  57393. pBt = sqlite3MallocZero( sizeof(*pBt) );
  57394. if( pBt==0 ){
  57395. rc = SQLITE_NOMEM_BKPT;
  57396. goto btree_open_out;
  57397. }
  57398. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  57399. sizeof(MemPage), flags, vfsFlags, pageReinit);
  57400. if( rc==SQLITE_OK ){
  57401. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  57402. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  57403. }
  57404. if( rc!=SQLITE_OK ){
  57405. goto btree_open_out;
  57406. }
  57407. pBt->openFlags = (u8)flags;
  57408. pBt->db = db;
  57409. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  57410. p->pBt = pBt;
  57411. pBt->pCursor = 0;
  57412. pBt->pPage1 = 0;
  57413. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  57414. #ifdef SQLITE_SECURE_DELETE
  57415. pBt->btsFlags |= BTS_SECURE_DELETE;
  57416. #endif
  57417. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  57418. ** determined by the 2-byte integer located at an offset of 16 bytes from
  57419. ** the beginning of the database file. */
  57420. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  57421. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  57422. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  57423. pBt->pageSize = 0;
  57424. #ifndef SQLITE_OMIT_AUTOVACUUM
  57425. /* If the magic name ":memory:" will create an in-memory database, then
  57426. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  57427. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  57428. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  57429. ** regular file-name. In this case the auto-vacuum applies as per normal.
  57430. */
  57431. if( zFilename && !isMemdb ){
  57432. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  57433. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  57434. }
  57435. #endif
  57436. nReserve = 0;
  57437. }else{
  57438. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  57439. ** determined by the one-byte unsigned integer found at an offset of 20
  57440. ** into the database file header. */
  57441. nReserve = zDbHeader[20];
  57442. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  57443. #ifndef SQLITE_OMIT_AUTOVACUUM
  57444. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  57445. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  57446. #endif
  57447. }
  57448. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  57449. if( rc ) goto btree_open_out;
  57450. pBt->usableSize = pBt->pageSize - nReserve;
  57451. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  57452. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  57453. /* Add the new BtShared object to the linked list sharable BtShareds.
  57454. */
  57455. pBt->nRef = 1;
  57456. if( p->sharable ){
  57457. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  57458. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  57459. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  57460. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  57461. if( pBt->mutex==0 ){
  57462. rc = SQLITE_NOMEM_BKPT;
  57463. goto btree_open_out;
  57464. }
  57465. }
  57466. sqlite3_mutex_enter(mutexShared);
  57467. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  57468. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  57469. sqlite3_mutex_leave(mutexShared);
  57470. }
  57471. #endif
  57472. }
  57473. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  57474. /* If the new Btree uses a sharable pBtShared, then link the new
  57475. ** Btree into the list of all sharable Btrees for the same connection.
  57476. ** The list is kept in ascending order by pBt address.
  57477. */
  57478. if( p->sharable ){
  57479. int i;
  57480. Btree *pSib;
  57481. for(i=0; i<db->nDb; i++){
  57482. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  57483. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  57484. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  57485. p->pNext = pSib;
  57486. p->pPrev = 0;
  57487. pSib->pPrev = p;
  57488. }else{
  57489. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  57490. pSib = pSib->pNext;
  57491. }
  57492. p->pNext = pSib->pNext;
  57493. p->pPrev = pSib;
  57494. if( p->pNext ){
  57495. p->pNext->pPrev = p;
  57496. }
  57497. pSib->pNext = p;
  57498. }
  57499. break;
  57500. }
  57501. }
  57502. }
  57503. #endif
  57504. *ppBtree = p;
  57505. btree_open_out:
  57506. if( rc!=SQLITE_OK ){
  57507. if( pBt && pBt->pPager ){
  57508. sqlite3PagerClose(pBt->pPager, 0);
  57509. }
  57510. sqlite3_free(pBt);
  57511. sqlite3_free(p);
  57512. *ppBtree = 0;
  57513. }else{
  57514. sqlite3_file *pFile;
  57515. /* If the B-Tree was successfully opened, set the pager-cache size to the
  57516. ** default value. Except, when opening on an existing shared pager-cache,
  57517. ** do not change the pager-cache size.
  57518. */
  57519. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  57520. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  57521. }
  57522. pFile = sqlite3PagerFile(pBt->pPager);
  57523. if( pFile->pMethods ){
  57524. sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
  57525. }
  57526. }
  57527. if( mutexOpen ){
  57528. assert( sqlite3_mutex_held(mutexOpen) );
  57529. sqlite3_mutex_leave(mutexOpen);
  57530. }
  57531. assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
  57532. return rc;
  57533. }
  57534. /*
  57535. ** Decrement the BtShared.nRef counter. When it reaches zero,
  57536. ** remove the BtShared structure from the sharing list. Return
  57537. ** true if the BtShared.nRef counter reaches zero and return
  57538. ** false if it is still positive.
  57539. */
  57540. static int removeFromSharingList(BtShared *pBt){
  57541. #ifndef SQLITE_OMIT_SHARED_CACHE
  57542. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  57543. BtShared *pList;
  57544. int removed = 0;
  57545. assert( sqlite3_mutex_notheld(pBt->mutex) );
  57546. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  57547. sqlite3_mutex_enter(pMaster);
  57548. pBt->nRef--;
  57549. if( pBt->nRef<=0 ){
  57550. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  57551. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  57552. }else{
  57553. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  57554. while( ALWAYS(pList) && pList->pNext!=pBt ){
  57555. pList=pList->pNext;
  57556. }
  57557. if( ALWAYS(pList) ){
  57558. pList->pNext = pBt->pNext;
  57559. }
  57560. }
  57561. if( SQLITE_THREADSAFE ){
  57562. sqlite3_mutex_free(pBt->mutex);
  57563. }
  57564. removed = 1;
  57565. }
  57566. sqlite3_mutex_leave(pMaster);
  57567. return removed;
  57568. #else
  57569. return 1;
  57570. #endif
  57571. }
  57572. /*
  57573. ** Make sure pBt->pTmpSpace points to an allocation of
  57574. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  57575. ** pointer.
  57576. */
  57577. static void allocateTempSpace(BtShared *pBt){
  57578. if( !pBt->pTmpSpace ){
  57579. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  57580. /* One of the uses of pBt->pTmpSpace is to format cells before
  57581. ** inserting them into a leaf page (function fillInCell()). If
  57582. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  57583. ** by the various routines that manipulate binary cells. Which
  57584. ** can mean that fillInCell() only initializes the first 2 or 3
  57585. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  57586. ** it into a database page. This is not actually a problem, but it
  57587. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  57588. ** data is passed to system call write(). So to avoid this error,
  57589. ** zero the first 4 bytes of temp space here.
  57590. **
  57591. ** Also: Provide four bytes of initialized space before the
  57592. ** beginning of pTmpSpace as an area available to prepend the
  57593. ** left-child pointer to the beginning of a cell.
  57594. */
  57595. if( pBt->pTmpSpace ){
  57596. memset(pBt->pTmpSpace, 0, 8);
  57597. pBt->pTmpSpace += 4;
  57598. }
  57599. }
  57600. }
  57601. /*
  57602. ** Free the pBt->pTmpSpace allocation
  57603. */
  57604. static void freeTempSpace(BtShared *pBt){
  57605. if( pBt->pTmpSpace ){
  57606. pBt->pTmpSpace -= 4;
  57607. sqlite3PageFree(pBt->pTmpSpace);
  57608. pBt->pTmpSpace = 0;
  57609. }
  57610. }
  57611. /*
  57612. ** Close an open database and invalidate all cursors.
  57613. */
  57614. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  57615. BtShared *pBt = p->pBt;
  57616. BtCursor *pCur;
  57617. /* Close all cursors opened via this handle. */
  57618. assert( sqlite3_mutex_held(p->db->mutex) );
  57619. sqlite3BtreeEnter(p);
  57620. pCur = pBt->pCursor;
  57621. while( pCur ){
  57622. BtCursor *pTmp = pCur;
  57623. pCur = pCur->pNext;
  57624. if( pTmp->pBtree==p ){
  57625. sqlite3BtreeCloseCursor(pTmp);
  57626. }
  57627. }
  57628. /* Rollback any active transaction and free the handle structure.
  57629. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  57630. ** this handle.
  57631. */
  57632. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  57633. sqlite3BtreeLeave(p);
  57634. /* If there are still other outstanding references to the shared-btree
  57635. ** structure, return now. The remainder of this procedure cleans
  57636. ** up the shared-btree.
  57637. */
  57638. assert( p->wantToLock==0 && p->locked==0 );
  57639. if( !p->sharable || removeFromSharingList(pBt) ){
  57640. /* The pBt is no longer on the sharing list, so we can access
  57641. ** it without having to hold the mutex.
  57642. **
  57643. ** Clean out and delete the BtShared object.
  57644. */
  57645. assert( !pBt->pCursor );
  57646. sqlite3PagerClose(pBt->pPager, p->db);
  57647. if( pBt->xFreeSchema && pBt->pSchema ){
  57648. pBt->xFreeSchema(pBt->pSchema);
  57649. }
  57650. sqlite3DbFree(0, pBt->pSchema);
  57651. freeTempSpace(pBt);
  57652. sqlite3_free(pBt);
  57653. }
  57654. #ifndef SQLITE_OMIT_SHARED_CACHE
  57655. assert( p->wantToLock==0 );
  57656. assert( p->locked==0 );
  57657. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  57658. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  57659. #endif
  57660. sqlite3_free(p);
  57661. return SQLITE_OK;
  57662. }
  57663. /*
  57664. ** Change the "soft" limit on the number of pages in the cache.
  57665. ** Unused and unmodified pages will be recycled when the number of
  57666. ** pages in the cache exceeds this soft limit. But the size of the
  57667. ** cache is allowed to grow larger than this limit if it contains
  57668. ** dirty pages or pages still in active use.
  57669. */
  57670. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  57671. BtShared *pBt = p->pBt;
  57672. assert( sqlite3_mutex_held(p->db->mutex) );
  57673. sqlite3BtreeEnter(p);
  57674. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  57675. sqlite3BtreeLeave(p);
  57676. return SQLITE_OK;
  57677. }
  57678. /*
  57679. ** Change the "spill" limit on the number of pages in the cache.
  57680. ** If the number of pages exceeds this limit during a write transaction,
  57681. ** the pager might attempt to "spill" pages to the journal early in
  57682. ** order to free up memory.
  57683. **
  57684. ** The value returned is the current spill size. If zero is passed
  57685. ** as an argument, no changes are made to the spill size setting, so
  57686. ** using mxPage of 0 is a way to query the current spill size.
  57687. */
  57688. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  57689. BtShared *pBt = p->pBt;
  57690. int res;
  57691. assert( sqlite3_mutex_held(p->db->mutex) );
  57692. sqlite3BtreeEnter(p);
  57693. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  57694. sqlite3BtreeLeave(p);
  57695. return res;
  57696. }
  57697. #if SQLITE_MAX_MMAP_SIZE>0
  57698. /*
  57699. ** Change the limit on the amount of the database file that may be
  57700. ** memory mapped.
  57701. */
  57702. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  57703. BtShared *pBt = p->pBt;
  57704. assert( sqlite3_mutex_held(p->db->mutex) );
  57705. sqlite3BtreeEnter(p);
  57706. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  57707. sqlite3BtreeLeave(p);
  57708. return SQLITE_OK;
  57709. }
  57710. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  57711. /*
  57712. ** Change the way data is synced to disk in order to increase or decrease
  57713. ** how well the database resists damage due to OS crashes and power
  57714. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  57715. ** there is a high probability of damage) Level 2 is the default. There
  57716. ** is a very low but non-zero probability of damage. Level 3 reduces the
  57717. ** probability of damage to near zero but with a write performance reduction.
  57718. */
  57719. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  57720. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  57721. Btree *p, /* The btree to set the safety level on */
  57722. unsigned pgFlags /* Various PAGER_* flags */
  57723. ){
  57724. BtShared *pBt = p->pBt;
  57725. assert( sqlite3_mutex_held(p->db->mutex) );
  57726. sqlite3BtreeEnter(p);
  57727. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  57728. sqlite3BtreeLeave(p);
  57729. return SQLITE_OK;
  57730. }
  57731. #endif
  57732. /*
  57733. ** Change the default pages size and the number of reserved bytes per page.
  57734. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  57735. ** without changing anything.
  57736. **
  57737. ** The page size must be a power of 2 between 512 and 65536. If the page
  57738. ** size supplied does not meet this constraint then the page size is not
  57739. ** changed.
  57740. **
  57741. ** Page sizes are constrained to be a power of two so that the region
  57742. ** of the database file used for locking (beginning at PENDING_BYTE,
  57743. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  57744. ** at the beginning of a page.
  57745. **
  57746. ** If parameter nReserve is less than zero, then the number of reserved
  57747. ** bytes per page is left unchanged.
  57748. **
  57749. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  57750. ** and autovacuum mode can no longer be changed.
  57751. */
  57752. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  57753. int rc = SQLITE_OK;
  57754. BtShared *pBt = p->pBt;
  57755. assert( nReserve>=-1 && nReserve<=255 );
  57756. sqlite3BtreeEnter(p);
  57757. #if SQLITE_HAS_CODEC
  57758. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  57759. #endif
  57760. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  57761. sqlite3BtreeLeave(p);
  57762. return SQLITE_READONLY;
  57763. }
  57764. if( nReserve<0 ){
  57765. nReserve = pBt->pageSize - pBt->usableSize;
  57766. }
  57767. assert( nReserve>=0 && nReserve<=255 );
  57768. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  57769. ((pageSize-1)&pageSize)==0 ){
  57770. assert( (pageSize & 7)==0 );
  57771. assert( !pBt->pCursor );
  57772. pBt->pageSize = (u32)pageSize;
  57773. freeTempSpace(pBt);
  57774. }
  57775. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  57776. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  57777. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  57778. sqlite3BtreeLeave(p);
  57779. return rc;
  57780. }
  57781. /*
  57782. ** Return the currently defined page size
  57783. */
  57784. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  57785. return p->pBt->pageSize;
  57786. }
  57787. /*
  57788. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  57789. ** may only be called if it is guaranteed that the b-tree mutex is already
  57790. ** held.
  57791. **
  57792. ** This is useful in one special case in the backup API code where it is
  57793. ** known that the shared b-tree mutex is held, but the mutex on the
  57794. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  57795. ** were to be called, it might collide with some other operation on the
  57796. ** database handle that owns *p, causing undefined behavior.
  57797. */
  57798. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  57799. int n;
  57800. assert( sqlite3_mutex_held(p->pBt->mutex) );
  57801. n = p->pBt->pageSize - p->pBt->usableSize;
  57802. return n;
  57803. }
  57804. /*
  57805. ** Return the number of bytes of space at the end of every page that
  57806. ** are intentually left unused. This is the "reserved" space that is
  57807. ** sometimes used by extensions.
  57808. **
  57809. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  57810. ** greater of the current reserved space and the maximum requested
  57811. ** reserve space.
  57812. */
  57813. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  57814. int n;
  57815. sqlite3BtreeEnter(p);
  57816. n = sqlite3BtreeGetReserveNoMutex(p);
  57817. #ifdef SQLITE_HAS_CODEC
  57818. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  57819. #endif
  57820. sqlite3BtreeLeave(p);
  57821. return n;
  57822. }
  57823. /*
  57824. ** Set the maximum page count for a database if mxPage is positive.
  57825. ** No changes are made if mxPage is 0 or negative.
  57826. ** Regardless of the value of mxPage, return the maximum page count.
  57827. */
  57828. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  57829. int n;
  57830. sqlite3BtreeEnter(p);
  57831. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  57832. sqlite3BtreeLeave(p);
  57833. return n;
  57834. }
  57835. /*
  57836. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  57837. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  57838. ** setting after the change.
  57839. */
  57840. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  57841. int b;
  57842. if( p==0 ) return 0;
  57843. sqlite3BtreeEnter(p);
  57844. if( newFlag>=0 ){
  57845. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  57846. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  57847. }
  57848. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  57849. sqlite3BtreeLeave(p);
  57850. return b;
  57851. }
  57852. /*
  57853. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  57854. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  57855. ** is disabled. The default value for the auto-vacuum property is
  57856. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  57857. */
  57858. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  57859. #ifdef SQLITE_OMIT_AUTOVACUUM
  57860. return SQLITE_READONLY;
  57861. #else
  57862. BtShared *pBt = p->pBt;
  57863. int rc = SQLITE_OK;
  57864. u8 av = (u8)autoVacuum;
  57865. sqlite3BtreeEnter(p);
  57866. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  57867. rc = SQLITE_READONLY;
  57868. }else{
  57869. pBt->autoVacuum = av ?1:0;
  57870. pBt->incrVacuum = av==2 ?1:0;
  57871. }
  57872. sqlite3BtreeLeave(p);
  57873. return rc;
  57874. #endif
  57875. }
  57876. /*
  57877. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  57878. ** enabled 1 is returned. Otherwise 0.
  57879. */
  57880. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  57881. #ifdef SQLITE_OMIT_AUTOVACUUM
  57882. return BTREE_AUTOVACUUM_NONE;
  57883. #else
  57884. int rc;
  57885. sqlite3BtreeEnter(p);
  57886. rc = (
  57887. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  57888. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  57889. BTREE_AUTOVACUUM_INCR
  57890. );
  57891. sqlite3BtreeLeave(p);
  57892. return rc;
  57893. #endif
  57894. }
  57895. /*
  57896. ** If the user has not set the safety-level for this database connection
  57897. ** using "PRAGMA synchronous", and if the safety-level is not already
  57898. ** set to the value passed to this function as the second parameter,
  57899. ** set it so.
  57900. */
  57901. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
  57902. static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
  57903. sqlite3 *db;
  57904. Db *pDb;
  57905. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  57906. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  57907. if( pDb->bSyncSet==0
  57908. && pDb->safety_level!=safety_level
  57909. && pDb!=&db->aDb[1]
  57910. ){
  57911. pDb->safety_level = safety_level;
  57912. sqlite3PagerSetFlags(pBt->pPager,
  57913. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  57914. }
  57915. }
  57916. }
  57917. #else
  57918. # define setDefaultSyncFlag(pBt,safety_level)
  57919. #endif
  57920. /*
  57921. ** Get a reference to pPage1 of the database file. This will
  57922. ** also acquire a readlock on that file.
  57923. **
  57924. ** SQLITE_OK is returned on success. If the file is not a
  57925. ** well-formed database file, then SQLITE_CORRUPT is returned.
  57926. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  57927. ** is returned if we run out of memory.
  57928. */
  57929. static int lockBtree(BtShared *pBt){
  57930. int rc; /* Result code from subfunctions */
  57931. MemPage *pPage1; /* Page 1 of the database file */
  57932. int nPage; /* Number of pages in the database */
  57933. int nPageFile = 0; /* Number of pages in the database file */
  57934. int nPageHeader; /* Number of pages in the database according to hdr */
  57935. assert( sqlite3_mutex_held(pBt->mutex) );
  57936. assert( pBt->pPage1==0 );
  57937. rc = sqlite3PagerSharedLock(pBt->pPager);
  57938. if( rc!=SQLITE_OK ) return rc;
  57939. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  57940. if( rc!=SQLITE_OK ) return rc;
  57941. /* Do some checking to help insure the file we opened really is
  57942. ** a valid database file.
  57943. */
  57944. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  57945. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  57946. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  57947. nPage = nPageFile;
  57948. }
  57949. if( nPage>0 ){
  57950. u32 pageSize;
  57951. u32 usableSize;
  57952. u8 *page1 = pPage1->aData;
  57953. rc = SQLITE_NOTADB;
  57954. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  57955. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  57956. ** 61 74 20 33 00. */
  57957. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  57958. goto page1_init_failed;
  57959. }
  57960. #ifdef SQLITE_OMIT_WAL
  57961. if( page1[18]>1 ){
  57962. pBt->btsFlags |= BTS_READ_ONLY;
  57963. }
  57964. if( page1[19]>1 ){
  57965. goto page1_init_failed;
  57966. }
  57967. #else
  57968. if( page1[18]>2 ){
  57969. pBt->btsFlags |= BTS_READ_ONLY;
  57970. }
  57971. if( page1[19]>2 ){
  57972. goto page1_init_failed;
  57973. }
  57974. /* If the write version is set to 2, this database should be accessed
  57975. ** in WAL mode. If the log is not already open, open it now. Then
  57976. ** return SQLITE_OK and return without populating BtShared.pPage1.
  57977. ** The caller detects this and calls this function again. This is
  57978. ** required as the version of page 1 currently in the page1 buffer
  57979. ** may not be the latest version - there may be a newer one in the log
  57980. ** file.
  57981. */
  57982. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  57983. int isOpen = 0;
  57984. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  57985. if( rc!=SQLITE_OK ){
  57986. goto page1_init_failed;
  57987. }else{
  57988. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
  57989. if( isOpen==0 ){
  57990. releasePage(pPage1);
  57991. return SQLITE_OK;
  57992. }
  57993. }
  57994. rc = SQLITE_NOTADB;
  57995. }else{
  57996. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
  57997. }
  57998. #endif
  57999. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  58000. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  58001. **
  58002. ** The original design allowed these amounts to vary, but as of
  58003. ** version 3.6.0, we require them to be fixed.
  58004. */
  58005. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  58006. goto page1_init_failed;
  58007. }
  58008. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  58009. ** determined by the 2-byte integer located at an offset of 16 bytes from
  58010. ** the beginning of the database file. */
  58011. pageSize = (page1[16]<<8) | (page1[17]<<16);
  58012. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  58013. ** between 512 and 65536 inclusive. */
  58014. if( ((pageSize-1)&pageSize)!=0
  58015. || pageSize>SQLITE_MAX_PAGE_SIZE
  58016. || pageSize<=256
  58017. ){
  58018. goto page1_init_failed;
  58019. }
  58020. assert( (pageSize & 7)==0 );
  58021. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  58022. ** integer at offset 20 is the number of bytes of space at the end of
  58023. ** each page to reserve for extensions.
  58024. **
  58025. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  58026. ** determined by the one-byte unsigned integer found at an offset of 20
  58027. ** into the database file header. */
  58028. usableSize = pageSize - page1[20];
  58029. if( (u32)pageSize!=pBt->pageSize ){
  58030. /* After reading the first page of the database assuming a page size
  58031. ** of BtShared.pageSize, we have discovered that the page-size is
  58032. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  58033. ** zero and return SQLITE_OK. The caller will call this function
  58034. ** again with the correct page-size.
  58035. */
  58036. releasePage(pPage1);
  58037. pBt->usableSize = usableSize;
  58038. pBt->pageSize = pageSize;
  58039. freeTempSpace(pBt);
  58040. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  58041. pageSize-usableSize);
  58042. return rc;
  58043. }
  58044. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  58045. rc = SQLITE_CORRUPT_BKPT;
  58046. goto page1_init_failed;
  58047. }
  58048. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  58049. ** be less than 480. In other words, if the page size is 512, then the
  58050. ** reserved space size cannot exceed 32. */
  58051. if( usableSize<480 ){
  58052. goto page1_init_failed;
  58053. }
  58054. pBt->pageSize = pageSize;
  58055. pBt->usableSize = usableSize;
  58056. #ifndef SQLITE_OMIT_AUTOVACUUM
  58057. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  58058. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  58059. #endif
  58060. }
  58061. /* maxLocal is the maximum amount of payload to store locally for
  58062. ** a cell. Make sure it is small enough so that at least minFanout
  58063. ** cells can will fit on one page. We assume a 10-byte page header.
  58064. ** Besides the payload, the cell must store:
  58065. ** 2-byte pointer to the cell
  58066. ** 4-byte child pointer
  58067. ** 9-byte nKey value
  58068. ** 4-byte nData value
  58069. ** 4-byte overflow page pointer
  58070. ** So a cell consists of a 2-byte pointer, a header which is as much as
  58071. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  58072. ** page pointer.
  58073. */
  58074. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  58075. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  58076. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  58077. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  58078. if( pBt->maxLocal>127 ){
  58079. pBt->max1bytePayload = 127;
  58080. }else{
  58081. pBt->max1bytePayload = (u8)pBt->maxLocal;
  58082. }
  58083. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  58084. pBt->pPage1 = pPage1;
  58085. pBt->nPage = nPage;
  58086. return SQLITE_OK;
  58087. page1_init_failed:
  58088. releasePage(pPage1);
  58089. pBt->pPage1 = 0;
  58090. return rc;
  58091. }
  58092. #ifndef NDEBUG
  58093. /*
  58094. ** Return the number of cursors open on pBt. This is for use
  58095. ** in assert() expressions, so it is only compiled if NDEBUG is not
  58096. ** defined.
  58097. **
  58098. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  58099. ** false then all cursors are counted.
  58100. **
  58101. ** For the purposes of this routine, a cursor is any cursor that
  58102. ** is capable of reading or writing to the database. Cursors that
  58103. ** have been tripped into the CURSOR_FAULT state are not counted.
  58104. */
  58105. static int countValidCursors(BtShared *pBt, int wrOnly){
  58106. BtCursor *pCur;
  58107. int r = 0;
  58108. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  58109. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  58110. && pCur->eState!=CURSOR_FAULT ) r++;
  58111. }
  58112. return r;
  58113. }
  58114. #endif
  58115. /*
  58116. ** If there are no outstanding cursors and we are not in the middle
  58117. ** of a transaction but there is a read lock on the database, then
  58118. ** this routine unrefs the first page of the database file which
  58119. ** has the effect of releasing the read lock.
  58120. **
  58121. ** If there is a transaction in progress, this routine is a no-op.
  58122. */
  58123. static void unlockBtreeIfUnused(BtShared *pBt){
  58124. assert( sqlite3_mutex_held(pBt->mutex) );
  58125. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  58126. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  58127. MemPage *pPage1 = pBt->pPage1;
  58128. assert( pPage1->aData );
  58129. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  58130. pBt->pPage1 = 0;
  58131. releasePageNotNull(pPage1);
  58132. }
  58133. }
  58134. /*
  58135. ** If pBt points to an empty file then convert that empty file
  58136. ** into a new empty database by initializing the first page of
  58137. ** the database.
  58138. */
  58139. static int newDatabase(BtShared *pBt){
  58140. MemPage *pP1;
  58141. unsigned char *data;
  58142. int rc;
  58143. assert( sqlite3_mutex_held(pBt->mutex) );
  58144. if( pBt->nPage>0 ){
  58145. return SQLITE_OK;
  58146. }
  58147. pP1 = pBt->pPage1;
  58148. assert( pP1!=0 );
  58149. data = pP1->aData;
  58150. rc = sqlite3PagerWrite(pP1->pDbPage);
  58151. if( rc ) return rc;
  58152. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  58153. assert( sizeof(zMagicHeader)==16 );
  58154. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  58155. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  58156. data[18] = 1;
  58157. data[19] = 1;
  58158. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  58159. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  58160. data[21] = 64;
  58161. data[22] = 32;
  58162. data[23] = 32;
  58163. memset(&data[24], 0, 100-24);
  58164. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  58165. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  58166. #ifndef SQLITE_OMIT_AUTOVACUUM
  58167. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  58168. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  58169. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  58170. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  58171. #endif
  58172. pBt->nPage = 1;
  58173. data[31] = 1;
  58174. return SQLITE_OK;
  58175. }
  58176. /*
  58177. ** Initialize the first page of the database file (creating a database
  58178. ** consisting of a single page and no schema objects). Return SQLITE_OK
  58179. ** if successful, or an SQLite error code otherwise.
  58180. */
  58181. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  58182. int rc;
  58183. sqlite3BtreeEnter(p);
  58184. p->pBt->nPage = 0;
  58185. rc = newDatabase(p->pBt);
  58186. sqlite3BtreeLeave(p);
  58187. return rc;
  58188. }
  58189. /*
  58190. ** Attempt to start a new transaction. A write-transaction
  58191. ** is started if the second argument is nonzero, otherwise a read-
  58192. ** transaction. If the second argument is 2 or more and exclusive
  58193. ** transaction is started, meaning that no other process is allowed
  58194. ** to access the database. A preexisting transaction may not be
  58195. ** upgraded to exclusive by calling this routine a second time - the
  58196. ** exclusivity flag only works for a new transaction.
  58197. **
  58198. ** A write-transaction must be started before attempting any
  58199. ** changes to the database. None of the following routines
  58200. ** will work unless a transaction is started first:
  58201. **
  58202. ** sqlite3BtreeCreateTable()
  58203. ** sqlite3BtreeCreateIndex()
  58204. ** sqlite3BtreeClearTable()
  58205. ** sqlite3BtreeDropTable()
  58206. ** sqlite3BtreeInsert()
  58207. ** sqlite3BtreeDelete()
  58208. ** sqlite3BtreeUpdateMeta()
  58209. **
  58210. ** If an initial attempt to acquire the lock fails because of lock contention
  58211. ** and the database was previously unlocked, then invoke the busy handler
  58212. ** if there is one. But if there was previously a read-lock, do not
  58213. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  58214. ** returned when there is already a read-lock in order to avoid a deadlock.
  58215. **
  58216. ** Suppose there are two processes A and B. A has a read lock and B has
  58217. ** a reserved lock. B tries to promote to exclusive but is blocked because
  58218. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  58219. ** One or the other of the two processes must give way or there can be
  58220. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  58221. ** when A already has a read lock, we encourage A to give up and let B
  58222. ** proceed.
  58223. */
  58224. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  58225. BtShared *pBt = p->pBt;
  58226. int rc = SQLITE_OK;
  58227. sqlite3BtreeEnter(p);
  58228. btreeIntegrity(p);
  58229. /* If the btree is already in a write-transaction, or it
  58230. ** is already in a read-transaction and a read-transaction
  58231. ** is requested, this is a no-op.
  58232. */
  58233. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  58234. goto trans_begun;
  58235. }
  58236. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  58237. /* Write transactions are not possible on a read-only database */
  58238. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  58239. rc = SQLITE_READONLY;
  58240. goto trans_begun;
  58241. }
  58242. #ifndef SQLITE_OMIT_SHARED_CACHE
  58243. {
  58244. sqlite3 *pBlock = 0;
  58245. /* If another database handle has already opened a write transaction
  58246. ** on this shared-btree structure and a second write transaction is
  58247. ** requested, return SQLITE_LOCKED.
  58248. */
  58249. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  58250. || (pBt->btsFlags & BTS_PENDING)!=0
  58251. ){
  58252. pBlock = pBt->pWriter->db;
  58253. }else if( wrflag>1 ){
  58254. BtLock *pIter;
  58255. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  58256. if( pIter->pBtree!=p ){
  58257. pBlock = pIter->pBtree->db;
  58258. break;
  58259. }
  58260. }
  58261. }
  58262. if( pBlock ){
  58263. sqlite3ConnectionBlocked(p->db, pBlock);
  58264. rc = SQLITE_LOCKED_SHAREDCACHE;
  58265. goto trans_begun;
  58266. }
  58267. }
  58268. #endif
  58269. /* Any read-only or read-write transaction implies a read-lock on
  58270. ** page 1. So if some other shared-cache client already has a write-lock
  58271. ** on page 1, the transaction cannot be opened. */
  58272. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  58273. if( SQLITE_OK!=rc ) goto trans_begun;
  58274. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  58275. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  58276. do {
  58277. /* Call lockBtree() until either pBt->pPage1 is populated or
  58278. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  58279. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  58280. ** reading page 1 it discovers that the page-size of the database
  58281. ** file is not pBt->pageSize. In this case lockBtree() will update
  58282. ** pBt->pageSize to the page-size of the file on disk.
  58283. */
  58284. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  58285. if( rc==SQLITE_OK && wrflag ){
  58286. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  58287. rc = SQLITE_READONLY;
  58288. }else{
  58289. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  58290. if( rc==SQLITE_OK ){
  58291. rc = newDatabase(pBt);
  58292. }
  58293. }
  58294. }
  58295. if( rc!=SQLITE_OK ){
  58296. unlockBtreeIfUnused(pBt);
  58297. }
  58298. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  58299. btreeInvokeBusyHandler(pBt) );
  58300. if( rc==SQLITE_OK ){
  58301. if( p->inTrans==TRANS_NONE ){
  58302. pBt->nTransaction++;
  58303. #ifndef SQLITE_OMIT_SHARED_CACHE
  58304. if( p->sharable ){
  58305. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  58306. p->lock.eLock = READ_LOCK;
  58307. p->lock.pNext = pBt->pLock;
  58308. pBt->pLock = &p->lock;
  58309. }
  58310. #endif
  58311. }
  58312. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  58313. if( p->inTrans>pBt->inTransaction ){
  58314. pBt->inTransaction = p->inTrans;
  58315. }
  58316. if( wrflag ){
  58317. MemPage *pPage1 = pBt->pPage1;
  58318. #ifndef SQLITE_OMIT_SHARED_CACHE
  58319. assert( !pBt->pWriter );
  58320. pBt->pWriter = p;
  58321. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  58322. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  58323. #endif
  58324. /* If the db-size header field is incorrect (as it may be if an old
  58325. ** client has been writing the database file), update it now. Doing
  58326. ** this sooner rather than later means the database size can safely
  58327. ** re-read the database size from page 1 if a savepoint or transaction
  58328. ** rollback occurs within the transaction.
  58329. */
  58330. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  58331. rc = sqlite3PagerWrite(pPage1->pDbPage);
  58332. if( rc==SQLITE_OK ){
  58333. put4byte(&pPage1->aData[28], pBt->nPage);
  58334. }
  58335. }
  58336. }
  58337. }
  58338. trans_begun:
  58339. if( rc==SQLITE_OK && wrflag ){
  58340. /* This call makes sure that the pager has the correct number of
  58341. ** open savepoints. If the second parameter is greater than 0 and
  58342. ** the sub-journal is not already open, then it will be opened here.
  58343. */
  58344. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  58345. }
  58346. btreeIntegrity(p);
  58347. sqlite3BtreeLeave(p);
  58348. return rc;
  58349. }
  58350. #ifndef SQLITE_OMIT_AUTOVACUUM
  58351. /*
  58352. ** Set the pointer-map entries for all children of page pPage. Also, if
  58353. ** pPage contains cells that point to overflow pages, set the pointer
  58354. ** map entries for the overflow pages as well.
  58355. */
  58356. static int setChildPtrmaps(MemPage *pPage){
  58357. int i; /* Counter variable */
  58358. int nCell; /* Number of cells in page pPage */
  58359. int rc; /* Return code */
  58360. BtShared *pBt = pPage->pBt;
  58361. Pgno pgno = pPage->pgno;
  58362. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58363. rc = btreeInitPage(pPage);
  58364. if( rc!=SQLITE_OK ) return rc;
  58365. nCell = pPage->nCell;
  58366. for(i=0; i<nCell; i++){
  58367. u8 *pCell = findCell(pPage, i);
  58368. ptrmapPutOvflPtr(pPage, pCell, &rc);
  58369. if( !pPage->leaf ){
  58370. Pgno childPgno = get4byte(pCell);
  58371. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  58372. }
  58373. }
  58374. if( !pPage->leaf ){
  58375. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  58376. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  58377. }
  58378. return rc;
  58379. }
  58380. /*
  58381. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  58382. ** that it points to iTo. Parameter eType describes the type of pointer to
  58383. ** be modified, as follows:
  58384. **
  58385. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  58386. ** page of pPage.
  58387. **
  58388. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  58389. ** page pointed to by one of the cells on pPage.
  58390. **
  58391. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  58392. ** overflow page in the list.
  58393. */
  58394. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  58395. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58396. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  58397. if( eType==PTRMAP_OVERFLOW2 ){
  58398. /* The pointer is always the first 4 bytes of the page in this case. */
  58399. if( get4byte(pPage->aData)!=iFrom ){
  58400. return SQLITE_CORRUPT_BKPT;
  58401. }
  58402. put4byte(pPage->aData, iTo);
  58403. }else{
  58404. int i;
  58405. int nCell;
  58406. int rc;
  58407. rc = btreeInitPage(pPage);
  58408. if( rc ) return rc;
  58409. nCell = pPage->nCell;
  58410. for(i=0; i<nCell; i++){
  58411. u8 *pCell = findCell(pPage, i);
  58412. if( eType==PTRMAP_OVERFLOW1 ){
  58413. CellInfo info;
  58414. pPage->xParseCell(pPage, pCell, &info);
  58415. if( info.nLocal<info.nPayload ){
  58416. if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
  58417. return SQLITE_CORRUPT_BKPT;
  58418. }
  58419. if( iFrom==get4byte(pCell+info.nSize-4) ){
  58420. put4byte(pCell+info.nSize-4, iTo);
  58421. break;
  58422. }
  58423. }
  58424. }else{
  58425. if( get4byte(pCell)==iFrom ){
  58426. put4byte(pCell, iTo);
  58427. break;
  58428. }
  58429. }
  58430. }
  58431. if( i==nCell ){
  58432. if( eType!=PTRMAP_BTREE ||
  58433. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  58434. return SQLITE_CORRUPT_BKPT;
  58435. }
  58436. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  58437. }
  58438. }
  58439. return SQLITE_OK;
  58440. }
  58441. /*
  58442. ** Move the open database page pDbPage to location iFreePage in the
  58443. ** database. The pDbPage reference remains valid.
  58444. **
  58445. ** The isCommit flag indicates that there is no need to remember that
  58446. ** the journal needs to be sync()ed before database page pDbPage->pgno
  58447. ** can be written to. The caller has already promised not to write to that
  58448. ** page.
  58449. */
  58450. static int relocatePage(
  58451. BtShared *pBt, /* Btree */
  58452. MemPage *pDbPage, /* Open page to move */
  58453. u8 eType, /* Pointer map 'type' entry for pDbPage */
  58454. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  58455. Pgno iFreePage, /* The location to move pDbPage to */
  58456. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  58457. ){
  58458. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  58459. Pgno iDbPage = pDbPage->pgno;
  58460. Pager *pPager = pBt->pPager;
  58461. int rc;
  58462. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  58463. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  58464. assert( sqlite3_mutex_held(pBt->mutex) );
  58465. assert( pDbPage->pBt==pBt );
  58466. /* Move page iDbPage from its current location to page number iFreePage */
  58467. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  58468. iDbPage, iFreePage, iPtrPage, eType));
  58469. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  58470. if( rc!=SQLITE_OK ){
  58471. return rc;
  58472. }
  58473. pDbPage->pgno = iFreePage;
  58474. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  58475. ** that point to overflow pages. The pointer map entries for all these
  58476. ** pages need to be changed.
  58477. **
  58478. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  58479. ** pointer to a subsequent overflow page. If this is the case, then
  58480. ** the pointer map needs to be updated for the subsequent overflow page.
  58481. */
  58482. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  58483. rc = setChildPtrmaps(pDbPage);
  58484. if( rc!=SQLITE_OK ){
  58485. return rc;
  58486. }
  58487. }else{
  58488. Pgno nextOvfl = get4byte(pDbPage->aData);
  58489. if( nextOvfl!=0 ){
  58490. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  58491. if( rc!=SQLITE_OK ){
  58492. return rc;
  58493. }
  58494. }
  58495. }
  58496. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  58497. ** that it points at iFreePage. Also fix the pointer map entry for
  58498. ** iPtrPage.
  58499. */
  58500. if( eType!=PTRMAP_ROOTPAGE ){
  58501. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  58502. if( rc!=SQLITE_OK ){
  58503. return rc;
  58504. }
  58505. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  58506. if( rc!=SQLITE_OK ){
  58507. releasePage(pPtrPage);
  58508. return rc;
  58509. }
  58510. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  58511. releasePage(pPtrPage);
  58512. if( rc==SQLITE_OK ){
  58513. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  58514. }
  58515. }
  58516. return rc;
  58517. }
  58518. /* Forward declaration required by incrVacuumStep(). */
  58519. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  58520. /*
  58521. ** Perform a single step of an incremental-vacuum. If successful, return
  58522. ** SQLITE_OK. If there is no work to do (and therefore no point in
  58523. ** calling this function again), return SQLITE_DONE. Or, if an error
  58524. ** occurs, return some other error code.
  58525. **
  58526. ** More specifically, this function attempts to re-organize the database so
  58527. ** that the last page of the file currently in use is no longer in use.
  58528. **
  58529. ** Parameter nFin is the number of pages that this database would contain
  58530. ** were this function called until it returns SQLITE_DONE.
  58531. **
  58532. ** If the bCommit parameter is non-zero, this function assumes that the
  58533. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  58534. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  58535. ** operation, or false for an incremental vacuum.
  58536. */
  58537. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  58538. Pgno nFreeList; /* Number of pages still on the free-list */
  58539. int rc;
  58540. assert( sqlite3_mutex_held(pBt->mutex) );
  58541. assert( iLastPg>nFin );
  58542. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  58543. u8 eType;
  58544. Pgno iPtrPage;
  58545. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  58546. if( nFreeList==0 ){
  58547. return SQLITE_DONE;
  58548. }
  58549. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  58550. if( rc!=SQLITE_OK ){
  58551. return rc;
  58552. }
  58553. if( eType==PTRMAP_ROOTPAGE ){
  58554. return SQLITE_CORRUPT_BKPT;
  58555. }
  58556. if( eType==PTRMAP_FREEPAGE ){
  58557. if( bCommit==0 ){
  58558. /* Remove the page from the files free-list. This is not required
  58559. ** if bCommit is non-zero. In that case, the free-list will be
  58560. ** truncated to zero after this function returns, so it doesn't
  58561. ** matter if it still contains some garbage entries.
  58562. */
  58563. Pgno iFreePg;
  58564. MemPage *pFreePg;
  58565. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  58566. if( rc!=SQLITE_OK ){
  58567. return rc;
  58568. }
  58569. assert( iFreePg==iLastPg );
  58570. releasePage(pFreePg);
  58571. }
  58572. } else {
  58573. Pgno iFreePg; /* Index of free page to move pLastPg to */
  58574. MemPage *pLastPg;
  58575. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  58576. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  58577. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  58578. if( rc!=SQLITE_OK ){
  58579. return rc;
  58580. }
  58581. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  58582. ** is swapped with the first free page pulled off the free list.
  58583. **
  58584. ** On the other hand, if bCommit is greater than zero, then keep
  58585. ** looping until a free-page located within the first nFin pages
  58586. ** of the file is found.
  58587. */
  58588. if( bCommit==0 ){
  58589. eMode = BTALLOC_LE;
  58590. iNear = nFin;
  58591. }
  58592. do {
  58593. MemPage *pFreePg;
  58594. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  58595. if( rc!=SQLITE_OK ){
  58596. releasePage(pLastPg);
  58597. return rc;
  58598. }
  58599. releasePage(pFreePg);
  58600. }while( bCommit && iFreePg>nFin );
  58601. assert( iFreePg<iLastPg );
  58602. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  58603. releasePage(pLastPg);
  58604. if( rc!=SQLITE_OK ){
  58605. return rc;
  58606. }
  58607. }
  58608. }
  58609. if( bCommit==0 ){
  58610. do {
  58611. iLastPg--;
  58612. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  58613. pBt->bDoTruncate = 1;
  58614. pBt->nPage = iLastPg;
  58615. }
  58616. return SQLITE_OK;
  58617. }
  58618. /*
  58619. ** The database opened by the first argument is an auto-vacuum database
  58620. ** nOrig pages in size containing nFree free pages. Return the expected
  58621. ** size of the database in pages following an auto-vacuum operation.
  58622. */
  58623. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  58624. int nEntry; /* Number of entries on one ptrmap page */
  58625. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  58626. Pgno nFin; /* Return value */
  58627. nEntry = pBt->usableSize/5;
  58628. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  58629. nFin = nOrig - nFree - nPtrmap;
  58630. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  58631. nFin--;
  58632. }
  58633. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  58634. nFin--;
  58635. }
  58636. return nFin;
  58637. }
  58638. /*
  58639. ** A write-transaction must be opened before calling this function.
  58640. ** It performs a single unit of work towards an incremental vacuum.
  58641. **
  58642. ** If the incremental vacuum is finished after this function has run,
  58643. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  58644. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  58645. */
  58646. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  58647. int rc;
  58648. BtShared *pBt = p->pBt;
  58649. sqlite3BtreeEnter(p);
  58650. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  58651. if( !pBt->autoVacuum ){
  58652. rc = SQLITE_DONE;
  58653. }else{
  58654. Pgno nOrig = btreePagecount(pBt);
  58655. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  58656. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  58657. if( nOrig<nFin ){
  58658. rc = SQLITE_CORRUPT_BKPT;
  58659. }else if( nFree>0 ){
  58660. rc = saveAllCursors(pBt, 0, 0);
  58661. if( rc==SQLITE_OK ){
  58662. invalidateAllOverflowCache(pBt);
  58663. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  58664. }
  58665. if( rc==SQLITE_OK ){
  58666. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  58667. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  58668. }
  58669. }else{
  58670. rc = SQLITE_DONE;
  58671. }
  58672. }
  58673. sqlite3BtreeLeave(p);
  58674. return rc;
  58675. }
  58676. /*
  58677. ** This routine is called prior to sqlite3PagerCommit when a transaction
  58678. ** is committed for an auto-vacuum database.
  58679. **
  58680. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  58681. ** the database file should be truncated to during the commit process.
  58682. ** i.e. the database has been reorganized so that only the first *pnTrunc
  58683. ** pages are in use.
  58684. */
  58685. static int autoVacuumCommit(BtShared *pBt){
  58686. int rc = SQLITE_OK;
  58687. Pager *pPager = pBt->pPager;
  58688. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  58689. assert( sqlite3_mutex_held(pBt->mutex) );
  58690. invalidateAllOverflowCache(pBt);
  58691. assert(pBt->autoVacuum);
  58692. if( !pBt->incrVacuum ){
  58693. Pgno nFin; /* Number of pages in database after autovacuuming */
  58694. Pgno nFree; /* Number of pages on the freelist initially */
  58695. Pgno iFree; /* The next page to be freed */
  58696. Pgno nOrig; /* Database size before freeing */
  58697. nOrig = btreePagecount(pBt);
  58698. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  58699. /* It is not possible to create a database for which the final page
  58700. ** is either a pointer-map page or the pending-byte page. If one
  58701. ** is encountered, this indicates corruption.
  58702. */
  58703. return SQLITE_CORRUPT_BKPT;
  58704. }
  58705. nFree = get4byte(&pBt->pPage1->aData[36]);
  58706. nFin = finalDbSize(pBt, nOrig, nFree);
  58707. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  58708. if( nFin<nOrig ){
  58709. rc = saveAllCursors(pBt, 0, 0);
  58710. }
  58711. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  58712. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  58713. }
  58714. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  58715. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  58716. put4byte(&pBt->pPage1->aData[32], 0);
  58717. put4byte(&pBt->pPage1->aData[36], 0);
  58718. put4byte(&pBt->pPage1->aData[28], nFin);
  58719. pBt->bDoTruncate = 1;
  58720. pBt->nPage = nFin;
  58721. }
  58722. if( rc!=SQLITE_OK ){
  58723. sqlite3PagerRollback(pPager);
  58724. }
  58725. }
  58726. assert( nRef>=sqlite3PagerRefcount(pPager) );
  58727. return rc;
  58728. }
  58729. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  58730. # define setChildPtrmaps(x) SQLITE_OK
  58731. #endif
  58732. /*
  58733. ** This routine does the first phase of a two-phase commit. This routine
  58734. ** causes a rollback journal to be created (if it does not already exist)
  58735. ** and populated with enough information so that if a power loss occurs
  58736. ** the database can be restored to its original state by playing back
  58737. ** the journal. Then the contents of the journal are flushed out to
  58738. ** the disk. After the journal is safely on oxide, the changes to the
  58739. ** database are written into the database file and flushed to oxide.
  58740. ** At the end of this call, the rollback journal still exists on the
  58741. ** disk and we are still holding all locks, so the transaction has not
  58742. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  58743. ** commit process.
  58744. **
  58745. ** This call is a no-op if no write-transaction is currently active on pBt.
  58746. **
  58747. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  58748. ** the name of a master journal file that should be written into the
  58749. ** individual journal file, or is NULL, indicating no master journal file
  58750. ** (single database transaction).
  58751. **
  58752. ** When this is called, the master journal should already have been
  58753. ** created, populated with this journal pointer and synced to disk.
  58754. **
  58755. ** Once this is routine has returned, the only thing required to commit
  58756. ** the write-transaction for this database file is to delete the journal.
  58757. */
  58758. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  58759. int rc = SQLITE_OK;
  58760. if( p->inTrans==TRANS_WRITE ){
  58761. BtShared *pBt = p->pBt;
  58762. sqlite3BtreeEnter(p);
  58763. #ifndef SQLITE_OMIT_AUTOVACUUM
  58764. if( pBt->autoVacuum ){
  58765. rc = autoVacuumCommit(pBt);
  58766. if( rc!=SQLITE_OK ){
  58767. sqlite3BtreeLeave(p);
  58768. return rc;
  58769. }
  58770. }
  58771. if( pBt->bDoTruncate ){
  58772. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  58773. }
  58774. #endif
  58775. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  58776. sqlite3BtreeLeave(p);
  58777. }
  58778. return rc;
  58779. }
  58780. /*
  58781. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  58782. ** at the conclusion of a transaction.
  58783. */
  58784. static void btreeEndTransaction(Btree *p){
  58785. BtShared *pBt = p->pBt;
  58786. sqlite3 *db = p->db;
  58787. assert( sqlite3BtreeHoldsMutex(p) );
  58788. #ifndef SQLITE_OMIT_AUTOVACUUM
  58789. pBt->bDoTruncate = 0;
  58790. #endif
  58791. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  58792. /* If there are other active statements that belong to this database
  58793. ** handle, downgrade to a read-only transaction. The other statements
  58794. ** may still be reading from the database. */
  58795. downgradeAllSharedCacheTableLocks(p);
  58796. p->inTrans = TRANS_READ;
  58797. }else{
  58798. /* If the handle had any kind of transaction open, decrement the
  58799. ** transaction count of the shared btree. If the transaction count
  58800. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  58801. ** call below will unlock the pager. */
  58802. if( p->inTrans!=TRANS_NONE ){
  58803. clearAllSharedCacheTableLocks(p);
  58804. pBt->nTransaction--;
  58805. if( 0==pBt->nTransaction ){
  58806. pBt->inTransaction = TRANS_NONE;
  58807. }
  58808. }
  58809. /* Set the current transaction state to TRANS_NONE and unlock the
  58810. ** pager if this call closed the only read or write transaction. */
  58811. p->inTrans = TRANS_NONE;
  58812. unlockBtreeIfUnused(pBt);
  58813. }
  58814. btreeIntegrity(p);
  58815. }
  58816. /*
  58817. ** Commit the transaction currently in progress.
  58818. **
  58819. ** This routine implements the second phase of a 2-phase commit. The
  58820. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  58821. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  58822. ** routine did all the work of writing information out to disk and flushing the
  58823. ** contents so that they are written onto the disk platter. All this
  58824. ** routine has to do is delete or truncate or zero the header in the
  58825. ** the rollback journal (which causes the transaction to commit) and
  58826. ** drop locks.
  58827. **
  58828. ** Normally, if an error occurs while the pager layer is attempting to
  58829. ** finalize the underlying journal file, this function returns an error and
  58830. ** the upper layer will attempt a rollback. However, if the second argument
  58831. ** is non-zero then this b-tree transaction is part of a multi-file
  58832. ** transaction. In this case, the transaction has already been committed
  58833. ** (by deleting a master journal file) and the caller will ignore this
  58834. ** functions return code. So, even if an error occurs in the pager layer,
  58835. ** reset the b-tree objects internal state to indicate that the write
  58836. ** transaction has been closed. This is quite safe, as the pager will have
  58837. ** transitioned to the error state.
  58838. **
  58839. ** This will release the write lock on the database file. If there
  58840. ** are no active cursors, it also releases the read lock.
  58841. */
  58842. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  58843. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  58844. sqlite3BtreeEnter(p);
  58845. btreeIntegrity(p);
  58846. /* If the handle has a write-transaction open, commit the shared-btrees
  58847. ** transaction and set the shared state to TRANS_READ.
  58848. */
  58849. if( p->inTrans==TRANS_WRITE ){
  58850. int rc;
  58851. BtShared *pBt = p->pBt;
  58852. assert( pBt->inTransaction==TRANS_WRITE );
  58853. assert( pBt->nTransaction>0 );
  58854. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  58855. if( rc!=SQLITE_OK && bCleanup==0 ){
  58856. sqlite3BtreeLeave(p);
  58857. return rc;
  58858. }
  58859. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  58860. pBt->inTransaction = TRANS_READ;
  58861. btreeClearHasContent(pBt);
  58862. }
  58863. btreeEndTransaction(p);
  58864. sqlite3BtreeLeave(p);
  58865. return SQLITE_OK;
  58866. }
  58867. /*
  58868. ** Do both phases of a commit.
  58869. */
  58870. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  58871. int rc;
  58872. sqlite3BtreeEnter(p);
  58873. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  58874. if( rc==SQLITE_OK ){
  58875. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  58876. }
  58877. sqlite3BtreeLeave(p);
  58878. return rc;
  58879. }
  58880. /*
  58881. ** This routine sets the state to CURSOR_FAULT and the error
  58882. ** code to errCode for every cursor on any BtShared that pBtree
  58883. ** references. Or if the writeOnly flag is set to 1, then only
  58884. ** trip write cursors and leave read cursors unchanged.
  58885. **
  58886. ** Every cursor is a candidate to be tripped, including cursors
  58887. ** that belong to other database connections that happen to be
  58888. ** sharing the cache with pBtree.
  58889. **
  58890. ** This routine gets called when a rollback occurs. If the writeOnly
  58891. ** flag is true, then only write-cursors need be tripped - read-only
  58892. ** cursors save their current positions so that they may continue
  58893. ** following the rollback. Or, if writeOnly is false, all cursors are
  58894. ** tripped. In general, writeOnly is false if the transaction being
  58895. ** rolled back modified the database schema. In this case b-tree root
  58896. ** pages may be moved or deleted from the database altogether, making
  58897. ** it unsafe for read cursors to continue.
  58898. **
  58899. ** If the writeOnly flag is true and an error is encountered while
  58900. ** saving the current position of a read-only cursor, all cursors,
  58901. ** including all read-cursors are tripped.
  58902. **
  58903. ** SQLITE_OK is returned if successful, or if an error occurs while
  58904. ** saving a cursor position, an SQLite error code.
  58905. */
  58906. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  58907. BtCursor *p;
  58908. int rc = SQLITE_OK;
  58909. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  58910. if( pBtree ){
  58911. sqlite3BtreeEnter(pBtree);
  58912. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  58913. int i;
  58914. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  58915. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  58916. rc = saveCursorPosition(p);
  58917. if( rc!=SQLITE_OK ){
  58918. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  58919. break;
  58920. }
  58921. }
  58922. }else{
  58923. sqlite3BtreeClearCursor(p);
  58924. p->eState = CURSOR_FAULT;
  58925. p->skipNext = errCode;
  58926. }
  58927. for(i=0; i<=p->iPage; i++){
  58928. releasePage(p->apPage[i]);
  58929. p->apPage[i] = 0;
  58930. }
  58931. }
  58932. sqlite3BtreeLeave(pBtree);
  58933. }
  58934. return rc;
  58935. }
  58936. /*
  58937. ** Rollback the transaction in progress.
  58938. **
  58939. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  58940. ** Only write cursors are tripped if writeOnly is true but all cursors are
  58941. ** tripped if writeOnly is false. Any attempt to use
  58942. ** a tripped cursor will result in an error.
  58943. **
  58944. ** This will release the write lock on the database file. If there
  58945. ** are no active cursors, it also releases the read lock.
  58946. */
  58947. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  58948. int rc;
  58949. BtShared *pBt = p->pBt;
  58950. MemPage *pPage1;
  58951. assert( writeOnly==1 || writeOnly==0 );
  58952. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  58953. sqlite3BtreeEnter(p);
  58954. if( tripCode==SQLITE_OK ){
  58955. rc = tripCode = saveAllCursors(pBt, 0, 0);
  58956. if( rc ) writeOnly = 0;
  58957. }else{
  58958. rc = SQLITE_OK;
  58959. }
  58960. if( tripCode ){
  58961. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  58962. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  58963. if( rc2!=SQLITE_OK ) rc = rc2;
  58964. }
  58965. btreeIntegrity(p);
  58966. if( p->inTrans==TRANS_WRITE ){
  58967. int rc2;
  58968. assert( TRANS_WRITE==pBt->inTransaction );
  58969. rc2 = sqlite3PagerRollback(pBt->pPager);
  58970. if( rc2!=SQLITE_OK ){
  58971. rc = rc2;
  58972. }
  58973. /* The rollback may have destroyed the pPage1->aData value. So
  58974. ** call btreeGetPage() on page 1 again to make
  58975. ** sure pPage1->aData is set correctly. */
  58976. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  58977. int nPage = get4byte(28+(u8*)pPage1->aData);
  58978. testcase( nPage==0 );
  58979. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  58980. testcase( pBt->nPage!=nPage );
  58981. pBt->nPage = nPage;
  58982. releasePage(pPage1);
  58983. }
  58984. assert( countValidCursors(pBt, 1)==0 );
  58985. pBt->inTransaction = TRANS_READ;
  58986. btreeClearHasContent(pBt);
  58987. }
  58988. btreeEndTransaction(p);
  58989. sqlite3BtreeLeave(p);
  58990. return rc;
  58991. }
  58992. /*
  58993. ** Start a statement subtransaction. The subtransaction can be rolled
  58994. ** back independently of the main transaction. You must start a transaction
  58995. ** before starting a subtransaction. The subtransaction is ended automatically
  58996. ** if the main transaction commits or rolls back.
  58997. **
  58998. ** Statement subtransactions are used around individual SQL statements
  58999. ** that are contained within a BEGIN...COMMIT block. If a constraint
  59000. ** error occurs within the statement, the effect of that one statement
  59001. ** can be rolled back without having to rollback the entire transaction.
  59002. **
  59003. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  59004. ** value passed as the second parameter is the total number of savepoints,
  59005. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  59006. ** are no active savepoints and no other statement-transactions open,
  59007. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  59008. ** using the sqlite3BtreeSavepoint() function.
  59009. */
  59010. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  59011. int rc;
  59012. BtShared *pBt = p->pBt;
  59013. sqlite3BtreeEnter(p);
  59014. assert( p->inTrans==TRANS_WRITE );
  59015. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59016. assert( iStatement>0 );
  59017. assert( iStatement>p->db->nSavepoint );
  59018. assert( pBt->inTransaction==TRANS_WRITE );
  59019. /* At the pager level, a statement transaction is a savepoint with
  59020. ** an index greater than all savepoints created explicitly using
  59021. ** SQL statements. It is illegal to open, release or rollback any
  59022. ** such savepoints while the statement transaction savepoint is active.
  59023. */
  59024. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  59025. sqlite3BtreeLeave(p);
  59026. return rc;
  59027. }
  59028. /*
  59029. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  59030. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  59031. ** savepoint identified by parameter iSavepoint, depending on the value
  59032. ** of op.
  59033. **
  59034. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  59035. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  59036. ** contents of the entire transaction are rolled back. This is different
  59037. ** from a normal transaction rollback, as no locks are released and the
  59038. ** transaction remains open.
  59039. */
  59040. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  59041. int rc = SQLITE_OK;
  59042. if( p && p->inTrans==TRANS_WRITE ){
  59043. BtShared *pBt = p->pBt;
  59044. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  59045. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  59046. sqlite3BtreeEnter(p);
  59047. if( op==SAVEPOINT_ROLLBACK ){
  59048. rc = saveAllCursors(pBt, 0, 0);
  59049. }
  59050. if( rc==SQLITE_OK ){
  59051. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  59052. }
  59053. if( rc==SQLITE_OK ){
  59054. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  59055. pBt->nPage = 0;
  59056. }
  59057. rc = newDatabase(pBt);
  59058. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  59059. /* The database size was written into the offset 28 of the header
  59060. ** when the transaction started, so we know that the value at offset
  59061. ** 28 is nonzero. */
  59062. assert( pBt->nPage>0 );
  59063. }
  59064. sqlite3BtreeLeave(p);
  59065. }
  59066. return rc;
  59067. }
  59068. /*
  59069. ** Create a new cursor for the BTree whose root is on the page
  59070. ** iTable. If a read-only cursor is requested, it is assumed that
  59071. ** the caller already has at least a read-only transaction open
  59072. ** on the database already. If a write-cursor is requested, then
  59073. ** the caller is assumed to have an open write transaction.
  59074. **
  59075. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  59076. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  59077. ** can be used for reading or for writing if other conditions for writing
  59078. ** are also met. These are the conditions that must be met in order
  59079. ** for writing to be allowed:
  59080. **
  59081. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  59082. **
  59083. ** 2: Other database connections that share the same pager cache
  59084. ** but which are not in the READ_UNCOMMITTED state may not have
  59085. ** cursors open with wrFlag==0 on the same table. Otherwise
  59086. ** the changes made by this write cursor would be visible to
  59087. ** the read cursors in the other database connection.
  59088. **
  59089. ** 3: The database must be writable (not on read-only media)
  59090. **
  59091. ** 4: There must be an active transaction.
  59092. **
  59093. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  59094. ** is set. If FORDELETE is set, that is a hint to the implementation that
  59095. ** this cursor will only be used to seek to and delete entries of an index
  59096. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  59097. ** this implementation. But in a hypothetical alternative storage engine
  59098. ** in which index entries are automatically deleted when corresponding table
  59099. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  59100. ** operations on this cursor can be no-ops and all READ operations can
  59101. ** return a null row (2-bytes: 0x01 0x00).
  59102. **
  59103. ** No checking is done to make sure that page iTable really is the
  59104. ** root page of a b-tree. If it is not, then the cursor acquired
  59105. ** will not work correctly.
  59106. **
  59107. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  59108. ** on pCur to initialize the memory space prior to invoking this routine.
  59109. */
  59110. static int btreeCursor(
  59111. Btree *p, /* The btree */
  59112. int iTable, /* Root page of table to open */
  59113. int wrFlag, /* 1 to write. 0 read-only */
  59114. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  59115. BtCursor *pCur /* Space for new cursor */
  59116. ){
  59117. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  59118. BtCursor *pX; /* Looping over other all cursors */
  59119. assert( sqlite3BtreeHoldsMutex(p) );
  59120. assert( wrFlag==0
  59121. || wrFlag==BTREE_WRCSR
  59122. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  59123. );
  59124. /* The following assert statements verify that if this is a sharable
  59125. ** b-tree database, the connection is holding the required table locks,
  59126. ** and that no other connection has any open cursor that conflicts with
  59127. ** this lock. */
  59128. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  59129. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  59130. /* Assert that the caller has opened the required transaction. */
  59131. assert( p->inTrans>TRANS_NONE );
  59132. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  59133. assert( pBt->pPage1 && pBt->pPage1->aData );
  59134. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59135. if( wrFlag ){
  59136. allocateTempSpace(pBt);
  59137. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  59138. }
  59139. if( iTable==1 && btreePagecount(pBt)==0 ){
  59140. assert( wrFlag==0 );
  59141. iTable = 0;
  59142. }
  59143. /* Now that no other errors can occur, finish filling in the BtCursor
  59144. ** variables and link the cursor into the BtShared list. */
  59145. pCur->pgnoRoot = (Pgno)iTable;
  59146. pCur->iPage = -1;
  59147. pCur->pKeyInfo = pKeyInfo;
  59148. pCur->pBtree = p;
  59149. pCur->pBt = pBt;
  59150. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  59151. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  59152. /* If there are two or more cursors on the same btree, then all such
  59153. ** cursors *must* have the BTCF_Multiple flag set. */
  59154. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  59155. if( pX->pgnoRoot==(Pgno)iTable ){
  59156. pX->curFlags |= BTCF_Multiple;
  59157. pCur->curFlags |= BTCF_Multiple;
  59158. }
  59159. }
  59160. pCur->pNext = pBt->pCursor;
  59161. pBt->pCursor = pCur;
  59162. pCur->eState = CURSOR_INVALID;
  59163. return SQLITE_OK;
  59164. }
  59165. SQLITE_PRIVATE int sqlite3BtreeCursor(
  59166. Btree *p, /* The btree */
  59167. int iTable, /* Root page of table to open */
  59168. int wrFlag, /* 1 to write. 0 read-only */
  59169. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  59170. BtCursor *pCur /* Write new cursor here */
  59171. ){
  59172. int rc;
  59173. if( iTable<1 ){
  59174. rc = SQLITE_CORRUPT_BKPT;
  59175. }else{
  59176. sqlite3BtreeEnter(p);
  59177. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  59178. sqlite3BtreeLeave(p);
  59179. }
  59180. return rc;
  59181. }
  59182. /*
  59183. ** Return the size of a BtCursor object in bytes.
  59184. **
  59185. ** This interfaces is needed so that users of cursors can preallocate
  59186. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  59187. ** to users so they cannot do the sizeof() themselves - they must call
  59188. ** this routine.
  59189. */
  59190. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  59191. return ROUND8(sizeof(BtCursor));
  59192. }
  59193. /*
  59194. ** Initialize memory that will be converted into a BtCursor object.
  59195. **
  59196. ** The simple approach here would be to memset() the entire object
  59197. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  59198. ** do not need to be zeroed and they are large, so we can save a lot
  59199. ** of run-time by skipping the initialization of those elements.
  59200. */
  59201. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  59202. memset(p, 0, offsetof(BtCursor, iPage));
  59203. }
  59204. /*
  59205. ** Close a cursor. The read lock on the database file is released
  59206. ** when the last cursor is closed.
  59207. */
  59208. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  59209. Btree *pBtree = pCur->pBtree;
  59210. if( pBtree ){
  59211. int i;
  59212. BtShared *pBt = pCur->pBt;
  59213. sqlite3BtreeEnter(pBtree);
  59214. sqlite3BtreeClearCursor(pCur);
  59215. assert( pBt->pCursor!=0 );
  59216. if( pBt->pCursor==pCur ){
  59217. pBt->pCursor = pCur->pNext;
  59218. }else{
  59219. BtCursor *pPrev = pBt->pCursor;
  59220. do{
  59221. if( pPrev->pNext==pCur ){
  59222. pPrev->pNext = pCur->pNext;
  59223. break;
  59224. }
  59225. pPrev = pPrev->pNext;
  59226. }while( ALWAYS(pPrev) );
  59227. }
  59228. for(i=0; i<=pCur->iPage; i++){
  59229. releasePage(pCur->apPage[i]);
  59230. }
  59231. unlockBtreeIfUnused(pBt);
  59232. sqlite3_free(pCur->aOverflow);
  59233. /* sqlite3_free(pCur); */
  59234. sqlite3BtreeLeave(pBtree);
  59235. }
  59236. return SQLITE_OK;
  59237. }
  59238. /*
  59239. ** Make sure the BtCursor* given in the argument has a valid
  59240. ** BtCursor.info structure. If it is not already valid, call
  59241. ** btreeParseCell() to fill it in.
  59242. **
  59243. ** BtCursor.info is a cache of the information in the current cell.
  59244. ** Using this cache reduces the number of calls to btreeParseCell().
  59245. */
  59246. #ifndef NDEBUG
  59247. static void assertCellInfo(BtCursor *pCur){
  59248. CellInfo info;
  59249. int iPage = pCur->iPage;
  59250. memset(&info, 0, sizeof(info));
  59251. btreeParseCell(pCur->apPage[iPage], pCur->ix, &info);
  59252. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  59253. }
  59254. #else
  59255. #define assertCellInfo(x)
  59256. #endif
  59257. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  59258. if( pCur->info.nSize==0 ){
  59259. int iPage = pCur->iPage;
  59260. pCur->curFlags |= BTCF_ValidNKey;
  59261. btreeParseCell(pCur->apPage[iPage],pCur->ix,&pCur->info);
  59262. }else{
  59263. assertCellInfo(pCur);
  59264. }
  59265. }
  59266. #ifndef NDEBUG /* The next routine used only within assert() statements */
  59267. /*
  59268. ** Return true if the given BtCursor is valid. A valid cursor is one
  59269. ** that is currently pointing to a row in a (non-empty) table.
  59270. ** This is a verification routine is used only within assert() statements.
  59271. */
  59272. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  59273. return pCur && pCur->eState==CURSOR_VALID;
  59274. }
  59275. #endif /* NDEBUG */
  59276. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
  59277. assert( pCur!=0 );
  59278. return pCur->eState==CURSOR_VALID;
  59279. }
  59280. /*
  59281. ** Return the value of the integer key or "rowid" for a table btree.
  59282. ** This routine is only valid for a cursor that is pointing into a
  59283. ** ordinary table btree. If the cursor points to an index btree or
  59284. ** is invalid, the result of this routine is undefined.
  59285. */
  59286. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
  59287. assert( cursorHoldsMutex(pCur) );
  59288. assert( pCur->eState==CURSOR_VALID );
  59289. assert( pCur->curIntKey );
  59290. getCellInfo(pCur);
  59291. return pCur->info.nKey;
  59292. }
  59293. /*
  59294. ** Return the number of bytes of payload for the entry that pCur is
  59295. ** currently pointing to. For table btrees, this will be the amount
  59296. ** of data. For index btrees, this will be the size of the key.
  59297. **
  59298. ** The caller must guarantee that the cursor is pointing to a non-NULL
  59299. ** valid entry. In other words, the calling procedure must guarantee
  59300. ** that the cursor has Cursor.eState==CURSOR_VALID.
  59301. */
  59302. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
  59303. assert( cursorHoldsMutex(pCur) );
  59304. assert( pCur->eState==CURSOR_VALID );
  59305. getCellInfo(pCur);
  59306. return pCur->info.nPayload;
  59307. }
  59308. /*
  59309. ** Given the page number of an overflow page in the database (parameter
  59310. ** ovfl), this function finds the page number of the next page in the
  59311. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  59312. ** pointer-map data instead of reading the content of page ovfl to do so.
  59313. **
  59314. ** If an error occurs an SQLite error code is returned. Otherwise:
  59315. **
  59316. ** The page number of the next overflow page in the linked list is
  59317. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  59318. ** list, *pPgnoNext is set to zero.
  59319. **
  59320. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  59321. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  59322. ** reference. It is the responsibility of the caller to call releasePage()
  59323. ** on *ppPage to free the reference. In no reference was obtained (because
  59324. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  59325. ** *ppPage is set to zero.
  59326. */
  59327. static int getOverflowPage(
  59328. BtShared *pBt, /* The database file */
  59329. Pgno ovfl, /* Current overflow page number */
  59330. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  59331. Pgno *pPgnoNext /* OUT: Next overflow page number */
  59332. ){
  59333. Pgno next = 0;
  59334. MemPage *pPage = 0;
  59335. int rc = SQLITE_OK;
  59336. assert( sqlite3_mutex_held(pBt->mutex) );
  59337. assert(pPgnoNext);
  59338. #ifndef SQLITE_OMIT_AUTOVACUUM
  59339. /* Try to find the next page in the overflow list using the
  59340. ** autovacuum pointer-map pages. Guess that the next page in
  59341. ** the overflow list is page number (ovfl+1). If that guess turns
  59342. ** out to be wrong, fall back to loading the data of page
  59343. ** number ovfl to determine the next page number.
  59344. */
  59345. if( pBt->autoVacuum ){
  59346. Pgno pgno;
  59347. Pgno iGuess = ovfl+1;
  59348. u8 eType;
  59349. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  59350. iGuess++;
  59351. }
  59352. if( iGuess<=btreePagecount(pBt) ){
  59353. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  59354. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  59355. next = iGuess;
  59356. rc = SQLITE_DONE;
  59357. }
  59358. }
  59359. }
  59360. #endif
  59361. assert( next==0 || rc==SQLITE_DONE );
  59362. if( rc==SQLITE_OK ){
  59363. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  59364. assert( rc==SQLITE_OK || pPage==0 );
  59365. if( rc==SQLITE_OK ){
  59366. next = get4byte(pPage->aData);
  59367. }
  59368. }
  59369. *pPgnoNext = next;
  59370. if( ppPage ){
  59371. *ppPage = pPage;
  59372. }else{
  59373. releasePage(pPage);
  59374. }
  59375. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  59376. }
  59377. /*
  59378. ** Copy data from a buffer to a page, or from a page to a buffer.
  59379. **
  59380. ** pPayload is a pointer to data stored on database page pDbPage.
  59381. ** If argument eOp is false, then nByte bytes of data are copied
  59382. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  59383. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  59384. ** of data are copied from the buffer pBuf to pPayload.
  59385. **
  59386. ** SQLITE_OK is returned on success, otherwise an error code.
  59387. */
  59388. static int copyPayload(
  59389. void *pPayload, /* Pointer to page data */
  59390. void *pBuf, /* Pointer to buffer */
  59391. int nByte, /* Number of bytes to copy */
  59392. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  59393. DbPage *pDbPage /* Page containing pPayload */
  59394. ){
  59395. if( eOp ){
  59396. /* Copy data from buffer to page (a write operation) */
  59397. int rc = sqlite3PagerWrite(pDbPage);
  59398. if( rc!=SQLITE_OK ){
  59399. return rc;
  59400. }
  59401. memcpy(pPayload, pBuf, nByte);
  59402. }else{
  59403. /* Copy data from page to buffer (a read operation) */
  59404. memcpy(pBuf, pPayload, nByte);
  59405. }
  59406. return SQLITE_OK;
  59407. }
  59408. /*
  59409. ** This function is used to read or overwrite payload information
  59410. ** for the entry that the pCur cursor is pointing to. The eOp
  59411. ** argument is interpreted as follows:
  59412. **
  59413. ** 0: The operation is a read. Populate the overflow cache.
  59414. ** 1: The operation is a write. Populate the overflow cache.
  59415. **
  59416. ** A total of "amt" bytes are read or written beginning at "offset".
  59417. ** Data is read to or from the buffer pBuf.
  59418. **
  59419. ** The content being read or written might appear on the main page
  59420. ** or be scattered out on multiple overflow pages.
  59421. **
  59422. ** If the current cursor entry uses one or more overflow pages
  59423. ** this function may allocate space for and lazily populate
  59424. ** the overflow page-list cache array (BtCursor.aOverflow).
  59425. ** Subsequent calls use this cache to make seeking to the supplied offset
  59426. ** more efficient.
  59427. **
  59428. ** Once an overflow page-list cache has been allocated, it must be
  59429. ** invalidated if some other cursor writes to the same table, or if
  59430. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  59431. ** mode, the following events may invalidate an overflow page-list cache.
  59432. **
  59433. ** * An incremental vacuum,
  59434. ** * A commit in auto_vacuum="full" mode,
  59435. ** * Creating a table (may require moving an overflow page).
  59436. */
  59437. static int accessPayload(
  59438. BtCursor *pCur, /* Cursor pointing to entry to read from */
  59439. u32 offset, /* Begin reading this far into payload */
  59440. u32 amt, /* Read this many bytes */
  59441. unsigned char *pBuf, /* Write the bytes into this buffer */
  59442. int eOp /* zero to read. non-zero to write. */
  59443. ){
  59444. unsigned char *aPayload;
  59445. int rc = SQLITE_OK;
  59446. int iIdx = 0;
  59447. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  59448. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  59449. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  59450. unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
  59451. #endif
  59452. assert( pPage );
  59453. assert( eOp==0 || eOp==1 );
  59454. assert( pCur->eState==CURSOR_VALID );
  59455. assert( pCur->ix<pPage->nCell );
  59456. assert( cursorHoldsMutex(pCur) );
  59457. getCellInfo(pCur);
  59458. aPayload = pCur->info.pPayload;
  59459. assert( offset+amt <= pCur->info.nPayload );
  59460. assert( aPayload > pPage->aData );
  59461. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  59462. /* Trying to read or write past the end of the data is an error. The
  59463. ** conditional above is really:
  59464. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  59465. ** but is recast into its current form to avoid integer overflow problems
  59466. */
  59467. return SQLITE_CORRUPT_BKPT;
  59468. }
  59469. /* Check if data must be read/written to/from the btree page itself. */
  59470. if( offset<pCur->info.nLocal ){
  59471. int a = amt;
  59472. if( a+offset>pCur->info.nLocal ){
  59473. a = pCur->info.nLocal - offset;
  59474. }
  59475. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  59476. offset = 0;
  59477. pBuf += a;
  59478. amt -= a;
  59479. }else{
  59480. offset -= pCur->info.nLocal;
  59481. }
  59482. if( rc==SQLITE_OK && amt>0 ){
  59483. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  59484. Pgno nextPage;
  59485. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  59486. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  59487. **
  59488. ** The aOverflow[] array is sized at one entry for each overflow page
  59489. ** in the overflow chain. The page number of the first overflow page is
  59490. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  59491. ** means "not yet known" (the cache is lazily populated).
  59492. */
  59493. if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  59494. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  59495. if( nOvfl>pCur->nOvflAlloc ){
  59496. Pgno *aNew = (Pgno*)sqlite3Realloc(
  59497. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  59498. );
  59499. if( aNew==0 ){
  59500. return SQLITE_NOMEM_BKPT;
  59501. }else{
  59502. pCur->nOvflAlloc = nOvfl*2;
  59503. pCur->aOverflow = aNew;
  59504. }
  59505. }
  59506. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  59507. pCur->curFlags |= BTCF_ValidOvfl;
  59508. }else{
  59509. /* If the overflow page-list cache has been allocated and the
  59510. ** entry for the first required overflow page is valid, skip
  59511. ** directly to it.
  59512. */
  59513. if( pCur->aOverflow[offset/ovflSize] ){
  59514. iIdx = (offset/ovflSize);
  59515. nextPage = pCur->aOverflow[iIdx];
  59516. offset = (offset%ovflSize);
  59517. }
  59518. }
  59519. assert( rc==SQLITE_OK && amt>0 );
  59520. while( nextPage ){
  59521. /* If required, populate the overflow page-list cache. */
  59522. assert( pCur->aOverflow[iIdx]==0
  59523. || pCur->aOverflow[iIdx]==nextPage
  59524. || CORRUPT_DB );
  59525. pCur->aOverflow[iIdx] = nextPage;
  59526. if( offset>=ovflSize ){
  59527. /* The only reason to read this page is to obtain the page
  59528. ** number for the next page in the overflow chain. The page
  59529. ** data is not required. So first try to lookup the overflow
  59530. ** page-list cache, if any, then fall back to the getOverflowPage()
  59531. ** function.
  59532. */
  59533. assert( pCur->curFlags & BTCF_ValidOvfl );
  59534. assert( pCur->pBtree->db==pBt->db );
  59535. if( pCur->aOverflow[iIdx+1] ){
  59536. nextPage = pCur->aOverflow[iIdx+1];
  59537. }else{
  59538. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  59539. }
  59540. offset -= ovflSize;
  59541. }else{
  59542. /* Need to read this page properly. It contains some of the
  59543. ** range of data that is being read (eOp==0) or written (eOp!=0).
  59544. */
  59545. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  59546. sqlite3_file *fd; /* File from which to do direct overflow read */
  59547. #endif
  59548. int a = amt;
  59549. if( a + offset > ovflSize ){
  59550. a = ovflSize - offset;
  59551. }
  59552. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  59553. /* If all the following are true:
  59554. **
  59555. ** 1) this is a read operation, and
  59556. ** 2) data is required from the start of this overflow page, and
  59557. ** 3) there is no open write-transaction, and
  59558. ** 4) the database is file-backed, and
  59559. ** 5) the page is not in the WAL file
  59560. ** 6) at least 4 bytes have already been read into the output buffer
  59561. **
  59562. ** then data can be read directly from the database file into the
  59563. ** output buffer, bypassing the page-cache altogether. This speeds
  59564. ** up loading large records that span many overflow pages.
  59565. */
  59566. if( eOp==0 /* (1) */
  59567. && offset==0 /* (2) */
  59568. && pBt->inTransaction==TRANS_READ /* (3) */
  59569. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
  59570. && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
  59571. && &pBuf[-4]>=pBufStart /* (6) */
  59572. ){
  59573. u8 aSave[4];
  59574. u8 *aWrite = &pBuf[-4];
  59575. assert( aWrite>=pBufStart ); /* due to (6) */
  59576. memcpy(aSave, aWrite, 4);
  59577. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  59578. nextPage = get4byte(aWrite);
  59579. memcpy(aWrite, aSave, 4);
  59580. }else
  59581. #endif
  59582. {
  59583. DbPage *pDbPage;
  59584. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  59585. (eOp==0 ? PAGER_GET_READONLY : 0)
  59586. );
  59587. if( rc==SQLITE_OK ){
  59588. aPayload = sqlite3PagerGetData(pDbPage);
  59589. nextPage = get4byte(aPayload);
  59590. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  59591. sqlite3PagerUnref(pDbPage);
  59592. offset = 0;
  59593. }
  59594. }
  59595. amt -= a;
  59596. if( amt==0 ) return rc;
  59597. pBuf += a;
  59598. }
  59599. if( rc ) break;
  59600. iIdx++;
  59601. }
  59602. }
  59603. if( rc==SQLITE_OK && amt>0 ){
  59604. return SQLITE_CORRUPT_BKPT; /* Overflow chain ends prematurely */
  59605. }
  59606. return rc;
  59607. }
  59608. /*
  59609. ** Read part of the payload for the row at which that cursor pCur is currently
  59610. ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
  59611. ** begins at "offset".
  59612. **
  59613. ** pCur can be pointing to either a table or an index b-tree.
  59614. ** If pointing to a table btree, then the content section is read. If
  59615. ** pCur is pointing to an index b-tree then the key section is read.
  59616. **
  59617. ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
  59618. ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
  59619. ** cursor might be invalid or might need to be restored before being read.
  59620. **
  59621. ** Return SQLITE_OK on success or an error code if anything goes
  59622. ** wrong. An error is returned if "offset+amt" is larger than
  59623. ** the available payload.
  59624. */
  59625. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  59626. assert( cursorHoldsMutex(pCur) );
  59627. assert( pCur->eState==CURSOR_VALID );
  59628. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  59629. assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
  59630. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  59631. }
  59632. /*
  59633. ** This variant of sqlite3BtreePayload() works even if the cursor has not
  59634. ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
  59635. ** interface.
  59636. */
  59637. #ifndef SQLITE_OMIT_INCRBLOB
  59638. static SQLITE_NOINLINE int accessPayloadChecked(
  59639. BtCursor *pCur,
  59640. u32 offset,
  59641. u32 amt,
  59642. void *pBuf
  59643. ){
  59644. int rc;
  59645. if ( pCur->eState==CURSOR_INVALID ){
  59646. return SQLITE_ABORT;
  59647. }
  59648. assert( cursorOwnsBtShared(pCur) );
  59649. rc = btreeRestoreCursorPosition(pCur);
  59650. return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
  59651. }
  59652. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  59653. if( pCur->eState==CURSOR_VALID ){
  59654. assert( cursorOwnsBtShared(pCur) );
  59655. return accessPayload(pCur, offset, amt, pBuf, 0);
  59656. }else{
  59657. return accessPayloadChecked(pCur, offset, amt, pBuf);
  59658. }
  59659. }
  59660. #endif /* SQLITE_OMIT_INCRBLOB */
  59661. /*
  59662. ** Return a pointer to payload information from the entry that the
  59663. ** pCur cursor is pointing to. The pointer is to the beginning of
  59664. ** the key if index btrees (pPage->intKey==0) and is the data for
  59665. ** table btrees (pPage->intKey==1). The number of bytes of available
  59666. ** key/data is written into *pAmt. If *pAmt==0, then the value
  59667. ** returned will not be a valid pointer.
  59668. **
  59669. ** This routine is an optimization. It is common for the entire key
  59670. ** and data to fit on the local page and for there to be no overflow
  59671. ** pages. When that is so, this routine can be used to access the
  59672. ** key and data without making a copy. If the key and/or data spills
  59673. ** onto overflow pages, then accessPayload() must be used to reassemble
  59674. ** the key/data and copy it into a preallocated buffer.
  59675. **
  59676. ** The pointer returned by this routine looks directly into the cached
  59677. ** page of the database. The data might change or move the next time
  59678. ** any btree routine is called.
  59679. */
  59680. static const void *fetchPayload(
  59681. BtCursor *pCur, /* Cursor pointing to entry to read from */
  59682. u32 *pAmt /* Write the number of available bytes here */
  59683. ){
  59684. u32 amt;
  59685. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  59686. assert( pCur->eState==CURSOR_VALID );
  59687. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  59688. assert( cursorOwnsBtShared(pCur) );
  59689. assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
  59690. assert( pCur->info.nSize>0 );
  59691. assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
  59692. assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
  59693. amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
  59694. if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
  59695. *pAmt = amt;
  59696. return (void*)pCur->info.pPayload;
  59697. }
  59698. /*
  59699. ** For the entry that cursor pCur is point to, return as
  59700. ** many bytes of the key or data as are available on the local
  59701. ** b-tree page. Write the number of available bytes into *pAmt.
  59702. **
  59703. ** The pointer returned is ephemeral. The key/data may move
  59704. ** or be destroyed on the next call to any Btree routine,
  59705. ** including calls from other threads against the same cache.
  59706. ** Hence, a mutex on the BtShared should be held prior to calling
  59707. ** this routine.
  59708. **
  59709. ** These routines is used to get quick access to key and data
  59710. ** in the common case where no overflow pages are used.
  59711. */
  59712. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
  59713. return fetchPayload(pCur, pAmt);
  59714. }
  59715. /*
  59716. ** Move the cursor down to a new child page. The newPgno argument is the
  59717. ** page number of the child page to move to.
  59718. **
  59719. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  59720. ** the new child page does not match the flags field of the parent (i.e.
  59721. ** if an intkey page appears to be the parent of a non-intkey page, or
  59722. ** vice-versa).
  59723. */
  59724. static int moveToChild(BtCursor *pCur, u32 newPgno){
  59725. BtShared *pBt = pCur->pBt;
  59726. assert( cursorOwnsBtShared(pCur) );
  59727. assert( pCur->eState==CURSOR_VALID );
  59728. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  59729. assert( pCur->iPage>=0 );
  59730. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  59731. return SQLITE_CORRUPT_BKPT;
  59732. }
  59733. pCur->info.nSize = 0;
  59734. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  59735. pCur->aiIdx[pCur->iPage++] = pCur->ix;
  59736. pCur->ix = 0;
  59737. return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
  59738. pCur, pCur->curPagerFlags);
  59739. }
  59740. #ifdef SQLITE_DEBUG
  59741. /*
  59742. ** Page pParent is an internal (non-leaf) tree page. This function
  59743. ** asserts that page number iChild is the left-child if the iIdx'th
  59744. ** cell in page pParent. Or, if iIdx is equal to the total number of
  59745. ** cells in pParent, that page number iChild is the right-child of
  59746. ** the page.
  59747. */
  59748. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  59749. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  59750. ** in a corrupt database */
  59751. assert( iIdx<=pParent->nCell );
  59752. if( iIdx==pParent->nCell ){
  59753. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  59754. }else{
  59755. assert( get4byte(findCell(pParent, iIdx))==iChild );
  59756. }
  59757. }
  59758. #else
  59759. # define assertParentIndex(x,y,z)
  59760. #endif
  59761. /*
  59762. ** Move the cursor up to the parent page.
  59763. **
  59764. ** pCur->idx is set to the cell index that contains the pointer
  59765. ** to the page we are coming from. If we are coming from the
  59766. ** right-most child page then pCur->idx is set to one more than
  59767. ** the largest cell index.
  59768. */
  59769. static void moveToParent(BtCursor *pCur){
  59770. assert( cursorOwnsBtShared(pCur) );
  59771. assert( pCur->eState==CURSOR_VALID );
  59772. assert( pCur->iPage>0 );
  59773. assert( pCur->apPage[pCur->iPage] );
  59774. assertParentIndex(
  59775. pCur->apPage[pCur->iPage-1],
  59776. pCur->aiIdx[pCur->iPage-1],
  59777. pCur->apPage[pCur->iPage]->pgno
  59778. );
  59779. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  59780. pCur->info.nSize = 0;
  59781. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  59782. pCur->ix = pCur->aiIdx[pCur->iPage-1];
  59783. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  59784. }
  59785. /*
  59786. ** Move the cursor to point to the root page of its b-tree structure.
  59787. **
  59788. ** If the table has a virtual root page, then the cursor is moved to point
  59789. ** to the virtual root page instead of the actual root page. A table has a
  59790. ** virtual root page when the actual root page contains no cells and a
  59791. ** single child page. This can only happen with the table rooted at page 1.
  59792. **
  59793. ** If the b-tree structure is empty, the cursor state is set to
  59794. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  59795. ** cell located on the root (or virtual root) page and the cursor state
  59796. ** is set to CURSOR_VALID.
  59797. **
  59798. ** If this function returns successfully, it may be assumed that the
  59799. ** page-header flags indicate that the [virtual] root-page is the expected
  59800. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  59801. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  59802. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  59803. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  59804. ** b-tree).
  59805. */
  59806. static int moveToRoot(BtCursor *pCur){
  59807. MemPage *pRoot;
  59808. int rc = SQLITE_OK;
  59809. assert( cursorOwnsBtShared(pCur) );
  59810. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  59811. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  59812. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  59813. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  59814. if( pCur->eState==CURSOR_FAULT ){
  59815. assert( pCur->skipNext!=SQLITE_OK );
  59816. return pCur->skipNext;
  59817. }
  59818. sqlite3BtreeClearCursor(pCur);
  59819. }
  59820. if( pCur->iPage>=0 ){
  59821. if( pCur->iPage ){
  59822. do{
  59823. assert( pCur->apPage[pCur->iPage]!=0 );
  59824. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  59825. }while( pCur->iPage);
  59826. goto skip_init;
  59827. }
  59828. }else if( pCur->pgnoRoot==0 ){
  59829. pCur->eState = CURSOR_INVALID;
  59830. return SQLITE_OK;
  59831. }else{
  59832. assert( pCur->iPage==(-1) );
  59833. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
  59834. 0, pCur->curPagerFlags);
  59835. if( rc!=SQLITE_OK ){
  59836. pCur->eState = CURSOR_INVALID;
  59837. return rc;
  59838. }
  59839. pCur->iPage = 0;
  59840. pCur->curIntKey = pCur->apPage[0]->intKey;
  59841. }
  59842. pRoot = pCur->apPage[0];
  59843. assert( pRoot->pgno==pCur->pgnoRoot );
  59844. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  59845. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  59846. ** NULL, the caller expects a table b-tree. If this is not the case,
  59847. ** return an SQLITE_CORRUPT error.
  59848. **
  59849. ** Earlier versions of SQLite assumed that this test could not fail
  59850. ** if the root page was already loaded when this function was called (i.e.
  59851. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  59852. ** in such a way that page pRoot is linked into a second b-tree table
  59853. ** (or the freelist). */
  59854. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  59855. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  59856. return SQLITE_CORRUPT_BKPT;
  59857. }
  59858. skip_init:
  59859. pCur->ix = 0;
  59860. pCur->info.nSize = 0;
  59861. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  59862. pRoot = pCur->apPage[0];
  59863. if( pRoot->nCell>0 ){
  59864. pCur->eState = CURSOR_VALID;
  59865. }else if( !pRoot->leaf ){
  59866. Pgno subpage;
  59867. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  59868. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  59869. pCur->eState = CURSOR_VALID;
  59870. rc = moveToChild(pCur, subpage);
  59871. }else{
  59872. pCur->eState = CURSOR_INVALID;
  59873. }
  59874. return rc;
  59875. }
  59876. /*
  59877. ** Move the cursor down to the left-most leaf entry beneath the
  59878. ** entry to which it is currently pointing.
  59879. **
  59880. ** The left-most leaf is the one with the smallest key - the first
  59881. ** in ascending order.
  59882. */
  59883. static int moveToLeftmost(BtCursor *pCur){
  59884. Pgno pgno;
  59885. int rc = SQLITE_OK;
  59886. MemPage *pPage;
  59887. assert( cursorOwnsBtShared(pCur) );
  59888. assert( pCur->eState==CURSOR_VALID );
  59889. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  59890. assert( pCur->ix<pPage->nCell );
  59891. pgno = get4byte(findCell(pPage, pCur->ix));
  59892. rc = moveToChild(pCur, pgno);
  59893. }
  59894. return rc;
  59895. }
  59896. /*
  59897. ** Move the cursor down to the right-most leaf entry beneath the
  59898. ** page to which it is currently pointing. Notice the difference
  59899. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  59900. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  59901. ** finds the right-most entry beneath the *page*.
  59902. **
  59903. ** The right-most entry is the one with the largest key - the last
  59904. ** key in ascending order.
  59905. */
  59906. static int moveToRightmost(BtCursor *pCur){
  59907. Pgno pgno;
  59908. int rc = SQLITE_OK;
  59909. MemPage *pPage = 0;
  59910. assert( cursorOwnsBtShared(pCur) );
  59911. assert( pCur->eState==CURSOR_VALID );
  59912. while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  59913. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  59914. pCur->ix = pPage->nCell;
  59915. rc = moveToChild(pCur, pgno);
  59916. if( rc ) return rc;
  59917. }
  59918. pCur->ix = pPage->nCell-1;
  59919. assert( pCur->info.nSize==0 );
  59920. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  59921. return SQLITE_OK;
  59922. }
  59923. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  59924. ** on success. Set *pRes to 0 if the cursor actually points to something
  59925. ** or set *pRes to 1 if the table is empty.
  59926. */
  59927. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  59928. int rc;
  59929. assert( cursorOwnsBtShared(pCur) );
  59930. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  59931. rc = moveToRoot(pCur);
  59932. if( rc==SQLITE_OK ){
  59933. if( pCur->eState==CURSOR_INVALID ){
  59934. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  59935. *pRes = 1;
  59936. }else{
  59937. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  59938. *pRes = 0;
  59939. rc = moveToLeftmost(pCur);
  59940. }
  59941. }
  59942. return rc;
  59943. }
  59944. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  59945. ** on success. Set *pRes to 0 if the cursor actually points to something
  59946. ** or set *pRes to 1 if the table is empty.
  59947. */
  59948. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  59949. int rc;
  59950. assert( cursorOwnsBtShared(pCur) );
  59951. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  59952. /* If the cursor already points to the last entry, this is a no-op. */
  59953. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  59954. #ifdef SQLITE_DEBUG
  59955. /* This block serves to assert() that the cursor really does point
  59956. ** to the last entry in the b-tree. */
  59957. int ii;
  59958. for(ii=0; ii<pCur->iPage; ii++){
  59959. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  59960. }
  59961. assert( pCur->ix==pCur->apPage[pCur->iPage]->nCell-1 );
  59962. assert( pCur->apPage[pCur->iPage]->leaf );
  59963. #endif
  59964. return SQLITE_OK;
  59965. }
  59966. rc = moveToRoot(pCur);
  59967. if( rc==SQLITE_OK ){
  59968. if( CURSOR_INVALID==pCur->eState ){
  59969. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  59970. *pRes = 1;
  59971. }else{
  59972. assert( pCur->eState==CURSOR_VALID );
  59973. *pRes = 0;
  59974. rc = moveToRightmost(pCur);
  59975. if( rc==SQLITE_OK ){
  59976. pCur->curFlags |= BTCF_AtLast;
  59977. }else{
  59978. pCur->curFlags &= ~BTCF_AtLast;
  59979. }
  59980. }
  59981. }
  59982. return rc;
  59983. }
  59984. /* Move the cursor so that it points to an entry near the key
  59985. ** specified by pIdxKey or intKey. Return a success code.
  59986. **
  59987. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  59988. ** must be NULL. For index tables, pIdxKey is used and intKey
  59989. ** is ignored.
  59990. **
  59991. ** If an exact match is not found, then the cursor is always
  59992. ** left pointing at a leaf page which would hold the entry if it
  59993. ** were present. The cursor might point to an entry that comes
  59994. ** before or after the key.
  59995. **
  59996. ** An integer is written into *pRes which is the result of
  59997. ** comparing the key with the entry to which the cursor is
  59998. ** pointing. The meaning of the integer written into
  59999. ** *pRes is as follows:
  60000. **
  60001. ** *pRes<0 The cursor is left pointing at an entry that
  60002. ** is smaller than intKey/pIdxKey or if the table is empty
  60003. ** and the cursor is therefore left point to nothing.
  60004. **
  60005. ** *pRes==0 The cursor is left pointing at an entry that
  60006. ** exactly matches intKey/pIdxKey.
  60007. **
  60008. ** *pRes>0 The cursor is left pointing at an entry that
  60009. ** is larger than intKey/pIdxKey.
  60010. **
  60011. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  60012. ** exists an entry in the table that exactly matches pIdxKey.
  60013. */
  60014. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  60015. BtCursor *pCur, /* The cursor to be moved */
  60016. UnpackedRecord *pIdxKey, /* Unpacked index key */
  60017. i64 intKey, /* The table key */
  60018. int biasRight, /* If true, bias the search to the high end */
  60019. int *pRes /* Write search results here */
  60020. ){
  60021. int rc;
  60022. RecordCompare xRecordCompare;
  60023. assert( cursorOwnsBtShared(pCur) );
  60024. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  60025. assert( pRes );
  60026. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  60027. assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
  60028. /* If the cursor is already positioned at the point we are trying
  60029. ** to move to, then just return without doing any work */
  60030. if( pIdxKey==0
  60031. && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  60032. ){
  60033. if( pCur->info.nKey==intKey ){
  60034. *pRes = 0;
  60035. return SQLITE_OK;
  60036. }
  60037. if( pCur->info.nKey<intKey ){
  60038. if( (pCur->curFlags & BTCF_AtLast)!=0 ){
  60039. *pRes = -1;
  60040. return SQLITE_OK;
  60041. }
  60042. /* If the requested key is one more than the previous key, then
  60043. ** try to get there using sqlite3BtreeNext() rather than a full
  60044. ** binary search. This is an optimization only. The correct answer
  60045. ** is still obtained without this ase, only a little more slowely */
  60046. if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
  60047. *pRes = 0;
  60048. rc = sqlite3BtreeNext(pCur, pRes);
  60049. if( rc ) return rc;
  60050. if( *pRes==0 ){
  60051. getCellInfo(pCur);
  60052. if( pCur->info.nKey==intKey ){
  60053. return SQLITE_OK;
  60054. }
  60055. }
  60056. }
  60057. }
  60058. }
  60059. if( pIdxKey ){
  60060. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  60061. pIdxKey->errCode = 0;
  60062. assert( pIdxKey->default_rc==1
  60063. || pIdxKey->default_rc==0
  60064. || pIdxKey->default_rc==-1
  60065. );
  60066. }else{
  60067. xRecordCompare = 0; /* All keys are integers */
  60068. }
  60069. rc = moveToRoot(pCur);
  60070. if( rc ){
  60071. return rc;
  60072. }
  60073. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  60074. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  60075. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  60076. if( pCur->eState==CURSOR_INVALID ){
  60077. *pRes = -1;
  60078. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  60079. return SQLITE_OK;
  60080. }
  60081. assert( pCur->apPage[0]->intKey==pCur->curIntKey );
  60082. assert( pCur->curIntKey || pIdxKey );
  60083. for(;;){
  60084. int lwr, upr, idx, c;
  60085. Pgno chldPg;
  60086. MemPage *pPage = pCur->apPage[pCur->iPage];
  60087. u8 *pCell; /* Pointer to current cell in pPage */
  60088. /* pPage->nCell must be greater than zero. If this is the root-page
  60089. ** the cursor would have been INVALID above and this for(;;) loop
  60090. ** not run. If this is not the root-page, then the moveToChild() routine
  60091. ** would have already detected db corruption. Similarly, pPage must
  60092. ** be the right kind (index or table) of b-tree page. Otherwise
  60093. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  60094. assert( pPage->nCell>0 );
  60095. assert( pPage->intKey==(pIdxKey==0) );
  60096. lwr = 0;
  60097. upr = pPage->nCell-1;
  60098. assert( biasRight==0 || biasRight==1 );
  60099. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  60100. pCur->ix = (u16)idx;
  60101. if( xRecordCompare==0 ){
  60102. for(;;){
  60103. i64 nCellKey;
  60104. pCell = findCellPastPtr(pPage, idx);
  60105. if( pPage->intKeyLeaf ){
  60106. while( 0x80 <= *(pCell++) ){
  60107. if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  60108. }
  60109. }
  60110. getVarint(pCell, (u64*)&nCellKey);
  60111. if( nCellKey<intKey ){
  60112. lwr = idx+1;
  60113. if( lwr>upr ){ c = -1; break; }
  60114. }else if( nCellKey>intKey ){
  60115. upr = idx-1;
  60116. if( lwr>upr ){ c = +1; break; }
  60117. }else{
  60118. assert( nCellKey==intKey );
  60119. pCur->ix = (u16)idx;
  60120. if( !pPage->leaf ){
  60121. lwr = idx;
  60122. goto moveto_next_layer;
  60123. }else{
  60124. pCur->curFlags |= BTCF_ValidNKey;
  60125. pCur->info.nKey = nCellKey;
  60126. pCur->info.nSize = 0;
  60127. *pRes = 0;
  60128. return SQLITE_OK;
  60129. }
  60130. }
  60131. assert( lwr+upr>=0 );
  60132. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  60133. }
  60134. }else{
  60135. for(;;){
  60136. int nCell; /* Size of the pCell cell in bytes */
  60137. pCell = findCellPastPtr(pPage, idx);
  60138. /* The maximum supported page-size is 65536 bytes. This means that
  60139. ** the maximum number of record bytes stored on an index B-Tree
  60140. ** page is less than 16384 bytes and may be stored as a 2-byte
  60141. ** varint. This information is used to attempt to avoid parsing
  60142. ** the entire cell by checking for the cases where the record is
  60143. ** stored entirely within the b-tree page by inspecting the first
  60144. ** 2 bytes of the cell.
  60145. */
  60146. nCell = pCell[0];
  60147. if( nCell<=pPage->max1bytePayload ){
  60148. /* This branch runs if the record-size field of the cell is a
  60149. ** single byte varint and the record fits entirely on the main
  60150. ** b-tree page. */
  60151. testcase( pCell+nCell+1==pPage->aDataEnd );
  60152. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  60153. }else if( !(pCell[1] & 0x80)
  60154. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  60155. ){
  60156. /* The record-size field is a 2 byte varint and the record
  60157. ** fits entirely on the main b-tree page. */
  60158. testcase( pCell+nCell+2==pPage->aDataEnd );
  60159. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  60160. }else{
  60161. /* The record flows over onto one or more overflow pages. In
  60162. ** this case the whole cell needs to be parsed, a buffer allocated
  60163. ** and accessPayload() used to retrieve the record into the
  60164. ** buffer before VdbeRecordCompare() can be called.
  60165. **
  60166. ** If the record is corrupt, the xRecordCompare routine may read
  60167. ** up to two varints past the end of the buffer. An extra 18
  60168. ** bytes of padding is allocated at the end of the buffer in
  60169. ** case this happens. */
  60170. void *pCellKey;
  60171. u8 * const pCellBody = pCell - pPage->childPtrSize;
  60172. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  60173. nCell = (int)pCur->info.nKey;
  60174. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  60175. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  60176. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  60177. testcase( nCell==2 ); /* Minimum legal index key size */
  60178. if( nCell<2 ){
  60179. rc = SQLITE_CORRUPT_BKPT;
  60180. goto moveto_finish;
  60181. }
  60182. pCellKey = sqlite3Malloc( nCell+18 );
  60183. if( pCellKey==0 ){
  60184. rc = SQLITE_NOMEM_BKPT;
  60185. goto moveto_finish;
  60186. }
  60187. pCur->ix = (u16)idx;
  60188. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  60189. pCur->curFlags &= ~BTCF_ValidOvfl;
  60190. if( rc ){
  60191. sqlite3_free(pCellKey);
  60192. goto moveto_finish;
  60193. }
  60194. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  60195. sqlite3_free(pCellKey);
  60196. }
  60197. assert(
  60198. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  60199. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  60200. );
  60201. if( c<0 ){
  60202. lwr = idx+1;
  60203. }else if( c>0 ){
  60204. upr = idx-1;
  60205. }else{
  60206. assert( c==0 );
  60207. *pRes = 0;
  60208. rc = SQLITE_OK;
  60209. pCur->ix = (u16)idx;
  60210. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
  60211. goto moveto_finish;
  60212. }
  60213. if( lwr>upr ) break;
  60214. assert( lwr+upr>=0 );
  60215. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  60216. }
  60217. }
  60218. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  60219. assert( pPage->isInit );
  60220. if( pPage->leaf ){
  60221. assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
  60222. pCur->ix = (u16)idx;
  60223. *pRes = c;
  60224. rc = SQLITE_OK;
  60225. goto moveto_finish;
  60226. }
  60227. moveto_next_layer:
  60228. if( lwr>=pPage->nCell ){
  60229. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  60230. }else{
  60231. chldPg = get4byte(findCell(pPage, lwr));
  60232. }
  60233. pCur->ix = (u16)lwr;
  60234. rc = moveToChild(pCur, chldPg);
  60235. if( rc ) break;
  60236. }
  60237. moveto_finish:
  60238. pCur->info.nSize = 0;
  60239. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  60240. return rc;
  60241. }
  60242. /*
  60243. ** Return TRUE if the cursor is not pointing at an entry of the table.
  60244. **
  60245. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  60246. ** past the last entry in the table or sqlite3BtreePrev() moves past
  60247. ** the first entry. TRUE is also returned if the table is empty.
  60248. */
  60249. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  60250. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  60251. ** have been deleted? This API will need to change to return an error code
  60252. ** as well as the boolean result value.
  60253. */
  60254. return (CURSOR_VALID!=pCur->eState);
  60255. }
  60256. /*
  60257. ** Return an estimate for the number of rows in the table that pCur is
  60258. ** pointing to. Return a negative number if no estimate is currently
  60259. ** available.
  60260. */
  60261. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
  60262. i64 n;
  60263. u8 i;
  60264. assert( cursorOwnsBtShared(pCur) );
  60265. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  60266. /* Currently this interface is only called by the OP_IfSmaller
  60267. ** opcode, and it that case the cursor will always be valid and
  60268. ** will always point to a leaf node. */
  60269. if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
  60270. if( NEVER(pCur->apPage[pCur->iPage]->leaf==0) ) return -1;
  60271. for(n=1, i=0; i<=pCur->iPage; i++){
  60272. n *= pCur->apPage[i]->nCell;
  60273. }
  60274. return n;
  60275. }
  60276. /*
  60277. ** Advance the cursor to the next entry in the database. If
  60278. ** successful then set *pRes=0. If the cursor
  60279. ** was already pointing to the last entry in the database before
  60280. ** this routine was called, then set *pRes=1.
  60281. **
  60282. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  60283. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  60284. ** to the next cell on the current page. The (slower) btreeNext() helper
  60285. ** routine is called when it is necessary to move to a different page or
  60286. ** to restore the cursor.
  60287. **
  60288. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  60289. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  60290. ** if this routine could have been skipped if that SQL index had been
  60291. ** a unique index. Otherwise the caller will have set *pRes to zero.
  60292. ** Zero is the common case. The btree implementation is free to use the
  60293. ** initial *pRes value as a hint to improve performance, but the current
  60294. ** SQLite btree implementation does not. (Note that the comdb2 btree
  60295. ** implementation does use this hint, however.)
  60296. */
  60297. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
  60298. int rc;
  60299. int idx;
  60300. MemPage *pPage;
  60301. assert( cursorOwnsBtShared(pCur) );
  60302. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  60303. assert( *pRes==0 );
  60304. if( pCur->eState!=CURSOR_VALID ){
  60305. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  60306. rc = restoreCursorPosition(pCur);
  60307. if( rc!=SQLITE_OK ){
  60308. return rc;
  60309. }
  60310. if( CURSOR_INVALID==pCur->eState ){
  60311. *pRes = 1;
  60312. return SQLITE_OK;
  60313. }
  60314. if( pCur->skipNext ){
  60315. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  60316. pCur->eState = CURSOR_VALID;
  60317. if( pCur->skipNext>0 ){
  60318. pCur->skipNext = 0;
  60319. return SQLITE_OK;
  60320. }
  60321. pCur->skipNext = 0;
  60322. }
  60323. }
  60324. pPage = pCur->apPage[pCur->iPage];
  60325. idx = ++pCur->ix;
  60326. assert( pPage->isInit );
  60327. /* If the database file is corrupt, it is possible for the value of idx
  60328. ** to be invalid here. This can only occur if a second cursor modifies
  60329. ** the page while cursor pCur is holding a reference to it. Which can
  60330. ** only happen if the database is corrupt in such a way as to link the
  60331. ** page into more than one b-tree structure. */
  60332. testcase( idx>pPage->nCell );
  60333. if( idx>=pPage->nCell ){
  60334. if( !pPage->leaf ){
  60335. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  60336. if( rc ) return rc;
  60337. return moveToLeftmost(pCur);
  60338. }
  60339. do{
  60340. if( pCur->iPage==0 ){
  60341. *pRes = 1;
  60342. pCur->eState = CURSOR_INVALID;
  60343. return SQLITE_OK;
  60344. }
  60345. moveToParent(pCur);
  60346. pPage = pCur->apPage[pCur->iPage];
  60347. }while( pCur->ix>=pPage->nCell );
  60348. if( pPage->intKey ){
  60349. return sqlite3BtreeNext(pCur, pRes);
  60350. }else{
  60351. return SQLITE_OK;
  60352. }
  60353. }
  60354. if( pPage->leaf ){
  60355. return SQLITE_OK;
  60356. }else{
  60357. return moveToLeftmost(pCur);
  60358. }
  60359. }
  60360. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  60361. MemPage *pPage;
  60362. assert( cursorOwnsBtShared(pCur) );
  60363. assert( pRes!=0 );
  60364. assert( *pRes==0 || *pRes==1 );
  60365. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  60366. pCur->info.nSize = 0;
  60367. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  60368. *pRes = 0;
  60369. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
  60370. pPage = pCur->apPage[pCur->iPage];
  60371. if( (++pCur->ix)>=pPage->nCell ){
  60372. pCur->ix--;
  60373. return btreeNext(pCur, pRes);
  60374. }
  60375. if( pPage->leaf ){
  60376. return SQLITE_OK;
  60377. }else{
  60378. return moveToLeftmost(pCur);
  60379. }
  60380. }
  60381. /*
  60382. ** Step the cursor to the back to the previous entry in the database. If
  60383. ** successful then set *pRes=0. If the cursor
  60384. ** was already pointing to the first entry in the database before
  60385. ** this routine was called, then set *pRes=1.
  60386. **
  60387. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  60388. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  60389. ** to the previous cell on the current page. The (slower) btreePrevious()
  60390. ** helper routine is called when it is necessary to move to a different page
  60391. ** or to restore the cursor.
  60392. **
  60393. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  60394. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  60395. ** if this routine could have been skipped if that SQL index had been
  60396. ** a unique index. Otherwise the caller will have set *pRes to zero.
  60397. ** Zero is the common case. The btree implementation is free to use the
  60398. ** initial *pRes value as a hint to improve performance, but the current
  60399. ** SQLite btree implementation does not. (Note that the comdb2 btree
  60400. ** implementation does use this hint, however.)
  60401. */
  60402. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
  60403. int rc;
  60404. MemPage *pPage;
  60405. assert( cursorOwnsBtShared(pCur) );
  60406. assert( pRes!=0 );
  60407. assert( *pRes==0 );
  60408. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  60409. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  60410. assert( pCur->info.nSize==0 );
  60411. if( pCur->eState!=CURSOR_VALID ){
  60412. rc = restoreCursorPosition(pCur);
  60413. if( rc!=SQLITE_OK ){
  60414. return rc;
  60415. }
  60416. if( CURSOR_INVALID==pCur->eState ){
  60417. *pRes = 1;
  60418. return SQLITE_OK;
  60419. }
  60420. if( pCur->skipNext ){
  60421. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  60422. pCur->eState = CURSOR_VALID;
  60423. if( pCur->skipNext<0 ){
  60424. pCur->skipNext = 0;
  60425. return SQLITE_OK;
  60426. }
  60427. pCur->skipNext = 0;
  60428. }
  60429. }
  60430. pPage = pCur->apPage[pCur->iPage];
  60431. assert( pPage->isInit );
  60432. if( !pPage->leaf ){
  60433. int idx = pCur->ix;
  60434. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  60435. if( rc ) return rc;
  60436. rc = moveToRightmost(pCur);
  60437. }else{
  60438. while( pCur->ix==0 ){
  60439. if( pCur->iPage==0 ){
  60440. pCur->eState = CURSOR_INVALID;
  60441. *pRes = 1;
  60442. return SQLITE_OK;
  60443. }
  60444. moveToParent(pCur);
  60445. }
  60446. assert( pCur->info.nSize==0 );
  60447. assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
  60448. pCur->ix--;
  60449. pPage = pCur->apPage[pCur->iPage];
  60450. if( pPage->intKey && !pPage->leaf ){
  60451. rc = sqlite3BtreePrevious(pCur, pRes);
  60452. }else{
  60453. rc = SQLITE_OK;
  60454. }
  60455. }
  60456. return rc;
  60457. }
  60458. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  60459. assert( cursorOwnsBtShared(pCur) );
  60460. assert( pRes!=0 );
  60461. assert( *pRes==0 || *pRes==1 );
  60462. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  60463. *pRes = 0;
  60464. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  60465. pCur->info.nSize = 0;
  60466. if( pCur->eState!=CURSOR_VALID
  60467. || pCur->ix==0
  60468. || pCur->apPage[pCur->iPage]->leaf==0
  60469. ){
  60470. return btreePrevious(pCur, pRes);
  60471. }
  60472. pCur->ix--;
  60473. return SQLITE_OK;
  60474. }
  60475. /*
  60476. ** Allocate a new page from the database file.
  60477. **
  60478. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  60479. ** has already been called on the new page.) The new page has also
  60480. ** been referenced and the calling routine is responsible for calling
  60481. ** sqlite3PagerUnref() on the new page when it is done.
  60482. **
  60483. ** SQLITE_OK is returned on success. Any other return value indicates
  60484. ** an error. *ppPage is set to NULL in the event of an error.
  60485. **
  60486. ** If the "nearby" parameter is not 0, then an effort is made to
  60487. ** locate a page close to the page number "nearby". This can be used in an
  60488. ** attempt to keep related pages close to each other in the database file,
  60489. ** which in turn can make database access faster.
  60490. **
  60491. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  60492. ** anywhere on the free-list, then it is guaranteed to be returned. If
  60493. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  60494. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  60495. ** are no restrictions on which page is returned.
  60496. */
  60497. static int allocateBtreePage(
  60498. BtShared *pBt, /* The btree */
  60499. MemPage **ppPage, /* Store pointer to the allocated page here */
  60500. Pgno *pPgno, /* Store the page number here */
  60501. Pgno nearby, /* Search for a page near this one */
  60502. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  60503. ){
  60504. MemPage *pPage1;
  60505. int rc;
  60506. u32 n; /* Number of pages on the freelist */
  60507. u32 k; /* Number of leaves on the trunk of the freelist */
  60508. MemPage *pTrunk = 0;
  60509. MemPage *pPrevTrunk = 0;
  60510. Pgno mxPage; /* Total size of the database file */
  60511. assert( sqlite3_mutex_held(pBt->mutex) );
  60512. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  60513. pPage1 = pBt->pPage1;
  60514. mxPage = btreePagecount(pBt);
  60515. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  60516. ** stores stores the total number of pages on the freelist. */
  60517. n = get4byte(&pPage1->aData[36]);
  60518. testcase( n==mxPage-1 );
  60519. if( n>=mxPage ){
  60520. return SQLITE_CORRUPT_BKPT;
  60521. }
  60522. if( n>0 ){
  60523. /* There are pages on the freelist. Reuse one of those pages. */
  60524. Pgno iTrunk;
  60525. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  60526. u32 nSearch = 0; /* Count of the number of search attempts */
  60527. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  60528. ** shows that the page 'nearby' is somewhere on the free-list, then
  60529. ** the entire-list will be searched for that page.
  60530. */
  60531. #ifndef SQLITE_OMIT_AUTOVACUUM
  60532. if( eMode==BTALLOC_EXACT ){
  60533. if( nearby<=mxPage ){
  60534. u8 eType;
  60535. assert( nearby>0 );
  60536. assert( pBt->autoVacuum );
  60537. rc = ptrmapGet(pBt, nearby, &eType, 0);
  60538. if( rc ) return rc;
  60539. if( eType==PTRMAP_FREEPAGE ){
  60540. searchList = 1;
  60541. }
  60542. }
  60543. }else if( eMode==BTALLOC_LE ){
  60544. searchList = 1;
  60545. }
  60546. #endif
  60547. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  60548. ** first free-list trunk page. iPrevTrunk is initially 1.
  60549. */
  60550. rc = sqlite3PagerWrite(pPage1->pDbPage);
  60551. if( rc ) return rc;
  60552. put4byte(&pPage1->aData[36], n-1);
  60553. /* The code within this loop is run only once if the 'searchList' variable
  60554. ** is not true. Otherwise, it runs once for each trunk-page on the
  60555. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  60556. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  60557. */
  60558. do {
  60559. pPrevTrunk = pTrunk;
  60560. if( pPrevTrunk ){
  60561. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  60562. ** is the page number of the next freelist trunk page in the list or
  60563. ** zero if this is the last freelist trunk page. */
  60564. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  60565. }else{
  60566. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  60567. ** stores the page number of the first page of the freelist, or zero if
  60568. ** the freelist is empty. */
  60569. iTrunk = get4byte(&pPage1->aData[32]);
  60570. }
  60571. testcase( iTrunk==mxPage );
  60572. if( iTrunk>mxPage || nSearch++ > n ){
  60573. rc = SQLITE_CORRUPT_BKPT;
  60574. }else{
  60575. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  60576. }
  60577. if( rc ){
  60578. pTrunk = 0;
  60579. goto end_allocate_page;
  60580. }
  60581. assert( pTrunk!=0 );
  60582. assert( pTrunk->aData!=0 );
  60583. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  60584. ** is the number of leaf page pointers to follow. */
  60585. k = get4byte(&pTrunk->aData[4]);
  60586. if( k==0 && !searchList ){
  60587. /* The trunk has no leaves and the list is not being searched.
  60588. ** So extract the trunk page itself and use it as the newly
  60589. ** allocated page */
  60590. assert( pPrevTrunk==0 );
  60591. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  60592. if( rc ){
  60593. goto end_allocate_page;
  60594. }
  60595. *pPgno = iTrunk;
  60596. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  60597. *ppPage = pTrunk;
  60598. pTrunk = 0;
  60599. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  60600. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  60601. /* Value of k is out of range. Database corruption */
  60602. rc = SQLITE_CORRUPT_BKPT;
  60603. goto end_allocate_page;
  60604. #ifndef SQLITE_OMIT_AUTOVACUUM
  60605. }else if( searchList
  60606. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  60607. ){
  60608. /* The list is being searched and this trunk page is the page
  60609. ** to allocate, regardless of whether it has leaves.
  60610. */
  60611. *pPgno = iTrunk;
  60612. *ppPage = pTrunk;
  60613. searchList = 0;
  60614. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  60615. if( rc ){
  60616. goto end_allocate_page;
  60617. }
  60618. if( k==0 ){
  60619. if( !pPrevTrunk ){
  60620. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  60621. }else{
  60622. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  60623. if( rc!=SQLITE_OK ){
  60624. goto end_allocate_page;
  60625. }
  60626. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  60627. }
  60628. }else{
  60629. /* The trunk page is required by the caller but it contains
  60630. ** pointers to free-list leaves. The first leaf becomes a trunk
  60631. ** page in this case.
  60632. */
  60633. MemPage *pNewTrunk;
  60634. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  60635. if( iNewTrunk>mxPage ){
  60636. rc = SQLITE_CORRUPT_BKPT;
  60637. goto end_allocate_page;
  60638. }
  60639. testcase( iNewTrunk==mxPage );
  60640. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  60641. if( rc!=SQLITE_OK ){
  60642. goto end_allocate_page;
  60643. }
  60644. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  60645. if( rc!=SQLITE_OK ){
  60646. releasePage(pNewTrunk);
  60647. goto end_allocate_page;
  60648. }
  60649. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  60650. put4byte(&pNewTrunk->aData[4], k-1);
  60651. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  60652. releasePage(pNewTrunk);
  60653. if( !pPrevTrunk ){
  60654. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  60655. put4byte(&pPage1->aData[32], iNewTrunk);
  60656. }else{
  60657. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  60658. if( rc ){
  60659. goto end_allocate_page;
  60660. }
  60661. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  60662. }
  60663. }
  60664. pTrunk = 0;
  60665. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  60666. #endif
  60667. }else if( k>0 ){
  60668. /* Extract a leaf from the trunk */
  60669. u32 closest;
  60670. Pgno iPage;
  60671. unsigned char *aData = pTrunk->aData;
  60672. if( nearby>0 ){
  60673. u32 i;
  60674. closest = 0;
  60675. if( eMode==BTALLOC_LE ){
  60676. for(i=0; i<k; i++){
  60677. iPage = get4byte(&aData[8+i*4]);
  60678. if( iPage<=nearby ){
  60679. closest = i;
  60680. break;
  60681. }
  60682. }
  60683. }else{
  60684. int dist;
  60685. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  60686. for(i=1; i<k; i++){
  60687. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  60688. if( d2<dist ){
  60689. closest = i;
  60690. dist = d2;
  60691. }
  60692. }
  60693. }
  60694. }else{
  60695. closest = 0;
  60696. }
  60697. iPage = get4byte(&aData[8+closest*4]);
  60698. testcase( iPage==mxPage );
  60699. if( iPage>mxPage ){
  60700. rc = SQLITE_CORRUPT_BKPT;
  60701. goto end_allocate_page;
  60702. }
  60703. testcase( iPage==mxPage );
  60704. if( !searchList
  60705. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  60706. ){
  60707. int noContent;
  60708. *pPgno = iPage;
  60709. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  60710. ": %d more free pages\n",
  60711. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  60712. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  60713. if( rc ) goto end_allocate_page;
  60714. if( closest<k-1 ){
  60715. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  60716. }
  60717. put4byte(&aData[4], k-1);
  60718. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  60719. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  60720. if( rc==SQLITE_OK ){
  60721. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  60722. if( rc!=SQLITE_OK ){
  60723. releasePage(*ppPage);
  60724. *ppPage = 0;
  60725. }
  60726. }
  60727. searchList = 0;
  60728. }
  60729. }
  60730. releasePage(pPrevTrunk);
  60731. pPrevTrunk = 0;
  60732. }while( searchList );
  60733. }else{
  60734. /* There are no pages on the freelist, so append a new page to the
  60735. ** database image.
  60736. **
  60737. ** Normally, new pages allocated by this block can be requested from the
  60738. ** pager layer with the 'no-content' flag set. This prevents the pager
  60739. ** from trying to read the pages content from disk. However, if the
  60740. ** current transaction has already run one or more incremental-vacuum
  60741. ** steps, then the page we are about to allocate may contain content
  60742. ** that is required in the event of a rollback. In this case, do
  60743. ** not set the no-content flag. This causes the pager to load and journal
  60744. ** the current page content before overwriting it.
  60745. **
  60746. ** Note that the pager will not actually attempt to load or journal
  60747. ** content for any page that really does lie past the end of the database
  60748. ** file on disk. So the effects of disabling the no-content optimization
  60749. ** here are confined to those pages that lie between the end of the
  60750. ** database image and the end of the database file.
  60751. */
  60752. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  60753. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  60754. if( rc ) return rc;
  60755. pBt->nPage++;
  60756. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  60757. #ifndef SQLITE_OMIT_AUTOVACUUM
  60758. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  60759. /* If *pPgno refers to a pointer-map page, allocate two new pages
  60760. ** at the end of the file instead of one. The first allocated page
  60761. ** becomes a new pointer-map page, the second is used by the caller.
  60762. */
  60763. MemPage *pPg = 0;
  60764. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  60765. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  60766. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  60767. if( rc==SQLITE_OK ){
  60768. rc = sqlite3PagerWrite(pPg->pDbPage);
  60769. releasePage(pPg);
  60770. }
  60771. if( rc ) return rc;
  60772. pBt->nPage++;
  60773. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  60774. }
  60775. #endif
  60776. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  60777. *pPgno = pBt->nPage;
  60778. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  60779. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  60780. if( rc ) return rc;
  60781. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  60782. if( rc!=SQLITE_OK ){
  60783. releasePage(*ppPage);
  60784. *ppPage = 0;
  60785. }
  60786. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  60787. }
  60788. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  60789. end_allocate_page:
  60790. releasePage(pTrunk);
  60791. releasePage(pPrevTrunk);
  60792. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  60793. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  60794. return rc;
  60795. }
  60796. /*
  60797. ** This function is used to add page iPage to the database file free-list.
  60798. ** It is assumed that the page is not already a part of the free-list.
  60799. **
  60800. ** The value passed as the second argument to this function is optional.
  60801. ** If the caller happens to have a pointer to the MemPage object
  60802. ** corresponding to page iPage handy, it may pass it as the second value.
  60803. ** Otherwise, it may pass NULL.
  60804. **
  60805. ** If a pointer to a MemPage object is passed as the second argument,
  60806. ** its reference count is not altered by this function.
  60807. */
  60808. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  60809. MemPage *pTrunk = 0; /* Free-list trunk page */
  60810. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  60811. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  60812. MemPage *pPage; /* Page being freed. May be NULL. */
  60813. int rc; /* Return Code */
  60814. int nFree; /* Initial number of pages on free-list */
  60815. assert( sqlite3_mutex_held(pBt->mutex) );
  60816. assert( CORRUPT_DB || iPage>1 );
  60817. assert( !pMemPage || pMemPage->pgno==iPage );
  60818. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  60819. if( pMemPage ){
  60820. pPage = pMemPage;
  60821. sqlite3PagerRef(pPage->pDbPage);
  60822. }else{
  60823. pPage = btreePageLookup(pBt, iPage);
  60824. }
  60825. /* Increment the free page count on pPage1 */
  60826. rc = sqlite3PagerWrite(pPage1->pDbPage);
  60827. if( rc ) goto freepage_out;
  60828. nFree = get4byte(&pPage1->aData[36]);
  60829. put4byte(&pPage1->aData[36], nFree+1);
  60830. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  60831. /* If the secure_delete option is enabled, then
  60832. ** always fully overwrite deleted information with zeros.
  60833. */
  60834. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  60835. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  60836. ){
  60837. goto freepage_out;
  60838. }
  60839. memset(pPage->aData, 0, pPage->pBt->pageSize);
  60840. }
  60841. /* If the database supports auto-vacuum, write an entry in the pointer-map
  60842. ** to indicate that the page is free.
  60843. */
  60844. if( ISAUTOVACUUM ){
  60845. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  60846. if( rc ) goto freepage_out;
  60847. }
  60848. /* Now manipulate the actual database free-list structure. There are two
  60849. ** possibilities. If the free-list is currently empty, or if the first
  60850. ** trunk page in the free-list is full, then this page will become a
  60851. ** new free-list trunk page. Otherwise, it will become a leaf of the
  60852. ** first trunk page in the current free-list. This block tests if it
  60853. ** is possible to add the page as a new free-list leaf.
  60854. */
  60855. if( nFree!=0 ){
  60856. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  60857. iTrunk = get4byte(&pPage1->aData[32]);
  60858. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  60859. if( rc!=SQLITE_OK ){
  60860. goto freepage_out;
  60861. }
  60862. nLeaf = get4byte(&pTrunk->aData[4]);
  60863. assert( pBt->usableSize>32 );
  60864. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  60865. rc = SQLITE_CORRUPT_BKPT;
  60866. goto freepage_out;
  60867. }
  60868. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  60869. /* In this case there is room on the trunk page to insert the page
  60870. ** being freed as a new leaf.
  60871. **
  60872. ** Note that the trunk page is not really full until it contains
  60873. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  60874. ** coded. But due to a coding error in versions of SQLite prior to
  60875. ** 3.6.0, databases with freelist trunk pages holding more than
  60876. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  60877. ** to maintain backwards compatibility with older versions of SQLite,
  60878. ** we will continue to restrict the number of entries to usableSize/4 - 8
  60879. ** for now. At some point in the future (once everyone has upgraded
  60880. ** to 3.6.0 or later) we should consider fixing the conditional above
  60881. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  60882. **
  60883. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  60884. ** avoid using the last six entries in the freelist trunk page array in
  60885. ** order that database files created by newer versions of SQLite can be
  60886. ** read by older versions of SQLite.
  60887. */
  60888. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  60889. if( rc==SQLITE_OK ){
  60890. put4byte(&pTrunk->aData[4], nLeaf+1);
  60891. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  60892. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  60893. sqlite3PagerDontWrite(pPage->pDbPage);
  60894. }
  60895. rc = btreeSetHasContent(pBt, iPage);
  60896. }
  60897. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  60898. goto freepage_out;
  60899. }
  60900. }
  60901. /* If control flows to this point, then it was not possible to add the
  60902. ** the page being freed as a leaf page of the first trunk in the free-list.
  60903. ** Possibly because the free-list is empty, or possibly because the
  60904. ** first trunk in the free-list is full. Either way, the page being freed
  60905. ** will become the new first trunk page in the free-list.
  60906. */
  60907. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  60908. goto freepage_out;
  60909. }
  60910. rc = sqlite3PagerWrite(pPage->pDbPage);
  60911. if( rc!=SQLITE_OK ){
  60912. goto freepage_out;
  60913. }
  60914. put4byte(pPage->aData, iTrunk);
  60915. put4byte(&pPage->aData[4], 0);
  60916. put4byte(&pPage1->aData[32], iPage);
  60917. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  60918. freepage_out:
  60919. if( pPage ){
  60920. pPage->isInit = 0;
  60921. }
  60922. releasePage(pPage);
  60923. releasePage(pTrunk);
  60924. return rc;
  60925. }
  60926. static void freePage(MemPage *pPage, int *pRC){
  60927. if( (*pRC)==SQLITE_OK ){
  60928. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  60929. }
  60930. }
  60931. /*
  60932. ** Free any overflow pages associated with the given Cell. Write the
  60933. ** local Cell size (the number of bytes on the original page, omitting
  60934. ** overflow) into *pnSize.
  60935. */
  60936. static int clearCell(
  60937. MemPage *pPage, /* The page that contains the Cell */
  60938. unsigned char *pCell, /* First byte of the Cell */
  60939. CellInfo *pInfo /* Size information about the cell */
  60940. ){
  60941. BtShared *pBt = pPage->pBt;
  60942. Pgno ovflPgno;
  60943. int rc;
  60944. int nOvfl;
  60945. u32 ovflPageSize;
  60946. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60947. pPage->xParseCell(pPage, pCell, pInfo);
  60948. if( pInfo->nLocal==pInfo->nPayload ){
  60949. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  60950. }
  60951. if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
  60952. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  60953. }
  60954. ovflPgno = get4byte(pCell + pInfo->nSize - 4);
  60955. assert( pBt->usableSize > 4 );
  60956. ovflPageSize = pBt->usableSize - 4;
  60957. nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
  60958. assert( nOvfl>0 ||
  60959. (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
  60960. );
  60961. while( nOvfl-- ){
  60962. Pgno iNext = 0;
  60963. MemPage *pOvfl = 0;
  60964. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  60965. /* 0 is not a legal page number and page 1 cannot be an
  60966. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  60967. ** file the database must be corrupt. */
  60968. return SQLITE_CORRUPT_BKPT;
  60969. }
  60970. if( nOvfl ){
  60971. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  60972. if( rc ) return rc;
  60973. }
  60974. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  60975. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  60976. ){
  60977. /* There is no reason any cursor should have an outstanding reference
  60978. ** to an overflow page belonging to a cell that is being deleted/updated.
  60979. ** So if there exists more than one reference to this page, then it
  60980. ** must not really be an overflow page and the database must be corrupt.
  60981. ** It is helpful to detect this before calling freePage2(), as
  60982. ** freePage2() may zero the page contents if secure-delete mode is
  60983. ** enabled. If this 'overflow' page happens to be a page that the
  60984. ** caller is iterating through or using in some other way, this
  60985. ** can be problematic.
  60986. */
  60987. rc = SQLITE_CORRUPT_BKPT;
  60988. }else{
  60989. rc = freePage2(pBt, pOvfl, ovflPgno);
  60990. }
  60991. if( pOvfl ){
  60992. sqlite3PagerUnref(pOvfl->pDbPage);
  60993. }
  60994. if( rc ) return rc;
  60995. ovflPgno = iNext;
  60996. }
  60997. return SQLITE_OK;
  60998. }
  60999. /*
  61000. ** Create the byte sequence used to represent a cell on page pPage
  61001. ** and write that byte sequence into pCell[]. Overflow pages are
  61002. ** allocated and filled in as necessary. The calling procedure
  61003. ** is responsible for making sure sufficient space has been allocated
  61004. ** for pCell[].
  61005. **
  61006. ** Note that pCell does not necessary need to point to the pPage->aData
  61007. ** area. pCell might point to some temporary storage. The cell will
  61008. ** be constructed in this temporary area then copied into pPage->aData
  61009. ** later.
  61010. */
  61011. static int fillInCell(
  61012. MemPage *pPage, /* The page that contains the cell */
  61013. unsigned char *pCell, /* Complete text of the cell */
  61014. const BtreePayload *pX, /* Payload with which to construct the cell */
  61015. int *pnSize /* Write cell size here */
  61016. ){
  61017. int nPayload;
  61018. const u8 *pSrc;
  61019. int nSrc, n, rc;
  61020. int spaceLeft;
  61021. MemPage *pOvfl = 0;
  61022. MemPage *pToRelease = 0;
  61023. unsigned char *pPrior;
  61024. unsigned char *pPayload;
  61025. BtShared *pBt = pPage->pBt;
  61026. Pgno pgnoOvfl = 0;
  61027. int nHeader;
  61028. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61029. /* pPage is not necessarily writeable since pCell might be auxiliary
  61030. ** buffer space that is separate from the pPage buffer area */
  61031. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  61032. || sqlite3PagerIswriteable(pPage->pDbPage) );
  61033. /* Fill in the header. */
  61034. nHeader = pPage->childPtrSize;
  61035. if( pPage->intKey ){
  61036. nPayload = pX->nData + pX->nZero;
  61037. pSrc = pX->pData;
  61038. nSrc = pX->nData;
  61039. assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
  61040. nHeader += putVarint32(&pCell[nHeader], nPayload);
  61041. nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
  61042. }else{
  61043. assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
  61044. nSrc = nPayload = (int)pX->nKey;
  61045. pSrc = pX->pKey;
  61046. nHeader += putVarint32(&pCell[nHeader], nPayload);
  61047. }
  61048. /* Fill in the payload */
  61049. if( nPayload<=pPage->maxLocal ){
  61050. n = nHeader + nPayload;
  61051. testcase( n==3 );
  61052. testcase( n==4 );
  61053. if( n<4 ) n = 4;
  61054. *pnSize = n;
  61055. spaceLeft = nPayload;
  61056. pPrior = pCell;
  61057. }else{
  61058. int mn = pPage->minLocal;
  61059. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  61060. testcase( n==pPage->maxLocal );
  61061. testcase( n==pPage->maxLocal+1 );
  61062. if( n > pPage->maxLocal ) n = mn;
  61063. spaceLeft = n;
  61064. *pnSize = n + nHeader + 4;
  61065. pPrior = &pCell[nHeader+n];
  61066. }
  61067. pPayload = &pCell[nHeader];
  61068. /* At this point variables should be set as follows:
  61069. **
  61070. ** nPayload Total payload size in bytes
  61071. ** pPayload Begin writing payload here
  61072. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  61073. ** that means content must spill into overflow pages.
  61074. ** *pnSize Size of the local cell (not counting overflow pages)
  61075. ** pPrior Where to write the pgno of the first overflow page
  61076. **
  61077. ** Use a call to btreeParseCellPtr() to verify that the values above
  61078. ** were computed correctly.
  61079. */
  61080. #ifdef SQLITE_DEBUG
  61081. {
  61082. CellInfo info;
  61083. pPage->xParseCell(pPage, pCell, &info);
  61084. assert( nHeader==(int)(info.pPayload - pCell) );
  61085. assert( info.nKey==pX->nKey );
  61086. assert( *pnSize == info.nSize );
  61087. assert( spaceLeft == info.nLocal );
  61088. }
  61089. #endif
  61090. /* Write the payload into the local Cell and any extra into overflow pages */
  61091. while( nPayload>0 ){
  61092. if( spaceLeft==0 ){
  61093. #ifndef SQLITE_OMIT_AUTOVACUUM
  61094. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  61095. if( pBt->autoVacuum ){
  61096. do{
  61097. pgnoOvfl++;
  61098. } while(
  61099. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  61100. );
  61101. }
  61102. #endif
  61103. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  61104. #ifndef SQLITE_OMIT_AUTOVACUUM
  61105. /* If the database supports auto-vacuum, and the second or subsequent
  61106. ** overflow page is being allocated, add an entry to the pointer-map
  61107. ** for that page now.
  61108. **
  61109. ** If this is the first overflow page, then write a partial entry
  61110. ** to the pointer-map. If we write nothing to this pointer-map slot,
  61111. ** then the optimistic overflow chain processing in clearCell()
  61112. ** may misinterpret the uninitialized values and delete the
  61113. ** wrong pages from the database.
  61114. */
  61115. if( pBt->autoVacuum && rc==SQLITE_OK ){
  61116. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  61117. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  61118. if( rc ){
  61119. releasePage(pOvfl);
  61120. }
  61121. }
  61122. #endif
  61123. if( rc ){
  61124. releasePage(pToRelease);
  61125. return rc;
  61126. }
  61127. /* If pToRelease is not zero than pPrior points into the data area
  61128. ** of pToRelease. Make sure pToRelease is still writeable. */
  61129. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  61130. /* If pPrior is part of the data area of pPage, then make sure pPage
  61131. ** is still writeable */
  61132. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  61133. || sqlite3PagerIswriteable(pPage->pDbPage) );
  61134. put4byte(pPrior, pgnoOvfl);
  61135. releasePage(pToRelease);
  61136. pToRelease = pOvfl;
  61137. pPrior = pOvfl->aData;
  61138. put4byte(pPrior, 0);
  61139. pPayload = &pOvfl->aData[4];
  61140. spaceLeft = pBt->usableSize - 4;
  61141. }
  61142. n = nPayload;
  61143. if( n>spaceLeft ) n = spaceLeft;
  61144. /* If pToRelease is not zero than pPayload points into the data area
  61145. ** of pToRelease. Make sure pToRelease is still writeable. */
  61146. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  61147. /* If pPayload is part of the data area of pPage, then make sure pPage
  61148. ** is still writeable */
  61149. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  61150. || sqlite3PagerIswriteable(pPage->pDbPage) );
  61151. if( nSrc>0 ){
  61152. if( n>nSrc ) n = nSrc;
  61153. assert( pSrc );
  61154. memcpy(pPayload, pSrc, n);
  61155. }else{
  61156. memset(pPayload, 0, n);
  61157. }
  61158. nPayload -= n;
  61159. pPayload += n;
  61160. pSrc += n;
  61161. nSrc -= n;
  61162. spaceLeft -= n;
  61163. }
  61164. releasePage(pToRelease);
  61165. return SQLITE_OK;
  61166. }
  61167. /*
  61168. ** Remove the i-th cell from pPage. This routine effects pPage only.
  61169. ** The cell content is not freed or deallocated. It is assumed that
  61170. ** the cell content has been copied someplace else. This routine just
  61171. ** removes the reference to the cell from pPage.
  61172. **
  61173. ** "sz" must be the number of bytes in the cell.
  61174. */
  61175. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  61176. u32 pc; /* Offset to cell content of cell being deleted */
  61177. u8 *data; /* pPage->aData */
  61178. u8 *ptr; /* Used to move bytes around within data[] */
  61179. int rc; /* The return code */
  61180. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  61181. if( *pRC ) return;
  61182. assert( idx>=0 && idx<pPage->nCell );
  61183. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  61184. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61185. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61186. data = pPage->aData;
  61187. ptr = &pPage->aCellIdx[2*idx];
  61188. pc = get2byte(ptr);
  61189. hdr = pPage->hdrOffset;
  61190. testcase( pc==get2byte(&data[hdr+5]) );
  61191. testcase( pc+sz==pPage->pBt->usableSize );
  61192. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  61193. *pRC = SQLITE_CORRUPT_BKPT;
  61194. return;
  61195. }
  61196. rc = freeSpace(pPage, pc, sz);
  61197. if( rc ){
  61198. *pRC = rc;
  61199. return;
  61200. }
  61201. pPage->nCell--;
  61202. if( pPage->nCell==0 ){
  61203. memset(&data[hdr+1], 0, 4);
  61204. data[hdr+7] = 0;
  61205. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  61206. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  61207. - pPage->childPtrSize - 8;
  61208. }else{
  61209. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  61210. put2byte(&data[hdr+3], pPage->nCell);
  61211. pPage->nFree += 2;
  61212. }
  61213. }
  61214. /*
  61215. ** Insert a new cell on pPage at cell index "i". pCell points to the
  61216. ** content of the cell.
  61217. **
  61218. ** If the cell content will fit on the page, then put it there. If it
  61219. ** will not fit, then make a copy of the cell content into pTemp if
  61220. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  61221. ** in pPage->apOvfl[] and make it point to the cell content (either
  61222. ** in pTemp or the original pCell) and also record its index.
  61223. ** Allocating a new entry in pPage->aCell[] implies that
  61224. ** pPage->nOverflow is incremented.
  61225. **
  61226. ** *pRC must be SQLITE_OK when this routine is called.
  61227. */
  61228. static void insertCell(
  61229. MemPage *pPage, /* Page into which we are copying */
  61230. int i, /* New cell becomes the i-th cell of the page */
  61231. u8 *pCell, /* Content of the new cell */
  61232. int sz, /* Bytes of content in pCell */
  61233. u8 *pTemp, /* Temp storage space for pCell, if needed */
  61234. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  61235. int *pRC /* Read and write return code from here */
  61236. ){
  61237. int idx = 0; /* Where to write new cell content in data[] */
  61238. int j; /* Loop counter */
  61239. u8 *data; /* The content of the whole page */
  61240. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  61241. assert( *pRC==SQLITE_OK );
  61242. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  61243. assert( MX_CELL(pPage->pBt)<=10921 );
  61244. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  61245. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  61246. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  61247. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61248. /* The cell should normally be sized correctly. However, when moving a
  61249. ** malformed cell from a leaf page to an interior page, if the cell size
  61250. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  61251. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  61252. ** the term after the || in the following assert(). */
  61253. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  61254. if( pPage->nOverflow || sz+2>pPage->nFree ){
  61255. if( pTemp ){
  61256. memcpy(pTemp, pCell, sz);
  61257. pCell = pTemp;
  61258. }
  61259. if( iChild ){
  61260. put4byte(pCell, iChild);
  61261. }
  61262. j = pPage->nOverflow++;
  61263. /* Comparison against ArraySize-1 since we hold back one extra slot
  61264. ** as a contingency. In other words, never need more than 3 overflow
  61265. ** slots but 4 are allocated, just to be safe. */
  61266. assert( j < ArraySize(pPage->apOvfl)-1 );
  61267. pPage->apOvfl[j] = pCell;
  61268. pPage->aiOvfl[j] = (u16)i;
  61269. /* When multiple overflows occur, they are always sequential and in
  61270. ** sorted order. This invariants arise because multiple overflows can
  61271. ** only occur when inserting divider cells into the parent page during
  61272. ** balancing, and the dividers are adjacent and sorted.
  61273. */
  61274. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  61275. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  61276. }else{
  61277. int rc = sqlite3PagerWrite(pPage->pDbPage);
  61278. if( rc!=SQLITE_OK ){
  61279. *pRC = rc;
  61280. return;
  61281. }
  61282. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61283. data = pPage->aData;
  61284. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  61285. rc = allocateSpace(pPage, sz, &idx);
  61286. if( rc ){ *pRC = rc; return; }
  61287. /* The allocateSpace() routine guarantees the following properties
  61288. ** if it returns successfully */
  61289. assert( idx >= 0 );
  61290. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  61291. assert( idx+sz <= (int)pPage->pBt->usableSize );
  61292. pPage->nFree -= (u16)(2 + sz);
  61293. memcpy(&data[idx], pCell, sz);
  61294. if( iChild ){
  61295. put4byte(&data[idx], iChild);
  61296. }
  61297. pIns = pPage->aCellIdx + i*2;
  61298. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  61299. put2byte(pIns, idx);
  61300. pPage->nCell++;
  61301. /* increment the cell count */
  61302. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  61303. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  61304. #ifndef SQLITE_OMIT_AUTOVACUUM
  61305. if( pPage->pBt->autoVacuum ){
  61306. /* The cell may contain a pointer to an overflow page. If so, write
  61307. ** the entry for the overflow page into the pointer map.
  61308. */
  61309. ptrmapPutOvflPtr(pPage, pCell, pRC);
  61310. }
  61311. #endif
  61312. }
  61313. }
  61314. /*
  61315. ** A CellArray object contains a cache of pointers and sizes for a
  61316. ** consecutive sequence of cells that might be held on multiple pages.
  61317. */
  61318. typedef struct CellArray CellArray;
  61319. struct CellArray {
  61320. int nCell; /* Number of cells in apCell[] */
  61321. MemPage *pRef; /* Reference page */
  61322. u8 **apCell; /* All cells begin balanced */
  61323. u16 *szCell; /* Local size of all cells in apCell[] */
  61324. };
  61325. /*
  61326. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  61327. ** computed.
  61328. */
  61329. static void populateCellCache(CellArray *p, int idx, int N){
  61330. assert( idx>=0 && idx+N<=p->nCell );
  61331. while( N>0 ){
  61332. assert( p->apCell[idx]!=0 );
  61333. if( p->szCell[idx]==0 ){
  61334. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  61335. }else{
  61336. assert( CORRUPT_DB ||
  61337. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  61338. }
  61339. idx++;
  61340. N--;
  61341. }
  61342. }
  61343. /*
  61344. ** Return the size of the Nth element of the cell array
  61345. */
  61346. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  61347. assert( N>=0 && N<p->nCell );
  61348. assert( p->szCell[N]==0 );
  61349. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  61350. return p->szCell[N];
  61351. }
  61352. static u16 cachedCellSize(CellArray *p, int N){
  61353. assert( N>=0 && N<p->nCell );
  61354. if( p->szCell[N] ) return p->szCell[N];
  61355. return computeCellSize(p, N);
  61356. }
  61357. /*
  61358. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  61359. ** szCell[] array contains the size in bytes of each cell. This function
  61360. ** replaces the current contents of page pPg with the contents of the cell
  61361. ** array.
  61362. **
  61363. ** Some of the cells in apCell[] may currently be stored in pPg. This
  61364. ** function works around problems caused by this by making a copy of any
  61365. ** such cells before overwriting the page data.
  61366. **
  61367. ** The MemPage.nFree field is invalidated by this function. It is the
  61368. ** responsibility of the caller to set it correctly.
  61369. */
  61370. static int rebuildPage(
  61371. MemPage *pPg, /* Edit this page */
  61372. int nCell, /* Final number of cells on page */
  61373. u8 **apCell, /* Array of cells */
  61374. u16 *szCell /* Array of cell sizes */
  61375. ){
  61376. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  61377. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  61378. const int usableSize = pPg->pBt->usableSize;
  61379. u8 * const pEnd = &aData[usableSize];
  61380. int i;
  61381. u8 *pCellptr = pPg->aCellIdx;
  61382. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  61383. u8 *pData;
  61384. i = get2byte(&aData[hdr+5]);
  61385. memcpy(&pTmp[i], &aData[i], usableSize - i);
  61386. pData = pEnd;
  61387. for(i=0; i<nCell; i++){
  61388. u8 *pCell = apCell[i];
  61389. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  61390. pCell = &pTmp[pCell - aData];
  61391. }
  61392. pData -= szCell[i];
  61393. put2byte(pCellptr, (pData - aData));
  61394. pCellptr += 2;
  61395. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  61396. memcpy(pData, pCell, szCell[i]);
  61397. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  61398. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  61399. }
  61400. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  61401. pPg->nCell = nCell;
  61402. pPg->nOverflow = 0;
  61403. put2byte(&aData[hdr+1], 0);
  61404. put2byte(&aData[hdr+3], pPg->nCell);
  61405. put2byte(&aData[hdr+5], pData - aData);
  61406. aData[hdr+7] = 0x00;
  61407. return SQLITE_OK;
  61408. }
  61409. /*
  61410. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  61411. ** contains the size in bytes of each such cell. This function attempts to
  61412. ** add the cells stored in the array to page pPg. If it cannot (because
  61413. ** the page needs to be defragmented before the cells will fit), non-zero
  61414. ** is returned. Otherwise, if the cells are added successfully, zero is
  61415. ** returned.
  61416. **
  61417. ** Argument pCellptr points to the first entry in the cell-pointer array
  61418. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  61419. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  61420. ** cell in the array. It is the responsibility of the caller to ensure
  61421. ** that it is safe to overwrite this part of the cell-pointer array.
  61422. **
  61423. ** When this function is called, *ppData points to the start of the
  61424. ** content area on page pPg. If the size of the content area is extended,
  61425. ** *ppData is updated to point to the new start of the content area
  61426. ** before returning.
  61427. **
  61428. ** Finally, argument pBegin points to the byte immediately following the
  61429. ** end of the space required by this page for the cell-pointer area (for
  61430. ** all cells - not just those inserted by the current call). If the content
  61431. ** area must be extended to before this point in order to accomodate all
  61432. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  61433. */
  61434. static int pageInsertArray(
  61435. MemPage *pPg, /* Page to add cells to */
  61436. u8 *pBegin, /* End of cell-pointer array */
  61437. u8 **ppData, /* IN/OUT: Page content -area pointer */
  61438. u8 *pCellptr, /* Pointer to cell-pointer area */
  61439. int iFirst, /* Index of first cell to add */
  61440. int nCell, /* Number of cells to add to pPg */
  61441. CellArray *pCArray /* Array of cells */
  61442. ){
  61443. int i;
  61444. u8 *aData = pPg->aData;
  61445. u8 *pData = *ppData;
  61446. int iEnd = iFirst + nCell;
  61447. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  61448. for(i=iFirst; i<iEnd; i++){
  61449. int sz, rc;
  61450. u8 *pSlot;
  61451. sz = cachedCellSize(pCArray, i);
  61452. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  61453. if( (pData - pBegin)<sz ) return 1;
  61454. pData -= sz;
  61455. pSlot = pData;
  61456. }
  61457. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  61458. ** database. But they might for a corrupt database. Hence use memmove()
  61459. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  61460. assert( (pSlot+sz)<=pCArray->apCell[i]
  61461. || pSlot>=(pCArray->apCell[i]+sz)
  61462. || CORRUPT_DB );
  61463. memmove(pSlot, pCArray->apCell[i], sz);
  61464. put2byte(pCellptr, (pSlot - aData));
  61465. pCellptr += 2;
  61466. }
  61467. *ppData = pData;
  61468. return 0;
  61469. }
  61470. /*
  61471. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  61472. ** contains the size in bytes of each such cell. This function adds the
  61473. ** space associated with each cell in the array that is currently stored
  61474. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  61475. ** fields of the page are not updated.
  61476. **
  61477. ** This function returns the total number of cells added to the free-list.
  61478. */
  61479. static int pageFreeArray(
  61480. MemPage *pPg, /* Page to edit */
  61481. int iFirst, /* First cell to delete */
  61482. int nCell, /* Cells to delete */
  61483. CellArray *pCArray /* Array of cells */
  61484. ){
  61485. u8 * const aData = pPg->aData;
  61486. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  61487. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  61488. int nRet = 0;
  61489. int i;
  61490. int iEnd = iFirst + nCell;
  61491. u8 *pFree = 0;
  61492. int szFree = 0;
  61493. for(i=iFirst; i<iEnd; i++){
  61494. u8 *pCell = pCArray->apCell[i];
  61495. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  61496. int sz;
  61497. /* No need to use cachedCellSize() here. The sizes of all cells that
  61498. ** are to be freed have already been computing while deciding which
  61499. ** cells need freeing */
  61500. sz = pCArray->szCell[i]; assert( sz>0 );
  61501. if( pFree!=(pCell + sz) ){
  61502. if( pFree ){
  61503. assert( pFree>aData && (pFree - aData)<65536 );
  61504. freeSpace(pPg, (u16)(pFree - aData), szFree);
  61505. }
  61506. pFree = pCell;
  61507. szFree = sz;
  61508. if( pFree+sz>pEnd ) return 0;
  61509. }else{
  61510. pFree = pCell;
  61511. szFree += sz;
  61512. }
  61513. nRet++;
  61514. }
  61515. }
  61516. if( pFree ){
  61517. assert( pFree>aData && (pFree - aData)<65536 );
  61518. freeSpace(pPg, (u16)(pFree - aData), szFree);
  61519. }
  61520. return nRet;
  61521. }
  61522. /*
  61523. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  61524. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  61525. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  61526. ** starting at apCell[iNew].
  61527. **
  61528. ** This routine makes the necessary adjustments to pPg so that it contains
  61529. ** the correct cells after being balanced.
  61530. **
  61531. ** The pPg->nFree field is invalid when this function returns. It is the
  61532. ** responsibility of the caller to set it correctly.
  61533. */
  61534. static int editPage(
  61535. MemPage *pPg, /* Edit this page */
  61536. int iOld, /* Index of first cell currently on page */
  61537. int iNew, /* Index of new first cell on page */
  61538. int nNew, /* Final number of cells on page */
  61539. CellArray *pCArray /* Array of cells and sizes */
  61540. ){
  61541. u8 * const aData = pPg->aData;
  61542. const int hdr = pPg->hdrOffset;
  61543. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  61544. int nCell = pPg->nCell; /* Cells stored on pPg */
  61545. u8 *pData;
  61546. u8 *pCellptr;
  61547. int i;
  61548. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  61549. int iNewEnd = iNew + nNew;
  61550. #ifdef SQLITE_DEBUG
  61551. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  61552. memcpy(pTmp, aData, pPg->pBt->usableSize);
  61553. #endif
  61554. /* Remove cells from the start and end of the page */
  61555. if( iOld<iNew ){
  61556. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  61557. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  61558. nCell -= nShift;
  61559. }
  61560. if( iNewEnd < iOldEnd ){
  61561. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  61562. }
  61563. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  61564. if( pData<pBegin ) goto editpage_fail;
  61565. /* Add cells to the start of the page */
  61566. if( iNew<iOld ){
  61567. int nAdd = MIN(nNew,iOld-iNew);
  61568. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  61569. pCellptr = pPg->aCellIdx;
  61570. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  61571. if( pageInsertArray(
  61572. pPg, pBegin, &pData, pCellptr,
  61573. iNew, nAdd, pCArray
  61574. ) ) goto editpage_fail;
  61575. nCell += nAdd;
  61576. }
  61577. /* Add any overflow cells */
  61578. for(i=0; i<pPg->nOverflow; i++){
  61579. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  61580. if( iCell>=0 && iCell<nNew ){
  61581. pCellptr = &pPg->aCellIdx[iCell * 2];
  61582. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  61583. nCell++;
  61584. if( pageInsertArray(
  61585. pPg, pBegin, &pData, pCellptr,
  61586. iCell+iNew, 1, pCArray
  61587. ) ) goto editpage_fail;
  61588. }
  61589. }
  61590. /* Append cells to the end of the page */
  61591. pCellptr = &pPg->aCellIdx[nCell*2];
  61592. if( pageInsertArray(
  61593. pPg, pBegin, &pData, pCellptr,
  61594. iNew+nCell, nNew-nCell, pCArray
  61595. ) ) goto editpage_fail;
  61596. pPg->nCell = nNew;
  61597. pPg->nOverflow = 0;
  61598. put2byte(&aData[hdr+3], pPg->nCell);
  61599. put2byte(&aData[hdr+5], pData - aData);
  61600. #ifdef SQLITE_DEBUG
  61601. for(i=0; i<nNew && !CORRUPT_DB; i++){
  61602. u8 *pCell = pCArray->apCell[i+iNew];
  61603. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  61604. if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
  61605. pCell = &pTmp[pCell - aData];
  61606. }
  61607. assert( 0==memcmp(pCell, &aData[iOff],
  61608. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  61609. }
  61610. #endif
  61611. return SQLITE_OK;
  61612. editpage_fail:
  61613. /* Unable to edit this page. Rebuild it from scratch instead. */
  61614. populateCellCache(pCArray, iNew, nNew);
  61615. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  61616. }
  61617. /*
  61618. ** The following parameters determine how many adjacent pages get involved
  61619. ** in a balancing operation. NN is the number of neighbors on either side
  61620. ** of the page that participate in the balancing operation. NB is the
  61621. ** total number of pages that participate, including the target page and
  61622. ** NN neighbors on either side.
  61623. **
  61624. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  61625. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  61626. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  61627. ** The value of NN appears to give the best results overall.
  61628. */
  61629. #define NN 1 /* Number of neighbors on either side of pPage */
  61630. #define NB (NN*2+1) /* Total pages involved in the balance */
  61631. #ifndef SQLITE_OMIT_QUICKBALANCE
  61632. /*
  61633. ** This version of balance() handles the common special case where
  61634. ** a new entry is being inserted on the extreme right-end of the
  61635. ** tree, in other words, when the new entry will become the largest
  61636. ** entry in the tree.
  61637. **
  61638. ** Instead of trying to balance the 3 right-most leaf pages, just add
  61639. ** a new page to the right-hand side and put the one new entry in
  61640. ** that page. This leaves the right side of the tree somewhat
  61641. ** unbalanced. But odds are that we will be inserting new entries
  61642. ** at the end soon afterwards so the nearly empty page will quickly
  61643. ** fill up. On average.
  61644. **
  61645. ** pPage is the leaf page which is the right-most page in the tree.
  61646. ** pParent is its parent. pPage must have a single overflow entry
  61647. ** which is also the right-most entry on the page.
  61648. **
  61649. ** The pSpace buffer is used to store a temporary copy of the divider
  61650. ** cell that will be inserted into pParent. Such a cell consists of a 4
  61651. ** byte page number followed by a variable length integer. In other
  61652. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  61653. ** least 13 bytes in size.
  61654. */
  61655. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  61656. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  61657. MemPage *pNew; /* Newly allocated page */
  61658. int rc; /* Return Code */
  61659. Pgno pgnoNew; /* Page number of pNew */
  61660. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61661. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  61662. assert( pPage->nOverflow==1 );
  61663. /* This error condition is now caught prior to reaching this function */
  61664. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  61665. /* Allocate a new page. This page will become the right-sibling of
  61666. ** pPage. Make the parent page writable, so that the new divider cell
  61667. ** may be inserted. If both these operations are successful, proceed.
  61668. */
  61669. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  61670. if( rc==SQLITE_OK ){
  61671. u8 *pOut = &pSpace[4];
  61672. u8 *pCell = pPage->apOvfl[0];
  61673. u16 szCell = pPage->xCellSize(pPage, pCell);
  61674. u8 *pStop;
  61675. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  61676. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  61677. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  61678. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  61679. if( NEVER(rc) ) return rc;
  61680. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  61681. /* If this is an auto-vacuum database, update the pointer map
  61682. ** with entries for the new page, and any pointer from the
  61683. ** cell on the page to an overflow page. If either of these
  61684. ** operations fails, the return code is set, but the contents
  61685. ** of the parent page are still manipulated by thh code below.
  61686. ** That is Ok, at this point the parent page is guaranteed to
  61687. ** be marked as dirty. Returning an error code will cause a
  61688. ** rollback, undoing any changes made to the parent page.
  61689. */
  61690. if( ISAUTOVACUUM ){
  61691. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  61692. if( szCell>pNew->minLocal ){
  61693. ptrmapPutOvflPtr(pNew, pCell, &rc);
  61694. }
  61695. }
  61696. /* Create a divider cell to insert into pParent. The divider cell
  61697. ** consists of a 4-byte page number (the page number of pPage) and
  61698. ** a variable length key value (which must be the same value as the
  61699. ** largest key on pPage).
  61700. **
  61701. ** To find the largest key value on pPage, first find the right-most
  61702. ** cell on pPage. The first two fields of this cell are the
  61703. ** record-length (a variable length integer at most 32-bits in size)
  61704. ** and the key value (a variable length integer, may have any value).
  61705. ** The first of the while(...) loops below skips over the record-length
  61706. ** field. The second while(...) loop copies the key value from the
  61707. ** cell on pPage into the pSpace buffer.
  61708. */
  61709. pCell = findCell(pPage, pPage->nCell-1);
  61710. pStop = &pCell[9];
  61711. while( (*(pCell++)&0x80) && pCell<pStop );
  61712. pStop = &pCell[9];
  61713. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  61714. /* Insert the new divider cell into pParent. */
  61715. if( rc==SQLITE_OK ){
  61716. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  61717. 0, pPage->pgno, &rc);
  61718. }
  61719. /* Set the right-child pointer of pParent to point to the new page. */
  61720. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  61721. /* Release the reference to the new page. */
  61722. releasePage(pNew);
  61723. }
  61724. return rc;
  61725. }
  61726. #endif /* SQLITE_OMIT_QUICKBALANCE */
  61727. #if 0
  61728. /*
  61729. ** This function does not contribute anything to the operation of SQLite.
  61730. ** it is sometimes activated temporarily while debugging code responsible
  61731. ** for setting pointer-map entries.
  61732. */
  61733. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  61734. int i, j;
  61735. for(i=0; i<nPage; i++){
  61736. Pgno n;
  61737. u8 e;
  61738. MemPage *pPage = apPage[i];
  61739. BtShared *pBt = pPage->pBt;
  61740. assert( pPage->isInit );
  61741. for(j=0; j<pPage->nCell; j++){
  61742. CellInfo info;
  61743. u8 *z;
  61744. z = findCell(pPage, j);
  61745. pPage->xParseCell(pPage, z, &info);
  61746. if( info.nLocal<info.nPayload ){
  61747. Pgno ovfl = get4byte(&z[info.nSize-4]);
  61748. ptrmapGet(pBt, ovfl, &e, &n);
  61749. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  61750. }
  61751. if( !pPage->leaf ){
  61752. Pgno child = get4byte(z);
  61753. ptrmapGet(pBt, child, &e, &n);
  61754. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  61755. }
  61756. }
  61757. if( !pPage->leaf ){
  61758. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  61759. ptrmapGet(pBt, child, &e, &n);
  61760. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  61761. }
  61762. }
  61763. return 1;
  61764. }
  61765. #endif
  61766. /*
  61767. ** This function is used to copy the contents of the b-tree node stored
  61768. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  61769. ** the pointer-map entries for each child page are updated so that the
  61770. ** parent page stored in the pointer map is page pTo. If pFrom contained
  61771. ** any cells with overflow page pointers, then the corresponding pointer
  61772. ** map entries are also updated so that the parent page is page pTo.
  61773. **
  61774. ** If pFrom is currently carrying any overflow cells (entries in the
  61775. ** MemPage.apOvfl[] array), they are not copied to pTo.
  61776. **
  61777. ** Before returning, page pTo is reinitialized using btreeInitPage().
  61778. **
  61779. ** The performance of this function is not critical. It is only used by
  61780. ** the balance_shallower() and balance_deeper() procedures, neither of
  61781. ** which are called often under normal circumstances.
  61782. */
  61783. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  61784. if( (*pRC)==SQLITE_OK ){
  61785. BtShared * const pBt = pFrom->pBt;
  61786. u8 * const aFrom = pFrom->aData;
  61787. u8 * const aTo = pTo->aData;
  61788. int const iFromHdr = pFrom->hdrOffset;
  61789. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  61790. int rc;
  61791. int iData;
  61792. assert( pFrom->isInit );
  61793. assert( pFrom->nFree>=iToHdr );
  61794. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  61795. /* Copy the b-tree node content from page pFrom to page pTo. */
  61796. iData = get2byte(&aFrom[iFromHdr+5]);
  61797. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  61798. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  61799. /* Reinitialize page pTo so that the contents of the MemPage structure
  61800. ** match the new data. The initialization of pTo can actually fail under
  61801. ** fairly obscure circumstances, even though it is a copy of initialized
  61802. ** page pFrom.
  61803. */
  61804. pTo->isInit = 0;
  61805. rc = btreeInitPage(pTo);
  61806. if( rc!=SQLITE_OK ){
  61807. *pRC = rc;
  61808. return;
  61809. }
  61810. /* If this is an auto-vacuum database, update the pointer-map entries
  61811. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  61812. */
  61813. if( ISAUTOVACUUM ){
  61814. *pRC = setChildPtrmaps(pTo);
  61815. }
  61816. }
  61817. }
  61818. /*
  61819. ** This routine redistributes cells on the iParentIdx'th child of pParent
  61820. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  61821. ** same amount of free space. Usually a single sibling on either side of the
  61822. ** page are used in the balancing, though both siblings might come from one
  61823. ** side if the page is the first or last child of its parent. If the page
  61824. ** has fewer than 2 siblings (something which can only happen if the page
  61825. ** is a root page or a child of a root page) then all available siblings
  61826. ** participate in the balancing.
  61827. **
  61828. ** The number of siblings of the page might be increased or decreased by
  61829. ** one or two in an effort to keep pages nearly full but not over full.
  61830. **
  61831. ** Note that when this routine is called, some of the cells on the page
  61832. ** might not actually be stored in MemPage.aData[]. This can happen
  61833. ** if the page is overfull. This routine ensures that all cells allocated
  61834. ** to the page and its siblings fit into MemPage.aData[] before returning.
  61835. **
  61836. ** In the course of balancing the page and its siblings, cells may be
  61837. ** inserted into or removed from the parent page (pParent). Doing so
  61838. ** may cause the parent page to become overfull or underfull. If this
  61839. ** happens, it is the responsibility of the caller to invoke the correct
  61840. ** balancing routine to fix this problem (see the balance() routine).
  61841. **
  61842. ** If this routine fails for any reason, it might leave the database
  61843. ** in a corrupted state. So if this routine fails, the database should
  61844. ** be rolled back.
  61845. **
  61846. ** The third argument to this function, aOvflSpace, is a pointer to a
  61847. ** buffer big enough to hold one page. If while inserting cells into the parent
  61848. ** page (pParent) the parent page becomes overfull, this buffer is
  61849. ** used to store the parent's overflow cells. Because this function inserts
  61850. ** a maximum of four divider cells into the parent page, and the maximum
  61851. ** size of a cell stored within an internal node is always less than 1/4
  61852. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  61853. ** enough for all overflow cells.
  61854. **
  61855. ** If aOvflSpace is set to a null pointer, this function returns
  61856. ** SQLITE_NOMEM.
  61857. */
  61858. static int balance_nonroot(
  61859. MemPage *pParent, /* Parent page of siblings being balanced */
  61860. int iParentIdx, /* Index of "the page" in pParent */
  61861. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  61862. int isRoot, /* True if pParent is a root-page */
  61863. int bBulk /* True if this call is part of a bulk load */
  61864. ){
  61865. BtShared *pBt; /* The whole database */
  61866. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  61867. int nNew = 0; /* Number of pages in apNew[] */
  61868. int nOld; /* Number of pages in apOld[] */
  61869. int i, j, k; /* Loop counters */
  61870. int nxDiv; /* Next divider slot in pParent->aCell[] */
  61871. int rc = SQLITE_OK; /* The return code */
  61872. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  61873. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  61874. int usableSpace; /* Bytes in pPage beyond the header */
  61875. int pageFlags; /* Value of pPage->aData[0] */
  61876. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  61877. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  61878. int szScratch; /* Size of scratch memory requested */
  61879. MemPage *apOld[NB]; /* pPage and up to two siblings */
  61880. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  61881. u8 *pRight; /* Location in parent of right-sibling pointer */
  61882. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  61883. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  61884. int cntOld[NB+2]; /* Old index in b.apCell[] */
  61885. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  61886. u8 *aSpace1; /* Space for copies of dividers cells */
  61887. Pgno pgno; /* Temp var to store a page number in */
  61888. u8 abDone[NB+2]; /* True after i'th new page is populated */
  61889. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  61890. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  61891. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  61892. CellArray b; /* Parsed information on cells being balanced */
  61893. memset(abDone, 0, sizeof(abDone));
  61894. b.nCell = 0;
  61895. b.apCell = 0;
  61896. pBt = pParent->pBt;
  61897. assert( sqlite3_mutex_held(pBt->mutex) );
  61898. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  61899. #if 0
  61900. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  61901. #endif
  61902. /* At this point pParent may have at most one overflow cell. And if
  61903. ** this overflow cell is present, it must be the cell with
  61904. ** index iParentIdx. This scenario comes about when this function
  61905. ** is called (indirectly) from sqlite3BtreeDelete().
  61906. */
  61907. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  61908. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  61909. if( !aOvflSpace ){
  61910. return SQLITE_NOMEM_BKPT;
  61911. }
  61912. /* Find the sibling pages to balance. Also locate the cells in pParent
  61913. ** that divide the siblings. An attempt is made to find NN siblings on
  61914. ** either side of pPage. More siblings are taken from one side, however,
  61915. ** if there are fewer than NN siblings on the other side. If pParent
  61916. ** has NB or fewer children then all children of pParent are taken.
  61917. **
  61918. ** This loop also drops the divider cells from the parent page. This
  61919. ** way, the remainder of the function does not have to deal with any
  61920. ** overflow cells in the parent page, since if any existed they will
  61921. ** have already been removed.
  61922. */
  61923. i = pParent->nOverflow + pParent->nCell;
  61924. if( i<2 ){
  61925. nxDiv = 0;
  61926. }else{
  61927. assert( bBulk==0 || bBulk==1 );
  61928. if( iParentIdx==0 ){
  61929. nxDiv = 0;
  61930. }else if( iParentIdx==i ){
  61931. nxDiv = i-2+bBulk;
  61932. }else{
  61933. nxDiv = iParentIdx-1;
  61934. }
  61935. i = 2-bBulk;
  61936. }
  61937. nOld = i+1;
  61938. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  61939. pRight = &pParent->aData[pParent->hdrOffset+8];
  61940. }else{
  61941. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  61942. }
  61943. pgno = get4byte(pRight);
  61944. while( 1 ){
  61945. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  61946. if( rc ){
  61947. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  61948. goto balance_cleanup;
  61949. }
  61950. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  61951. if( (i--)==0 ) break;
  61952. if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
  61953. apDiv[i] = pParent->apOvfl[0];
  61954. pgno = get4byte(apDiv[i]);
  61955. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  61956. pParent->nOverflow = 0;
  61957. }else{
  61958. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  61959. pgno = get4byte(apDiv[i]);
  61960. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  61961. /* Drop the cell from the parent page. apDiv[i] still points to
  61962. ** the cell within the parent, even though it has been dropped.
  61963. ** This is safe because dropping a cell only overwrites the first
  61964. ** four bytes of it, and this function does not need the first
  61965. ** four bytes of the divider cell. So the pointer is safe to use
  61966. ** later on.
  61967. **
  61968. ** But not if we are in secure-delete mode. In secure-delete mode,
  61969. ** the dropCell() routine will overwrite the entire cell with zeroes.
  61970. ** In this case, temporarily copy the cell into the aOvflSpace[]
  61971. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  61972. ** is allocated. */
  61973. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  61974. int iOff;
  61975. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  61976. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  61977. rc = SQLITE_CORRUPT_BKPT;
  61978. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  61979. goto balance_cleanup;
  61980. }else{
  61981. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  61982. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  61983. }
  61984. }
  61985. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  61986. }
  61987. }
  61988. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  61989. ** alignment */
  61990. nMaxCells = (nMaxCells + 3)&~3;
  61991. /*
  61992. ** Allocate space for memory structures
  61993. */
  61994. szScratch =
  61995. nMaxCells*sizeof(u8*) /* b.apCell */
  61996. + nMaxCells*sizeof(u16) /* b.szCell */
  61997. + pBt->pageSize; /* aSpace1 */
  61998. /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
  61999. ** that is more than 6 times the database page size. */
  62000. assert( szScratch<=6*(int)pBt->pageSize );
  62001. b.apCell = sqlite3ScratchMalloc( szScratch );
  62002. if( b.apCell==0 ){
  62003. rc = SQLITE_NOMEM_BKPT;
  62004. goto balance_cleanup;
  62005. }
  62006. b.szCell = (u16*)&b.apCell[nMaxCells];
  62007. aSpace1 = (u8*)&b.szCell[nMaxCells];
  62008. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  62009. /*
  62010. ** Load pointers to all cells on sibling pages and the divider cells
  62011. ** into the local b.apCell[] array. Make copies of the divider cells
  62012. ** into space obtained from aSpace1[]. The divider cells have already
  62013. ** been removed from pParent.
  62014. **
  62015. ** If the siblings are on leaf pages, then the child pointers of the
  62016. ** divider cells are stripped from the cells before they are copied
  62017. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  62018. ** child pointers. If siblings are not leaves, then all cell in
  62019. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  62020. ** are alike.
  62021. **
  62022. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  62023. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  62024. */
  62025. b.pRef = apOld[0];
  62026. leafCorrection = b.pRef->leaf*4;
  62027. leafData = b.pRef->intKeyLeaf;
  62028. for(i=0; i<nOld; i++){
  62029. MemPage *pOld = apOld[i];
  62030. int limit = pOld->nCell;
  62031. u8 *aData = pOld->aData;
  62032. u16 maskPage = pOld->maskPage;
  62033. u8 *piCell = aData + pOld->cellOffset;
  62034. u8 *piEnd;
  62035. /* Verify that all sibling pages are of the same "type" (table-leaf,
  62036. ** table-interior, index-leaf, or index-interior).
  62037. */
  62038. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  62039. rc = SQLITE_CORRUPT_BKPT;
  62040. goto balance_cleanup;
  62041. }
  62042. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  62043. ** constains overflow cells, include them in the b.apCell[] array
  62044. ** in the correct spot.
  62045. **
  62046. ** Note that when there are multiple overflow cells, it is always the
  62047. ** case that they are sequential and adjacent. This invariant arises
  62048. ** because multiple overflows can only occurs when inserting divider
  62049. ** cells into a parent on a prior balance, and divider cells are always
  62050. ** adjacent and are inserted in order. There is an assert() tagged
  62051. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  62052. ** invariant.
  62053. **
  62054. ** This must be done in advance. Once the balance starts, the cell
  62055. ** offset section of the btree page will be overwritten and we will no
  62056. ** long be able to find the cells if a pointer to each cell is not saved
  62057. ** first.
  62058. */
  62059. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  62060. if( pOld->nOverflow>0 ){
  62061. limit = pOld->aiOvfl[0];
  62062. for(j=0; j<limit; j++){
  62063. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  62064. piCell += 2;
  62065. b.nCell++;
  62066. }
  62067. for(k=0; k<pOld->nOverflow; k++){
  62068. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  62069. b.apCell[b.nCell] = pOld->apOvfl[k];
  62070. b.nCell++;
  62071. }
  62072. }
  62073. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  62074. while( piCell<piEnd ){
  62075. assert( b.nCell<nMaxCells );
  62076. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  62077. piCell += 2;
  62078. b.nCell++;
  62079. }
  62080. cntOld[i] = b.nCell;
  62081. if( i<nOld-1 && !leafData){
  62082. u16 sz = (u16)szNew[i];
  62083. u8 *pTemp;
  62084. assert( b.nCell<nMaxCells );
  62085. b.szCell[b.nCell] = sz;
  62086. pTemp = &aSpace1[iSpace1];
  62087. iSpace1 += sz;
  62088. assert( sz<=pBt->maxLocal+23 );
  62089. assert( iSpace1 <= (int)pBt->pageSize );
  62090. memcpy(pTemp, apDiv[i], sz);
  62091. b.apCell[b.nCell] = pTemp+leafCorrection;
  62092. assert( leafCorrection==0 || leafCorrection==4 );
  62093. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  62094. if( !pOld->leaf ){
  62095. assert( leafCorrection==0 );
  62096. assert( pOld->hdrOffset==0 );
  62097. /* The right pointer of the child page pOld becomes the left
  62098. ** pointer of the divider cell */
  62099. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  62100. }else{
  62101. assert( leafCorrection==4 );
  62102. while( b.szCell[b.nCell]<4 ){
  62103. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  62104. ** does exist, pad it with 0x00 bytes. */
  62105. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  62106. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  62107. aSpace1[iSpace1++] = 0x00;
  62108. b.szCell[b.nCell]++;
  62109. }
  62110. }
  62111. b.nCell++;
  62112. }
  62113. }
  62114. /*
  62115. ** Figure out the number of pages needed to hold all b.nCell cells.
  62116. ** Store this number in "k". Also compute szNew[] which is the total
  62117. ** size of all cells on the i-th page and cntNew[] which is the index
  62118. ** in b.apCell[] of the cell that divides page i from page i+1.
  62119. ** cntNew[k] should equal b.nCell.
  62120. **
  62121. ** Values computed by this block:
  62122. **
  62123. ** k: The total number of sibling pages
  62124. ** szNew[i]: Spaced used on the i-th sibling page.
  62125. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  62126. ** the right of the i-th sibling page.
  62127. ** usableSpace: Number of bytes of space available on each sibling.
  62128. **
  62129. */
  62130. usableSpace = pBt->usableSize - 12 + leafCorrection;
  62131. for(i=0; i<nOld; i++){
  62132. MemPage *p = apOld[i];
  62133. szNew[i] = usableSpace - p->nFree;
  62134. for(j=0; j<p->nOverflow; j++){
  62135. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  62136. }
  62137. cntNew[i] = cntOld[i];
  62138. }
  62139. k = nOld;
  62140. for(i=0; i<k; i++){
  62141. int sz;
  62142. while( szNew[i]>usableSpace ){
  62143. if( i+1>=k ){
  62144. k = i+2;
  62145. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  62146. szNew[k-1] = 0;
  62147. cntNew[k-1] = b.nCell;
  62148. }
  62149. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  62150. szNew[i] -= sz;
  62151. if( !leafData ){
  62152. if( cntNew[i]<b.nCell ){
  62153. sz = 2 + cachedCellSize(&b, cntNew[i]);
  62154. }else{
  62155. sz = 0;
  62156. }
  62157. }
  62158. szNew[i+1] += sz;
  62159. cntNew[i]--;
  62160. }
  62161. while( cntNew[i]<b.nCell ){
  62162. sz = 2 + cachedCellSize(&b, cntNew[i]);
  62163. if( szNew[i]+sz>usableSpace ) break;
  62164. szNew[i] += sz;
  62165. cntNew[i]++;
  62166. if( !leafData ){
  62167. if( cntNew[i]<b.nCell ){
  62168. sz = 2 + cachedCellSize(&b, cntNew[i]);
  62169. }else{
  62170. sz = 0;
  62171. }
  62172. }
  62173. szNew[i+1] -= sz;
  62174. }
  62175. if( cntNew[i]>=b.nCell ){
  62176. k = i+1;
  62177. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  62178. rc = SQLITE_CORRUPT_BKPT;
  62179. goto balance_cleanup;
  62180. }
  62181. }
  62182. /*
  62183. ** The packing computed by the previous block is biased toward the siblings
  62184. ** on the left side (siblings with smaller keys). The left siblings are
  62185. ** always nearly full, while the right-most sibling might be nearly empty.
  62186. ** The next block of code attempts to adjust the packing of siblings to
  62187. ** get a better balance.
  62188. **
  62189. ** This adjustment is more than an optimization. The packing above might
  62190. ** be so out of balance as to be illegal. For example, the right-most
  62191. ** sibling might be completely empty. This adjustment is not optional.
  62192. */
  62193. for(i=k-1; i>0; i--){
  62194. int szRight = szNew[i]; /* Size of sibling on the right */
  62195. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  62196. int r; /* Index of right-most cell in left sibling */
  62197. int d; /* Index of first cell to the left of right sibling */
  62198. r = cntNew[i-1] - 1;
  62199. d = r + 1 - leafData;
  62200. (void)cachedCellSize(&b, d);
  62201. do{
  62202. assert( d<nMaxCells );
  62203. assert( r<nMaxCells );
  62204. (void)cachedCellSize(&b, r);
  62205. if( szRight!=0
  62206. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
  62207. break;
  62208. }
  62209. szRight += b.szCell[d] + 2;
  62210. szLeft -= b.szCell[r] + 2;
  62211. cntNew[i-1] = r;
  62212. r--;
  62213. d--;
  62214. }while( r>=0 );
  62215. szNew[i] = szRight;
  62216. szNew[i-1] = szLeft;
  62217. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  62218. rc = SQLITE_CORRUPT_BKPT;
  62219. goto balance_cleanup;
  62220. }
  62221. }
  62222. /* Sanity check: For a non-corrupt database file one of the follwing
  62223. ** must be true:
  62224. ** (1) We found one or more cells (cntNew[0])>0), or
  62225. ** (2) pPage is a virtual root page. A virtual root page is when
  62226. ** the real root page is page 1 and we are the only child of
  62227. ** that page.
  62228. */
  62229. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  62230. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  62231. apOld[0]->pgno, apOld[0]->nCell,
  62232. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  62233. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  62234. ));
  62235. /*
  62236. ** Allocate k new pages. Reuse old pages where possible.
  62237. */
  62238. pageFlags = apOld[0]->aData[0];
  62239. for(i=0; i<k; i++){
  62240. MemPage *pNew;
  62241. if( i<nOld ){
  62242. pNew = apNew[i] = apOld[i];
  62243. apOld[i] = 0;
  62244. rc = sqlite3PagerWrite(pNew->pDbPage);
  62245. nNew++;
  62246. if( rc ) goto balance_cleanup;
  62247. }else{
  62248. assert( i>0 );
  62249. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  62250. if( rc ) goto balance_cleanup;
  62251. zeroPage(pNew, pageFlags);
  62252. apNew[i] = pNew;
  62253. nNew++;
  62254. cntOld[i] = b.nCell;
  62255. /* Set the pointer-map entry for the new sibling page. */
  62256. if( ISAUTOVACUUM ){
  62257. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  62258. if( rc!=SQLITE_OK ){
  62259. goto balance_cleanup;
  62260. }
  62261. }
  62262. }
  62263. }
  62264. /*
  62265. ** Reassign page numbers so that the new pages are in ascending order.
  62266. ** This helps to keep entries in the disk file in order so that a scan
  62267. ** of the table is closer to a linear scan through the file. That in turn
  62268. ** helps the operating system to deliver pages from the disk more rapidly.
  62269. **
  62270. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  62271. ** than (NB+2) (a small constant), that should not be a problem.
  62272. **
  62273. ** When NB==3, this one optimization makes the database about 25% faster
  62274. ** for large insertions and deletions.
  62275. */
  62276. for(i=0; i<nNew; i++){
  62277. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  62278. aPgFlags[i] = apNew[i]->pDbPage->flags;
  62279. for(j=0; j<i; j++){
  62280. if( aPgno[j]==aPgno[i] ){
  62281. /* This branch is taken if the set of sibling pages somehow contains
  62282. ** duplicate entries. This can happen if the database is corrupt.
  62283. ** It would be simpler to detect this as part of the loop below, but
  62284. ** we do the detection here in order to avoid populating the pager
  62285. ** cache with two separate objects associated with the same
  62286. ** page number. */
  62287. assert( CORRUPT_DB );
  62288. rc = SQLITE_CORRUPT_BKPT;
  62289. goto balance_cleanup;
  62290. }
  62291. }
  62292. }
  62293. for(i=0; i<nNew; i++){
  62294. int iBest = 0; /* aPgno[] index of page number to use */
  62295. for(j=1; j<nNew; j++){
  62296. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  62297. }
  62298. pgno = aPgOrder[iBest];
  62299. aPgOrder[iBest] = 0xffffffff;
  62300. if( iBest!=i ){
  62301. if( iBest>i ){
  62302. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  62303. }
  62304. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  62305. apNew[i]->pgno = pgno;
  62306. }
  62307. }
  62308. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  62309. "%d(%d nc=%d) %d(%d nc=%d)\n",
  62310. apNew[0]->pgno, szNew[0], cntNew[0],
  62311. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  62312. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  62313. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  62314. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  62315. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  62316. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  62317. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  62318. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  62319. ));
  62320. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  62321. put4byte(pRight, apNew[nNew-1]->pgno);
  62322. /* If the sibling pages are not leaves, ensure that the right-child pointer
  62323. ** of the right-most new sibling page is set to the value that was
  62324. ** originally in the same field of the right-most old sibling page. */
  62325. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  62326. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  62327. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  62328. }
  62329. /* Make any required updates to pointer map entries associated with
  62330. ** cells stored on sibling pages following the balance operation. Pointer
  62331. ** map entries associated with divider cells are set by the insertCell()
  62332. ** routine. The associated pointer map entries are:
  62333. **
  62334. ** a) if the cell contains a reference to an overflow chain, the
  62335. ** entry associated with the first page in the overflow chain, and
  62336. **
  62337. ** b) if the sibling pages are not leaves, the child page associated
  62338. ** with the cell.
  62339. **
  62340. ** If the sibling pages are not leaves, then the pointer map entry
  62341. ** associated with the right-child of each sibling may also need to be
  62342. ** updated. This happens below, after the sibling pages have been
  62343. ** populated, not here.
  62344. */
  62345. if( ISAUTOVACUUM ){
  62346. MemPage *pNew = apNew[0];
  62347. u8 *aOld = pNew->aData;
  62348. int cntOldNext = pNew->nCell + pNew->nOverflow;
  62349. int usableSize = pBt->usableSize;
  62350. int iNew = 0;
  62351. int iOld = 0;
  62352. for(i=0; i<b.nCell; i++){
  62353. u8 *pCell = b.apCell[i];
  62354. if( i==cntOldNext ){
  62355. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  62356. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  62357. aOld = pOld->aData;
  62358. }
  62359. if( i==cntNew[iNew] ){
  62360. pNew = apNew[++iNew];
  62361. if( !leafData ) continue;
  62362. }
  62363. /* Cell pCell is destined for new sibling page pNew. Originally, it
  62364. ** was either part of sibling page iOld (possibly an overflow cell),
  62365. ** or else the divider cell to the left of sibling page iOld. So,
  62366. ** if sibling page iOld had the same page number as pNew, and if
  62367. ** pCell really was a part of sibling page iOld (not a divider or
  62368. ** overflow cell), we can skip updating the pointer map entries. */
  62369. if( iOld>=nNew
  62370. || pNew->pgno!=aPgno[iOld]
  62371. || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
  62372. ){
  62373. if( !leafCorrection ){
  62374. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  62375. }
  62376. if( cachedCellSize(&b,i)>pNew->minLocal ){
  62377. ptrmapPutOvflPtr(pNew, pCell, &rc);
  62378. }
  62379. if( rc ) goto balance_cleanup;
  62380. }
  62381. }
  62382. }
  62383. /* Insert new divider cells into pParent. */
  62384. for(i=0; i<nNew-1; i++){
  62385. u8 *pCell;
  62386. u8 *pTemp;
  62387. int sz;
  62388. MemPage *pNew = apNew[i];
  62389. j = cntNew[i];
  62390. assert( j<nMaxCells );
  62391. assert( b.apCell[j]!=0 );
  62392. pCell = b.apCell[j];
  62393. sz = b.szCell[j] + leafCorrection;
  62394. pTemp = &aOvflSpace[iOvflSpace];
  62395. if( !pNew->leaf ){
  62396. memcpy(&pNew->aData[8], pCell, 4);
  62397. }else if( leafData ){
  62398. /* If the tree is a leaf-data tree, and the siblings are leaves,
  62399. ** then there is no divider cell in b.apCell[]. Instead, the divider
  62400. ** cell consists of the integer key for the right-most cell of
  62401. ** the sibling-page assembled above only.
  62402. */
  62403. CellInfo info;
  62404. j--;
  62405. pNew->xParseCell(pNew, b.apCell[j], &info);
  62406. pCell = pTemp;
  62407. sz = 4 + putVarint(&pCell[4], info.nKey);
  62408. pTemp = 0;
  62409. }else{
  62410. pCell -= 4;
  62411. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  62412. ** previously stored on a leaf node, and its reported size was 4
  62413. ** bytes, then it may actually be smaller than this
  62414. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  62415. ** any cell). But it is important to pass the correct size to
  62416. ** insertCell(), so reparse the cell now.
  62417. **
  62418. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  62419. ** and WITHOUT ROWID tables with exactly one column which is the
  62420. ** primary key.
  62421. */
  62422. if( b.szCell[j]==4 ){
  62423. assert(leafCorrection==4);
  62424. sz = pParent->xCellSize(pParent, pCell);
  62425. }
  62426. }
  62427. iOvflSpace += sz;
  62428. assert( sz<=pBt->maxLocal+23 );
  62429. assert( iOvflSpace <= (int)pBt->pageSize );
  62430. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  62431. if( rc!=SQLITE_OK ) goto balance_cleanup;
  62432. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  62433. }
  62434. /* Now update the actual sibling pages. The order in which they are updated
  62435. ** is important, as this code needs to avoid disrupting any page from which
  62436. ** cells may still to be read. In practice, this means:
  62437. **
  62438. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  62439. ** then it is not safe to update page apNew[iPg] until after
  62440. ** the left-hand sibling apNew[iPg-1] has been updated.
  62441. **
  62442. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  62443. ** then it is not safe to update page apNew[iPg] until after
  62444. ** the right-hand sibling apNew[iPg+1] has been updated.
  62445. **
  62446. ** If neither of the above apply, the page is safe to update.
  62447. **
  62448. ** The iPg value in the following loop starts at nNew-1 goes down
  62449. ** to 0, then back up to nNew-1 again, thus making two passes over
  62450. ** the pages. On the initial downward pass, only condition (1) above
  62451. ** needs to be tested because (2) will always be true from the previous
  62452. ** step. On the upward pass, both conditions are always true, so the
  62453. ** upwards pass simply processes pages that were missed on the downward
  62454. ** pass.
  62455. */
  62456. for(i=1-nNew; i<nNew; i++){
  62457. int iPg = i<0 ? -i : i;
  62458. assert( iPg>=0 && iPg<nNew );
  62459. if( abDone[iPg] ) continue; /* Skip pages already processed */
  62460. if( i>=0 /* On the upwards pass, or... */
  62461. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  62462. ){
  62463. int iNew;
  62464. int iOld;
  62465. int nNewCell;
  62466. /* Verify condition (1): If cells are moving left, update iPg
  62467. ** only after iPg-1 has already been updated. */
  62468. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  62469. /* Verify condition (2): If cells are moving right, update iPg
  62470. ** only after iPg+1 has already been updated. */
  62471. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  62472. if( iPg==0 ){
  62473. iNew = iOld = 0;
  62474. nNewCell = cntNew[0];
  62475. }else{
  62476. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  62477. iNew = cntNew[iPg-1] + !leafData;
  62478. nNewCell = cntNew[iPg] - iNew;
  62479. }
  62480. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  62481. if( rc ) goto balance_cleanup;
  62482. abDone[iPg]++;
  62483. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  62484. assert( apNew[iPg]->nOverflow==0 );
  62485. assert( apNew[iPg]->nCell==nNewCell );
  62486. }
  62487. }
  62488. /* All pages have been processed exactly once */
  62489. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  62490. assert( nOld>0 );
  62491. assert( nNew>0 );
  62492. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  62493. /* The root page of the b-tree now contains no cells. The only sibling
  62494. ** page is the right-child of the parent. Copy the contents of the
  62495. ** child page into the parent, decreasing the overall height of the
  62496. ** b-tree structure by one. This is described as the "balance-shallower"
  62497. ** sub-algorithm in some documentation.
  62498. **
  62499. ** If this is an auto-vacuum database, the call to copyNodeContent()
  62500. ** sets all pointer-map entries corresponding to database image pages
  62501. ** for which the pointer is stored within the content being copied.
  62502. **
  62503. ** It is critical that the child page be defragmented before being
  62504. ** copied into the parent, because if the parent is page 1 then it will
  62505. ** by smaller than the child due to the database header, and so all the
  62506. ** free space needs to be up front.
  62507. */
  62508. assert( nNew==1 || CORRUPT_DB );
  62509. rc = defragmentPage(apNew[0], -1);
  62510. testcase( rc!=SQLITE_OK );
  62511. assert( apNew[0]->nFree ==
  62512. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  62513. || rc!=SQLITE_OK
  62514. );
  62515. copyNodeContent(apNew[0], pParent, &rc);
  62516. freePage(apNew[0], &rc);
  62517. }else if( ISAUTOVACUUM && !leafCorrection ){
  62518. /* Fix the pointer map entries associated with the right-child of each
  62519. ** sibling page. All other pointer map entries have already been taken
  62520. ** care of. */
  62521. for(i=0; i<nNew; i++){
  62522. u32 key = get4byte(&apNew[i]->aData[8]);
  62523. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  62524. }
  62525. }
  62526. assert( pParent->isInit );
  62527. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  62528. nOld, nNew, b.nCell));
  62529. /* Free any old pages that were not reused as new pages.
  62530. */
  62531. for(i=nNew; i<nOld; i++){
  62532. freePage(apOld[i], &rc);
  62533. }
  62534. #if 0
  62535. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  62536. /* The ptrmapCheckPages() contains assert() statements that verify that
  62537. ** all pointer map pages are set correctly. This is helpful while
  62538. ** debugging. This is usually disabled because a corrupt database may
  62539. ** cause an assert() statement to fail. */
  62540. ptrmapCheckPages(apNew, nNew);
  62541. ptrmapCheckPages(&pParent, 1);
  62542. }
  62543. #endif
  62544. /*
  62545. ** Cleanup before returning.
  62546. */
  62547. balance_cleanup:
  62548. sqlite3ScratchFree(b.apCell);
  62549. for(i=0; i<nOld; i++){
  62550. releasePage(apOld[i]);
  62551. }
  62552. for(i=0; i<nNew; i++){
  62553. releasePage(apNew[i]);
  62554. }
  62555. return rc;
  62556. }
  62557. /*
  62558. ** This function is called when the root page of a b-tree structure is
  62559. ** overfull (has one or more overflow pages).
  62560. **
  62561. ** A new child page is allocated and the contents of the current root
  62562. ** page, including overflow cells, are copied into the child. The root
  62563. ** page is then overwritten to make it an empty page with the right-child
  62564. ** pointer pointing to the new page.
  62565. **
  62566. ** Before returning, all pointer-map entries corresponding to pages
  62567. ** that the new child-page now contains pointers to are updated. The
  62568. ** entry corresponding to the new right-child pointer of the root
  62569. ** page is also updated.
  62570. **
  62571. ** If successful, *ppChild is set to contain a reference to the child
  62572. ** page and SQLITE_OK is returned. In this case the caller is required
  62573. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  62574. ** an error code is returned and *ppChild is set to 0.
  62575. */
  62576. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  62577. int rc; /* Return value from subprocedures */
  62578. MemPage *pChild = 0; /* Pointer to a new child page */
  62579. Pgno pgnoChild = 0; /* Page number of the new child page */
  62580. BtShared *pBt = pRoot->pBt; /* The BTree */
  62581. assert( pRoot->nOverflow>0 );
  62582. assert( sqlite3_mutex_held(pBt->mutex) );
  62583. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  62584. ** page that will become the new right-child of pPage. Copy the contents
  62585. ** of the node stored on pRoot into the new child page.
  62586. */
  62587. rc = sqlite3PagerWrite(pRoot->pDbPage);
  62588. if( rc==SQLITE_OK ){
  62589. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  62590. copyNodeContent(pRoot, pChild, &rc);
  62591. if( ISAUTOVACUUM ){
  62592. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  62593. }
  62594. }
  62595. if( rc ){
  62596. *ppChild = 0;
  62597. releasePage(pChild);
  62598. return rc;
  62599. }
  62600. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  62601. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  62602. assert( pChild->nCell==pRoot->nCell );
  62603. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  62604. /* Copy the overflow cells from pRoot to pChild */
  62605. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  62606. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  62607. memcpy(pChild->apOvfl, pRoot->apOvfl,
  62608. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  62609. pChild->nOverflow = pRoot->nOverflow;
  62610. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  62611. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  62612. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  62613. *ppChild = pChild;
  62614. return SQLITE_OK;
  62615. }
  62616. /*
  62617. ** The page that pCur currently points to has just been modified in
  62618. ** some way. This function figures out if this modification means the
  62619. ** tree needs to be balanced, and if so calls the appropriate balancing
  62620. ** routine. Balancing routines are:
  62621. **
  62622. ** balance_quick()
  62623. ** balance_deeper()
  62624. ** balance_nonroot()
  62625. */
  62626. static int balance(BtCursor *pCur){
  62627. int rc = SQLITE_OK;
  62628. const int nMin = pCur->pBt->usableSize * 2 / 3;
  62629. u8 aBalanceQuickSpace[13];
  62630. u8 *pFree = 0;
  62631. VVA_ONLY( int balance_quick_called = 0 );
  62632. VVA_ONLY( int balance_deeper_called = 0 );
  62633. do {
  62634. int iPage = pCur->iPage;
  62635. MemPage *pPage = pCur->apPage[iPage];
  62636. if( iPage==0 ){
  62637. if( pPage->nOverflow ){
  62638. /* The root page of the b-tree is overfull. In this case call the
  62639. ** balance_deeper() function to create a new child for the root-page
  62640. ** and copy the current contents of the root-page to it. The
  62641. ** next iteration of the do-loop will balance the child page.
  62642. */
  62643. assert( balance_deeper_called==0 );
  62644. VVA_ONLY( balance_deeper_called++ );
  62645. rc = balance_deeper(pPage, &pCur->apPage[1]);
  62646. if( rc==SQLITE_OK ){
  62647. pCur->iPage = 1;
  62648. pCur->ix = 0;
  62649. pCur->aiIdx[0] = 0;
  62650. assert( pCur->apPage[1]->nOverflow );
  62651. }
  62652. }else{
  62653. break;
  62654. }
  62655. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  62656. break;
  62657. }else{
  62658. MemPage * const pParent = pCur->apPage[iPage-1];
  62659. int const iIdx = pCur->aiIdx[iPage-1];
  62660. rc = sqlite3PagerWrite(pParent->pDbPage);
  62661. if( rc==SQLITE_OK ){
  62662. #ifndef SQLITE_OMIT_QUICKBALANCE
  62663. if( pPage->intKeyLeaf
  62664. && pPage->nOverflow==1
  62665. && pPage->aiOvfl[0]==pPage->nCell
  62666. && pParent->pgno!=1
  62667. && pParent->nCell==iIdx
  62668. ){
  62669. /* Call balance_quick() to create a new sibling of pPage on which
  62670. ** to store the overflow cell. balance_quick() inserts a new cell
  62671. ** into pParent, which may cause pParent overflow. If this
  62672. ** happens, the next iteration of the do-loop will balance pParent
  62673. ** use either balance_nonroot() or balance_deeper(). Until this
  62674. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  62675. ** buffer.
  62676. **
  62677. ** The purpose of the following assert() is to check that only a
  62678. ** single call to balance_quick() is made for each call to this
  62679. ** function. If this were not verified, a subtle bug involving reuse
  62680. ** of the aBalanceQuickSpace[] might sneak in.
  62681. */
  62682. assert( balance_quick_called==0 );
  62683. VVA_ONLY( balance_quick_called++ );
  62684. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  62685. }else
  62686. #endif
  62687. {
  62688. /* In this case, call balance_nonroot() to redistribute cells
  62689. ** between pPage and up to 2 of its sibling pages. This involves
  62690. ** modifying the contents of pParent, which may cause pParent to
  62691. ** become overfull or underfull. The next iteration of the do-loop
  62692. ** will balance the parent page to correct this.
  62693. **
  62694. ** If the parent page becomes overfull, the overflow cell or cells
  62695. ** are stored in the pSpace buffer allocated immediately below.
  62696. ** A subsequent iteration of the do-loop will deal with this by
  62697. ** calling balance_nonroot() (balance_deeper() may be called first,
  62698. ** but it doesn't deal with overflow cells - just moves them to a
  62699. ** different page). Once this subsequent call to balance_nonroot()
  62700. ** has completed, it is safe to release the pSpace buffer used by
  62701. ** the previous call, as the overflow cell data will have been
  62702. ** copied either into the body of a database page or into the new
  62703. ** pSpace buffer passed to the latter call to balance_nonroot().
  62704. */
  62705. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  62706. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  62707. pCur->hints&BTREE_BULKLOAD);
  62708. if( pFree ){
  62709. /* If pFree is not NULL, it points to the pSpace buffer used
  62710. ** by a previous call to balance_nonroot(). Its contents are
  62711. ** now stored either on real database pages or within the
  62712. ** new pSpace buffer, so it may be safely freed here. */
  62713. sqlite3PageFree(pFree);
  62714. }
  62715. /* The pSpace buffer will be freed after the next call to
  62716. ** balance_nonroot(), or just before this function returns, whichever
  62717. ** comes first. */
  62718. pFree = pSpace;
  62719. }
  62720. }
  62721. pPage->nOverflow = 0;
  62722. /* The next iteration of the do-loop balances the parent page. */
  62723. releasePage(pPage);
  62724. pCur->iPage--;
  62725. assert( pCur->iPage>=0 );
  62726. }
  62727. }while( rc==SQLITE_OK );
  62728. if( pFree ){
  62729. sqlite3PageFree(pFree);
  62730. }
  62731. return rc;
  62732. }
  62733. /*
  62734. ** Insert a new record into the BTree. The content of the new record
  62735. ** is described by the pX object. The pCur cursor is used only to
  62736. ** define what table the record should be inserted into, and is left
  62737. ** pointing at a random location.
  62738. **
  62739. ** For a table btree (used for rowid tables), only the pX.nKey value of
  62740. ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
  62741. ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
  62742. ** hold the content of the row.
  62743. **
  62744. ** For an index btree (used for indexes and WITHOUT ROWID tables), the
  62745. ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
  62746. ** pX.pData,nData,nZero fields must be zero.
  62747. **
  62748. ** If the seekResult parameter is non-zero, then a successful call to
  62749. ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
  62750. ** been performed. In other words, if seekResult!=0 then the cursor
  62751. ** is currently pointing to a cell that will be adjacent to the cell
  62752. ** to be inserted. If seekResult<0 then pCur points to a cell that is
  62753. ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
  62754. ** that is larger than (pKey,nKey).
  62755. **
  62756. ** If seekResult==0, that means pCur is pointing at some unknown location.
  62757. ** In that case, this routine must seek the cursor to the correct insertion
  62758. ** point for (pKey,nKey) before doing the insertion. For index btrees,
  62759. ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
  62760. ** key values and pX->aMem can be used instead of pX->pKey to avoid having
  62761. ** to decode the key.
  62762. */
  62763. SQLITE_PRIVATE int sqlite3BtreeInsert(
  62764. BtCursor *pCur, /* Insert data into the table of this cursor */
  62765. const BtreePayload *pX, /* Content of the row to be inserted */
  62766. int flags, /* True if this is likely an append */
  62767. int seekResult /* Result of prior MovetoUnpacked() call */
  62768. ){
  62769. int rc;
  62770. int loc = seekResult; /* -1: before desired location +1: after */
  62771. int szNew = 0;
  62772. int idx;
  62773. MemPage *pPage;
  62774. Btree *p = pCur->pBtree;
  62775. BtShared *pBt = p->pBt;
  62776. unsigned char *oldCell;
  62777. unsigned char *newCell = 0;
  62778. assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
  62779. if( pCur->eState==CURSOR_FAULT ){
  62780. assert( pCur->skipNext!=SQLITE_OK );
  62781. return pCur->skipNext;
  62782. }
  62783. assert( cursorOwnsBtShared(pCur) );
  62784. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  62785. && pBt->inTransaction==TRANS_WRITE
  62786. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  62787. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  62788. /* Assert that the caller has been consistent. If this cursor was opened
  62789. ** expecting an index b-tree, then the caller should be inserting blob
  62790. ** keys with no associated data. If the cursor was opened expecting an
  62791. ** intkey table, the caller should be inserting integer keys with a
  62792. ** blob of associated data. */
  62793. assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
  62794. /* Save the positions of any other cursors open on this table.
  62795. **
  62796. ** In some cases, the call to btreeMoveto() below is a no-op. For
  62797. ** example, when inserting data into a table with auto-generated integer
  62798. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  62799. ** integer key to use. It then calls this function to actually insert the
  62800. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  62801. ** that the cursor is already where it needs to be and returns without
  62802. ** doing any work. To avoid thwarting these optimizations, it is important
  62803. ** not to clear the cursor here.
  62804. */
  62805. if( pCur->curFlags & BTCF_Multiple ){
  62806. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  62807. if( rc ) return rc;
  62808. }
  62809. if( pCur->pKeyInfo==0 ){
  62810. assert( pX->pKey==0 );
  62811. /* If this is an insert into a table b-tree, invalidate any incrblob
  62812. ** cursors open on the row being replaced */
  62813. invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
  62814. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  62815. ** to a row with the same key as the new entry being inserted. */
  62816. assert( (flags & BTREE_SAVEPOSITION)==0 ||
  62817. ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
  62818. /* If the cursor is currently on the last row and we are appending a
  62819. ** new row onto the end, set the "loc" to avoid an unnecessary
  62820. ** btreeMoveto() call */
  62821. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
  62822. loc = 0;
  62823. }else if( loc==0 ){
  62824. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
  62825. if( rc ) return rc;
  62826. }
  62827. }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
  62828. if( pX->nMem ){
  62829. UnpackedRecord r;
  62830. r.pKeyInfo = pCur->pKeyInfo;
  62831. r.aMem = pX->aMem;
  62832. r.nField = pX->nMem;
  62833. r.default_rc = 0;
  62834. r.errCode = 0;
  62835. r.r1 = 0;
  62836. r.r2 = 0;
  62837. r.eqSeen = 0;
  62838. rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
  62839. }else{
  62840. rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
  62841. }
  62842. if( rc ) return rc;
  62843. }
  62844. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  62845. pPage = pCur->apPage[pCur->iPage];
  62846. assert( pPage->intKey || pX->nKey>=0 );
  62847. assert( pPage->leaf || !pPage->intKey );
  62848. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  62849. pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
  62850. loc==0 ? "overwrite" : "new entry"));
  62851. assert( pPage->isInit );
  62852. newCell = pBt->pTmpSpace;
  62853. assert( newCell!=0 );
  62854. rc = fillInCell(pPage, newCell, pX, &szNew);
  62855. if( rc ) goto end_insert;
  62856. assert( szNew==pPage->xCellSize(pPage, newCell) );
  62857. assert( szNew <= MX_CELL_SIZE(pBt) );
  62858. idx = pCur->ix;
  62859. if( loc==0 ){
  62860. CellInfo info;
  62861. assert( idx<pPage->nCell );
  62862. rc = sqlite3PagerWrite(pPage->pDbPage);
  62863. if( rc ){
  62864. goto end_insert;
  62865. }
  62866. oldCell = findCell(pPage, idx);
  62867. if( !pPage->leaf ){
  62868. memcpy(newCell, oldCell, 4);
  62869. }
  62870. rc = clearCell(pPage, oldCell, &info);
  62871. if( info.nSize==szNew && info.nLocal==info.nPayload
  62872. && (!ISAUTOVACUUM || szNew<pPage->minLocal)
  62873. ){
  62874. /* Overwrite the old cell with the new if they are the same size.
  62875. ** We could also try to do this if the old cell is smaller, then add
  62876. ** the leftover space to the free list. But experiments show that
  62877. ** doing that is no faster then skipping this optimization and just
  62878. ** calling dropCell() and insertCell().
  62879. **
  62880. ** This optimization cannot be used on an autovacuum database if the
  62881. ** new entry uses overflow pages, as the insertCell() call below is
  62882. ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
  62883. assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
  62884. if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  62885. memcpy(oldCell, newCell, szNew);
  62886. return SQLITE_OK;
  62887. }
  62888. dropCell(pPage, idx, info.nSize, &rc);
  62889. if( rc ) goto end_insert;
  62890. }else if( loc<0 && pPage->nCell>0 ){
  62891. assert( pPage->leaf );
  62892. idx = ++pCur->ix;
  62893. pCur->curFlags &= ~BTCF_ValidNKey;
  62894. }else{
  62895. assert( pPage->leaf );
  62896. }
  62897. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  62898. assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  62899. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  62900. /* If no error has occurred and pPage has an overflow cell, call balance()
  62901. ** to redistribute the cells within the tree. Since balance() may move
  62902. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  62903. ** variables.
  62904. **
  62905. ** Previous versions of SQLite called moveToRoot() to move the cursor
  62906. ** back to the root page as balance() used to invalidate the contents
  62907. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  62908. ** set the cursor state to "invalid". This makes common insert operations
  62909. ** slightly faster.
  62910. **
  62911. ** There is a subtle but important optimization here too. When inserting
  62912. ** multiple records into an intkey b-tree using a single cursor (as can
  62913. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  62914. ** is advantageous to leave the cursor pointing to the last entry in
  62915. ** the b-tree if possible. If the cursor is left pointing to the last
  62916. ** entry in the table, and the next row inserted has an integer key
  62917. ** larger than the largest existing key, it is possible to insert the
  62918. ** row without seeking the cursor. This can be a big performance boost.
  62919. */
  62920. pCur->info.nSize = 0;
  62921. if( pPage->nOverflow ){
  62922. assert( rc==SQLITE_OK );
  62923. pCur->curFlags &= ~(BTCF_ValidNKey);
  62924. rc = balance(pCur);
  62925. /* Must make sure nOverflow is reset to zero even if the balance()
  62926. ** fails. Internal data structure corruption will result otherwise.
  62927. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  62928. ** from trying to save the current position of the cursor. */
  62929. pCur->apPage[pCur->iPage]->nOverflow = 0;
  62930. pCur->eState = CURSOR_INVALID;
  62931. if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
  62932. rc = moveToRoot(pCur);
  62933. if( pCur->pKeyInfo ){
  62934. assert( pCur->pKey==0 );
  62935. pCur->pKey = sqlite3Malloc( pX->nKey );
  62936. if( pCur->pKey==0 ){
  62937. rc = SQLITE_NOMEM;
  62938. }else{
  62939. memcpy(pCur->pKey, pX->pKey, pX->nKey);
  62940. }
  62941. }
  62942. pCur->eState = CURSOR_REQUIRESEEK;
  62943. pCur->nKey = pX->nKey;
  62944. }
  62945. }
  62946. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  62947. end_insert:
  62948. return rc;
  62949. }
  62950. /*
  62951. ** Delete the entry that the cursor is pointing to.
  62952. **
  62953. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  62954. ** the cursor is left pointing at an arbitrary location after the delete.
  62955. ** But if that bit is set, then the cursor is left in a state such that
  62956. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  62957. ** as it would have been on if the call to BtreeDelete() had been omitted.
  62958. **
  62959. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  62960. ** associated with a single table entry and its indexes. Only one of those
  62961. ** deletes is considered the "primary" delete. The primary delete occurs
  62962. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  62963. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  62964. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  62965. ** but which might be used by alternative storage engines.
  62966. */
  62967. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  62968. Btree *p = pCur->pBtree;
  62969. BtShared *pBt = p->pBt;
  62970. int rc; /* Return code */
  62971. MemPage *pPage; /* Page to delete cell from */
  62972. unsigned char *pCell; /* Pointer to cell to delete */
  62973. int iCellIdx; /* Index of cell to delete */
  62974. int iCellDepth; /* Depth of node containing pCell */
  62975. CellInfo info; /* Size of the cell being deleted */
  62976. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  62977. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  62978. assert( cursorOwnsBtShared(pCur) );
  62979. assert( pBt->inTransaction==TRANS_WRITE );
  62980. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  62981. assert( pCur->curFlags & BTCF_WriteFlag );
  62982. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  62983. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  62984. assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
  62985. assert( pCur->eState==CURSOR_VALID );
  62986. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  62987. iCellDepth = pCur->iPage;
  62988. iCellIdx = pCur->ix;
  62989. pPage = pCur->apPage[iCellDepth];
  62990. pCell = findCell(pPage, iCellIdx);
  62991. /* If the bPreserve flag is set to true, then the cursor position must
  62992. ** be preserved following this delete operation. If the current delete
  62993. ** will cause a b-tree rebalance, then this is done by saving the cursor
  62994. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  62995. ** returning.
  62996. **
  62997. ** Or, if the current delete will not cause a rebalance, then the cursor
  62998. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  62999. ** before or after the deleted entry. In this case set bSkipnext to true. */
  63000. if( bPreserve ){
  63001. if( !pPage->leaf
  63002. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  63003. ){
  63004. /* A b-tree rebalance will be required after deleting this entry.
  63005. ** Save the cursor key. */
  63006. rc = saveCursorKey(pCur);
  63007. if( rc ) return rc;
  63008. }else{
  63009. bSkipnext = 1;
  63010. }
  63011. }
  63012. /* If the page containing the entry to delete is not a leaf page, move
  63013. ** the cursor to the largest entry in the tree that is smaller than
  63014. ** the entry being deleted. This cell will replace the cell being deleted
  63015. ** from the internal node. The 'previous' entry is used for this instead
  63016. ** of the 'next' entry, as the previous entry is always a part of the
  63017. ** sub-tree headed by the child page of the cell being deleted. This makes
  63018. ** balancing the tree following the delete operation easier. */
  63019. if( !pPage->leaf ){
  63020. int notUsed = 0;
  63021. rc = sqlite3BtreePrevious(pCur, &notUsed);
  63022. if( rc ) return rc;
  63023. }
  63024. /* Save the positions of any other cursors open on this table before
  63025. ** making any modifications. */
  63026. if( pCur->curFlags & BTCF_Multiple ){
  63027. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  63028. if( rc ) return rc;
  63029. }
  63030. /* If this is a delete operation to remove a row from a table b-tree,
  63031. ** invalidate any incrblob cursors open on the row being deleted. */
  63032. if( pCur->pKeyInfo==0 ){
  63033. invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
  63034. }
  63035. /* Make the page containing the entry to be deleted writable. Then free any
  63036. ** overflow pages associated with the entry and finally remove the cell
  63037. ** itself from within the page. */
  63038. rc = sqlite3PagerWrite(pPage->pDbPage);
  63039. if( rc ) return rc;
  63040. rc = clearCell(pPage, pCell, &info);
  63041. dropCell(pPage, iCellIdx, info.nSize, &rc);
  63042. if( rc ) return rc;
  63043. /* If the cell deleted was not located on a leaf page, then the cursor
  63044. ** is currently pointing to the largest entry in the sub-tree headed
  63045. ** by the child-page of the cell that was just deleted from an internal
  63046. ** node. The cell from the leaf node needs to be moved to the internal
  63047. ** node to replace the deleted cell. */
  63048. if( !pPage->leaf ){
  63049. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  63050. int nCell;
  63051. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  63052. unsigned char *pTmp;
  63053. pCell = findCell(pLeaf, pLeaf->nCell-1);
  63054. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  63055. nCell = pLeaf->xCellSize(pLeaf, pCell);
  63056. assert( MX_CELL_SIZE(pBt) >= nCell );
  63057. pTmp = pBt->pTmpSpace;
  63058. assert( pTmp!=0 );
  63059. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  63060. if( rc==SQLITE_OK ){
  63061. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  63062. }
  63063. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  63064. if( rc ) return rc;
  63065. }
  63066. /* Balance the tree. If the entry deleted was located on a leaf page,
  63067. ** then the cursor still points to that page. In this case the first
  63068. ** call to balance() repairs the tree, and the if(...) condition is
  63069. ** never true.
  63070. **
  63071. ** Otherwise, if the entry deleted was on an internal node page, then
  63072. ** pCur is pointing to the leaf page from which a cell was removed to
  63073. ** replace the cell deleted from the internal node. This is slightly
  63074. ** tricky as the leaf node may be underfull, and the internal node may
  63075. ** be either under or overfull. In this case run the balancing algorithm
  63076. ** on the leaf node first. If the balance proceeds far enough up the
  63077. ** tree that we can be sure that any problem in the internal node has
  63078. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  63079. ** walk the cursor up the tree to the internal node and balance it as
  63080. ** well. */
  63081. rc = balance(pCur);
  63082. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  63083. while( pCur->iPage>iCellDepth ){
  63084. releasePage(pCur->apPage[pCur->iPage--]);
  63085. }
  63086. rc = balance(pCur);
  63087. }
  63088. if( rc==SQLITE_OK ){
  63089. if( bSkipnext ){
  63090. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  63091. assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
  63092. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  63093. pCur->eState = CURSOR_SKIPNEXT;
  63094. if( iCellIdx>=pPage->nCell ){
  63095. pCur->skipNext = -1;
  63096. pCur->ix = pPage->nCell-1;
  63097. }else{
  63098. pCur->skipNext = 1;
  63099. }
  63100. }else{
  63101. rc = moveToRoot(pCur);
  63102. if( bPreserve ){
  63103. pCur->eState = CURSOR_REQUIRESEEK;
  63104. }
  63105. }
  63106. }
  63107. return rc;
  63108. }
  63109. /*
  63110. ** Create a new BTree table. Write into *piTable the page
  63111. ** number for the root page of the new table.
  63112. **
  63113. ** The type of type is determined by the flags parameter. Only the
  63114. ** following values of flags are currently in use. Other values for
  63115. ** flags might not work:
  63116. **
  63117. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  63118. ** BTREE_ZERODATA Used for SQL indices
  63119. */
  63120. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  63121. BtShared *pBt = p->pBt;
  63122. MemPage *pRoot;
  63123. Pgno pgnoRoot;
  63124. int rc;
  63125. int ptfFlags; /* Page-type flage for the root page of new table */
  63126. assert( sqlite3BtreeHoldsMutex(p) );
  63127. assert( pBt->inTransaction==TRANS_WRITE );
  63128. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63129. #ifdef SQLITE_OMIT_AUTOVACUUM
  63130. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  63131. if( rc ){
  63132. return rc;
  63133. }
  63134. #else
  63135. if( pBt->autoVacuum ){
  63136. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  63137. MemPage *pPageMove; /* The page to move to. */
  63138. /* Creating a new table may probably require moving an existing database
  63139. ** to make room for the new tables root page. In case this page turns
  63140. ** out to be an overflow page, delete all overflow page-map caches
  63141. ** held by open cursors.
  63142. */
  63143. invalidateAllOverflowCache(pBt);
  63144. /* Read the value of meta[3] from the database to determine where the
  63145. ** root page of the new table should go. meta[3] is the largest root-page
  63146. ** created so far, so the new root-page is (meta[3]+1).
  63147. */
  63148. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  63149. pgnoRoot++;
  63150. /* The new root-page may not be allocated on a pointer-map page, or the
  63151. ** PENDING_BYTE page.
  63152. */
  63153. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  63154. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  63155. pgnoRoot++;
  63156. }
  63157. assert( pgnoRoot>=3 || CORRUPT_DB );
  63158. testcase( pgnoRoot<3 );
  63159. /* Allocate a page. The page that currently resides at pgnoRoot will
  63160. ** be moved to the allocated page (unless the allocated page happens
  63161. ** to reside at pgnoRoot).
  63162. */
  63163. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  63164. if( rc!=SQLITE_OK ){
  63165. return rc;
  63166. }
  63167. if( pgnoMove!=pgnoRoot ){
  63168. /* pgnoRoot is the page that will be used for the root-page of
  63169. ** the new table (assuming an error did not occur). But we were
  63170. ** allocated pgnoMove. If required (i.e. if it was not allocated
  63171. ** by extending the file), the current page at position pgnoMove
  63172. ** is already journaled.
  63173. */
  63174. u8 eType = 0;
  63175. Pgno iPtrPage = 0;
  63176. /* Save the positions of any open cursors. This is required in
  63177. ** case they are holding a reference to an xFetch reference
  63178. ** corresponding to page pgnoRoot. */
  63179. rc = saveAllCursors(pBt, 0, 0);
  63180. releasePage(pPageMove);
  63181. if( rc!=SQLITE_OK ){
  63182. return rc;
  63183. }
  63184. /* Move the page currently at pgnoRoot to pgnoMove. */
  63185. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  63186. if( rc!=SQLITE_OK ){
  63187. return rc;
  63188. }
  63189. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  63190. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  63191. rc = SQLITE_CORRUPT_BKPT;
  63192. }
  63193. if( rc!=SQLITE_OK ){
  63194. releasePage(pRoot);
  63195. return rc;
  63196. }
  63197. assert( eType!=PTRMAP_ROOTPAGE );
  63198. assert( eType!=PTRMAP_FREEPAGE );
  63199. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  63200. releasePage(pRoot);
  63201. /* Obtain the page at pgnoRoot */
  63202. if( rc!=SQLITE_OK ){
  63203. return rc;
  63204. }
  63205. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  63206. if( rc!=SQLITE_OK ){
  63207. return rc;
  63208. }
  63209. rc = sqlite3PagerWrite(pRoot->pDbPage);
  63210. if( rc!=SQLITE_OK ){
  63211. releasePage(pRoot);
  63212. return rc;
  63213. }
  63214. }else{
  63215. pRoot = pPageMove;
  63216. }
  63217. /* Update the pointer-map and meta-data with the new root-page number. */
  63218. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  63219. if( rc ){
  63220. releasePage(pRoot);
  63221. return rc;
  63222. }
  63223. /* When the new root page was allocated, page 1 was made writable in
  63224. ** order either to increase the database filesize, or to decrement the
  63225. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  63226. */
  63227. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  63228. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  63229. if( NEVER(rc) ){
  63230. releasePage(pRoot);
  63231. return rc;
  63232. }
  63233. }else{
  63234. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  63235. if( rc ) return rc;
  63236. }
  63237. #endif
  63238. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  63239. if( createTabFlags & BTREE_INTKEY ){
  63240. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  63241. }else{
  63242. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  63243. }
  63244. zeroPage(pRoot, ptfFlags);
  63245. sqlite3PagerUnref(pRoot->pDbPage);
  63246. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  63247. *piTable = (int)pgnoRoot;
  63248. return SQLITE_OK;
  63249. }
  63250. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  63251. int rc;
  63252. sqlite3BtreeEnter(p);
  63253. rc = btreeCreateTable(p, piTable, flags);
  63254. sqlite3BtreeLeave(p);
  63255. return rc;
  63256. }
  63257. /*
  63258. ** Erase the given database page and all its children. Return
  63259. ** the page to the freelist.
  63260. */
  63261. static int clearDatabasePage(
  63262. BtShared *pBt, /* The BTree that contains the table */
  63263. Pgno pgno, /* Page number to clear */
  63264. int freePageFlag, /* Deallocate page if true */
  63265. int *pnChange /* Add number of Cells freed to this counter */
  63266. ){
  63267. MemPage *pPage;
  63268. int rc;
  63269. unsigned char *pCell;
  63270. int i;
  63271. int hdr;
  63272. CellInfo info;
  63273. assert( sqlite3_mutex_held(pBt->mutex) );
  63274. if( pgno>btreePagecount(pBt) ){
  63275. return SQLITE_CORRUPT_BKPT;
  63276. }
  63277. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  63278. if( rc ) return rc;
  63279. if( pPage->bBusy ){
  63280. rc = SQLITE_CORRUPT_BKPT;
  63281. goto cleardatabasepage_out;
  63282. }
  63283. pPage->bBusy = 1;
  63284. hdr = pPage->hdrOffset;
  63285. for(i=0; i<pPage->nCell; i++){
  63286. pCell = findCell(pPage, i);
  63287. if( !pPage->leaf ){
  63288. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  63289. if( rc ) goto cleardatabasepage_out;
  63290. }
  63291. rc = clearCell(pPage, pCell, &info);
  63292. if( rc ) goto cleardatabasepage_out;
  63293. }
  63294. if( !pPage->leaf ){
  63295. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  63296. if( rc ) goto cleardatabasepage_out;
  63297. }else if( pnChange ){
  63298. assert( pPage->intKey || CORRUPT_DB );
  63299. testcase( !pPage->intKey );
  63300. *pnChange += pPage->nCell;
  63301. }
  63302. if( freePageFlag ){
  63303. freePage(pPage, &rc);
  63304. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  63305. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  63306. }
  63307. cleardatabasepage_out:
  63308. pPage->bBusy = 0;
  63309. releasePage(pPage);
  63310. return rc;
  63311. }
  63312. /*
  63313. ** Delete all information from a single table in the database. iTable is
  63314. ** the page number of the root of the table. After this routine returns,
  63315. ** the root page is empty, but still exists.
  63316. **
  63317. ** This routine will fail with SQLITE_LOCKED if there are any open
  63318. ** read cursors on the table. Open write cursors are moved to the
  63319. ** root of the table.
  63320. **
  63321. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  63322. ** integer value pointed to by pnChange is incremented by the number of
  63323. ** entries in the table.
  63324. */
  63325. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  63326. int rc;
  63327. BtShared *pBt = p->pBt;
  63328. sqlite3BtreeEnter(p);
  63329. assert( p->inTrans==TRANS_WRITE );
  63330. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  63331. if( SQLITE_OK==rc ){
  63332. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  63333. ** is the root of a table b-tree - if it is not, the following call is
  63334. ** a no-op). */
  63335. invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
  63336. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  63337. }
  63338. sqlite3BtreeLeave(p);
  63339. return rc;
  63340. }
  63341. /*
  63342. ** Delete all information from the single table that pCur is open on.
  63343. **
  63344. ** This routine only work for pCur on an ephemeral table.
  63345. */
  63346. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  63347. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  63348. }
  63349. /*
  63350. ** Erase all information in a table and add the root of the table to
  63351. ** the freelist. Except, the root of the principle table (the one on
  63352. ** page 1) is never added to the freelist.
  63353. **
  63354. ** This routine will fail with SQLITE_LOCKED if there are any open
  63355. ** cursors on the table.
  63356. **
  63357. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  63358. ** root page in the database file, then the last root page
  63359. ** in the database file is moved into the slot formerly occupied by
  63360. ** iTable and that last slot formerly occupied by the last root page
  63361. ** is added to the freelist instead of iTable. In this say, all
  63362. ** root pages are kept at the beginning of the database file, which
  63363. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  63364. ** page number that used to be the last root page in the file before
  63365. ** the move. If no page gets moved, *piMoved is set to 0.
  63366. ** The last root page is recorded in meta[3] and the value of
  63367. ** meta[3] is updated by this procedure.
  63368. */
  63369. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  63370. int rc;
  63371. MemPage *pPage = 0;
  63372. BtShared *pBt = p->pBt;
  63373. assert( sqlite3BtreeHoldsMutex(p) );
  63374. assert( p->inTrans==TRANS_WRITE );
  63375. assert( iTable>=2 );
  63376. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  63377. if( rc ) return rc;
  63378. rc = sqlite3BtreeClearTable(p, iTable, 0);
  63379. if( rc ){
  63380. releasePage(pPage);
  63381. return rc;
  63382. }
  63383. *piMoved = 0;
  63384. #ifdef SQLITE_OMIT_AUTOVACUUM
  63385. freePage(pPage, &rc);
  63386. releasePage(pPage);
  63387. #else
  63388. if( pBt->autoVacuum ){
  63389. Pgno maxRootPgno;
  63390. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  63391. if( iTable==maxRootPgno ){
  63392. /* If the table being dropped is the table with the largest root-page
  63393. ** number in the database, put the root page on the free list.
  63394. */
  63395. freePage(pPage, &rc);
  63396. releasePage(pPage);
  63397. if( rc!=SQLITE_OK ){
  63398. return rc;
  63399. }
  63400. }else{
  63401. /* The table being dropped does not have the largest root-page
  63402. ** number in the database. So move the page that does into the
  63403. ** gap left by the deleted root-page.
  63404. */
  63405. MemPage *pMove;
  63406. releasePage(pPage);
  63407. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  63408. if( rc!=SQLITE_OK ){
  63409. return rc;
  63410. }
  63411. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  63412. releasePage(pMove);
  63413. if( rc!=SQLITE_OK ){
  63414. return rc;
  63415. }
  63416. pMove = 0;
  63417. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  63418. freePage(pMove, &rc);
  63419. releasePage(pMove);
  63420. if( rc!=SQLITE_OK ){
  63421. return rc;
  63422. }
  63423. *piMoved = maxRootPgno;
  63424. }
  63425. /* Set the new 'max-root-page' value in the database header. This
  63426. ** is the old value less one, less one more if that happens to
  63427. ** be a root-page number, less one again if that is the
  63428. ** PENDING_BYTE_PAGE.
  63429. */
  63430. maxRootPgno--;
  63431. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  63432. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  63433. maxRootPgno--;
  63434. }
  63435. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  63436. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  63437. }else{
  63438. freePage(pPage, &rc);
  63439. releasePage(pPage);
  63440. }
  63441. #endif
  63442. return rc;
  63443. }
  63444. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  63445. int rc;
  63446. sqlite3BtreeEnter(p);
  63447. rc = btreeDropTable(p, iTable, piMoved);
  63448. sqlite3BtreeLeave(p);
  63449. return rc;
  63450. }
  63451. /*
  63452. ** This function may only be called if the b-tree connection already
  63453. ** has a read or write transaction open on the database.
  63454. **
  63455. ** Read the meta-information out of a database file. Meta[0]
  63456. ** is the number of free pages currently in the database. Meta[1]
  63457. ** through meta[15] are available for use by higher layers. Meta[0]
  63458. ** is read-only, the others are read/write.
  63459. **
  63460. ** The schema layer numbers meta values differently. At the schema
  63461. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  63462. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  63463. **
  63464. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  63465. ** of reading the value out of the header, it instead loads the "DataVersion"
  63466. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  63467. ** database file. It is a number computed by the pager. But its access
  63468. ** pattern is the same as header meta values, and so it is convenient to
  63469. ** read it from this routine.
  63470. */
  63471. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  63472. BtShared *pBt = p->pBt;
  63473. sqlite3BtreeEnter(p);
  63474. assert( p->inTrans>TRANS_NONE );
  63475. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  63476. assert( pBt->pPage1 );
  63477. assert( idx>=0 && idx<=15 );
  63478. if( idx==BTREE_DATA_VERSION ){
  63479. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  63480. }else{
  63481. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  63482. }
  63483. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  63484. ** database, mark the database as read-only. */
  63485. #ifdef SQLITE_OMIT_AUTOVACUUM
  63486. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  63487. pBt->btsFlags |= BTS_READ_ONLY;
  63488. }
  63489. #endif
  63490. sqlite3BtreeLeave(p);
  63491. }
  63492. /*
  63493. ** Write meta-information back into the database. Meta[0] is
  63494. ** read-only and may not be written.
  63495. */
  63496. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  63497. BtShared *pBt = p->pBt;
  63498. unsigned char *pP1;
  63499. int rc;
  63500. assert( idx>=1 && idx<=15 );
  63501. sqlite3BtreeEnter(p);
  63502. assert( p->inTrans==TRANS_WRITE );
  63503. assert( pBt->pPage1!=0 );
  63504. pP1 = pBt->pPage1->aData;
  63505. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  63506. if( rc==SQLITE_OK ){
  63507. put4byte(&pP1[36 + idx*4], iMeta);
  63508. #ifndef SQLITE_OMIT_AUTOVACUUM
  63509. if( idx==BTREE_INCR_VACUUM ){
  63510. assert( pBt->autoVacuum || iMeta==0 );
  63511. assert( iMeta==0 || iMeta==1 );
  63512. pBt->incrVacuum = (u8)iMeta;
  63513. }
  63514. #endif
  63515. }
  63516. sqlite3BtreeLeave(p);
  63517. return rc;
  63518. }
  63519. #ifndef SQLITE_OMIT_BTREECOUNT
  63520. /*
  63521. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  63522. ** number of entries in the b-tree and write the result to *pnEntry.
  63523. **
  63524. ** SQLITE_OK is returned if the operation is successfully executed.
  63525. ** Otherwise, if an error is encountered (i.e. an IO error or database
  63526. ** corruption) an SQLite error code is returned.
  63527. */
  63528. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  63529. i64 nEntry = 0; /* Value to return in *pnEntry */
  63530. int rc; /* Return code */
  63531. if( pCur->pgnoRoot==0 ){
  63532. *pnEntry = 0;
  63533. return SQLITE_OK;
  63534. }
  63535. rc = moveToRoot(pCur);
  63536. /* Unless an error occurs, the following loop runs one iteration for each
  63537. ** page in the B-Tree structure (not including overflow pages).
  63538. */
  63539. while( rc==SQLITE_OK ){
  63540. int iIdx; /* Index of child node in parent */
  63541. MemPage *pPage; /* Current page of the b-tree */
  63542. /* If this is a leaf page or the tree is not an int-key tree, then
  63543. ** this page contains countable entries. Increment the entry counter
  63544. ** accordingly.
  63545. */
  63546. pPage = pCur->apPage[pCur->iPage];
  63547. if( pPage->leaf || !pPage->intKey ){
  63548. nEntry += pPage->nCell;
  63549. }
  63550. /* pPage is a leaf node. This loop navigates the cursor so that it
  63551. ** points to the first interior cell that it points to the parent of
  63552. ** the next page in the tree that has not yet been visited. The
  63553. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  63554. ** of the page, or to the number of cells in the page if the next page
  63555. ** to visit is the right-child of its parent.
  63556. **
  63557. ** If all pages in the tree have been visited, return SQLITE_OK to the
  63558. ** caller.
  63559. */
  63560. if( pPage->leaf ){
  63561. do {
  63562. if( pCur->iPage==0 ){
  63563. /* All pages of the b-tree have been visited. Return successfully. */
  63564. *pnEntry = nEntry;
  63565. return moveToRoot(pCur);
  63566. }
  63567. moveToParent(pCur);
  63568. }while ( pCur->ix>=pCur->apPage[pCur->iPage]->nCell );
  63569. pCur->ix++;
  63570. pPage = pCur->apPage[pCur->iPage];
  63571. }
  63572. /* Descend to the child node of the cell that the cursor currently
  63573. ** points at. This is the right-child if (iIdx==pPage->nCell).
  63574. */
  63575. iIdx = pCur->ix;
  63576. if( iIdx==pPage->nCell ){
  63577. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  63578. }else{
  63579. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  63580. }
  63581. }
  63582. /* An error has occurred. Return an error code. */
  63583. return rc;
  63584. }
  63585. #endif
  63586. /*
  63587. ** Return the pager associated with a BTree. This routine is used for
  63588. ** testing and debugging only.
  63589. */
  63590. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  63591. return p->pBt->pPager;
  63592. }
  63593. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  63594. /*
  63595. ** Append a message to the error message string.
  63596. */
  63597. static void checkAppendMsg(
  63598. IntegrityCk *pCheck,
  63599. const char *zFormat,
  63600. ...
  63601. ){
  63602. va_list ap;
  63603. if( !pCheck->mxErr ) return;
  63604. pCheck->mxErr--;
  63605. pCheck->nErr++;
  63606. va_start(ap, zFormat);
  63607. if( pCheck->errMsg.nChar ){
  63608. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  63609. }
  63610. if( pCheck->zPfx ){
  63611. sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  63612. }
  63613. sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
  63614. va_end(ap);
  63615. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  63616. pCheck->mallocFailed = 1;
  63617. }
  63618. }
  63619. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  63620. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  63621. /*
  63622. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  63623. ** corresponds to page iPg is already set.
  63624. */
  63625. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  63626. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  63627. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  63628. }
  63629. /*
  63630. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  63631. */
  63632. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  63633. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  63634. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  63635. }
  63636. /*
  63637. ** Add 1 to the reference count for page iPage. If this is the second
  63638. ** reference to the page, add an error message to pCheck->zErrMsg.
  63639. ** Return 1 if there are 2 or more references to the page and 0 if
  63640. ** if this is the first reference to the page.
  63641. **
  63642. ** Also check that the page number is in bounds.
  63643. */
  63644. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  63645. if( iPage==0 ) return 1;
  63646. if( iPage>pCheck->nPage ){
  63647. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  63648. return 1;
  63649. }
  63650. if( getPageReferenced(pCheck, iPage) ){
  63651. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  63652. return 1;
  63653. }
  63654. setPageReferenced(pCheck, iPage);
  63655. return 0;
  63656. }
  63657. #ifndef SQLITE_OMIT_AUTOVACUUM
  63658. /*
  63659. ** Check that the entry in the pointer-map for page iChild maps to
  63660. ** page iParent, pointer type ptrType. If not, append an error message
  63661. ** to pCheck.
  63662. */
  63663. static void checkPtrmap(
  63664. IntegrityCk *pCheck, /* Integrity check context */
  63665. Pgno iChild, /* Child page number */
  63666. u8 eType, /* Expected pointer map type */
  63667. Pgno iParent /* Expected pointer map parent page number */
  63668. ){
  63669. int rc;
  63670. u8 ePtrmapType;
  63671. Pgno iPtrmapParent;
  63672. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  63673. if( rc!=SQLITE_OK ){
  63674. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  63675. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  63676. return;
  63677. }
  63678. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  63679. checkAppendMsg(pCheck,
  63680. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  63681. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  63682. }
  63683. }
  63684. #endif
  63685. /*
  63686. ** Check the integrity of the freelist or of an overflow page list.
  63687. ** Verify that the number of pages on the list is N.
  63688. */
  63689. static void checkList(
  63690. IntegrityCk *pCheck, /* Integrity checking context */
  63691. int isFreeList, /* True for a freelist. False for overflow page list */
  63692. int iPage, /* Page number for first page in the list */
  63693. int N /* Expected number of pages in the list */
  63694. ){
  63695. int i;
  63696. int expected = N;
  63697. int iFirst = iPage;
  63698. while( N-- > 0 && pCheck->mxErr ){
  63699. DbPage *pOvflPage;
  63700. unsigned char *pOvflData;
  63701. if( iPage<1 ){
  63702. checkAppendMsg(pCheck,
  63703. "%d of %d pages missing from overflow list starting at %d",
  63704. N+1, expected, iFirst);
  63705. break;
  63706. }
  63707. if( checkRef(pCheck, iPage) ) break;
  63708. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  63709. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  63710. break;
  63711. }
  63712. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  63713. if( isFreeList ){
  63714. int n = get4byte(&pOvflData[4]);
  63715. #ifndef SQLITE_OMIT_AUTOVACUUM
  63716. if( pCheck->pBt->autoVacuum ){
  63717. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  63718. }
  63719. #endif
  63720. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  63721. checkAppendMsg(pCheck,
  63722. "freelist leaf count too big on page %d", iPage);
  63723. N--;
  63724. }else{
  63725. for(i=0; i<n; i++){
  63726. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  63727. #ifndef SQLITE_OMIT_AUTOVACUUM
  63728. if( pCheck->pBt->autoVacuum ){
  63729. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  63730. }
  63731. #endif
  63732. checkRef(pCheck, iFreePage);
  63733. }
  63734. N -= n;
  63735. }
  63736. }
  63737. #ifndef SQLITE_OMIT_AUTOVACUUM
  63738. else{
  63739. /* If this database supports auto-vacuum and iPage is not the last
  63740. ** page in this overflow list, check that the pointer-map entry for
  63741. ** the following page matches iPage.
  63742. */
  63743. if( pCheck->pBt->autoVacuum && N>0 ){
  63744. i = get4byte(pOvflData);
  63745. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  63746. }
  63747. }
  63748. #endif
  63749. iPage = get4byte(pOvflData);
  63750. sqlite3PagerUnref(pOvflPage);
  63751. if( isFreeList && N<(iPage!=0) ){
  63752. checkAppendMsg(pCheck, "free-page count in header is too small");
  63753. }
  63754. }
  63755. }
  63756. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  63757. /*
  63758. ** An implementation of a min-heap.
  63759. **
  63760. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  63761. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  63762. ** and aHeap[N*2+1].
  63763. **
  63764. ** The heap property is this: Every node is less than or equal to both
  63765. ** of its daughter nodes. A consequence of the heap property is that the
  63766. ** root node aHeap[1] is always the minimum value currently in the heap.
  63767. **
  63768. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  63769. ** the heap, preserving the heap property. The btreeHeapPull() routine
  63770. ** removes the root element from the heap (the minimum value in the heap)
  63771. ** and then moves other nodes around as necessary to preserve the heap
  63772. ** property.
  63773. **
  63774. ** This heap is used for cell overlap and coverage testing. Each u32
  63775. ** entry represents the span of a cell or freeblock on a btree page.
  63776. ** The upper 16 bits are the index of the first byte of a range and the
  63777. ** lower 16 bits are the index of the last byte of that range.
  63778. */
  63779. static void btreeHeapInsert(u32 *aHeap, u32 x){
  63780. u32 j, i = ++aHeap[0];
  63781. aHeap[i] = x;
  63782. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  63783. x = aHeap[j];
  63784. aHeap[j] = aHeap[i];
  63785. aHeap[i] = x;
  63786. i = j;
  63787. }
  63788. }
  63789. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  63790. u32 j, i, x;
  63791. if( (x = aHeap[0])==0 ) return 0;
  63792. *pOut = aHeap[1];
  63793. aHeap[1] = aHeap[x];
  63794. aHeap[x] = 0xffffffff;
  63795. aHeap[0]--;
  63796. i = 1;
  63797. while( (j = i*2)<=aHeap[0] ){
  63798. if( aHeap[j]>aHeap[j+1] ) j++;
  63799. if( aHeap[i]<aHeap[j] ) break;
  63800. x = aHeap[i];
  63801. aHeap[i] = aHeap[j];
  63802. aHeap[j] = x;
  63803. i = j;
  63804. }
  63805. return 1;
  63806. }
  63807. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  63808. /*
  63809. ** Do various sanity checks on a single page of a tree. Return
  63810. ** the tree depth. Root pages return 0. Parents of root pages
  63811. ** return 1, and so forth.
  63812. **
  63813. ** These checks are done:
  63814. **
  63815. ** 1. Make sure that cells and freeblocks do not overlap
  63816. ** but combine to completely cover the page.
  63817. ** 2. Make sure integer cell keys are in order.
  63818. ** 3. Check the integrity of overflow pages.
  63819. ** 4. Recursively call checkTreePage on all children.
  63820. ** 5. Verify that the depth of all children is the same.
  63821. */
  63822. static int checkTreePage(
  63823. IntegrityCk *pCheck, /* Context for the sanity check */
  63824. int iPage, /* Page number of the page to check */
  63825. i64 *piMinKey, /* Write minimum integer primary key here */
  63826. i64 maxKey /* Error if integer primary key greater than this */
  63827. ){
  63828. MemPage *pPage = 0; /* The page being analyzed */
  63829. int i; /* Loop counter */
  63830. int rc; /* Result code from subroutine call */
  63831. int depth = -1, d2; /* Depth of a subtree */
  63832. int pgno; /* Page number */
  63833. int nFrag; /* Number of fragmented bytes on the page */
  63834. int hdr; /* Offset to the page header */
  63835. int cellStart; /* Offset to the start of the cell pointer array */
  63836. int nCell; /* Number of cells */
  63837. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  63838. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  63839. ** False if IPK must be strictly less than maxKey */
  63840. u8 *data; /* Page content */
  63841. u8 *pCell; /* Cell content */
  63842. u8 *pCellIdx; /* Next element of the cell pointer array */
  63843. BtShared *pBt; /* The BtShared object that owns pPage */
  63844. u32 pc; /* Address of a cell */
  63845. u32 usableSize; /* Usable size of the page */
  63846. u32 contentOffset; /* Offset to the start of the cell content area */
  63847. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  63848. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  63849. const char *saved_zPfx = pCheck->zPfx;
  63850. int saved_v1 = pCheck->v1;
  63851. int saved_v2 = pCheck->v2;
  63852. u8 savedIsInit = 0;
  63853. /* Check that the page exists
  63854. */
  63855. pBt = pCheck->pBt;
  63856. usableSize = pBt->usableSize;
  63857. if( iPage==0 ) return 0;
  63858. if( checkRef(pCheck, iPage) ) return 0;
  63859. pCheck->zPfx = "Page %d: ";
  63860. pCheck->v1 = iPage;
  63861. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  63862. checkAppendMsg(pCheck,
  63863. "unable to get the page. error code=%d", rc);
  63864. goto end_of_check;
  63865. }
  63866. /* Clear MemPage.isInit to make sure the corruption detection code in
  63867. ** btreeInitPage() is executed. */
  63868. savedIsInit = pPage->isInit;
  63869. pPage->isInit = 0;
  63870. if( (rc = btreeInitPage(pPage))!=0 ){
  63871. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  63872. checkAppendMsg(pCheck,
  63873. "btreeInitPage() returns error code %d", rc);
  63874. goto end_of_check;
  63875. }
  63876. data = pPage->aData;
  63877. hdr = pPage->hdrOffset;
  63878. /* Set up for cell analysis */
  63879. pCheck->zPfx = "On tree page %d cell %d: ";
  63880. contentOffset = get2byteNotZero(&data[hdr+5]);
  63881. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  63882. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  63883. ** number of cells on the page. */
  63884. nCell = get2byte(&data[hdr+3]);
  63885. assert( pPage->nCell==nCell );
  63886. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  63887. ** immediately follows the b-tree page header. */
  63888. cellStart = hdr + 12 - 4*pPage->leaf;
  63889. assert( pPage->aCellIdx==&data[cellStart] );
  63890. pCellIdx = &data[cellStart + 2*(nCell-1)];
  63891. if( !pPage->leaf ){
  63892. /* Analyze the right-child page of internal pages */
  63893. pgno = get4byte(&data[hdr+8]);
  63894. #ifndef SQLITE_OMIT_AUTOVACUUM
  63895. if( pBt->autoVacuum ){
  63896. pCheck->zPfx = "On page %d at right child: ";
  63897. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  63898. }
  63899. #endif
  63900. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  63901. keyCanBeEqual = 0;
  63902. }else{
  63903. /* For leaf pages, the coverage check will occur in the same loop
  63904. ** as the other cell checks, so initialize the heap. */
  63905. heap = pCheck->heap;
  63906. heap[0] = 0;
  63907. }
  63908. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  63909. ** integer offsets to the cell contents. */
  63910. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  63911. CellInfo info;
  63912. /* Check cell size */
  63913. pCheck->v2 = i;
  63914. assert( pCellIdx==&data[cellStart + i*2] );
  63915. pc = get2byteAligned(pCellIdx);
  63916. pCellIdx -= 2;
  63917. if( pc<contentOffset || pc>usableSize-4 ){
  63918. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  63919. pc, contentOffset, usableSize-4);
  63920. doCoverageCheck = 0;
  63921. continue;
  63922. }
  63923. pCell = &data[pc];
  63924. pPage->xParseCell(pPage, pCell, &info);
  63925. if( pc+info.nSize>usableSize ){
  63926. checkAppendMsg(pCheck, "Extends off end of page");
  63927. doCoverageCheck = 0;
  63928. continue;
  63929. }
  63930. /* Check for integer primary key out of range */
  63931. if( pPage->intKey ){
  63932. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  63933. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  63934. }
  63935. maxKey = info.nKey;
  63936. keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
  63937. }
  63938. /* Check the content overflow list */
  63939. if( info.nPayload>info.nLocal ){
  63940. int nPage; /* Number of pages on the overflow chain */
  63941. Pgno pgnoOvfl; /* First page of the overflow chain */
  63942. assert( pc + info.nSize - 4 <= usableSize );
  63943. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  63944. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  63945. #ifndef SQLITE_OMIT_AUTOVACUUM
  63946. if( pBt->autoVacuum ){
  63947. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  63948. }
  63949. #endif
  63950. checkList(pCheck, 0, pgnoOvfl, nPage);
  63951. }
  63952. if( !pPage->leaf ){
  63953. /* Check sanity of left child page for internal pages */
  63954. pgno = get4byte(pCell);
  63955. #ifndef SQLITE_OMIT_AUTOVACUUM
  63956. if( pBt->autoVacuum ){
  63957. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  63958. }
  63959. #endif
  63960. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  63961. keyCanBeEqual = 0;
  63962. if( d2!=depth ){
  63963. checkAppendMsg(pCheck, "Child page depth differs");
  63964. depth = d2;
  63965. }
  63966. }else{
  63967. /* Populate the coverage-checking heap for leaf pages */
  63968. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  63969. }
  63970. }
  63971. *piMinKey = maxKey;
  63972. /* Check for complete coverage of the page
  63973. */
  63974. pCheck->zPfx = 0;
  63975. if( doCoverageCheck && pCheck->mxErr>0 ){
  63976. /* For leaf pages, the min-heap has already been initialized and the
  63977. ** cells have already been inserted. But for internal pages, that has
  63978. ** not yet been done, so do it now */
  63979. if( !pPage->leaf ){
  63980. heap = pCheck->heap;
  63981. heap[0] = 0;
  63982. for(i=nCell-1; i>=0; i--){
  63983. u32 size;
  63984. pc = get2byteAligned(&data[cellStart+i*2]);
  63985. size = pPage->xCellSize(pPage, &data[pc]);
  63986. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  63987. }
  63988. }
  63989. /* Add the freeblocks to the min-heap
  63990. **
  63991. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  63992. ** is the offset of the first freeblock, or zero if there are no
  63993. ** freeblocks on the page.
  63994. */
  63995. i = get2byte(&data[hdr+1]);
  63996. while( i>0 ){
  63997. int size, j;
  63998. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  63999. size = get2byte(&data[i+2]);
  64000. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  64001. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  64002. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  64003. ** big-endian integer which is the offset in the b-tree page of the next
  64004. ** freeblock in the chain, or zero if the freeblock is the last on the
  64005. ** chain. */
  64006. j = get2byte(&data[i]);
  64007. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  64008. ** increasing offset. */
  64009. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  64010. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  64011. i = j;
  64012. }
  64013. /* Analyze the min-heap looking for overlap between cells and/or
  64014. ** freeblocks, and counting the number of untracked bytes in nFrag.
  64015. **
  64016. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  64017. ** There is an implied first entry the covers the page header, the cell
  64018. ** pointer index, and the gap between the cell pointer index and the start
  64019. ** of cell content.
  64020. **
  64021. ** The loop below pulls entries from the min-heap in order and compares
  64022. ** the start_address against the previous end_address. If there is an
  64023. ** overlap, that means bytes are used multiple times. If there is a gap,
  64024. ** that gap is added to the fragmentation count.
  64025. */
  64026. nFrag = 0;
  64027. prev = contentOffset - 1; /* Implied first min-heap entry */
  64028. while( btreeHeapPull(heap,&x) ){
  64029. if( (prev&0xffff)>=(x>>16) ){
  64030. checkAppendMsg(pCheck,
  64031. "Multiple uses for byte %u of page %d", x>>16, iPage);
  64032. break;
  64033. }else{
  64034. nFrag += (x>>16) - (prev&0xffff) - 1;
  64035. prev = x;
  64036. }
  64037. }
  64038. nFrag += usableSize - (prev&0xffff) - 1;
  64039. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  64040. ** is stored in the fifth field of the b-tree page header.
  64041. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  64042. ** number of fragmented free bytes within the cell content area.
  64043. */
  64044. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  64045. checkAppendMsg(pCheck,
  64046. "Fragmentation of %d bytes reported as %d on page %d",
  64047. nFrag, data[hdr+7], iPage);
  64048. }
  64049. }
  64050. end_of_check:
  64051. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  64052. releasePage(pPage);
  64053. pCheck->zPfx = saved_zPfx;
  64054. pCheck->v1 = saved_v1;
  64055. pCheck->v2 = saved_v2;
  64056. return depth+1;
  64057. }
  64058. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  64059. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  64060. /*
  64061. ** This routine does a complete check of the given BTree file. aRoot[] is
  64062. ** an array of pages numbers were each page number is the root page of
  64063. ** a table. nRoot is the number of entries in aRoot.
  64064. **
  64065. ** A read-only or read-write transaction must be opened before calling
  64066. ** this function.
  64067. **
  64068. ** Write the number of error seen in *pnErr. Except for some memory
  64069. ** allocation errors, an error message held in memory obtained from
  64070. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  64071. ** returned. If a memory allocation error occurs, NULL is returned.
  64072. */
  64073. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  64074. Btree *p, /* The btree to be checked */
  64075. int *aRoot, /* An array of root pages numbers for individual trees */
  64076. int nRoot, /* Number of entries in aRoot[] */
  64077. int mxErr, /* Stop reporting errors after this many */
  64078. int *pnErr /* Write number of errors seen to this variable */
  64079. ){
  64080. Pgno i;
  64081. IntegrityCk sCheck;
  64082. BtShared *pBt = p->pBt;
  64083. int savedDbFlags = pBt->db->flags;
  64084. char zErr[100];
  64085. VVA_ONLY( int nRef );
  64086. sqlite3BtreeEnter(p);
  64087. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  64088. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  64089. assert( nRef>=0 );
  64090. sCheck.pBt = pBt;
  64091. sCheck.pPager = pBt->pPager;
  64092. sCheck.nPage = btreePagecount(sCheck.pBt);
  64093. sCheck.mxErr = mxErr;
  64094. sCheck.nErr = 0;
  64095. sCheck.mallocFailed = 0;
  64096. sCheck.zPfx = 0;
  64097. sCheck.v1 = 0;
  64098. sCheck.v2 = 0;
  64099. sCheck.aPgRef = 0;
  64100. sCheck.heap = 0;
  64101. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  64102. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  64103. if( sCheck.nPage==0 ){
  64104. goto integrity_ck_cleanup;
  64105. }
  64106. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  64107. if( !sCheck.aPgRef ){
  64108. sCheck.mallocFailed = 1;
  64109. goto integrity_ck_cleanup;
  64110. }
  64111. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  64112. if( sCheck.heap==0 ){
  64113. sCheck.mallocFailed = 1;
  64114. goto integrity_ck_cleanup;
  64115. }
  64116. i = PENDING_BYTE_PAGE(pBt);
  64117. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  64118. /* Check the integrity of the freelist
  64119. */
  64120. sCheck.zPfx = "Main freelist: ";
  64121. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  64122. get4byte(&pBt->pPage1->aData[36]));
  64123. sCheck.zPfx = 0;
  64124. /* Check all the tables.
  64125. */
  64126. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  64127. pBt->db->flags &= ~SQLITE_CellSizeCk;
  64128. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  64129. i64 notUsed;
  64130. if( aRoot[i]==0 ) continue;
  64131. #ifndef SQLITE_OMIT_AUTOVACUUM
  64132. if( pBt->autoVacuum && aRoot[i]>1 ){
  64133. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  64134. }
  64135. #endif
  64136. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  64137. }
  64138. pBt->db->flags = savedDbFlags;
  64139. /* Make sure every page in the file is referenced
  64140. */
  64141. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  64142. #ifdef SQLITE_OMIT_AUTOVACUUM
  64143. if( getPageReferenced(&sCheck, i)==0 ){
  64144. checkAppendMsg(&sCheck, "Page %d is never used", i);
  64145. }
  64146. #else
  64147. /* If the database supports auto-vacuum, make sure no tables contain
  64148. ** references to pointer-map pages.
  64149. */
  64150. if( getPageReferenced(&sCheck, i)==0 &&
  64151. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  64152. checkAppendMsg(&sCheck, "Page %d is never used", i);
  64153. }
  64154. if( getPageReferenced(&sCheck, i)!=0 &&
  64155. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  64156. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  64157. }
  64158. #endif
  64159. }
  64160. /* Clean up and report errors.
  64161. */
  64162. integrity_ck_cleanup:
  64163. sqlite3PageFree(sCheck.heap);
  64164. sqlite3_free(sCheck.aPgRef);
  64165. if( sCheck.mallocFailed ){
  64166. sqlite3StrAccumReset(&sCheck.errMsg);
  64167. sCheck.nErr++;
  64168. }
  64169. *pnErr = sCheck.nErr;
  64170. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  64171. /* Make sure this analysis did not leave any unref() pages. */
  64172. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  64173. sqlite3BtreeLeave(p);
  64174. return sqlite3StrAccumFinish(&sCheck.errMsg);
  64175. }
  64176. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  64177. /*
  64178. ** Return the full pathname of the underlying database file. Return
  64179. ** an empty string if the database is in-memory or a TEMP database.
  64180. **
  64181. ** The pager filename is invariant as long as the pager is
  64182. ** open so it is safe to access without the BtShared mutex.
  64183. */
  64184. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  64185. assert( p->pBt->pPager!=0 );
  64186. return sqlite3PagerFilename(p->pBt->pPager, 1);
  64187. }
  64188. /*
  64189. ** Return the pathname of the journal file for this database. The return
  64190. ** value of this routine is the same regardless of whether the journal file
  64191. ** has been created or not.
  64192. **
  64193. ** The pager journal filename is invariant as long as the pager is
  64194. ** open so it is safe to access without the BtShared mutex.
  64195. */
  64196. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  64197. assert( p->pBt->pPager!=0 );
  64198. return sqlite3PagerJournalname(p->pBt->pPager);
  64199. }
  64200. /*
  64201. ** Return non-zero if a transaction is active.
  64202. */
  64203. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  64204. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  64205. return (p && (p->inTrans==TRANS_WRITE));
  64206. }
  64207. #ifndef SQLITE_OMIT_WAL
  64208. /*
  64209. ** Run a checkpoint on the Btree passed as the first argument.
  64210. **
  64211. ** Return SQLITE_LOCKED if this or any other connection has an open
  64212. ** transaction on the shared-cache the argument Btree is connected to.
  64213. **
  64214. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  64215. */
  64216. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  64217. int rc = SQLITE_OK;
  64218. if( p ){
  64219. BtShared *pBt = p->pBt;
  64220. sqlite3BtreeEnter(p);
  64221. if( pBt->inTransaction!=TRANS_NONE ){
  64222. rc = SQLITE_LOCKED;
  64223. }else{
  64224. rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
  64225. }
  64226. sqlite3BtreeLeave(p);
  64227. }
  64228. return rc;
  64229. }
  64230. #endif
  64231. /*
  64232. ** Return non-zero if a read (or write) transaction is active.
  64233. */
  64234. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  64235. assert( p );
  64236. assert( sqlite3_mutex_held(p->db->mutex) );
  64237. return p->inTrans!=TRANS_NONE;
  64238. }
  64239. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  64240. assert( p );
  64241. assert( sqlite3_mutex_held(p->db->mutex) );
  64242. return p->nBackup!=0;
  64243. }
  64244. /*
  64245. ** This function returns a pointer to a blob of memory associated with
  64246. ** a single shared-btree. The memory is used by client code for its own
  64247. ** purposes (for example, to store a high-level schema associated with
  64248. ** the shared-btree). The btree layer manages reference counting issues.
  64249. **
  64250. ** The first time this is called on a shared-btree, nBytes bytes of memory
  64251. ** are allocated, zeroed, and returned to the caller. For each subsequent
  64252. ** call the nBytes parameter is ignored and a pointer to the same blob
  64253. ** of memory returned.
  64254. **
  64255. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  64256. ** allocated, a null pointer is returned. If the blob has already been
  64257. ** allocated, it is returned as normal.
  64258. **
  64259. ** Just before the shared-btree is closed, the function passed as the
  64260. ** xFree argument when the memory allocation was made is invoked on the
  64261. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  64262. ** on the memory, the btree layer does that.
  64263. */
  64264. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  64265. BtShared *pBt = p->pBt;
  64266. sqlite3BtreeEnter(p);
  64267. if( !pBt->pSchema && nBytes ){
  64268. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  64269. pBt->xFreeSchema = xFree;
  64270. }
  64271. sqlite3BtreeLeave(p);
  64272. return pBt->pSchema;
  64273. }
  64274. /*
  64275. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  64276. ** btree as the argument handle holds an exclusive lock on the
  64277. ** sqlite_master table. Otherwise SQLITE_OK.
  64278. */
  64279. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  64280. int rc;
  64281. assert( sqlite3_mutex_held(p->db->mutex) );
  64282. sqlite3BtreeEnter(p);
  64283. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  64284. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  64285. sqlite3BtreeLeave(p);
  64286. return rc;
  64287. }
  64288. #ifndef SQLITE_OMIT_SHARED_CACHE
  64289. /*
  64290. ** Obtain a lock on the table whose root page is iTab. The
  64291. ** lock is a write lock if isWritelock is true or a read lock
  64292. ** if it is false.
  64293. */
  64294. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  64295. int rc = SQLITE_OK;
  64296. assert( p->inTrans!=TRANS_NONE );
  64297. if( p->sharable ){
  64298. u8 lockType = READ_LOCK + isWriteLock;
  64299. assert( READ_LOCK+1==WRITE_LOCK );
  64300. assert( isWriteLock==0 || isWriteLock==1 );
  64301. sqlite3BtreeEnter(p);
  64302. rc = querySharedCacheTableLock(p, iTab, lockType);
  64303. if( rc==SQLITE_OK ){
  64304. rc = setSharedCacheTableLock(p, iTab, lockType);
  64305. }
  64306. sqlite3BtreeLeave(p);
  64307. }
  64308. return rc;
  64309. }
  64310. #endif
  64311. #ifndef SQLITE_OMIT_INCRBLOB
  64312. /*
  64313. ** Argument pCsr must be a cursor opened for writing on an
  64314. ** INTKEY table currently pointing at a valid table entry.
  64315. ** This function modifies the data stored as part of that entry.
  64316. **
  64317. ** Only the data content may only be modified, it is not possible to
  64318. ** change the length of the data stored. If this function is called with
  64319. ** parameters that attempt to write past the end of the existing data,
  64320. ** no modifications are made and SQLITE_CORRUPT is returned.
  64321. */
  64322. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  64323. int rc;
  64324. assert( cursorOwnsBtShared(pCsr) );
  64325. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  64326. assert( pCsr->curFlags & BTCF_Incrblob );
  64327. rc = restoreCursorPosition(pCsr);
  64328. if( rc!=SQLITE_OK ){
  64329. return rc;
  64330. }
  64331. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  64332. if( pCsr->eState!=CURSOR_VALID ){
  64333. return SQLITE_ABORT;
  64334. }
  64335. /* Save the positions of all other cursors open on this table. This is
  64336. ** required in case any of them are holding references to an xFetch
  64337. ** version of the b-tree page modified by the accessPayload call below.
  64338. **
  64339. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  64340. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  64341. ** saveAllCursors can only return SQLITE_OK.
  64342. */
  64343. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  64344. assert( rc==SQLITE_OK );
  64345. /* Check some assumptions:
  64346. ** (a) the cursor is open for writing,
  64347. ** (b) there is a read/write transaction open,
  64348. ** (c) the connection holds a write-lock on the table (if required),
  64349. ** (d) there are no conflicting read-locks, and
  64350. ** (e) the cursor points at a valid row of an intKey table.
  64351. */
  64352. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  64353. return SQLITE_READONLY;
  64354. }
  64355. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  64356. && pCsr->pBt->inTransaction==TRANS_WRITE );
  64357. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  64358. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  64359. assert( pCsr->apPage[pCsr->iPage]->intKey );
  64360. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  64361. }
  64362. /*
  64363. ** Mark this cursor as an incremental blob cursor.
  64364. */
  64365. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  64366. pCur->curFlags |= BTCF_Incrblob;
  64367. pCur->pBtree->hasIncrblobCur = 1;
  64368. }
  64369. #endif
  64370. /*
  64371. ** Set both the "read version" (single byte at byte offset 18) and
  64372. ** "write version" (single byte at byte offset 19) fields in the database
  64373. ** header to iVersion.
  64374. */
  64375. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  64376. BtShared *pBt = pBtree->pBt;
  64377. int rc; /* Return code */
  64378. assert( iVersion==1 || iVersion==2 );
  64379. /* If setting the version fields to 1, do not automatically open the
  64380. ** WAL connection, even if the version fields are currently set to 2.
  64381. */
  64382. pBt->btsFlags &= ~BTS_NO_WAL;
  64383. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  64384. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  64385. if( rc==SQLITE_OK ){
  64386. u8 *aData = pBt->pPage1->aData;
  64387. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  64388. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  64389. if( rc==SQLITE_OK ){
  64390. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  64391. if( rc==SQLITE_OK ){
  64392. aData[18] = (u8)iVersion;
  64393. aData[19] = (u8)iVersion;
  64394. }
  64395. }
  64396. }
  64397. }
  64398. pBt->btsFlags &= ~BTS_NO_WAL;
  64399. return rc;
  64400. }
  64401. /*
  64402. ** Return true if the cursor has a hint specified. This routine is
  64403. ** only used from within assert() statements
  64404. */
  64405. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  64406. return (pCsr->hints & mask)!=0;
  64407. }
  64408. /*
  64409. ** Return true if the given Btree is read-only.
  64410. */
  64411. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  64412. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  64413. }
  64414. /*
  64415. ** Return the size of the header added to each page by this module.
  64416. */
  64417. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  64418. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  64419. /*
  64420. ** Return true if the Btree passed as the only argument is sharable.
  64421. */
  64422. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  64423. return p->sharable;
  64424. }
  64425. /*
  64426. ** Return the number of connections to the BtShared object accessed by
  64427. ** the Btree handle passed as the only argument. For private caches
  64428. ** this is always 1. For shared caches it may be 1 or greater.
  64429. */
  64430. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
  64431. testcase( p->sharable );
  64432. return p->pBt->nRef;
  64433. }
  64434. #endif
  64435. /************** End of btree.c ***********************************************/
  64436. /************** Begin file backup.c ******************************************/
  64437. /*
  64438. ** 2009 January 28
  64439. **
  64440. ** The author disclaims copyright to this source code. In place of
  64441. ** a legal notice, here is a blessing:
  64442. **
  64443. ** May you do good and not evil.
  64444. ** May you find forgiveness for yourself and forgive others.
  64445. ** May you share freely, never taking more than you give.
  64446. **
  64447. *************************************************************************
  64448. ** This file contains the implementation of the sqlite3_backup_XXX()
  64449. ** API functions and the related features.
  64450. */
  64451. /* #include "sqliteInt.h" */
  64452. /* #include "btreeInt.h" */
  64453. /*
  64454. ** Structure allocated for each backup operation.
  64455. */
  64456. struct sqlite3_backup {
  64457. sqlite3* pDestDb; /* Destination database handle */
  64458. Btree *pDest; /* Destination b-tree file */
  64459. u32 iDestSchema; /* Original schema cookie in destination */
  64460. int bDestLocked; /* True once a write-transaction is open on pDest */
  64461. Pgno iNext; /* Page number of the next source page to copy */
  64462. sqlite3* pSrcDb; /* Source database handle */
  64463. Btree *pSrc; /* Source b-tree file */
  64464. int rc; /* Backup process error code */
  64465. /* These two variables are set by every call to backup_step(). They are
  64466. ** read by calls to backup_remaining() and backup_pagecount().
  64467. */
  64468. Pgno nRemaining; /* Number of pages left to copy */
  64469. Pgno nPagecount; /* Total number of pages to copy */
  64470. int isAttached; /* True once backup has been registered with pager */
  64471. sqlite3_backup *pNext; /* Next backup associated with source pager */
  64472. };
  64473. /*
  64474. ** THREAD SAFETY NOTES:
  64475. **
  64476. ** Once it has been created using backup_init(), a single sqlite3_backup
  64477. ** structure may be accessed via two groups of thread-safe entry points:
  64478. **
  64479. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  64480. ** backup_finish(). Both these functions obtain the source database
  64481. ** handle mutex and the mutex associated with the source BtShared
  64482. ** structure, in that order.
  64483. **
  64484. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  64485. ** invoked by the pager layer to report various state changes in
  64486. ** the page cache associated with the source database. The mutex
  64487. ** associated with the source database BtShared structure will always
  64488. ** be held when either of these functions are invoked.
  64489. **
  64490. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  64491. ** backup_pagecount() are not thread-safe functions. If they are called
  64492. ** while some other thread is calling backup_step() or backup_finish(),
  64493. ** the values returned may be invalid. There is no way for a call to
  64494. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  64495. ** or backup_pagecount().
  64496. **
  64497. ** Depending on the SQLite configuration, the database handles and/or
  64498. ** the Btree objects may have their own mutexes that require locking.
  64499. ** Non-sharable Btrees (in-memory databases for example), do not have
  64500. ** associated mutexes.
  64501. */
  64502. /*
  64503. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  64504. ** in connection handle pDb. If such a database cannot be found, return
  64505. ** a NULL pointer and write an error message to pErrorDb.
  64506. **
  64507. ** If the "temp" database is requested, it may need to be opened by this
  64508. ** function. If an error occurs while doing so, return 0 and write an
  64509. ** error message to pErrorDb.
  64510. */
  64511. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  64512. int i = sqlite3FindDbName(pDb, zDb);
  64513. if( i==1 ){
  64514. Parse sParse;
  64515. int rc = 0;
  64516. memset(&sParse, 0, sizeof(sParse));
  64517. sParse.db = pDb;
  64518. if( sqlite3OpenTempDatabase(&sParse) ){
  64519. sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  64520. rc = SQLITE_ERROR;
  64521. }
  64522. sqlite3DbFree(pErrorDb, sParse.zErrMsg);
  64523. sqlite3ParserReset(&sParse);
  64524. if( rc ){
  64525. return 0;
  64526. }
  64527. }
  64528. if( i<0 ){
  64529. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  64530. return 0;
  64531. }
  64532. return pDb->aDb[i].pBt;
  64533. }
  64534. /*
  64535. ** Attempt to set the page size of the destination to match the page size
  64536. ** of the source.
  64537. */
  64538. static int setDestPgsz(sqlite3_backup *p){
  64539. int rc;
  64540. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  64541. return rc;
  64542. }
  64543. /*
  64544. ** Check that there is no open read-transaction on the b-tree passed as the
  64545. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  64546. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  64547. ** message in database handle db.
  64548. */
  64549. static int checkReadTransaction(sqlite3 *db, Btree *p){
  64550. if( sqlite3BtreeIsInReadTrans(p) ){
  64551. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  64552. return SQLITE_ERROR;
  64553. }
  64554. return SQLITE_OK;
  64555. }
  64556. /*
  64557. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  64558. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  64559. ** a pointer to the new sqlite3_backup object.
  64560. **
  64561. ** If an error occurs, NULL is returned and an error code and error message
  64562. ** stored in database handle pDestDb.
  64563. */
  64564. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  64565. sqlite3* pDestDb, /* Database to write to */
  64566. const char *zDestDb, /* Name of database within pDestDb */
  64567. sqlite3* pSrcDb, /* Database connection to read from */
  64568. const char *zSrcDb /* Name of database within pSrcDb */
  64569. ){
  64570. sqlite3_backup *p; /* Value to return */
  64571. #ifdef SQLITE_ENABLE_API_ARMOR
  64572. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  64573. (void)SQLITE_MISUSE_BKPT;
  64574. return 0;
  64575. }
  64576. #endif
  64577. /* Lock the source database handle. The destination database
  64578. ** handle is not locked in this routine, but it is locked in
  64579. ** sqlite3_backup_step(). The user is required to ensure that no
  64580. ** other thread accesses the destination handle for the duration
  64581. ** of the backup operation. Any attempt to use the destination
  64582. ** database connection while a backup is in progress may cause
  64583. ** a malfunction or a deadlock.
  64584. */
  64585. sqlite3_mutex_enter(pSrcDb->mutex);
  64586. sqlite3_mutex_enter(pDestDb->mutex);
  64587. if( pSrcDb==pDestDb ){
  64588. sqlite3ErrorWithMsg(
  64589. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  64590. );
  64591. p = 0;
  64592. }else {
  64593. /* Allocate space for a new sqlite3_backup object...
  64594. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  64595. ** call to sqlite3_backup_init() and is destroyed by a call to
  64596. ** sqlite3_backup_finish(). */
  64597. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  64598. if( !p ){
  64599. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  64600. }
  64601. }
  64602. /* If the allocation succeeded, populate the new object. */
  64603. if( p ){
  64604. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  64605. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  64606. p->pDestDb = pDestDb;
  64607. p->pSrcDb = pSrcDb;
  64608. p->iNext = 1;
  64609. p->isAttached = 0;
  64610. if( 0==p->pSrc || 0==p->pDest
  64611. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  64612. ){
  64613. /* One (or both) of the named databases did not exist or an OOM
  64614. ** error was hit. Or there is a transaction open on the destination
  64615. ** database. The error has already been written into the pDestDb
  64616. ** handle. All that is left to do here is free the sqlite3_backup
  64617. ** structure. */
  64618. sqlite3_free(p);
  64619. p = 0;
  64620. }
  64621. }
  64622. if( p ){
  64623. p->pSrc->nBackup++;
  64624. }
  64625. sqlite3_mutex_leave(pDestDb->mutex);
  64626. sqlite3_mutex_leave(pSrcDb->mutex);
  64627. return p;
  64628. }
  64629. /*
  64630. ** Argument rc is an SQLite error code. Return true if this error is
  64631. ** considered fatal if encountered during a backup operation. All errors
  64632. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  64633. */
  64634. static int isFatalError(int rc){
  64635. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  64636. }
  64637. /*
  64638. ** Parameter zSrcData points to a buffer containing the data for
  64639. ** page iSrcPg from the source database. Copy this data into the
  64640. ** destination database.
  64641. */
  64642. static int backupOnePage(
  64643. sqlite3_backup *p, /* Backup handle */
  64644. Pgno iSrcPg, /* Source database page to backup */
  64645. const u8 *zSrcData, /* Source database page data */
  64646. int bUpdate /* True for an update, false otherwise */
  64647. ){
  64648. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  64649. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  64650. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  64651. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  64652. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  64653. #ifdef SQLITE_HAS_CODEC
  64654. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  64655. ** guaranteed that the shared-mutex is held by this thread, handle
  64656. ** p->pSrc may not actually be the owner. */
  64657. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  64658. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  64659. #endif
  64660. int rc = SQLITE_OK;
  64661. i64 iOff;
  64662. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  64663. assert( p->bDestLocked );
  64664. assert( !isFatalError(p->rc) );
  64665. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  64666. assert( zSrcData );
  64667. /* Catch the case where the destination is an in-memory database and the
  64668. ** page sizes of the source and destination differ.
  64669. */
  64670. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  64671. rc = SQLITE_READONLY;
  64672. }
  64673. #ifdef SQLITE_HAS_CODEC
  64674. /* Backup is not possible if the page size of the destination is changing
  64675. ** and a codec is in use.
  64676. */
  64677. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  64678. rc = SQLITE_READONLY;
  64679. }
  64680. /* Backup is not possible if the number of bytes of reserve space differ
  64681. ** between source and destination. If there is a difference, try to
  64682. ** fix the destination to agree with the source. If that is not possible,
  64683. ** then the backup cannot proceed.
  64684. */
  64685. if( nSrcReserve!=nDestReserve ){
  64686. u32 newPgsz = nSrcPgsz;
  64687. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  64688. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  64689. }
  64690. #endif
  64691. /* This loop runs once for each destination page spanned by the source
  64692. ** page. For each iteration, variable iOff is set to the byte offset
  64693. ** of the destination page.
  64694. */
  64695. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  64696. DbPage *pDestPg = 0;
  64697. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  64698. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  64699. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  64700. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  64701. ){
  64702. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  64703. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  64704. u8 *zOut = &zDestData[iOff%nDestPgsz];
  64705. /* Copy the data from the source page into the destination page.
  64706. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  64707. ** and the pager code use this trick (clearing the first byte
  64708. ** of the page 'extra' space to invalidate the Btree layers
  64709. ** cached parse of the page). MemPage.isInit is marked
  64710. ** "MUST BE FIRST" for this purpose.
  64711. */
  64712. memcpy(zOut, zIn, nCopy);
  64713. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  64714. if( iOff==0 && bUpdate==0 ){
  64715. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  64716. }
  64717. }
  64718. sqlite3PagerUnref(pDestPg);
  64719. }
  64720. return rc;
  64721. }
  64722. /*
  64723. ** If pFile is currently larger than iSize bytes, then truncate it to
  64724. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  64725. ** this function is a no-op.
  64726. **
  64727. ** Return SQLITE_OK if everything is successful, or an SQLite error
  64728. ** code if an error occurs.
  64729. */
  64730. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  64731. i64 iCurrent;
  64732. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  64733. if( rc==SQLITE_OK && iCurrent>iSize ){
  64734. rc = sqlite3OsTruncate(pFile, iSize);
  64735. }
  64736. return rc;
  64737. }
  64738. /*
  64739. ** Register this backup object with the associated source pager for
  64740. ** callbacks when pages are changed or the cache invalidated.
  64741. */
  64742. static void attachBackupObject(sqlite3_backup *p){
  64743. sqlite3_backup **pp;
  64744. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  64745. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  64746. p->pNext = *pp;
  64747. *pp = p;
  64748. p->isAttached = 1;
  64749. }
  64750. /*
  64751. ** Copy nPage pages from the source b-tree to the destination.
  64752. */
  64753. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  64754. int rc;
  64755. int destMode; /* Destination journal mode */
  64756. int pgszSrc = 0; /* Source page size */
  64757. int pgszDest = 0; /* Destination page size */
  64758. #ifdef SQLITE_ENABLE_API_ARMOR
  64759. if( p==0 ) return SQLITE_MISUSE_BKPT;
  64760. #endif
  64761. sqlite3_mutex_enter(p->pSrcDb->mutex);
  64762. sqlite3BtreeEnter(p->pSrc);
  64763. if( p->pDestDb ){
  64764. sqlite3_mutex_enter(p->pDestDb->mutex);
  64765. }
  64766. rc = p->rc;
  64767. if( !isFatalError(rc) ){
  64768. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  64769. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  64770. int ii; /* Iterator variable */
  64771. int nSrcPage = -1; /* Size of source db in pages */
  64772. int bCloseTrans = 0; /* True if src db requires unlocking */
  64773. /* If the source pager is currently in a write-transaction, return
  64774. ** SQLITE_BUSY immediately.
  64775. */
  64776. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  64777. rc = SQLITE_BUSY;
  64778. }else{
  64779. rc = SQLITE_OK;
  64780. }
  64781. /* If there is no open read-transaction on the source database, open
  64782. ** one now. If a transaction is opened here, then it will be closed
  64783. ** before this function exits.
  64784. */
  64785. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  64786. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  64787. bCloseTrans = 1;
  64788. }
  64789. /* If the destination database has not yet been locked (i.e. if this
  64790. ** is the first call to backup_step() for the current backup operation),
  64791. ** try to set its page size to the same as the source database. This
  64792. ** is especially important on ZipVFS systems, as in that case it is
  64793. ** not possible to create a database file that uses one page size by
  64794. ** writing to it with another. */
  64795. if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
  64796. rc = SQLITE_NOMEM;
  64797. }
  64798. /* Lock the destination database, if it is not locked already. */
  64799. if( SQLITE_OK==rc && p->bDestLocked==0
  64800. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  64801. ){
  64802. p->bDestLocked = 1;
  64803. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  64804. }
  64805. /* Do not allow backup if the destination database is in WAL mode
  64806. ** and the page sizes are different between source and destination */
  64807. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  64808. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  64809. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  64810. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  64811. rc = SQLITE_READONLY;
  64812. }
  64813. /* Now that there is a read-lock on the source database, query the
  64814. ** source pager for the number of pages in the database.
  64815. */
  64816. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  64817. assert( nSrcPage>=0 );
  64818. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  64819. const Pgno iSrcPg = p->iNext; /* Source page number */
  64820. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  64821. DbPage *pSrcPg; /* Source page object */
  64822. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  64823. if( rc==SQLITE_OK ){
  64824. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  64825. sqlite3PagerUnref(pSrcPg);
  64826. }
  64827. }
  64828. p->iNext++;
  64829. }
  64830. if( rc==SQLITE_OK ){
  64831. p->nPagecount = nSrcPage;
  64832. p->nRemaining = nSrcPage+1-p->iNext;
  64833. if( p->iNext>(Pgno)nSrcPage ){
  64834. rc = SQLITE_DONE;
  64835. }else if( !p->isAttached ){
  64836. attachBackupObject(p);
  64837. }
  64838. }
  64839. /* Update the schema version field in the destination database. This
  64840. ** is to make sure that the schema-version really does change in
  64841. ** the case where the source and destination databases have the
  64842. ** same schema version.
  64843. */
  64844. if( rc==SQLITE_DONE ){
  64845. if( nSrcPage==0 ){
  64846. rc = sqlite3BtreeNewDb(p->pDest);
  64847. nSrcPage = 1;
  64848. }
  64849. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  64850. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  64851. }
  64852. if( rc==SQLITE_OK ){
  64853. if( p->pDestDb ){
  64854. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  64855. }
  64856. if( destMode==PAGER_JOURNALMODE_WAL ){
  64857. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  64858. }
  64859. }
  64860. if( rc==SQLITE_OK ){
  64861. int nDestTruncate;
  64862. /* Set nDestTruncate to the final number of pages in the destination
  64863. ** database. The complication here is that the destination page
  64864. ** size may be different to the source page size.
  64865. **
  64866. ** If the source page size is smaller than the destination page size,
  64867. ** round up. In this case the call to sqlite3OsTruncate() below will
  64868. ** fix the size of the file. However it is important to call
  64869. ** sqlite3PagerTruncateImage() here so that any pages in the
  64870. ** destination file that lie beyond the nDestTruncate page mark are
  64871. ** journalled by PagerCommitPhaseOne() before they are destroyed
  64872. ** by the file truncation.
  64873. */
  64874. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  64875. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  64876. if( pgszSrc<pgszDest ){
  64877. int ratio = pgszDest/pgszSrc;
  64878. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  64879. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  64880. nDestTruncate--;
  64881. }
  64882. }else{
  64883. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  64884. }
  64885. assert( nDestTruncate>0 );
  64886. if( pgszSrc<pgszDest ){
  64887. /* If the source page-size is smaller than the destination page-size,
  64888. ** two extra things may need to happen:
  64889. **
  64890. ** * The destination may need to be truncated, and
  64891. **
  64892. ** * Data stored on the pages immediately following the
  64893. ** pending-byte page in the source database may need to be
  64894. ** copied into the destination database.
  64895. */
  64896. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  64897. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  64898. Pgno iPg;
  64899. int nDstPage;
  64900. i64 iOff;
  64901. i64 iEnd;
  64902. assert( pFile );
  64903. assert( nDestTruncate==0
  64904. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  64905. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  64906. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  64907. ));
  64908. /* This block ensures that all data required to recreate the original
  64909. ** database has been stored in the journal for pDestPager and the
  64910. ** journal synced to disk. So at this point we may safely modify
  64911. ** the database file in any way, knowing that if a power failure
  64912. ** occurs, the original database will be reconstructed from the
  64913. ** journal file. */
  64914. sqlite3PagerPagecount(pDestPager, &nDstPage);
  64915. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  64916. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  64917. DbPage *pPg;
  64918. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  64919. if( rc==SQLITE_OK ){
  64920. rc = sqlite3PagerWrite(pPg);
  64921. sqlite3PagerUnref(pPg);
  64922. }
  64923. }
  64924. }
  64925. if( rc==SQLITE_OK ){
  64926. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  64927. }
  64928. /* Write the extra pages and truncate the database file as required */
  64929. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  64930. for(
  64931. iOff=PENDING_BYTE+pgszSrc;
  64932. rc==SQLITE_OK && iOff<iEnd;
  64933. iOff+=pgszSrc
  64934. ){
  64935. PgHdr *pSrcPg = 0;
  64936. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  64937. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  64938. if( rc==SQLITE_OK ){
  64939. u8 *zData = sqlite3PagerGetData(pSrcPg);
  64940. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  64941. }
  64942. sqlite3PagerUnref(pSrcPg);
  64943. }
  64944. if( rc==SQLITE_OK ){
  64945. rc = backupTruncateFile(pFile, iSize);
  64946. }
  64947. /* Sync the database file to disk. */
  64948. if( rc==SQLITE_OK ){
  64949. rc = sqlite3PagerSync(pDestPager, 0);
  64950. }
  64951. }else{
  64952. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  64953. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  64954. }
  64955. /* Finish committing the transaction to the destination database. */
  64956. if( SQLITE_OK==rc
  64957. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  64958. ){
  64959. rc = SQLITE_DONE;
  64960. }
  64961. }
  64962. }
  64963. /* If bCloseTrans is true, then this function opened a read transaction
  64964. ** on the source database. Close the read transaction here. There is
  64965. ** no need to check the return values of the btree methods here, as
  64966. ** "committing" a read-only transaction cannot fail.
  64967. */
  64968. if( bCloseTrans ){
  64969. TESTONLY( int rc2 );
  64970. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  64971. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  64972. assert( rc2==SQLITE_OK );
  64973. }
  64974. if( rc==SQLITE_IOERR_NOMEM ){
  64975. rc = SQLITE_NOMEM_BKPT;
  64976. }
  64977. p->rc = rc;
  64978. }
  64979. if( p->pDestDb ){
  64980. sqlite3_mutex_leave(p->pDestDb->mutex);
  64981. }
  64982. sqlite3BtreeLeave(p->pSrc);
  64983. sqlite3_mutex_leave(p->pSrcDb->mutex);
  64984. return rc;
  64985. }
  64986. /*
  64987. ** Release all resources associated with an sqlite3_backup* handle.
  64988. */
  64989. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  64990. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  64991. sqlite3 *pSrcDb; /* Source database connection */
  64992. int rc; /* Value to return */
  64993. /* Enter the mutexes */
  64994. if( p==0 ) return SQLITE_OK;
  64995. pSrcDb = p->pSrcDb;
  64996. sqlite3_mutex_enter(pSrcDb->mutex);
  64997. sqlite3BtreeEnter(p->pSrc);
  64998. if( p->pDestDb ){
  64999. sqlite3_mutex_enter(p->pDestDb->mutex);
  65000. }
  65001. /* Detach this backup from the source pager. */
  65002. if( p->pDestDb ){
  65003. p->pSrc->nBackup--;
  65004. }
  65005. if( p->isAttached ){
  65006. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  65007. while( *pp!=p ){
  65008. pp = &(*pp)->pNext;
  65009. }
  65010. *pp = p->pNext;
  65011. }
  65012. /* If a transaction is still open on the Btree, roll it back. */
  65013. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  65014. /* Set the error code of the destination database handle. */
  65015. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  65016. if( p->pDestDb ){
  65017. sqlite3Error(p->pDestDb, rc);
  65018. /* Exit the mutexes and free the backup context structure. */
  65019. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  65020. }
  65021. sqlite3BtreeLeave(p->pSrc);
  65022. if( p->pDestDb ){
  65023. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  65024. ** call to sqlite3_backup_init() and is destroyed by a call to
  65025. ** sqlite3_backup_finish(). */
  65026. sqlite3_free(p);
  65027. }
  65028. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  65029. return rc;
  65030. }
  65031. /*
  65032. ** Return the number of pages still to be backed up as of the most recent
  65033. ** call to sqlite3_backup_step().
  65034. */
  65035. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  65036. #ifdef SQLITE_ENABLE_API_ARMOR
  65037. if( p==0 ){
  65038. (void)SQLITE_MISUSE_BKPT;
  65039. return 0;
  65040. }
  65041. #endif
  65042. return p->nRemaining;
  65043. }
  65044. /*
  65045. ** Return the total number of pages in the source database as of the most
  65046. ** recent call to sqlite3_backup_step().
  65047. */
  65048. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  65049. #ifdef SQLITE_ENABLE_API_ARMOR
  65050. if( p==0 ){
  65051. (void)SQLITE_MISUSE_BKPT;
  65052. return 0;
  65053. }
  65054. #endif
  65055. return p->nPagecount;
  65056. }
  65057. /*
  65058. ** This function is called after the contents of page iPage of the
  65059. ** source database have been modified. If page iPage has already been
  65060. ** copied into the destination database, then the data written to the
  65061. ** destination is now invalidated. The destination copy of iPage needs
  65062. ** to be updated with the new data before the backup operation is
  65063. ** complete.
  65064. **
  65065. ** It is assumed that the mutex associated with the BtShared object
  65066. ** corresponding to the source database is held when this function is
  65067. ** called.
  65068. */
  65069. static SQLITE_NOINLINE void backupUpdate(
  65070. sqlite3_backup *p,
  65071. Pgno iPage,
  65072. const u8 *aData
  65073. ){
  65074. assert( p!=0 );
  65075. do{
  65076. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  65077. if( !isFatalError(p->rc) && iPage<p->iNext ){
  65078. /* The backup process p has already copied page iPage. But now it
  65079. ** has been modified by a transaction on the source pager. Copy
  65080. ** the new data into the backup.
  65081. */
  65082. int rc;
  65083. assert( p->pDestDb );
  65084. sqlite3_mutex_enter(p->pDestDb->mutex);
  65085. rc = backupOnePage(p, iPage, aData, 1);
  65086. sqlite3_mutex_leave(p->pDestDb->mutex);
  65087. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  65088. if( rc!=SQLITE_OK ){
  65089. p->rc = rc;
  65090. }
  65091. }
  65092. }while( (p = p->pNext)!=0 );
  65093. }
  65094. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  65095. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  65096. }
  65097. /*
  65098. ** Restart the backup process. This is called when the pager layer
  65099. ** detects that the database has been modified by an external database
  65100. ** connection. In this case there is no way of knowing which of the
  65101. ** pages that have been copied into the destination database are still
  65102. ** valid and which are not, so the entire process needs to be restarted.
  65103. **
  65104. ** It is assumed that the mutex associated with the BtShared object
  65105. ** corresponding to the source database is held when this function is
  65106. ** called.
  65107. */
  65108. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  65109. sqlite3_backup *p; /* Iterator variable */
  65110. for(p=pBackup; p; p=p->pNext){
  65111. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  65112. p->iNext = 1;
  65113. }
  65114. }
  65115. #ifndef SQLITE_OMIT_VACUUM
  65116. /*
  65117. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  65118. ** must be active for both files.
  65119. **
  65120. ** The size of file pTo may be reduced by this operation. If anything
  65121. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  65122. ** transaction is committed before returning.
  65123. */
  65124. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  65125. int rc;
  65126. sqlite3_file *pFd; /* File descriptor for database pTo */
  65127. sqlite3_backup b;
  65128. sqlite3BtreeEnter(pTo);
  65129. sqlite3BtreeEnter(pFrom);
  65130. assert( sqlite3BtreeIsInTrans(pTo) );
  65131. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  65132. if( pFd->pMethods ){
  65133. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  65134. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  65135. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  65136. if( rc ) goto copy_finished;
  65137. }
  65138. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  65139. ** to 0. This is used by the implementations of sqlite3_backup_step()
  65140. ** and sqlite3_backup_finish() to detect that they are being called
  65141. ** from this function, not directly by the user.
  65142. */
  65143. memset(&b, 0, sizeof(b));
  65144. b.pSrcDb = pFrom->db;
  65145. b.pSrc = pFrom;
  65146. b.pDest = pTo;
  65147. b.iNext = 1;
  65148. #ifdef SQLITE_HAS_CODEC
  65149. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  65150. #endif
  65151. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  65152. ** file. By passing this as the number of pages to copy to
  65153. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  65154. ** within a single call (unless an error occurs). The assert() statement
  65155. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  65156. ** or an error code. */
  65157. sqlite3_backup_step(&b, 0x7FFFFFFF);
  65158. assert( b.rc!=SQLITE_OK );
  65159. rc = sqlite3_backup_finish(&b);
  65160. if( rc==SQLITE_OK ){
  65161. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  65162. }else{
  65163. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  65164. }
  65165. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  65166. copy_finished:
  65167. sqlite3BtreeLeave(pFrom);
  65168. sqlite3BtreeLeave(pTo);
  65169. return rc;
  65170. }
  65171. #endif /* SQLITE_OMIT_VACUUM */
  65172. /************** End of backup.c **********************************************/
  65173. /************** Begin file vdbemem.c *****************************************/
  65174. /*
  65175. ** 2004 May 26
  65176. **
  65177. ** The author disclaims copyright to this source code. In place of
  65178. ** a legal notice, here is a blessing:
  65179. **
  65180. ** May you do good and not evil.
  65181. ** May you find forgiveness for yourself and forgive others.
  65182. ** May you share freely, never taking more than you give.
  65183. **
  65184. *************************************************************************
  65185. **
  65186. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  65187. ** stores a single value in the VDBE. Mem is an opaque structure visible
  65188. ** only within the VDBE. Interface routines refer to a Mem using the
  65189. ** name sqlite_value
  65190. */
  65191. /* #include "sqliteInt.h" */
  65192. /* #include "vdbeInt.h" */
  65193. #ifdef SQLITE_DEBUG
  65194. /*
  65195. ** Check invariants on a Mem object.
  65196. **
  65197. ** This routine is intended for use inside of assert() statements, like
  65198. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  65199. */
  65200. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  65201. /* If MEM_Dyn is set then Mem.xDel!=0.
  65202. ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
  65203. */
  65204. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  65205. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  65206. ** ensure that if Mem.szMalloc>0 then it is safe to do
  65207. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  65208. ** That saves a few cycles in inner loops. */
  65209. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  65210. /* Cannot be both MEM_Int and MEM_Real at the same time */
  65211. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  65212. /* Cannot be both MEM_Null and some other type */
  65213. assert( (p->flags & MEM_Null)==0 ||
  65214. (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob))==0 );
  65215. /* The szMalloc field holds the correct memory allocation size */
  65216. assert( p->szMalloc==0
  65217. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  65218. /* If p holds a string or blob, the Mem.z must point to exactly
  65219. ** one of the following:
  65220. **
  65221. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  65222. ** (2) Memory to be freed using Mem.xDel
  65223. ** (3) An ephemeral string or blob
  65224. ** (4) A static string or blob
  65225. */
  65226. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  65227. assert(
  65228. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  65229. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  65230. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  65231. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  65232. );
  65233. }
  65234. return 1;
  65235. }
  65236. #endif
  65237. /*
  65238. ** If pMem is an object with a valid string representation, this routine
  65239. ** ensures the internal encoding for the string representation is
  65240. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  65241. **
  65242. ** If pMem is not a string object, or the encoding of the string
  65243. ** representation is already stored using the requested encoding, then this
  65244. ** routine is a no-op.
  65245. **
  65246. ** SQLITE_OK is returned if the conversion is successful (or not required).
  65247. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  65248. ** between formats.
  65249. */
  65250. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  65251. #ifndef SQLITE_OMIT_UTF16
  65252. int rc;
  65253. #endif
  65254. assert( (pMem->flags&MEM_RowSet)==0 );
  65255. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  65256. || desiredEnc==SQLITE_UTF16BE );
  65257. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  65258. return SQLITE_OK;
  65259. }
  65260. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65261. #ifdef SQLITE_OMIT_UTF16
  65262. return SQLITE_ERROR;
  65263. #else
  65264. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  65265. ** then the encoding of the value may not have changed.
  65266. */
  65267. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  65268. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  65269. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  65270. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  65271. return rc;
  65272. #endif
  65273. }
  65274. /*
  65275. ** Make sure pMem->z points to a writable allocation of at least
  65276. ** min(n,32) bytes.
  65277. **
  65278. ** If the bPreserve argument is true, then copy of the content of
  65279. ** pMem->z into the new allocation. pMem must be either a string or
  65280. ** blob if bPreserve is true. If bPreserve is false, any prior content
  65281. ** in pMem->z is discarded.
  65282. */
  65283. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  65284. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  65285. assert( (pMem->flags&MEM_RowSet)==0 );
  65286. testcase( pMem->db==0 );
  65287. /* If the bPreserve flag is set to true, then the memory cell must already
  65288. ** contain a valid string or blob value. */
  65289. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  65290. testcase( bPreserve && pMem->z==0 );
  65291. assert( pMem->szMalloc==0
  65292. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  65293. if( n<32 ) n = 32;
  65294. if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
  65295. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  65296. bPreserve = 0;
  65297. }else{
  65298. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  65299. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  65300. }
  65301. if( pMem->zMalloc==0 ){
  65302. sqlite3VdbeMemSetNull(pMem);
  65303. pMem->z = 0;
  65304. pMem->szMalloc = 0;
  65305. return SQLITE_NOMEM_BKPT;
  65306. }else{
  65307. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  65308. }
  65309. if( bPreserve && pMem->z && ALWAYS(pMem->z!=pMem->zMalloc) ){
  65310. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  65311. }
  65312. if( (pMem->flags&MEM_Dyn)!=0 ){
  65313. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  65314. pMem->xDel((void *)(pMem->z));
  65315. }
  65316. pMem->z = pMem->zMalloc;
  65317. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  65318. return SQLITE_OK;
  65319. }
  65320. /*
  65321. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  65322. ** If pMem->zMalloc already meets or exceeds the requested size, this
  65323. ** routine is a no-op.
  65324. **
  65325. ** Any prior string or blob content in the pMem object may be discarded.
  65326. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  65327. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  65328. ** values are preserved.
  65329. **
  65330. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  65331. ** if unable to complete the resizing.
  65332. */
  65333. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  65334. assert( szNew>0 );
  65335. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  65336. if( pMem->szMalloc<szNew ){
  65337. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  65338. }
  65339. assert( (pMem->flags & MEM_Dyn)==0 );
  65340. pMem->z = pMem->zMalloc;
  65341. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  65342. return SQLITE_OK;
  65343. }
  65344. /*
  65345. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  65346. ** MEM.zMalloc, where it can be safely written.
  65347. **
  65348. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  65349. */
  65350. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  65351. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65352. assert( (pMem->flags&MEM_RowSet)==0 );
  65353. if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
  65354. if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
  65355. if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
  65356. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  65357. return SQLITE_NOMEM_BKPT;
  65358. }
  65359. pMem->z[pMem->n] = 0;
  65360. pMem->z[pMem->n+1] = 0;
  65361. pMem->flags |= MEM_Term;
  65362. }
  65363. }
  65364. pMem->flags &= ~MEM_Ephem;
  65365. #ifdef SQLITE_DEBUG
  65366. pMem->pScopyFrom = 0;
  65367. #endif
  65368. return SQLITE_OK;
  65369. }
  65370. /*
  65371. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  65372. ** blob stored in dynamically allocated space.
  65373. */
  65374. #ifndef SQLITE_OMIT_INCRBLOB
  65375. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  65376. int nByte;
  65377. assert( pMem->flags & MEM_Zero );
  65378. assert( pMem->flags&MEM_Blob );
  65379. assert( (pMem->flags&MEM_RowSet)==0 );
  65380. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65381. /* Set nByte to the number of bytes required to store the expanded blob. */
  65382. nByte = pMem->n + pMem->u.nZero;
  65383. if( nByte<=0 ){
  65384. nByte = 1;
  65385. }
  65386. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  65387. return SQLITE_NOMEM_BKPT;
  65388. }
  65389. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  65390. pMem->n += pMem->u.nZero;
  65391. pMem->flags &= ~(MEM_Zero|MEM_Term);
  65392. return SQLITE_OK;
  65393. }
  65394. #endif
  65395. /*
  65396. ** It is already known that pMem contains an unterminated string.
  65397. ** Add the zero terminator.
  65398. */
  65399. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  65400. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  65401. return SQLITE_NOMEM_BKPT;
  65402. }
  65403. pMem->z[pMem->n] = 0;
  65404. pMem->z[pMem->n+1] = 0;
  65405. pMem->flags |= MEM_Term;
  65406. return SQLITE_OK;
  65407. }
  65408. /*
  65409. ** Make sure the given Mem is \u0000 terminated.
  65410. */
  65411. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  65412. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65413. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  65414. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  65415. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  65416. return SQLITE_OK; /* Nothing to do */
  65417. }else{
  65418. return vdbeMemAddTerminator(pMem);
  65419. }
  65420. }
  65421. /*
  65422. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  65423. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  65424. ** is a no-op.
  65425. **
  65426. ** Existing representations MEM_Int and MEM_Real are invalidated if
  65427. ** bForce is true but are retained if bForce is false.
  65428. **
  65429. ** A MEM_Null value will never be passed to this function. This function is
  65430. ** used for converting values to text for returning to the user (i.e. via
  65431. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  65432. ** keys are strings. In the former case a NULL pointer is returned the
  65433. ** user and the latter is an internal programming error.
  65434. */
  65435. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  65436. int fg = pMem->flags;
  65437. const int nByte = 32;
  65438. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65439. assert( !(fg&MEM_Zero) );
  65440. assert( !(fg&(MEM_Str|MEM_Blob)) );
  65441. assert( fg&(MEM_Int|MEM_Real) );
  65442. assert( (pMem->flags&MEM_RowSet)==0 );
  65443. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65444. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  65445. pMem->enc = 0;
  65446. return SQLITE_NOMEM_BKPT;
  65447. }
  65448. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  65449. ** string representation of the value. Then, if the required encoding
  65450. ** is UTF-16le or UTF-16be do a translation.
  65451. **
  65452. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  65453. */
  65454. if( fg & MEM_Int ){
  65455. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  65456. }else{
  65457. assert( fg & MEM_Real );
  65458. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  65459. }
  65460. pMem->n = sqlite3Strlen30(pMem->z);
  65461. pMem->enc = SQLITE_UTF8;
  65462. pMem->flags |= MEM_Str|MEM_Term;
  65463. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  65464. sqlite3VdbeChangeEncoding(pMem, enc);
  65465. return SQLITE_OK;
  65466. }
  65467. /*
  65468. ** Memory cell pMem contains the context of an aggregate function.
  65469. ** This routine calls the finalize method for that function. The
  65470. ** result of the aggregate is stored back into pMem.
  65471. **
  65472. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  65473. ** otherwise.
  65474. */
  65475. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  65476. int rc = SQLITE_OK;
  65477. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  65478. sqlite3_context ctx;
  65479. Mem t;
  65480. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  65481. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65482. memset(&ctx, 0, sizeof(ctx));
  65483. memset(&t, 0, sizeof(t));
  65484. t.flags = MEM_Null;
  65485. t.db = pMem->db;
  65486. ctx.pOut = &t;
  65487. ctx.pMem = pMem;
  65488. ctx.pFunc = pFunc;
  65489. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  65490. assert( (pMem->flags & MEM_Dyn)==0 );
  65491. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  65492. memcpy(pMem, &t, sizeof(t));
  65493. rc = ctx.isError;
  65494. }
  65495. return rc;
  65496. }
  65497. /*
  65498. ** If the memory cell contains a value that must be freed by
  65499. ** invoking the external callback in Mem.xDel, then this routine
  65500. ** will free that value. It also sets Mem.flags to MEM_Null.
  65501. **
  65502. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  65503. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  65504. ** entry point for releasing Mem resources.
  65505. */
  65506. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  65507. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  65508. assert( VdbeMemDynamic(p) );
  65509. if( p->flags&MEM_Agg ){
  65510. sqlite3VdbeMemFinalize(p, p->u.pDef);
  65511. assert( (p->flags & MEM_Agg)==0 );
  65512. testcase( p->flags & MEM_Dyn );
  65513. }
  65514. if( p->flags&MEM_Dyn ){
  65515. assert( (p->flags&MEM_RowSet)==0 );
  65516. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  65517. p->xDel((void *)p->z);
  65518. }else if( p->flags&MEM_RowSet ){
  65519. sqlite3RowSetClear(p->u.pRowSet);
  65520. }else if( p->flags&MEM_Frame ){
  65521. VdbeFrame *pFrame = p->u.pFrame;
  65522. pFrame->pParent = pFrame->v->pDelFrame;
  65523. pFrame->v->pDelFrame = pFrame;
  65524. }
  65525. p->flags = MEM_Null;
  65526. }
  65527. /*
  65528. ** Release memory held by the Mem p, both external memory cleared
  65529. ** by p->xDel and memory in p->zMalloc.
  65530. **
  65531. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  65532. ** the unusual case where there really is memory in p that needs
  65533. ** to be freed.
  65534. */
  65535. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  65536. if( VdbeMemDynamic(p) ){
  65537. vdbeMemClearExternAndSetNull(p);
  65538. }
  65539. if( p->szMalloc ){
  65540. sqlite3DbFreeNN(p->db, p->zMalloc);
  65541. p->szMalloc = 0;
  65542. }
  65543. p->z = 0;
  65544. }
  65545. /*
  65546. ** Release any memory resources held by the Mem. Both the memory that is
  65547. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  65548. **
  65549. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  65550. ** reset a Mem back to its minimum memory utilization.
  65551. **
  65552. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  65553. ** prior to inserting new content into the Mem.
  65554. */
  65555. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  65556. assert( sqlite3VdbeCheckMemInvariants(p) );
  65557. if( VdbeMemDynamic(p) || p->szMalloc ){
  65558. vdbeMemClear(p);
  65559. }
  65560. }
  65561. /*
  65562. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  65563. ** If the double is out of range of a 64-bit signed integer then
  65564. ** return the closest available 64-bit signed integer.
  65565. */
  65566. static SQLITE_NOINLINE i64 doubleToInt64(double r){
  65567. #ifdef SQLITE_OMIT_FLOATING_POINT
  65568. /* When floating-point is omitted, double and int64 are the same thing */
  65569. return r;
  65570. #else
  65571. /*
  65572. ** Many compilers we encounter do not define constants for the
  65573. ** minimum and maximum 64-bit integers, or they define them
  65574. ** inconsistently. And many do not understand the "LL" notation.
  65575. ** So we define our own static constants here using nothing
  65576. ** larger than a 32-bit integer constant.
  65577. */
  65578. static const i64 maxInt = LARGEST_INT64;
  65579. static const i64 minInt = SMALLEST_INT64;
  65580. if( r<=(double)minInt ){
  65581. return minInt;
  65582. }else if( r>=(double)maxInt ){
  65583. return maxInt;
  65584. }else{
  65585. return (i64)r;
  65586. }
  65587. #endif
  65588. }
  65589. /*
  65590. ** Return some kind of integer value which is the best we can do
  65591. ** at representing the value that *pMem describes as an integer.
  65592. ** If pMem is an integer, then the value is exact. If pMem is
  65593. ** a floating-point then the value returned is the integer part.
  65594. ** If pMem is a string or blob, then we make an attempt to convert
  65595. ** it into an integer and return that. If pMem represents an
  65596. ** an SQL-NULL value, return 0.
  65597. **
  65598. ** If pMem represents a string value, its encoding might be changed.
  65599. */
  65600. static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
  65601. i64 value = 0;
  65602. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  65603. return value;
  65604. }
  65605. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  65606. int flags;
  65607. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65608. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65609. flags = pMem->flags;
  65610. if( flags & MEM_Int ){
  65611. return pMem->u.i;
  65612. }else if( flags & MEM_Real ){
  65613. return doubleToInt64(pMem->u.r);
  65614. }else if( flags & (MEM_Str|MEM_Blob) ){
  65615. assert( pMem->z || pMem->n==0 );
  65616. return memIntValue(pMem);
  65617. }else{
  65618. return 0;
  65619. }
  65620. }
  65621. /*
  65622. ** Return the best representation of pMem that we can get into a
  65623. ** double. If pMem is already a double or an integer, return its
  65624. ** value. If it is a string or blob, try to convert it to a double.
  65625. ** If it is a NULL, return 0.0.
  65626. */
  65627. static SQLITE_NOINLINE double memRealValue(Mem *pMem){
  65628. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  65629. double val = (double)0;
  65630. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  65631. return val;
  65632. }
  65633. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  65634. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65635. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65636. if( pMem->flags & MEM_Real ){
  65637. return pMem->u.r;
  65638. }else if( pMem->flags & MEM_Int ){
  65639. return (double)pMem->u.i;
  65640. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  65641. return memRealValue(pMem);
  65642. }else{
  65643. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  65644. return (double)0;
  65645. }
  65646. }
  65647. /*
  65648. ** The MEM structure is already a MEM_Real. Try to also make it a
  65649. ** MEM_Int if we can.
  65650. */
  65651. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  65652. i64 ix;
  65653. assert( pMem->flags & MEM_Real );
  65654. assert( (pMem->flags & MEM_RowSet)==0 );
  65655. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65656. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65657. ix = doubleToInt64(pMem->u.r);
  65658. /* Only mark the value as an integer if
  65659. **
  65660. ** (1) the round-trip conversion real->int->real is a no-op, and
  65661. ** (2) The integer is neither the largest nor the smallest
  65662. ** possible integer (ticket #3922)
  65663. **
  65664. ** The second and third terms in the following conditional enforces
  65665. ** the second condition under the assumption that addition overflow causes
  65666. ** values to wrap around.
  65667. */
  65668. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  65669. pMem->u.i = ix;
  65670. MemSetTypeFlag(pMem, MEM_Int);
  65671. }
  65672. }
  65673. /*
  65674. ** Convert pMem to type integer. Invalidate any prior representations.
  65675. */
  65676. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  65677. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65678. assert( (pMem->flags & MEM_RowSet)==0 );
  65679. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65680. pMem->u.i = sqlite3VdbeIntValue(pMem);
  65681. MemSetTypeFlag(pMem, MEM_Int);
  65682. return SQLITE_OK;
  65683. }
  65684. /*
  65685. ** Convert pMem so that it is of type MEM_Real.
  65686. ** Invalidate any prior representations.
  65687. */
  65688. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  65689. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65690. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65691. pMem->u.r = sqlite3VdbeRealValue(pMem);
  65692. MemSetTypeFlag(pMem, MEM_Real);
  65693. return SQLITE_OK;
  65694. }
  65695. /*
  65696. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  65697. ** Invalidate any prior representations.
  65698. **
  65699. ** Every effort is made to force the conversion, even if the input
  65700. ** is a string that does not look completely like a number. Convert
  65701. ** as much of the string as we can and ignore the rest.
  65702. */
  65703. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  65704. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  65705. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  65706. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65707. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  65708. MemSetTypeFlag(pMem, MEM_Int);
  65709. }else{
  65710. pMem->u.r = sqlite3VdbeRealValue(pMem);
  65711. MemSetTypeFlag(pMem, MEM_Real);
  65712. sqlite3VdbeIntegerAffinity(pMem);
  65713. }
  65714. }
  65715. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  65716. pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
  65717. return SQLITE_OK;
  65718. }
  65719. /*
  65720. ** Cast the datatype of the value in pMem according to the affinity
  65721. ** "aff". Casting is different from applying affinity in that a cast
  65722. ** is forced. In other words, the value is converted into the desired
  65723. ** affinity even if that results in loss of data. This routine is
  65724. ** used (for example) to implement the SQL "cast()" operator.
  65725. */
  65726. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  65727. if( pMem->flags & MEM_Null ) return;
  65728. switch( aff ){
  65729. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  65730. if( (pMem->flags & MEM_Blob)==0 ){
  65731. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  65732. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  65733. if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
  65734. }else{
  65735. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  65736. }
  65737. break;
  65738. }
  65739. case SQLITE_AFF_NUMERIC: {
  65740. sqlite3VdbeMemNumerify(pMem);
  65741. break;
  65742. }
  65743. case SQLITE_AFF_INTEGER: {
  65744. sqlite3VdbeMemIntegerify(pMem);
  65745. break;
  65746. }
  65747. case SQLITE_AFF_REAL: {
  65748. sqlite3VdbeMemRealify(pMem);
  65749. break;
  65750. }
  65751. default: {
  65752. assert( aff==SQLITE_AFF_TEXT );
  65753. assert( MEM_Str==(MEM_Blob>>3) );
  65754. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  65755. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  65756. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  65757. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  65758. break;
  65759. }
  65760. }
  65761. }
  65762. /*
  65763. ** Initialize bulk memory to be a consistent Mem object.
  65764. **
  65765. ** The minimum amount of initialization feasible is performed.
  65766. */
  65767. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  65768. assert( (flags & ~MEM_TypeMask)==0 );
  65769. pMem->flags = flags;
  65770. pMem->db = db;
  65771. pMem->szMalloc = 0;
  65772. }
  65773. /*
  65774. ** Delete any previous value and set the value stored in *pMem to NULL.
  65775. **
  65776. ** This routine calls the Mem.xDel destructor to dispose of values that
  65777. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  65778. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  65779. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  65780. **
  65781. ** Use this routine to reset the Mem prior to insert a new value.
  65782. **
  65783. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  65784. */
  65785. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  65786. if( VdbeMemDynamic(pMem) ){
  65787. vdbeMemClearExternAndSetNull(pMem);
  65788. }else{
  65789. pMem->flags = MEM_Null;
  65790. }
  65791. }
  65792. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  65793. sqlite3VdbeMemSetNull((Mem*)p);
  65794. }
  65795. /*
  65796. ** Delete any previous value and set the value to be a BLOB of length
  65797. ** n containing all zeros.
  65798. */
  65799. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  65800. sqlite3VdbeMemRelease(pMem);
  65801. pMem->flags = MEM_Blob|MEM_Zero;
  65802. pMem->n = 0;
  65803. if( n<0 ) n = 0;
  65804. pMem->u.nZero = n;
  65805. pMem->enc = SQLITE_UTF8;
  65806. pMem->z = 0;
  65807. }
  65808. /*
  65809. ** The pMem is known to contain content that needs to be destroyed prior
  65810. ** to a value change. So invoke the destructor, then set the value to
  65811. ** a 64-bit integer.
  65812. */
  65813. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  65814. sqlite3VdbeMemSetNull(pMem);
  65815. pMem->u.i = val;
  65816. pMem->flags = MEM_Int;
  65817. }
  65818. /*
  65819. ** Delete any previous value and set the value stored in *pMem to val,
  65820. ** manifest type INTEGER.
  65821. */
  65822. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  65823. if( VdbeMemDynamic(pMem) ){
  65824. vdbeReleaseAndSetInt64(pMem, val);
  65825. }else{
  65826. pMem->u.i = val;
  65827. pMem->flags = MEM_Int;
  65828. }
  65829. }
  65830. #ifndef SQLITE_OMIT_FLOATING_POINT
  65831. /*
  65832. ** Delete any previous value and set the value stored in *pMem to val,
  65833. ** manifest type REAL.
  65834. */
  65835. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  65836. sqlite3VdbeMemSetNull(pMem);
  65837. if( !sqlite3IsNaN(val) ){
  65838. pMem->u.r = val;
  65839. pMem->flags = MEM_Real;
  65840. }
  65841. }
  65842. #endif
  65843. /*
  65844. ** Delete any previous value and set the value of pMem to be an
  65845. ** empty boolean index.
  65846. */
  65847. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  65848. sqlite3 *db = pMem->db;
  65849. assert( db!=0 );
  65850. assert( (pMem->flags & MEM_RowSet)==0 );
  65851. sqlite3VdbeMemRelease(pMem);
  65852. pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
  65853. if( db->mallocFailed ){
  65854. pMem->flags = MEM_Null;
  65855. pMem->szMalloc = 0;
  65856. }else{
  65857. assert( pMem->zMalloc );
  65858. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  65859. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  65860. assert( pMem->u.pRowSet!=0 );
  65861. pMem->flags = MEM_RowSet;
  65862. }
  65863. }
  65864. /*
  65865. ** Return true if the Mem object contains a TEXT or BLOB that is
  65866. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  65867. */
  65868. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  65869. assert( p->db!=0 );
  65870. if( p->flags & (MEM_Str|MEM_Blob) ){
  65871. int n = p->n;
  65872. if( p->flags & MEM_Zero ){
  65873. n += p->u.nZero;
  65874. }
  65875. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  65876. }
  65877. return 0;
  65878. }
  65879. #ifdef SQLITE_DEBUG
  65880. /*
  65881. ** This routine prepares a memory cell for modification by breaking
  65882. ** its link to a shallow copy and by marking any current shallow
  65883. ** copies of this cell as invalid.
  65884. **
  65885. ** This is used for testing and debugging only - to make sure shallow
  65886. ** copies are not misused.
  65887. */
  65888. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  65889. int i;
  65890. Mem *pX;
  65891. for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
  65892. if( pX->pScopyFrom==pMem ){
  65893. pX->flags |= MEM_Undefined;
  65894. pX->pScopyFrom = 0;
  65895. }
  65896. }
  65897. pMem->pScopyFrom = 0;
  65898. }
  65899. #endif /* SQLITE_DEBUG */
  65900. /*
  65901. ** Make an shallow copy of pFrom into pTo. Prior contents of
  65902. ** pTo are freed. The pFrom->z field is not duplicated. If
  65903. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  65904. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  65905. */
  65906. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  65907. vdbeMemClearExternAndSetNull(pTo);
  65908. assert( !VdbeMemDynamic(pTo) );
  65909. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  65910. }
  65911. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  65912. assert( (pFrom->flags & MEM_RowSet)==0 );
  65913. assert( pTo->db==pFrom->db );
  65914. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  65915. memcpy(pTo, pFrom, MEMCELLSIZE);
  65916. if( (pFrom->flags&MEM_Static)==0 ){
  65917. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  65918. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  65919. pTo->flags |= srcType;
  65920. }
  65921. }
  65922. /*
  65923. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  65924. ** freed before the copy is made.
  65925. */
  65926. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  65927. int rc = SQLITE_OK;
  65928. assert( (pFrom->flags & MEM_RowSet)==0 );
  65929. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  65930. memcpy(pTo, pFrom, MEMCELLSIZE);
  65931. pTo->flags &= ~MEM_Dyn;
  65932. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  65933. if( 0==(pFrom->flags&MEM_Static) ){
  65934. pTo->flags |= MEM_Ephem;
  65935. rc = sqlite3VdbeMemMakeWriteable(pTo);
  65936. }
  65937. }
  65938. return rc;
  65939. }
  65940. /*
  65941. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  65942. ** freed. If pFrom contains ephemeral data, a copy is made.
  65943. **
  65944. ** pFrom contains an SQL NULL when this routine returns.
  65945. */
  65946. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  65947. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  65948. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  65949. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  65950. sqlite3VdbeMemRelease(pTo);
  65951. memcpy(pTo, pFrom, sizeof(Mem));
  65952. pFrom->flags = MEM_Null;
  65953. pFrom->szMalloc = 0;
  65954. }
  65955. /*
  65956. ** Change the value of a Mem to be a string or a BLOB.
  65957. **
  65958. ** The memory management strategy depends on the value of the xDel
  65959. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  65960. ** string is copied into a (possibly existing) buffer managed by the
  65961. ** Mem structure. Otherwise, any existing buffer is freed and the
  65962. ** pointer copied.
  65963. **
  65964. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  65965. ** size limit) then no memory allocation occurs. If the string can be
  65966. ** stored without allocating memory, then it is. If a memory allocation
  65967. ** is required to store the string, then value of pMem is unchanged. In
  65968. ** either case, SQLITE_TOOBIG is returned.
  65969. */
  65970. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  65971. Mem *pMem, /* Memory cell to set to string value */
  65972. const char *z, /* String pointer */
  65973. int n, /* Bytes in string, or negative */
  65974. u8 enc, /* Encoding of z. 0 for BLOBs */
  65975. void (*xDel)(void*) /* Destructor function */
  65976. ){
  65977. int nByte = n; /* New value for pMem->n */
  65978. int iLimit; /* Maximum allowed string or blob size */
  65979. u16 flags = 0; /* New value for pMem->flags */
  65980. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65981. assert( (pMem->flags & MEM_RowSet)==0 );
  65982. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  65983. if( !z ){
  65984. sqlite3VdbeMemSetNull(pMem);
  65985. return SQLITE_OK;
  65986. }
  65987. if( pMem->db ){
  65988. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  65989. }else{
  65990. iLimit = SQLITE_MAX_LENGTH;
  65991. }
  65992. flags = (enc==0?MEM_Blob:MEM_Str);
  65993. if( nByte<0 ){
  65994. assert( enc!=0 );
  65995. if( enc==SQLITE_UTF8 ){
  65996. nByte = sqlite3Strlen30(z);
  65997. if( nByte>iLimit ) nByte = iLimit+1;
  65998. }else{
  65999. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  66000. }
  66001. flags |= MEM_Term;
  66002. }
  66003. /* The following block sets the new values of Mem.z and Mem.xDel. It
  66004. ** also sets a flag in local variable "flags" to indicate the memory
  66005. ** management (one of MEM_Dyn or MEM_Static).
  66006. */
  66007. if( xDel==SQLITE_TRANSIENT ){
  66008. int nAlloc = nByte;
  66009. if( flags&MEM_Term ){
  66010. nAlloc += (enc==SQLITE_UTF8?1:2);
  66011. }
  66012. if( nByte>iLimit ){
  66013. return SQLITE_TOOBIG;
  66014. }
  66015. testcase( nAlloc==0 );
  66016. testcase( nAlloc==31 );
  66017. testcase( nAlloc==32 );
  66018. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  66019. return SQLITE_NOMEM_BKPT;
  66020. }
  66021. memcpy(pMem->z, z, nAlloc);
  66022. }else if( xDel==SQLITE_DYNAMIC ){
  66023. sqlite3VdbeMemRelease(pMem);
  66024. pMem->zMalloc = pMem->z = (char *)z;
  66025. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  66026. }else{
  66027. sqlite3VdbeMemRelease(pMem);
  66028. pMem->z = (char *)z;
  66029. pMem->xDel = xDel;
  66030. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  66031. }
  66032. pMem->n = nByte;
  66033. pMem->flags = flags;
  66034. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  66035. #ifndef SQLITE_OMIT_UTF16
  66036. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  66037. return SQLITE_NOMEM_BKPT;
  66038. }
  66039. #endif
  66040. if( nByte>iLimit ){
  66041. return SQLITE_TOOBIG;
  66042. }
  66043. return SQLITE_OK;
  66044. }
  66045. /*
  66046. ** Move data out of a btree key or data field and into a Mem structure.
  66047. ** The data is payload from the entry that pCur is currently pointing
  66048. ** to. offset and amt determine what portion of the data or key to retrieve.
  66049. ** The result is written into the pMem element.
  66050. **
  66051. ** The pMem object must have been initialized. This routine will use
  66052. ** pMem->zMalloc to hold the content from the btree, if possible. New
  66053. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  66054. ** is responsible for making sure that the pMem object is eventually
  66055. ** destroyed.
  66056. **
  66057. ** If this routine fails for any reason (malloc returns NULL or unable
  66058. ** to read from the disk) then the pMem is left in an inconsistent state.
  66059. */
  66060. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  66061. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  66062. u32 offset, /* Offset from the start of data to return bytes from. */
  66063. u32 amt, /* Number of bytes to return. */
  66064. Mem *pMem /* OUT: Return data in this Mem structure. */
  66065. ){
  66066. int rc;
  66067. pMem->flags = MEM_Null;
  66068. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
  66069. rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
  66070. if( rc==SQLITE_OK ){
  66071. pMem->z[amt] = 0;
  66072. pMem->z[amt+1] = 0;
  66073. pMem->flags = MEM_Blob|MEM_Term;
  66074. pMem->n = (int)amt;
  66075. }else{
  66076. sqlite3VdbeMemRelease(pMem);
  66077. }
  66078. }
  66079. return rc;
  66080. }
  66081. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  66082. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  66083. u32 offset, /* Offset from the start of data to return bytes from. */
  66084. u32 amt, /* Number of bytes to return. */
  66085. Mem *pMem /* OUT: Return data in this Mem structure. */
  66086. ){
  66087. char *zData; /* Data from the btree layer */
  66088. u32 available = 0; /* Number of bytes available on the local btree page */
  66089. int rc = SQLITE_OK; /* Return code */
  66090. assert( sqlite3BtreeCursorIsValid(pCur) );
  66091. assert( !VdbeMemDynamic(pMem) );
  66092. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  66093. ** that both the BtShared and database handle mutexes are held. */
  66094. assert( (pMem->flags & MEM_RowSet)==0 );
  66095. zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
  66096. assert( zData!=0 );
  66097. if( offset+amt<=available ){
  66098. pMem->z = &zData[offset];
  66099. pMem->flags = MEM_Blob|MEM_Ephem;
  66100. pMem->n = (int)amt;
  66101. }else{
  66102. rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
  66103. }
  66104. return rc;
  66105. }
  66106. /*
  66107. ** The pVal argument is known to be a value other than NULL.
  66108. ** Convert it into a string with encoding enc and return a pointer
  66109. ** to a zero-terminated version of that string.
  66110. */
  66111. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  66112. assert( pVal!=0 );
  66113. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  66114. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  66115. assert( (pVal->flags & MEM_RowSet)==0 );
  66116. assert( (pVal->flags & (MEM_Null))==0 );
  66117. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  66118. if( ExpandBlob(pVal) ) return 0;
  66119. pVal->flags |= MEM_Str;
  66120. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  66121. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  66122. }
  66123. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  66124. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  66125. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  66126. return 0;
  66127. }
  66128. }
  66129. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  66130. }else{
  66131. sqlite3VdbeMemStringify(pVal, enc, 0);
  66132. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  66133. }
  66134. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  66135. || pVal->db->mallocFailed );
  66136. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  66137. return pVal->z;
  66138. }else{
  66139. return 0;
  66140. }
  66141. }
  66142. /* This function is only available internally, it is not part of the
  66143. ** external API. It works in a similar way to sqlite3_value_text(),
  66144. ** except the data returned is in the encoding specified by the second
  66145. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  66146. ** SQLITE_UTF8.
  66147. **
  66148. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  66149. ** If that is the case, then the result must be aligned on an even byte
  66150. ** boundary.
  66151. */
  66152. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  66153. if( !pVal ) return 0;
  66154. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  66155. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  66156. assert( (pVal->flags & MEM_RowSet)==0 );
  66157. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  66158. return pVal->z;
  66159. }
  66160. if( pVal->flags&MEM_Null ){
  66161. return 0;
  66162. }
  66163. return valueToText(pVal, enc);
  66164. }
  66165. /*
  66166. ** Create a new sqlite3_value object.
  66167. */
  66168. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  66169. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  66170. if( p ){
  66171. p->flags = MEM_Null;
  66172. p->db = db;
  66173. }
  66174. return p;
  66175. }
  66176. /*
  66177. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  66178. ** valueNew(). See comments above valueNew() for details.
  66179. */
  66180. struct ValueNewStat4Ctx {
  66181. Parse *pParse;
  66182. Index *pIdx;
  66183. UnpackedRecord **ppRec;
  66184. int iVal;
  66185. };
  66186. /*
  66187. ** Allocate and return a pointer to a new sqlite3_value object. If
  66188. ** the second argument to this function is NULL, the object is allocated
  66189. ** by calling sqlite3ValueNew().
  66190. **
  66191. ** Otherwise, if the second argument is non-zero, then this function is
  66192. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  66193. ** already been allocated, allocate the UnpackedRecord structure that
  66194. ** that function will return to its caller here. Then return a pointer to
  66195. ** an sqlite3_value within the UnpackedRecord.a[] array.
  66196. */
  66197. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  66198. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66199. if( p ){
  66200. UnpackedRecord *pRec = p->ppRec[0];
  66201. if( pRec==0 ){
  66202. Index *pIdx = p->pIdx; /* Index being probed */
  66203. int nByte; /* Bytes of space to allocate */
  66204. int i; /* Counter variable */
  66205. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  66206. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  66207. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  66208. if( pRec ){
  66209. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  66210. if( pRec->pKeyInfo ){
  66211. assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  66212. assert( pRec->pKeyInfo->enc==ENC(db) );
  66213. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  66214. for(i=0; i<nCol; i++){
  66215. pRec->aMem[i].flags = MEM_Null;
  66216. pRec->aMem[i].db = db;
  66217. }
  66218. }else{
  66219. sqlite3DbFreeNN(db, pRec);
  66220. pRec = 0;
  66221. }
  66222. }
  66223. if( pRec==0 ) return 0;
  66224. p->ppRec[0] = pRec;
  66225. }
  66226. pRec->nField = p->iVal+1;
  66227. return &pRec->aMem[p->iVal];
  66228. }
  66229. #else
  66230. UNUSED_PARAMETER(p);
  66231. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  66232. return sqlite3ValueNew(db);
  66233. }
  66234. /*
  66235. ** The expression object indicated by the second argument is guaranteed
  66236. ** to be a scalar SQL function. If
  66237. **
  66238. ** * all function arguments are SQL literals,
  66239. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  66240. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  66241. **
  66242. ** then this routine attempts to invoke the SQL function. Assuming no
  66243. ** error occurs, output parameter (*ppVal) is set to point to a value
  66244. ** object containing the result before returning SQLITE_OK.
  66245. **
  66246. ** Affinity aff is applied to the result of the function before returning.
  66247. ** If the result is a text value, the sqlite3_value object uses encoding
  66248. ** enc.
  66249. **
  66250. ** If the conditions above are not met, this function returns SQLITE_OK
  66251. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  66252. ** NULL and an SQLite error code returned.
  66253. */
  66254. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66255. static int valueFromFunction(
  66256. sqlite3 *db, /* The database connection */
  66257. Expr *p, /* The expression to evaluate */
  66258. u8 enc, /* Encoding to use */
  66259. u8 aff, /* Affinity to use */
  66260. sqlite3_value **ppVal, /* Write the new value here */
  66261. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  66262. ){
  66263. sqlite3_context ctx; /* Context object for function invocation */
  66264. sqlite3_value **apVal = 0; /* Function arguments */
  66265. int nVal = 0; /* Size of apVal[] array */
  66266. FuncDef *pFunc = 0; /* Function definition */
  66267. sqlite3_value *pVal = 0; /* New value */
  66268. int rc = SQLITE_OK; /* Return code */
  66269. ExprList *pList = 0; /* Function arguments */
  66270. int i; /* Iterator variable */
  66271. assert( pCtx!=0 );
  66272. assert( (p->flags & EP_TokenOnly)==0 );
  66273. pList = p->x.pList;
  66274. if( pList ) nVal = pList->nExpr;
  66275. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  66276. assert( pFunc );
  66277. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  66278. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  66279. ){
  66280. return SQLITE_OK;
  66281. }
  66282. if( pList ){
  66283. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  66284. if( apVal==0 ){
  66285. rc = SQLITE_NOMEM_BKPT;
  66286. goto value_from_function_out;
  66287. }
  66288. for(i=0; i<nVal; i++){
  66289. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  66290. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  66291. }
  66292. }
  66293. pVal = valueNew(db, pCtx);
  66294. if( pVal==0 ){
  66295. rc = SQLITE_NOMEM_BKPT;
  66296. goto value_from_function_out;
  66297. }
  66298. assert( pCtx->pParse->rc==SQLITE_OK );
  66299. memset(&ctx, 0, sizeof(ctx));
  66300. ctx.pOut = pVal;
  66301. ctx.pFunc = pFunc;
  66302. pFunc->xSFunc(&ctx, nVal, apVal);
  66303. if( ctx.isError ){
  66304. rc = ctx.isError;
  66305. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  66306. }else{
  66307. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  66308. assert( rc==SQLITE_OK );
  66309. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  66310. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  66311. rc = SQLITE_TOOBIG;
  66312. pCtx->pParse->nErr++;
  66313. }
  66314. }
  66315. pCtx->pParse->rc = rc;
  66316. value_from_function_out:
  66317. if( rc!=SQLITE_OK ){
  66318. pVal = 0;
  66319. }
  66320. if( apVal ){
  66321. for(i=0; i<nVal; i++){
  66322. sqlite3ValueFree(apVal[i]);
  66323. }
  66324. sqlite3DbFreeNN(db, apVal);
  66325. }
  66326. *ppVal = pVal;
  66327. return rc;
  66328. }
  66329. #else
  66330. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  66331. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  66332. /*
  66333. ** Extract a value from the supplied expression in the manner described
  66334. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  66335. ** using valueNew().
  66336. **
  66337. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  66338. ** has been allocated, it is freed before returning. Or, if pCtx is not
  66339. ** NULL, it is assumed that the caller will free any allocated object
  66340. ** in all cases.
  66341. */
  66342. static int valueFromExpr(
  66343. sqlite3 *db, /* The database connection */
  66344. Expr *pExpr, /* The expression to evaluate */
  66345. u8 enc, /* Encoding to use */
  66346. u8 affinity, /* Affinity to use */
  66347. sqlite3_value **ppVal, /* Write the new value here */
  66348. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  66349. ){
  66350. int op;
  66351. char *zVal = 0;
  66352. sqlite3_value *pVal = 0;
  66353. int negInt = 1;
  66354. const char *zNeg = "";
  66355. int rc = SQLITE_OK;
  66356. assert( pExpr!=0 );
  66357. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  66358. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  66359. /* Compressed expressions only appear when parsing the DEFAULT clause
  66360. ** on a table column definition, and hence only when pCtx==0. This
  66361. ** check ensures that an EP_TokenOnly expression is never passed down
  66362. ** into valueFromFunction(). */
  66363. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  66364. if( op==TK_CAST ){
  66365. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  66366. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  66367. testcase( rc!=SQLITE_OK );
  66368. if( *ppVal ){
  66369. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  66370. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  66371. }
  66372. return rc;
  66373. }
  66374. /* Handle negative integers in a single step. This is needed in the
  66375. ** case when the value is -9223372036854775808.
  66376. */
  66377. if( op==TK_UMINUS
  66378. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  66379. pExpr = pExpr->pLeft;
  66380. op = pExpr->op;
  66381. negInt = -1;
  66382. zNeg = "-";
  66383. }
  66384. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  66385. pVal = valueNew(db, pCtx);
  66386. if( pVal==0 ) goto no_mem;
  66387. if( ExprHasProperty(pExpr, EP_IntValue) ){
  66388. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  66389. }else{
  66390. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  66391. if( zVal==0 ) goto no_mem;
  66392. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  66393. }
  66394. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  66395. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  66396. }else{
  66397. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  66398. }
  66399. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  66400. if( enc!=SQLITE_UTF8 ){
  66401. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  66402. }
  66403. }else if( op==TK_UMINUS ) {
  66404. /* This branch happens for multiple negative signs. Ex: -(-5) */
  66405. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  66406. && pVal!=0
  66407. ){
  66408. sqlite3VdbeMemNumerify(pVal);
  66409. if( pVal->flags & MEM_Real ){
  66410. pVal->u.r = -pVal->u.r;
  66411. }else if( pVal->u.i==SMALLEST_INT64 ){
  66412. pVal->u.r = -(double)SMALLEST_INT64;
  66413. MemSetTypeFlag(pVal, MEM_Real);
  66414. }else{
  66415. pVal->u.i = -pVal->u.i;
  66416. }
  66417. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  66418. }
  66419. }else if( op==TK_NULL ){
  66420. pVal = valueNew(db, pCtx);
  66421. if( pVal==0 ) goto no_mem;
  66422. sqlite3VdbeMemNumerify(pVal);
  66423. }
  66424. #ifndef SQLITE_OMIT_BLOB_LITERAL
  66425. else if( op==TK_BLOB ){
  66426. int nVal;
  66427. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  66428. assert( pExpr->u.zToken[1]=='\'' );
  66429. pVal = valueNew(db, pCtx);
  66430. if( !pVal ) goto no_mem;
  66431. zVal = &pExpr->u.zToken[2];
  66432. nVal = sqlite3Strlen30(zVal)-1;
  66433. assert( zVal[nVal]=='\'' );
  66434. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  66435. 0, SQLITE_DYNAMIC);
  66436. }
  66437. #endif
  66438. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66439. else if( op==TK_FUNCTION && pCtx!=0 ){
  66440. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  66441. }
  66442. #endif
  66443. *ppVal = pVal;
  66444. return rc;
  66445. no_mem:
  66446. sqlite3OomFault(db);
  66447. sqlite3DbFree(db, zVal);
  66448. assert( *ppVal==0 );
  66449. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66450. if( pCtx==0 ) sqlite3ValueFree(pVal);
  66451. #else
  66452. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  66453. #endif
  66454. return SQLITE_NOMEM_BKPT;
  66455. }
  66456. /*
  66457. ** Create a new sqlite3_value object, containing the value of pExpr.
  66458. **
  66459. ** This only works for very simple expressions that consist of one constant
  66460. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  66461. ** be converted directly into a value, then the value is allocated and
  66462. ** a pointer written to *ppVal. The caller is responsible for deallocating
  66463. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  66464. ** cannot be converted to a value, then *ppVal is set to NULL.
  66465. */
  66466. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  66467. sqlite3 *db, /* The database connection */
  66468. Expr *pExpr, /* The expression to evaluate */
  66469. u8 enc, /* Encoding to use */
  66470. u8 affinity, /* Affinity to use */
  66471. sqlite3_value **ppVal /* Write the new value here */
  66472. ){
  66473. return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
  66474. }
  66475. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66476. /*
  66477. ** The implementation of the sqlite_record() function. This function accepts
  66478. ** a single argument of any type. The return value is a formatted database
  66479. ** record (a blob) containing the argument value.
  66480. **
  66481. ** This is used to convert the value stored in the 'sample' column of the
  66482. ** sqlite_stat3 table to the record format SQLite uses internally.
  66483. */
  66484. static void recordFunc(
  66485. sqlite3_context *context,
  66486. int argc,
  66487. sqlite3_value **argv
  66488. ){
  66489. const int file_format = 1;
  66490. u32 iSerial; /* Serial type */
  66491. int nSerial; /* Bytes of space for iSerial as varint */
  66492. u32 nVal; /* Bytes of space required for argv[0] */
  66493. int nRet;
  66494. sqlite3 *db;
  66495. u8 *aRet;
  66496. UNUSED_PARAMETER( argc );
  66497. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  66498. nSerial = sqlite3VarintLen(iSerial);
  66499. db = sqlite3_context_db_handle(context);
  66500. nRet = 1 + nSerial + nVal;
  66501. aRet = sqlite3DbMallocRawNN(db, nRet);
  66502. if( aRet==0 ){
  66503. sqlite3_result_error_nomem(context);
  66504. }else{
  66505. aRet[0] = nSerial+1;
  66506. putVarint32(&aRet[1], iSerial);
  66507. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  66508. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  66509. sqlite3DbFreeNN(db, aRet);
  66510. }
  66511. }
  66512. /*
  66513. ** Register built-in functions used to help read ANALYZE data.
  66514. */
  66515. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  66516. static FuncDef aAnalyzeTableFuncs[] = {
  66517. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  66518. };
  66519. sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
  66520. }
  66521. /*
  66522. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  66523. **
  66524. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  66525. ** pAlloc if one does not exist and the new value is added to the
  66526. ** UnpackedRecord object.
  66527. **
  66528. ** A value is extracted in the following cases:
  66529. **
  66530. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  66531. **
  66532. ** * The expression is a bound variable, and this is a reprepare, or
  66533. **
  66534. ** * The expression is a literal value.
  66535. **
  66536. ** On success, *ppVal is made to point to the extracted value. The caller
  66537. ** is responsible for ensuring that the value is eventually freed.
  66538. */
  66539. static int stat4ValueFromExpr(
  66540. Parse *pParse, /* Parse context */
  66541. Expr *pExpr, /* The expression to extract a value from */
  66542. u8 affinity, /* Affinity to use */
  66543. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  66544. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  66545. ){
  66546. int rc = SQLITE_OK;
  66547. sqlite3_value *pVal = 0;
  66548. sqlite3 *db = pParse->db;
  66549. /* Skip over any TK_COLLATE nodes */
  66550. pExpr = sqlite3ExprSkipCollate(pExpr);
  66551. if( !pExpr ){
  66552. pVal = valueNew(db, pAlloc);
  66553. if( pVal ){
  66554. sqlite3VdbeMemSetNull((Mem*)pVal);
  66555. }
  66556. }else if( pExpr->op==TK_VARIABLE
  66557. || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  66558. ){
  66559. Vdbe *v;
  66560. int iBindVar = pExpr->iColumn;
  66561. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  66562. if( (v = pParse->pReprepare)!=0 ){
  66563. pVal = valueNew(db, pAlloc);
  66564. if( pVal ){
  66565. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  66566. if( rc==SQLITE_OK ){
  66567. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  66568. }
  66569. pVal->db = pParse->db;
  66570. }
  66571. }
  66572. }else{
  66573. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  66574. }
  66575. assert( pVal==0 || pVal->db==db );
  66576. *ppVal = pVal;
  66577. return rc;
  66578. }
  66579. /*
  66580. ** This function is used to allocate and populate UnpackedRecord
  66581. ** structures intended to be compared against sample index keys stored
  66582. ** in the sqlite_stat4 table.
  66583. **
  66584. ** A single call to this function populates zero or more fields of the
  66585. ** record starting with field iVal (fields are numbered from left to
  66586. ** right starting with 0). A single field is populated if:
  66587. **
  66588. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  66589. **
  66590. ** * The expression is a bound variable, and this is a reprepare, or
  66591. **
  66592. ** * The sqlite3ValueFromExpr() function is able to extract a value
  66593. ** from the expression (i.e. the expression is a literal value).
  66594. **
  66595. ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
  66596. ** vector components that match either of the two latter criteria listed
  66597. ** above.
  66598. **
  66599. ** Before any value is appended to the record, the affinity of the
  66600. ** corresponding column within index pIdx is applied to it. Before
  66601. ** this function returns, output parameter *pnExtract is set to the
  66602. ** number of values appended to the record.
  66603. **
  66604. ** When this function is called, *ppRec must either point to an object
  66605. ** allocated by an earlier call to this function, or must be NULL. If it
  66606. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  66607. ** is allocated (and *ppRec set to point to it) before returning.
  66608. **
  66609. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  66610. ** error if a value cannot be extracted from pExpr. If an error does
  66611. ** occur, an SQLite error code is returned.
  66612. */
  66613. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  66614. Parse *pParse, /* Parse context */
  66615. Index *pIdx, /* Index being probed */
  66616. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  66617. Expr *pExpr, /* The expression to extract a value from */
  66618. int nElem, /* Maximum number of values to append */
  66619. int iVal, /* Array element to populate */
  66620. int *pnExtract /* OUT: Values appended to the record */
  66621. ){
  66622. int rc = SQLITE_OK;
  66623. int nExtract = 0;
  66624. if( pExpr==0 || pExpr->op!=TK_SELECT ){
  66625. int i;
  66626. struct ValueNewStat4Ctx alloc;
  66627. alloc.pParse = pParse;
  66628. alloc.pIdx = pIdx;
  66629. alloc.ppRec = ppRec;
  66630. for(i=0; i<nElem; i++){
  66631. sqlite3_value *pVal = 0;
  66632. Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
  66633. u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
  66634. alloc.iVal = iVal+i;
  66635. rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
  66636. if( !pVal ) break;
  66637. nExtract++;
  66638. }
  66639. }
  66640. *pnExtract = nExtract;
  66641. return rc;
  66642. }
  66643. /*
  66644. ** Attempt to extract a value from expression pExpr using the methods
  66645. ** as described for sqlite3Stat4ProbeSetValue() above.
  66646. **
  66647. ** If successful, set *ppVal to point to a new value object and return
  66648. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  66649. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  66650. ** does occur, return an SQLite error code. The final value of *ppVal
  66651. ** is undefined in this case.
  66652. */
  66653. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  66654. Parse *pParse, /* Parse context */
  66655. Expr *pExpr, /* The expression to extract a value from */
  66656. u8 affinity, /* Affinity to use */
  66657. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  66658. ){
  66659. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  66660. }
  66661. /*
  66662. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  66663. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  66664. ** sqlite3_value object is allocated.
  66665. **
  66666. ** If *ppVal is initially NULL then the caller is responsible for
  66667. ** ensuring that the value written into *ppVal is eventually freed.
  66668. */
  66669. SQLITE_PRIVATE int sqlite3Stat4Column(
  66670. sqlite3 *db, /* Database handle */
  66671. const void *pRec, /* Pointer to buffer containing record */
  66672. int nRec, /* Size of buffer pRec in bytes */
  66673. int iCol, /* Column to extract */
  66674. sqlite3_value **ppVal /* OUT: Extracted value */
  66675. ){
  66676. u32 t; /* a column type code */
  66677. int nHdr; /* Size of the header in the record */
  66678. int iHdr; /* Next unread header byte */
  66679. int iField; /* Next unread data byte */
  66680. int szField; /* Size of the current data field */
  66681. int i; /* Column index */
  66682. u8 *a = (u8*)pRec; /* Typecast byte array */
  66683. Mem *pMem = *ppVal; /* Write result into this Mem object */
  66684. assert( iCol>0 );
  66685. iHdr = getVarint32(a, nHdr);
  66686. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  66687. iField = nHdr;
  66688. for(i=0; i<=iCol; i++){
  66689. iHdr += getVarint32(&a[iHdr], t);
  66690. testcase( iHdr==nHdr );
  66691. testcase( iHdr==nHdr+1 );
  66692. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  66693. szField = sqlite3VdbeSerialTypeLen(t);
  66694. iField += szField;
  66695. }
  66696. testcase( iField==nRec );
  66697. testcase( iField==nRec+1 );
  66698. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  66699. if( pMem==0 ){
  66700. pMem = *ppVal = sqlite3ValueNew(db);
  66701. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  66702. }
  66703. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  66704. pMem->enc = ENC(db);
  66705. return SQLITE_OK;
  66706. }
  66707. /*
  66708. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  66709. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  66710. ** the object.
  66711. */
  66712. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  66713. if( pRec ){
  66714. int i;
  66715. int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
  66716. Mem *aMem = pRec->aMem;
  66717. sqlite3 *db = aMem[0].db;
  66718. for(i=0; i<nCol; i++){
  66719. sqlite3VdbeMemRelease(&aMem[i]);
  66720. }
  66721. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  66722. sqlite3DbFreeNN(db, pRec);
  66723. }
  66724. }
  66725. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  66726. /*
  66727. ** Change the string value of an sqlite3_value object
  66728. */
  66729. SQLITE_PRIVATE void sqlite3ValueSetStr(
  66730. sqlite3_value *v, /* Value to be set */
  66731. int n, /* Length of string z */
  66732. const void *z, /* Text of the new string */
  66733. u8 enc, /* Encoding to use */
  66734. void (*xDel)(void*) /* Destructor for the string */
  66735. ){
  66736. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  66737. }
  66738. /*
  66739. ** Free an sqlite3_value object
  66740. */
  66741. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  66742. if( !v ) return;
  66743. sqlite3VdbeMemRelease((Mem *)v);
  66744. sqlite3DbFreeNN(((Mem*)v)->db, v);
  66745. }
  66746. /*
  66747. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  66748. ** sqlite3_value object assuming that it uses the encoding "enc".
  66749. ** The valueBytes() routine is a helper function.
  66750. */
  66751. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  66752. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  66753. }
  66754. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  66755. Mem *p = (Mem*)pVal;
  66756. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  66757. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  66758. return p->n;
  66759. }
  66760. if( (p->flags & MEM_Blob)!=0 ){
  66761. if( p->flags & MEM_Zero ){
  66762. return p->n + p->u.nZero;
  66763. }else{
  66764. return p->n;
  66765. }
  66766. }
  66767. if( p->flags & MEM_Null ) return 0;
  66768. return valueBytes(pVal, enc);
  66769. }
  66770. /************** End of vdbemem.c *********************************************/
  66771. /************** Begin file vdbeaux.c *****************************************/
  66772. /*
  66773. ** 2003 September 6
  66774. **
  66775. ** The author disclaims copyright to this source code. In place of
  66776. ** a legal notice, here is a blessing:
  66777. **
  66778. ** May you do good and not evil.
  66779. ** May you find forgiveness for yourself and forgive others.
  66780. ** May you share freely, never taking more than you give.
  66781. **
  66782. *************************************************************************
  66783. ** This file contains code used for creating, destroying, and populating
  66784. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  66785. */
  66786. /* #include "sqliteInt.h" */
  66787. /* #include "vdbeInt.h" */
  66788. /*
  66789. ** Create a new virtual database engine.
  66790. */
  66791. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  66792. sqlite3 *db = pParse->db;
  66793. Vdbe *p;
  66794. p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
  66795. if( p==0 ) return 0;
  66796. memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
  66797. p->db = db;
  66798. if( db->pVdbe ){
  66799. db->pVdbe->pPrev = p;
  66800. }
  66801. p->pNext = db->pVdbe;
  66802. p->pPrev = 0;
  66803. db->pVdbe = p;
  66804. p->magic = VDBE_MAGIC_INIT;
  66805. p->pParse = pParse;
  66806. assert( pParse->aLabel==0 );
  66807. assert( pParse->nLabel==0 );
  66808. assert( pParse->nOpAlloc==0 );
  66809. assert( pParse->szOpAlloc==0 );
  66810. return p;
  66811. }
  66812. /*
  66813. ** Change the error string stored in Vdbe.zErrMsg
  66814. */
  66815. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  66816. va_list ap;
  66817. sqlite3DbFree(p->db, p->zErrMsg);
  66818. va_start(ap, zFormat);
  66819. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  66820. va_end(ap);
  66821. }
  66822. /*
  66823. ** Remember the SQL string for a prepared statement.
  66824. */
  66825. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  66826. assert( isPrepareV2==1 || isPrepareV2==0 );
  66827. if( p==0 ) return;
  66828. if( !isPrepareV2 ) p->expmask = 0;
  66829. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  66830. if( !isPrepareV2 ) return;
  66831. #endif
  66832. assert( p->zSql==0 );
  66833. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  66834. p->isPrepareV2 = (u8)isPrepareV2;
  66835. }
  66836. /*
  66837. ** Swap all content between two VDBE structures.
  66838. */
  66839. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  66840. Vdbe tmp, *pTmp;
  66841. char *zTmp;
  66842. assert( pA->db==pB->db );
  66843. tmp = *pA;
  66844. *pA = *pB;
  66845. *pB = tmp;
  66846. pTmp = pA->pNext;
  66847. pA->pNext = pB->pNext;
  66848. pB->pNext = pTmp;
  66849. pTmp = pA->pPrev;
  66850. pA->pPrev = pB->pPrev;
  66851. pB->pPrev = pTmp;
  66852. zTmp = pA->zSql;
  66853. pA->zSql = pB->zSql;
  66854. pB->zSql = zTmp;
  66855. pB->isPrepareV2 = pA->isPrepareV2;
  66856. pB->expmask = pA->expmask;
  66857. }
  66858. /*
  66859. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  66860. ** than its current size. nOp is guaranteed to be less than or equal
  66861. ** to 1024/sizeof(Op).
  66862. **
  66863. ** If an out-of-memory error occurs while resizing the array, return
  66864. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  66865. ** unchanged (this is so that any opcodes already allocated can be
  66866. ** correctly deallocated along with the rest of the Vdbe).
  66867. */
  66868. static int growOpArray(Vdbe *v, int nOp){
  66869. VdbeOp *pNew;
  66870. Parse *p = v->pParse;
  66871. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  66872. ** more frequent reallocs and hence provide more opportunities for
  66873. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  66874. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  66875. ** by the minimum* amount required until the size reaches 512. Normal
  66876. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  66877. ** size of the op array or add 1KB of space, whichever is smaller. */
  66878. #ifdef SQLITE_TEST_REALLOC_STRESS
  66879. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  66880. #else
  66881. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  66882. UNUSED_PARAMETER(nOp);
  66883. #endif
  66884. /* Ensure that the size of a VDBE does not grow too large */
  66885. if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
  66886. sqlite3OomFault(p->db);
  66887. return SQLITE_NOMEM;
  66888. }
  66889. assert( nOp<=(1024/sizeof(Op)) );
  66890. assert( nNew>=(p->nOpAlloc+nOp) );
  66891. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  66892. if( pNew ){
  66893. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  66894. p->nOpAlloc = p->szOpAlloc/sizeof(Op);
  66895. v->aOp = pNew;
  66896. }
  66897. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  66898. }
  66899. #ifdef SQLITE_DEBUG
  66900. /* This routine is just a convenient place to set a breakpoint that will
  66901. ** fire after each opcode is inserted and displayed using
  66902. ** "PRAGMA vdbe_addoptrace=on".
  66903. */
  66904. static void test_addop_breakpoint(void){
  66905. static int n = 0;
  66906. n++;
  66907. }
  66908. #endif
  66909. /*
  66910. ** Add a new instruction to the list of instructions current in the
  66911. ** VDBE. Return the address of the new instruction.
  66912. **
  66913. ** Parameters:
  66914. **
  66915. ** p Pointer to the VDBE
  66916. **
  66917. ** op The opcode for this instruction
  66918. **
  66919. ** p1, p2, p3 Operands
  66920. **
  66921. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  66922. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  66923. ** operand.
  66924. */
  66925. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  66926. assert( p->pParse->nOpAlloc<=p->nOp );
  66927. if( growOpArray(p, 1) ) return 1;
  66928. assert( p->pParse->nOpAlloc>p->nOp );
  66929. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  66930. }
  66931. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  66932. int i;
  66933. VdbeOp *pOp;
  66934. i = p->nOp;
  66935. assert( p->magic==VDBE_MAGIC_INIT );
  66936. assert( op>=0 && op<0xff );
  66937. if( p->pParse->nOpAlloc<=i ){
  66938. return growOp3(p, op, p1, p2, p3);
  66939. }
  66940. p->nOp++;
  66941. pOp = &p->aOp[i];
  66942. pOp->opcode = (u8)op;
  66943. pOp->p5 = 0;
  66944. pOp->p1 = p1;
  66945. pOp->p2 = p2;
  66946. pOp->p3 = p3;
  66947. pOp->p4.p = 0;
  66948. pOp->p4type = P4_NOTUSED;
  66949. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  66950. pOp->zComment = 0;
  66951. #endif
  66952. #ifdef SQLITE_DEBUG
  66953. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  66954. int jj, kk;
  66955. Parse *pParse = p->pParse;
  66956. for(jj=kk=0; jj<pParse->nColCache; jj++){
  66957. struct yColCache *x = pParse->aColCache + jj;
  66958. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  66959. kk++;
  66960. }
  66961. if( kk ) printf("\n");
  66962. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  66963. test_addop_breakpoint();
  66964. }
  66965. #endif
  66966. #ifdef VDBE_PROFILE
  66967. pOp->cycles = 0;
  66968. pOp->cnt = 0;
  66969. #endif
  66970. #ifdef SQLITE_VDBE_COVERAGE
  66971. pOp->iSrcLine = 0;
  66972. #endif
  66973. return i;
  66974. }
  66975. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  66976. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  66977. }
  66978. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  66979. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  66980. }
  66981. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  66982. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  66983. }
  66984. /* Generate code for an unconditional jump to instruction iDest
  66985. */
  66986. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  66987. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  66988. }
  66989. /* Generate code to cause the string zStr to be loaded into
  66990. ** register iDest
  66991. */
  66992. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  66993. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  66994. }
  66995. /*
  66996. ** Generate code that initializes multiple registers to string or integer
  66997. ** constants. The registers begin with iDest and increase consecutively.
  66998. ** One register is initialized for each characgter in zTypes[]. For each
  66999. ** "s" character in zTypes[], the register is a string if the argument is
  67000. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  67001. ** in zTypes[], the register is initialized to an integer.
  67002. */
  67003. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  67004. va_list ap;
  67005. int i;
  67006. char c;
  67007. va_start(ap, zTypes);
  67008. for(i=0; (c = zTypes[i])!=0; i++){
  67009. if( c=='s' ){
  67010. const char *z = va_arg(ap, const char*);
  67011. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
  67012. }else{
  67013. assert( c=='i' );
  67014. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
  67015. }
  67016. }
  67017. va_end(ap);
  67018. }
  67019. /*
  67020. ** Add an opcode that includes the p4 value as a pointer.
  67021. */
  67022. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  67023. Vdbe *p, /* Add the opcode to this VM */
  67024. int op, /* The new opcode */
  67025. int p1, /* The P1 operand */
  67026. int p2, /* The P2 operand */
  67027. int p3, /* The P3 operand */
  67028. const char *zP4, /* The P4 operand */
  67029. int p4type /* P4 operand type */
  67030. ){
  67031. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  67032. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  67033. return addr;
  67034. }
  67035. /*
  67036. ** Add an opcode that includes the p4 value with a P4_INT64 or
  67037. ** P4_REAL type.
  67038. */
  67039. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  67040. Vdbe *p, /* Add the opcode to this VM */
  67041. int op, /* The new opcode */
  67042. int p1, /* The P1 operand */
  67043. int p2, /* The P2 operand */
  67044. int p3, /* The P3 operand */
  67045. const u8 *zP4, /* The P4 operand */
  67046. int p4type /* P4 operand type */
  67047. ){
  67048. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  67049. if( p4copy ) memcpy(p4copy, zP4, 8);
  67050. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  67051. }
  67052. /*
  67053. ** Add an OP_ParseSchema opcode. This routine is broken out from
  67054. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  67055. ** as having been used.
  67056. **
  67057. ** The zWhere string must have been obtained from sqlite3_malloc().
  67058. ** This routine will take ownership of the allocated memory.
  67059. */
  67060. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  67061. int j;
  67062. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  67063. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  67064. }
  67065. /*
  67066. ** Add an opcode that includes the p4 value as an integer.
  67067. */
  67068. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  67069. Vdbe *p, /* Add the opcode to this VM */
  67070. int op, /* The new opcode */
  67071. int p1, /* The P1 operand */
  67072. int p2, /* The P2 operand */
  67073. int p3, /* The P3 operand */
  67074. int p4 /* The P4 operand as an integer */
  67075. ){
  67076. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  67077. if( p->db->mallocFailed==0 ){
  67078. VdbeOp *pOp = &p->aOp[addr];
  67079. pOp->p4type = P4_INT32;
  67080. pOp->p4.i = p4;
  67081. }
  67082. return addr;
  67083. }
  67084. /* Insert the end of a co-routine
  67085. */
  67086. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  67087. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  67088. /* Clear the temporary register cache, thereby ensuring that each
  67089. ** co-routine has its own independent set of registers, because co-routines
  67090. ** might expect their registers to be preserved across an OP_Yield, and
  67091. ** that could cause problems if two or more co-routines are using the same
  67092. ** temporary register.
  67093. */
  67094. v->pParse->nTempReg = 0;
  67095. v->pParse->nRangeReg = 0;
  67096. }
  67097. /*
  67098. ** Create a new symbolic label for an instruction that has yet to be
  67099. ** coded. The symbolic label is really just a negative number. The
  67100. ** label can be used as the P2 value of an operation. Later, when
  67101. ** the label is resolved to a specific address, the VDBE will scan
  67102. ** through its operation list and change all values of P2 which match
  67103. ** the label into the resolved address.
  67104. **
  67105. ** The VDBE knows that a P2 value is a label because labels are
  67106. ** always negative and P2 values are suppose to be non-negative.
  67107. ** Hence, a negative P2 value is a label that has yet to be resolved.
  67108. **
  67109. ** Zero is returned if a malloc() fails.
  67110. */
  67111. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  67112. Parse *p = v->pParse;
  67113. int i = p->nLabel++;
  67114. assert( v->magic==VDBE_MAGIC_INIT );
  67115. if( (i & (i-1))==0 ){
  67116. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  67117. (i*2+1)*sizeof(p->aLabel[0]));
  67118. }
  67119. if( p->aLabel ){
  67120. p->aLabel[i] = -1;
  67121. }
  67122. return ADDR(i);
  67123. }
  67124. /*
  67125. ** Resolve label "x" to be the address of the next instruction to
  67126. ** be inserted. The parameter "x" must have been obtained from
  67127. ** a prior call to sqlite3VdbeMakeLabel().
  67128. */
  67129. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  67130. Parse *p = v->pParse;
  67131. int j = ADDR(x);
  67132. assert( v->magic==VDBE_MAGIC_INIT );
  67133. assert( j<p->nLabel );
  67134. assert( j>=0 );
  67135. if( p->aLabel ){
  67136. p->aLabel[j] = v->nOp;
  67137. }
  67138. }
  67139. /*
  67140. ** Mark the VDBE as one that can only be run one time.
  67141. */
  67142. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  67143. p->runOnlyOnce = 1;
  67144. }
  67145. /*
  67146. ** Mark the VDBE as one that can only be run multiple times.
  67147. */
  67148. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  67149. p->runOnlyOnce = 0;
  67150. }
  67151. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  67152. /*
  67153. ** The following type and function are used to iterate through all opcodes
  67154. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  67155. ** invoke directly or indirectly. It should be used as follows:
  67156. **
  67157. ** Op *pOp;
  67158. ** VdbeOpIter sIter;
  67159. **
  67160. ** memset(&sIter, 0, sizeof(sIter));
  67161. ** sIter.v = v; // v is of type Vdbe*
  67162. ** while( (pOp = opIterNext(&sIter)) ){
  67163. ** // Do something with pOp
  67164. ** }
  67165. ** sqlite3DbFree(v->db, sIter.apSub);
  67166. **
  67167. */
  67168. typedef struct VdbeOpIter VdbeOpIter;
  67169. struct VdbeOpIter {
  67170. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  67171. SubProgram **apSub; /* Array of subprograms */
  67172. int nSub; /* Number of entries in apSub */
  67173. int iAddr; /* Address of next instruction to return */
  67174. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  67175. };
  67176. static Op *opIterNext(VdbeOpIter *p){
  67177. Vdbe *v = p->v;
  67178. Op *pRet = 0;
  67179. Op *aOp;
  67180. int nOp;
  67181. if( p->iSub<=p->nSub ){
  67182. if( p->iSub==0 ){
  67183. aOp = v->aOp;
  67184. nOp = v->nOp;
  67185. }else{
  67186. aOp = p->apSub[p->iSub-1]->aOp;
  67187. nOp = p->apSub[p->iSub-1]->nOp;
  67188. }
  67189. assert( p->iAddr<nOp );
  67190. pRet = &aOp[p->iAddr];
  67191. p->iAddr++;
  67192. if( p->iAddr==nOp ){
  67193. p->iSub++;
  67194. p->iAddr = 0;
  67195. }
  67196. if( pRet->p4type==P4_SUBPROGRAM ){
  67197. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  67198. int j;
  67199. for(j=0; j<p->nSub; j++){
  67200. if( p->apSub[j]==pRet->p4.pProgram ) break;
  67201. }
  67202. if( j==p->nSub ){
  67203. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  67204. if( !p->apSub ){
  67205. pRet = 0;
  67206. }else{
  67207. p->apSub[p->nSub++] = pRet->p4.pProgram;
  67208. }
  67209. }
  67210. }
  67211. }
  67212. return pRet;
  67213. }
  67214. /*
  67215. ** Check if the program stored in the VM associated with pParse may
  67216. ** throw an ABORT exception (causing the statement, but not entire transaction
  67217. ** to be rolled back). This condition is true if the main program or any
  67218. ** sub-programs contains any of the following:
  67219. **
  67220. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  67221. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  67222. ** * OP_Destroy
  67223. ** * OP_VUpdate
  67224. ** * OP_VRename
  67225. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  67226. ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
  67227. **
  67228. ** Then check that the value of Parse.mayAbort is true if an
  67229. ** ABORT may be thrown, or false otherwise. Return true if it does
  67230. ** match, or false otherwise. This function is intended to be used as
  67231. ** part of an assert statement in the compiler. Similar to:
  67232. **
  67233. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  67234. */
  67235. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  67236. int hasAbort = 0;
  67237. int hasFkCounter = 0;
  67238. int hasCreateTable = 0;
  67239. int hasInitCoroutine = 0;
  67240. Op *pOp;
  67241. VdbeOpIter sIter;
  67242. memset(&sIter, 0, sizeof(sIter));
  67243. sIter.v = v;
  67244. while( (pOp = opIterNext(&sIter))!=0 ){
  67245. int opcode = pOp->opcode;
  67246. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  67247. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  67248. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  67249. ){
  67250. hasAbort = 1;
  67251. break;
  67252. }
  67253. if( opcode==OP_CreateTable ) hasCreateTable = 1;
  67254. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  67255. #ifndef SQLITE_OMIT_FOREIGN_KEY
  67256. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  67257. hasFkCounter = 1;
  67258. }
  67259. #endif
  67260. }
  67261. sqlite3DbFree(v->db, sIter.apSub);
  67262. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  67263. ** If malloc failed, then the while() loop above may not have iterated
  67264. ** through all opcodes and hasAbort may be set incorrectly. Return
  67265. ** true for this case to prevent the assert() in the callers frame
  67266. ** from failing. */
  67267. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  67268. || (hasCreateTable && hasInitCoroutine) );
  67269. }
  67270. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  67271. /*
  67272. ** This routine is called after all opcodes have been inserted. It loops
  67273. ** through all the opcodes and fixes up some details.
  67274. **
  67275. ** (1) For each jump instruction with a negative P2 value (a label)
  67276. ** resolve the P2 value to an actual address.
  67277. **
  67278. ** (2) Compute the maximum number of arguments used by any SQL function
  67279. ** and store that value in *pMaxFuncArgs.
  67280. **
  67281. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  67282. ** indicate what the prepared statement actually does.
  67283. **
  67284. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  67285. **
  67286. ** (5) Reclaim the memory allocated for storing labels.
  67287. **
  67288. ** This routine will only function correctly if the mkopcodeh.tcl generator
  67289. ** script numbers the opcodes correctly. Changes to this routine must be
  67290. ** coordinated with changes to mkopcodeh.tcl.
  67291. */
  67292. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  67293. int nMaxArgs = *pMaxFuncArgs;
  67294. Op *pOp;
  67295. Parse *pParse = p->pParse;
  67296. int *aLabel = pParse->aLabel;
  67297. p->readOnly = 1;
  67298. p->bIsReader = 0;
  67299. pOp = &p->aOp[p->nOp-1];
  67300. while(1){
  67301. /* Only JUMP opcodes and the short list of special opcodes in the switch
  67302. ** below need to be considered. The mkopcodeh.tcl generator script groups
  67303. ** all these opcodes together near the front of the opcode list. Skip
  67304. ** any opcode that does not need processing by virtual of the fact that
  67305. ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
  67306. */
  67307. if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
  67308. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  67309. ** cases from this switch! */
  67310. switch( pOp->opcode ){
  67311. case OP_Transaction: {
  67312. if( pOp->p2!=0 ) p->readOnly = 0;
  67313. /* fall thru */
  67314. }
  67315. case OP_AutoCommit:
  67316. case OP_Savepoint: {
  67317. p->bIsReader = 1;
  67318. break;
  67319. }
  67320. #ifndef SQLITE_OMIT_WAL
  67321. case OP_Checkpoint:
  67322. #endif
  67323. case OP_Vacuum:
  67324. case OP_JournalMode: {
  67325. p->readOnly = 0;
  67326. p->bIsReader = 1;
  67327. break;
  67328. }
  67329. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67330. case OP_VUpdate: {
  67331. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  67332. break;
  67333. }
  67334. case OP_VFilter: {
  67335. int n;
  67336. assert( (pOp - p->aOp) >= 3 );
  67337. assert( pOp[-1].opcode==OP_Integer );
  67338. n = pOp[-1].p1;
  67339. if( n>nMaxArgs ) nMaxArgs = n;
  67340. break;
  67341. }
  67342. #endif
  67343. case OP_Next:
  67344. case OP_NextIfOpen:
  67345. case OP_SorterNext: {
  67346. pOp->p4.xAdvance = sqlite3BtreeNext;
  67347. pOp->p4type = P4_ADVANCE;
  67348. break;
  67349. }
  67350. case OP_Prev:
  67351. case OP_PrevIfOpen: {
  67352. pOp->p4.xAdvance = sqlite3BtreePrevious;
  67353. pOp->p4type = P4_ADVANCE;
  67354. break;
  67355. }
  67356. }
  67357. if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  67358. assert( ADDR(pOp->p2)<pParse->nLabel );
  67359. pOp->p2 = aLabel[ADDR(pOp->p2)];
  67360. }
  67361. }
  67362. if( pOp==p->aOp ) break;
  67363. pOp--;
  67364. }
  67365. sqlite3DbFree(p->db, pParse->aLabel);
  67366. pParse->aLabel = 0;
  67367. pParse->nLabel = 0;
  67368. *pMaxFuncArgs = nMaxArgs;
  67369. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  67370. }
  67371. /*
  67372. ** Return the address of the next instruction to be inserted.
  67373. */
  67374. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  67375. assert( p->magic==VDBE_MAGIC_INIT );
  67376. return p->nOp;
  67377. }
  67378. /*
  67379. ** Verify that at least N opcode slots are available in p without
  67380. ** having to malloc for more space (except when compiled using
  67381. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  67382. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  67383. ** fail due to a OOM fault and hence that the return value from
  67384. ** sqlite3VdbeAddOpList() will always be non-NULL.
  67385. */
  67386. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  67387. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  67388. assert( p->nOp + N <= p->pParse->nOpAlloc );
  67389. }
  67390. #endif
  67391. /*
  67392. ** Verify that the VM passed as the only argument does not contain
  67393. ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
  67394. ** by code in pragma.c to ensure that the implementation of certain
  67395. ** pragmas comports with the flags specified in the mkpragmatab.tcl
  67396. ** script.
  67397. */
  67398. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  67399. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
  67400. int i;
  67401. for(i=0; i<p->nOp; i++){
  67402. assert( p->aOp[i].opcode!=OP_ResultRow );
  67403. }
  67404. }
  67405. #endif
  67406. /*
  67407. ** This function returns a pointer to the array of opcodes associated with
  67408. ** the Vdbe passed as the first argument. It is the callers responsibility
  67409. ** to arrange for the returned array to be eventually freed using the
  67410. ** vdbeFreeOpArray() function.
  67411. **
  67412. ** Before returning, *pnOp is set to the number of entries in the returned
  67413. ** array. Also, *pnMaxArg is set to the larger of its current value and
  67414. ** the number of entries in the Vdbe.apArg[] array required to execute the
  67415. ** returned program.
  67416. */
  67417. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  67418. VdbeOp *aOp = p->aOp;
  67419. assert( aOp && !p->db->mallocFailed );
  67420. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  67421. assert( DbMaskAllZero(p->btreeMask) );
  67422. resolveP2Values(p, pnMaxArg);
  67423. *pnOp = p->nOp;
  67424. p->aOp = 0;
  67425. return aOp;
  67426. }
  67427. /*
  67428. ** Add a whole list of operations to the operation stack. Return a
  67429. ** pointer to the first operation inserted.
  67430. **
  67431. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  67432. ** so that the jump target is relative to the first operation inserted.
  67433. */
  67434. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  67435. Vdbe *p, /* Add opcodes to the prepared statement */
  67436. int nOp, /* Number of opcodes to add */
  67437. VdbeOpList const *aOp, /* The opcodes to be added */
  67438. int iLineno /* Source-file line number of first opcode */
  67439. ){
  67440. int i;
  67441. VdbeOp *pOut, *pFirst;
  67442. assert( nOp>0 );
  67443. assert( p->magic==VDBE_MAGIC_INIT );
  67444. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  67445. return 0;
  67446. }
  67447. pFirst = pOut = &p->aOp[p->nOp];
  67448. for(i=0; i<nOp; i++, aOp++, pOut++){
  67449. pOut->opcode = aOp->opcode;
  67450. pOut->p1 = aOp->p1;
  67451. pOut->p2 = aOp->p2;
  67452. assert( aOp->p2>=0 );
  67453. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  67454. pOut->p2 += p->nOp;
  67455. }
  67456. pOut->p3 = aOp->p3;
  67457. pOut->p4type = P4_NOTUSED;
  67458. pOut->p4.p = 0;
  67459. pOut->p5 = 0;
  67460. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  67461. pOut->zComment = 0;
  67462. #endif
  67463. #ifdef SQLITE_VDBE_COVERAGE
  67464. pOut->iSrcLine = iLineno+i;
  67465. #else
  67466. (void)iLineno;
  67467. #endif
  67468. #ifdef SQLITE_DEBUG
  67469. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  67470. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  67471. }
  67472. #endif
  67473. }
  67474. p->nOp += nOp;
  67475. return pFirst;
  67476. }
  67477. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  67478. /*
  67479. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  67480. */
  67481. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  67482. Vdbe *p, /* VM to add scanstatus() to */
  67483. int addrExplain, /* Address of OP_Explain (or 0) */
  67484. int addrLoop, /* Address of loop counter */
  67485. int addrVisit, /* Address of rows visited counter */
  67486. LogEst nEst, /* Estimated number of output rows */
  67487. const char *zName /* Name of table or index being scanned */
  67488. ){
  67489. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  67490. ScanStatus *aNew;
  67491. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  67492. if( aNew ){
  67493. ScanStatus *pNew = &aNew[p->nScan++];
  67494. pNew->addrExplain = addrExplain;
  67495. pNew->addrLoop = addrLoop;
  67496. pNew->addrVisit = addrVisit;
  67497. pNew->nEst = nEst;
  67498. pNew->zName = sqlite3DbStrDup(p->db, zName);
  67499. p->aScan = aNew;
  67500. }
  67501. }
  67502. #endif
  67503. /*
  67504. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  67505. ** for a specific instruction.
  67506. */
  67507. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  67508. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  67509. }
  67510. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  67511. sqlite3VdbeGetOp(p,addr)->p1 = val;
  67512. }
  67513. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  67514. sqlite3VdbeGetOp(p,addr)->p2 = val;
  67515. }
  67516. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  67517. sqlite3VdbeGetOp(p,addr)->p3 = val;
  67518. }
  67519. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  67520. assert( p->nOp>0 || p->db->mallocFailed );
  67521. if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
  67522. }
  67523. /*
  67524. ** Change the P2 operand of instruction addr so that it points to
  67525. ** the address of the next instruction to be coded.
  67526. */
  67527. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  67528. sqlite3VdbeChangeP2(p, addr, p->nOp);
  67529. }
  67530. /*
  67531. ** If the input FuncDef structure is ephemeral, then free it. If
  67532. ** the FuncDef is not ephermal, then do nothing.
  67533. */
  67534. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  67535. if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  67536. sqlite3DbFreeNN(db, pDef);
  67537. }
  67538. }
  67539. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  67540. /*
  67541. ** Delete a P4 value if necessary.
  67542. */
  67543. static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  67544. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  67545. sqlite3DbFreeNN(db, p);
  67546. }
  67547. static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
  67548. freeEphemeralFunction(db, p->pFunc);
  67549. sqlite3DbFreeNN(db, p);
  67550. }
  67551. static void freeP4(sqlite3 *db, int p4type, void *p4){
  67552. assert( db );
  67553. switch( p4type ){
  67554. case P4_FUNCCTX: {
  67555. freeP4FuncCtx(db, (sqlite3_context*)p4);
  67556. break;
  67557. }
  67558. case P4_REAL:
  67559. case P4_INT64:
  67560. case P4_DYNAMIC:
  67561. case P4_INTARRAY: {
  67562. sqlite3DbFree(db, p4);
  67563. break;
  67564. }
  67565. case P4_KEYINFO: {
  67566. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  67567. break;
  67568. }
  67569. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  67570. case P4_EXPR: {
  67571. sqlite3ExprDelete(db, (Expr*)p4);
  67572. break;
  67573. }
  67574. #endif
  67575. case P4_FUNCDEF: {
  67576. freeEphemeralFunction(db, (FuncDef*)p4);
  67577. break;
  67578. }
  67579. case P4_MEM: {
  67580. if( db->pnBytesFreed==0 ){
  67581. sqlite3ValueFree((sqlite3_value*)p4);
  67582. }else{
  67583. freeP4Mem(db, (Mem*)p4);
  67584. }
  67585. break;
  67586. }
  67587. case P4_VTAB : {
  67588. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  67589. break;
  67590. }
  67591. }
  67592. }
  67593. /*
  67594. ** Free the space allocated for aOp and any p4 values allocated for the
  67595. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  67596. ** nOp entries.
  67597. */
  67598. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  67599. if( aOp ){
  67600. Op *pOp;
  67601. for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
  67602. if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
  67603. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  67604. sqlite3DbFree(db, pOp->zComment);
  67605. #endif
  67606. }
  67607. sqlite3DbFreeNN(db, aOp);
  67608. }
  67609. }
  67610. /*
  67611. ** Link the SubProgram object passed as the second argument into the linked
  67612. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  67613. ** objects when the VM is no longer required.
  67614. */
  67615. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  67616. p->pNext = pVdbe->pProgram;
  67617. pVdbe->pProgram = p;
  67618. }
  67619. /*
  67620. ** Change the opcode at addr into OP_Noop
  67621. */
  67622. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  67623. VdbeOp *pOp;
  67624. if( p->db->mallocFailed ) return 0;
  67625. assert( addr>=0 && addr<p->nOp );
  67626. pOp = &p->aOp[addr];
  67627. freeP4(p->db, pOp->p4type, pOp->p4.p);
  67628. pOp->p4type = P4_NOTUSED;
  67629. pOp->p4.z = 0;
  67630. pOp->opcode = OP_Noop;
  67631. return 1;
  67632. }
  67633. /*
  67634. ** If the last opcode is "op" and it is not a jump destination,
  67635. ** then remove it. Return true if and only if an opcode was removed.
  67636. */
  67637. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  67638. if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
  67639. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  67640. }else{
  67641. return 0;
  67642. }
  67643. }
  67644. /*
  67645. ** Change the value of the P4 operand for a specific instruction.
  67646. ** This routine is useful when a large program is loaded from a
  67647. ** static array using sqlite3VdbeAddOpList but we want to make a
  67648. ** few minor changes to the program.
  67649. **
  67650. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  67651. ** the string is made into memory obtained from sqlite3_malloc().
  67652. ** A value of n==0 means copy bytes of zP4 up to and including the
  67653. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  67654. **
  67655. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  67656. ** to a string or structure that is guaranteed to exist for the lifetime of
  67657. ** the Vdbe. In these cases we can just copy the pointer.
  67658. **
  67659. ** If addr<0 then change P4 on the most recently inserted instruction.
  67660. */
  67661. static void SQLITE_NOINLINE vdbeChangeP4Full(
  67662. Vdbe *p,
  67663. Op *pOp,
  67664. const char *zP4,
  67665. int n
  67666. ){
  67667. if( pOp->p4type ){
  67668. freeP4(p->db, pOp->p4type, pOp->p4.p);
  67669. pOp->p4type = 0;
  67670. pOp->p4.p = 0;
  67671. }
  67672. if( n<0 ){
  67673. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  67674. }else{
  67675. if( n==0 ) n = sqlite3Strlen30(zP4);
  67676. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  67677. pOp->p4type = P4_DYNAMIC;
  67678. }
  67679. }
  67680. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  67681. Op *pOp;
  67682. sqlite3 *db;
  67683. assert( p!=0 );
  67684. db = p->db;
  67685. assert( p->magic==VDBE_MAGIC_INIT );
  67686. assert( p->aOp!=0 || db->mallocFailed );
  67687. if( db->mallocFailed ){
  67688. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  67689. return;
  67690. }
  67691. assert( p->nOp>0 );
  67692. assert( addr<p->nOp );
  67693. if( addr<0 ){
  67694. addr = p->nOp - 1;
  67695. }
  67696. pOp = &p->aOp[addr];
  67697. if( n>=0 || pOp->p4type ){
  67698. vdbeChangeP4Full(p, pOp, zP4, n);
  67699. return;
  67700. }
  67701. if( n==P4_INT32 ){
  67702. /* Note: this cast is safe, because the origin data point was an int
  67703. ** that was cast to a (const char *). */
  67704. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  67705. pOp->p4type = P4_INT32;
  67706. }else if( zP4!=0 ){
  67707. assert( n<0 );
  67708. pOp->p4.p = (void*)zP4;
  67709. pOp->p4type = (signed char)n;
  67710. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  67711. }
  67712. }
  67713. /*
  67714. ** Change the P4 operand of the most recently coded instruction
  67715. ** to the value defined by the arguments. This is a high-speed
  67716. ** version of sqlite3VdbeChangeP4().
  67717. **
  67718. ** The P4 operand must not have been previously defined. And the new
  67719. ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
  67720. ** those cases.
  67721. */
  67722. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
  67723. VdbeOp *pOp;
  67724. assert( n!=P4_INT32 && n!=P4_VTAB );
  67725. assert( n<=0 );
  67726. if( p->db->mallocFailed ){
  67727. freeP4(p->db, n, pP4);
  67728. }else{
  67729. assert( pP4!=0 );
  67730. assert( p->nOp>0 );
  67731. pOp = &p->aOp[p->nOp-1];
  67732. assert( pOp->p4type==P4_NOTUSED );
  67733. pOp->p4type = n;
  67734. pOp->p4.p = pP4;
  67735. }
  67736. }
  67737. /*
  67738. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  67739. ** index given.
  67740. */
  67741. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  67742. Vdbe *v = pParse->pVdbe;
  67743. KeyInfo *pKeyInfo;
  67744. assert( v!=0 );
  67745. assert( pIdx!=0 );
  67746. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
  67747. if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  67748. }
  67749. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  67750. /*
  67751. ** Change the comment on the most recently coded instruction. Or
  67752. ** insert a No-op and add the comment to that new instruction. This
  67753. ** makes the code easier to read during debugging. None of this happens
  67754. ** in a production build.
  67755. */
  67756. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  67757. assert( p->nOp>0 || p->aOp==0 );
  67758. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  67759. if( p->nOp ){
  67760. assert( p->aOp );
  67761. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  67762. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  67763. }
  67764. }
  67765. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  67766. va_list ap;
  67767. if( p ){
  67768. va_start(ap, zFormat);
  67769. vdbeVComment(p, zFormat, ap);
  67770. va_end(ap);
  67771. }
  67772. }
  67773. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  67774. va_list ap;
  67775. if( p ){
  67776. sqlite3VdbeAddOp0(p, OP_Noop);
  67777. va_start(ap, zFormat);
  67778. vdbeVComment(p, zFormat, ap);
  67779. va_end(ap);
  67780. }
  67781. }
  67782. #endif /* NDEBUG */
  67783. #ifdef SQLITE_VDBE_COVERAGE
  67784. /*
  67785. ** Set the value if the iSrcLine field for the previously coded instruction.
  67786. */
  67787. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  67788. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  67789. }
  67790. #endif /* SQLITE_VDBE_COVERAGE */
  67791. /*
  67792. ** Return the opcode for a given address. If the address is -1, then
  67793. ** return the most recently inserted opcode.
  67794. **
  67795. ** If a memory allocation error has occurred prior to the calling of this
  67796. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  67797. ** is readable but not writable, though it is cast to a writable value.
  67798. ** The return of a dummy opcode allows the call to continue functioning
  67799. ** after an OOM fault without having to check to see if the return from
  67800. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  67801. ** dummy will never be written to. This is verified by code inspection and
  67802. ** by running with Valgrind.
  67803. */
  67804. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  67805. /* C89 specifies that the constant "dummy" will be initialized to all
  67806. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  67807. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  67808. assert( p->magic==VDBE_MAGIC_INIT );
  67809. if( addr<0 ){
  67810. addr = p->nOp - 1;
  67811. }
  67812. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  67813. if( p->db->mallocFailed ){
  67814. return (VdbeOp*)&dummy;
  67815. }else{
  67816. return &p->aOp[addr];
  67817. }
  67818. }
  67819. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  67820. /*
  67821. ** Return an integer value for one of the parameters to the opcode pOp
  67822. ** determined by character c.
  67823. */
  67824. static int translateP(char c, const Op *pOp){
  67825. if( c=='1' ) return pOp->p1;
  67826. if( c=='2' ) return pOp->p2;
  67827. if( c=='3' ) return pOp->p3;
  67828. if( c=='4' ) return pOp->p4.i;
  67829. return pOp->p5;
  67830. }
  67831. /*
  67832. ** Compute a string for the "comment" field of a VDBE opcode listing.
  67833. **
  67834. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  67835. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  67836. ** absence of other comments, this synopsis becomes the comment on the opcode.
  67837. ** Some translation occurs:
  67838. **
  67839. ** "PX" -> "r[X]"
  67840. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  67841. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  67842. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  67843. */
  67844. static int displayComment(
  67845. const Op *pOp, /* The opcode to be commented */
  67846. const char *zP4, /* Previously obtained value for P4 */
  67847. char *zTemp, /* Write result here */
  67848. int nTemp /* Space available in zTemp[] */
  67849. ){
  67850. const char *zOpName;
  67851. const char *zSynopsis;
  67852. int nOpName;
  67853. int ii, jj;
  67854. char zAlt[50];
  67855. zOpName = sqlite3OpcodeName(pOp->opcode);
  67856. nOpName = sqlite3Strlen30(zOpName);
  67857. if( zOpName[nOpName+1] ){
  67858. int seenCom = 0;
  67859. char c;
  67860. zSynopsis = zOpName += nOpName + 1;
  67861. if( strncmp(zSynopsis,"IF ",3)==0 ){
  67862. if( pOp->p5 & SQLITE_STOREP2 ){
  67863. sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
  67864. }else{
  67865. sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
  67866. }
  67867. zSynopsis = zAlt;
  67868. }
  67869. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  67870. if( c=='P' ){
  67871. c = zSynopsis[++ii];
  67872. if( c=='4' ){
  67873. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  67874. }else if( c=='X' ){
  67875. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  67876. seenCom = 1;
  67877. }else{
  67878. int v1 = translateP(c, pOp);
  67879. int v2;
  67880. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  67881. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  67882. ii += 3;
  67883. jj += sqlite3Strlen30(zTemp+jj);
  67884. v2 = translateP(zSynopsis[ii], pOp);
  67885. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  67886. ii += 2;
  67887. v2++;
  67888. }
  67889. if( v2>1 ){
  67890. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  67891. }
  67892. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  67893. ii += 4;
  67894. }
  67895. }
  67896. jj += sqlite3Strlen30(zTemp+jj);
  67897. }else{
  67898. zTemp[jj++] = c;
  67899. }
  67900. }
  67901. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  67902. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  67903. jj += sqlite3Strlen30(zTemp+jj);
  67904. }
  67905. if( jj<nTemp ) zTemp[jj] = 0;
  67906. }else if( pOp->zComment ){
  67907. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  67908. jj = sqlite3Strlen30(zTemp);
  67909. }else{
  67910. zTemp[0] = 0;
  67911. jj = 0;
  67912. }
  67913. return jj;
  67914. }
  67915. #endif /* SQLITE_DEBUG */
  67916. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  67917. /*
  67918. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  67919. ** that can be displayed in the P4 column of EXPLAIN output.
  67920. */
  67921. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  67922. const char *zOp = 0;
  67923. switch( pExpr->op ){
  67924. case TK_STRING:
  67925. sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
  67926. break;
  67927. case TK_INTEGER:
  67928. sqlite3XPrintf(p, "%d", pExpr->u.iValue);
  67929. break;
  67930. case TK_NULL:
  67931. sqlite3XPrintf(p, "NULL");
  67932. break;
  67933. case TK_REGISTER: {
  67934. sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
  67935. break;
  67936. }
  67937. case TK_COLUMN: {
  67938. if( pExpr->iColumn<0 ){
  67939. sqlite3XPrintf(p, "rowid");
  67940. }else{
  67941. sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
  67942. }
  67943. break;
  67944. }
  67945. case TK_LT: zOp = "LT"; break;
  67946. case TK_LE: zOp = "LE"; break;
  67947. case TK_GT: zOp = "GT"; break;
  67948. case TK_GE: zOp = "GE"; break;
  67949. case TK_NE: zOp = "NE"; break;
  67950. case TK_EQ: zOp = "EQ"; break;
  67951. case TK_IS: zOp = "IS"; break;
  67952. case TK_ISNOT: zOp = "ISNOT"; break;
  67953. case TK_AND: zOp = "AND"; break;
  67954. case TK_OR: zOp = "OR"; break;
  67955. case TK_PLUS: zOp = "ADD"; break;
  67956. case TK_STAR: zOp = "MUL"; break;
  67957. case TK_MINUS: zOp = "SUB"; break;
  67958. case TK_REM: zOp = "REM"; break;
  67959. case TK_BITAND: zOp = "BITAND"; break;
  67960. case TK_BITOR: zOp = "BITOR"; break;
  67961. case TK_SLASH: zOp = "DIV"; break;
  67962. case TK_LSHIFT: zOp = "LSHIFT"; break;
  67963. case TK_RSHIFT: zOp = "RSHIFT"; break;
  67964. case TK_CONCAT: zOp = "CONCAT"; break;
  67965. case TK_UMINUS: zOp = "MINUS"; break;
  67966. case TK_UPLUS: zOp = "PLUS"; break;
  67967. case TK_BITNOT: zOp = "BITNOT"; break;
  67968. case TK_NOT: zOp = "NOT"; break;
  67969. case TK_ISNULL: zOp = "ISNULL"; break;
  67970. case TK_NOTNULL: zOp = "NOTNULL"; break;
  67971. default:
  67972. sqlite3XPrintf(p, "%s", "expr");
  67973. break;
  67974. }
  67975. if( zOp ){
  67976. sqlite3XPrintf(p, "%s(", zOp);
  67977. displayP4Expr(p, pExpr->pLeft);
  67978. if( pExpr->pRight ){
  67979. sqlite3StrAccumAppend(p, ",", 1);
  67980. displayP4Expr(p, pExpr->pRight);
  67981. }
  67982. sqlite3StrAccumAppend(p, ")", 1);
  67983. }
  67984. }
  67985. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  67986. #if VDBE_DISPLAY_P4
  67987. /*
  67988. ** Compute a string that describes the P4 parameter for an opcode.
  67989. ** Use zTemp for any required temporary buffer space.
  67990. */
  67991. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  67992. char *zP4 = zTemp;
  67993. StrAccum x;
  67994. assert( nTemp>=20 );
  67995. sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
  67996. switch( pOp->p4type ){
  67997. case P4_KEYINFO: {
  67998. int j;
  67999. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  68000. assert( pKeyInfo->aSortOrder!=0 );
  68001. sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
  68002. for(j=0; j<pKeyInfo->nField; j++){
  68003. CollSeq *pColl = pKeyInfo->aColl[j];
  68004. const char *zColl = pColl ? pColl->zName : "";
  68005. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  68006. sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
  68007. }
  68008. sqlite3StrAccumAppend(&x, ")", 1);
  68009. break;
  68010. }
  68011. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  68012. case P4_EXPR: {
  68013. displayP4Expr(&x, pOp->p4.pExpr);
  68014. break;
  68015. }
  68016. #endif
  68017. case P4_COLLSEQ: {
  68018. CollSeq *pColl = pOp->p4.pColl;
  68019. sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
  68020. break;
  68021. }
  68022. case P4_FUNCDEF: {
  68023. FuncDef *pDef = pOp->p4.pFunc;
  68024. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  68025. break;
  68026. }
  68027. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  68028. case P4_FUNCCTX: {
  68029. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  68030. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  68031. break;
  68032. }
  68033. #endif
  68034. case P4_INT64: {
  68035. sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
  68036. break;
  68037. }
  68038. case P4_INT32: {
  68039. sqlite3XPrintf(&x, "%d", pOp->p4.i);
  68040. break;
  68041. }
  68042. case P4_REAL: {
  68043. sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
  68044. break;
  68045. }
  68046. case P4_MEM: {
  68047. Mem *pMem = pOp->p4.pMem;
  68048. if( pMem->flags & MEM_Str ){
  68049. zP4 = pMem->z;
  68050. }else if( pMem->flags & MEM_Int ){
  68051. sqlite3XPrintf(&x, "%lld", pMem->u.i);
  68052. }else if( pMem->flags & MEM_Real ){
  68053. sqlite3XPrintf(&x, "%.16g", pMem->u.r);
  68054. }else if( pMem->flags & MEM_Null ){
  68055. zP4 = "NULL";
  68056. }else{
  68057. assert( pMem->flags & MEM_Blob );
  68058. zP4 = "(blob)";
  68059. }
  68060. break;
  68061. }
  68062. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68063. case P4_VTAB: {
  68064. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  68065. sqlite3XPrintf(&x, "vtab:%p", pVtab);
  68066. break;
  68067. }
  68068. #endif
  68069. case P4_INTARRAY: {
  68070. int i;
  68071. int *ai = pOp->p4.ai;
  68072. int n = ai[0]; /* The first element of an INTARRAY is always the
  68073. ** count of the number of elements to follow */
  68074. for(i=1; i<n; i++){
  68075. sqlite3XPrintf(&x, ",%d", ai[i]);
  68076. }
  68077. zTemp[0] = '[';
  68078. sqlite3StrAccumAppend(&x, "]", 1);
  68079. break;
  68080. }
  68081. case P4_SUBPROGRAM: {
  68082. sqlite3XPrintf(&x, "program");
  68083. break;
  68084. }
  68085. case P4_ADVANCE: {
  68086. zTemp[0] = 0;
  68087. break;
  68088. }
  68089. case P4_TABLE: {
  68090. sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
  68091. break;
  68092. }
  68093. default: {
  68094. zP4 = pOp->p4.z;
  68095. if( zP4==0 ){
  68096. zP4 = zTemp;
  68097. zTemp[0] = 0;
  68098. }
  68099. }
  68100. }
  68101. sqlite3StrAccumFinish(&x);
  68102. assert( zP4!=0 );
  68103. return zP4;
  68104. }
  68105. #endif /* VDBE_DISPLAY_P4 */
  68106. /*
  68107. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  68108. **
  68109. ** The prepared statements need to know in advance the complete set of
  68110. ** attached databases that will be use. A mask of these databases
  68111. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  68112. ** p->btreeMask of databases that will require a lock.
  68113. */
  68114. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  68115. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  68116. assert( i<(int)sizeof(p->btreeMask)*8 );
  68117. DbMaskSet(p->btreeMask, i);
  68118. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  68119. DbMaskSet(p->lockMask, i);
  68120. }
  68121. }
  68122. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  68123. /*
  68124. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  68125. ** this routine obtains the mutex associated with each BtShared structure
  68126. ** that may be accessed by the VM passed as an argument. In doing so it also
  68127. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  68128. ** that the correct busy-handler callback is invoked if required.
  68129. **
  68130. ** If SQLite is not threadsafe but does support shared-cache mode, then
  68131. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  68132. ** of all of BtShared structures accessible via the database handle
  68133. ** associated with the VM.
  68134. **
  68135. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  68136. ** function is a no-op.
  68137. **
  68138. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  68139. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  68140. ** corresponding to btrees that use shared cache. Then the runtime of
  68141. ** this routine is N*N. But as N is rarely more than 1, this should not
  68142. ** be a problem.
  68143. */
  68144. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  68145. int i;
  68146. sqlite3 *db;
  68147. Db *aDb;
  68148. int nDb;
  68149. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  68150. db = p->db;
  68151. aDb = db->aDb;
  68152. nDb = db->nDb;
  68153. for(i=0; i<nDb; i++){
  68154. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  68155. sqlite3BtreeEnter(aDb[i].pBt);
  68156. }
  68157. }
  68158. }
  68159. #endif
  68160. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  68161. /*
  68162. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  68163. */
  68164. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  68165. int i;
  68166. sqlite3 *db;
  68167. Db *aDb;
  68168. int nDb;
  68169. db = p->db;
  68170. aDb = db->aDb;
  68171. nDb = db->nDb;
  68172. for(i=0; i<nDb; i++){
  68173. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  68174. sqlite3BtreeLeave(aDb[i].pBt);
  68175. }
  68176. }
  68177. }
  68178. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  68179. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  68180. vdbeLeave(p);
  68181. }
  68182. #endif
  68183. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  68184. /*
  68185. ** Print a single opcode. This routine is used for debugging only.
  68186. */
  68187. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  68188. char *zP4;
  68189. char zPtr[50];
  68190. char zCom[100];
  68191. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  68192. if( pOut==0 ) pOut = stdout;
  68193. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  68194. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  68195. displayComment(pOp, zP4, zCom, sizeof(zCom));
  68196. #else
  68197. zCom[0] = 0;
  68198. #endif
  68199. /* NB: The sqlite3OpcodeName() function is implemented by code created
  68200. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  68201. ** information from the vdbe.c source text */
  68202. fprintf(pOut, zFormat1, pc,
  68203. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  68204. zCom
  68205. );
  68206. fflush(pOut);
  68207. }
  68208. #endif
  68209. /*
  68210. ** Initialize an array of N Mem element.
  68211. */
  68212. static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
  68213. while( (N--)>0 ){
  68214. p->db = db;
  68215. p->flags = flags;
  68216. p->szMalloc = 0;
  68217. #ifdef SQLITE_DEBUG
  68218. p->pScopyFrom = 0;
  68219. #endif
  68220. p++;
  68221. }
  68222. }
  68223. /*
  68224. ** Release an array of N Mem elements
  68225. */
  68226. static void releaseMemArray(Mem *p, int N){
  68227. if( p && N ){
  68228. Mem *pEnd = &p[N];
  68229. sqlite3 *db = p->db;
  68230. if( db->pnBytesFreed ){
  68231. do{
  68232. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  68233. }while( (++p)<pEnd );
  68234. return;
  68235. }
  68236. do{
  68237. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  68238. assert( sqlite3VdbeCheckMemInvariants(p) );
  68239. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  68240. ** that takes advantage of the fact that the memory cell value is
  68241. ** being set to NULL after releasing any dynamic resources.
  68242. **
  68243. ** The justification for duplicating code is that according to
  68244. ** callgrind, this causes a certain test case to hit the CPU 4.7
  68245. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  68246. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  68247. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  68248. ** with no indexes using a single prepared INSERT statement, bind()
  68249. ** and reset(). Inserts are grouped into a transaction.
  68250. */
  68251. testcase( p->flags & MEM_Agg );
  68252. testcase( p->flags & MEM_Dyn );
  68253. testcase( p->flags & MEM_Frame );
  68254. testcase( p->flags & MEM_RowSet );
  68255. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  68256. sqlite3VdbeMemRelease(p);
  68257. }else if( p->szMalloc ){
  68258. sqlite3DbFreeNN(db, p->zMalloc);
  68259. p->szMalloc = 0;
  68260. }
  68261. p->flags = MEM_Undefined;
  68262. }while( (++p)<pEnd );
  68263. }
  68264. }
  68265. /*
  68266. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  68267. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  68268. */
  68269. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  68270. int i;
  68271. Mem *aMem = VdbeFrameMem(p);
  68272. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  68273. for(i=0; i<p->nChildCsr; i++){
  68274. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  68275. }
  68276. releaseMemArray(aMem, p->nChildMem);
  68277. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  68278. sqlite3DbFree(p->v->db, p);
  68279. }
  68280. #ifndef SQLITE_OMIT_EXPLAIN
  68281. /*
  68282. ** Give a listing of the program in the virtual machine.
  68283. **
  68284. ** The interface is the same as sqlite3VdbeExec(). But instead of
  68285. ** running the code, it invokes the callback once for each instruction.
  68286. ** This feature is used to implement "EXPLAIN".
  68287. **
  68288. ** When p->explain==1, each instruction is listed. When
  68289. ** p->explain==2, only OP_Explain instructions are listed and these
  68290. ** are shown in a different format. p->explain==2 is used to implement
  68291. ** EXPLAIN QUERY PLAN.
  68292. **
  68293. ** When p->explain==1, first the main program is listed, then each of
  68294. ** the trigger subprograms are listed one by one.
  68295. */
  68296. SQLITE_PRIVATE int sqlite3VdbeList(
  68297. Vdbe *p /* The VDBE */
  68298. ){
  68299. int nRow; /* Stop when row count reaches this */
  68300. int nSub = 0; /* Number of sub-vdbes seen so far */
  68301. SubProgram **apSub = 0; /* Array of sub-vdbes */
  68302. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  68303. sqlite3 *db = p->db; /* The database connection */
  68304. int i; /* Loop counter */
  68305. int rc = SQLITE_OK; /* Return code */
  68306. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  68307. assert( p->explain );
  68308. assert( p->magic==VDBE_MAGIC_RUN );
  68309. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  68310. /* Even though this opcode does not use dynamic strings for
  68311. ** the result, result columns may become dynamic if the user calls
  68312. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  68313. */
  68314. releaseMemArray(pMem, 8);
  68315. p->pResultSet = 0;
  68316. if( p->rc==SQLITE_NOMEM_BKPT ){
  68317. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  68318. ** sqlite3_column_text16() failed. */
  68319. sqlite3OomFault(db);
  68320. return SQLITE_ERROR;
  68321. }
  68322. /* When the number of output rows reaches nRow, that means the
  68323. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  68324. ** nRow is the sum of the number of rows in the main program, plus
  68325. ** the sum of the number of rows in all trigger subprograms encountered
  68326. ** so far. The nRow value will increase as new trigger subprograms are
  68327. ** encountered, but p->pc will eventually catch up to nRow.
  68328. */
  68329. nRow = p->nOp;
  68330. if( p->explain==1 ){
  68331. /* The first 8 memory cells are used for the result set. So we will
  68332. ** commandeer the 9th cell to use as storage for an array of pointers
  68333. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  68334. ** cells. */
  68335. assert( p->nMem>9 );
  68336. pSub = &p->aMem[9];
  68337. if( pSub->flags&MEM_Blob ){
  68338. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  68339. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  68340. nSub = pSub->n/sizeof(Vdbe*);
  68341. apSub = (SubProgram **)pSub->z;
  68342. }
  68343. for(i=0; i<nSub; i++){
  68344. nRow += apSub[i]->nOp;
  68345. }
  68346. }
  68347. do{
  68348. i = p->pc++;
  68349. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  68350. if( i>=nRow ){
  68351. p->rc = SQLITE_OK;
  68352. rc = SQLITE_DONE;
  68353. }else if( db->u1.isInterrupted ){
  68354. p->rc = SQLITE_INTERRUPT;
  68355. rc = SQLITE_ERROR;
  68356. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  68357. }else{
  68358. char *zP4;
  68359. Op *pOp;
  68360. if( i<p->nOp ){
  68361. /* The output line number is small enough that we are still in the
  68362. ** main program. */
  68363. pOp = &p->aOp[i];
  68364. }else{
  68365. /* We are currently listing subprograms. Figure out which one and
  68366. ** pick up the appropriate opcode. */
  68367. int j;
  68368. i -= p->nOp;
  68369. for(j=0; i>=apSub[j]->nOp; j++){
  68370. i -= apSub[j]->nOp;
  68371. }
  68372. pOp = &apSub[j]->aOp[i];
  68373. }
  68374. if( p->explain==1 ){
  68375. pMem->flags = MEM_Int;
  68376. pMem->u.i = i; /* Program counter */
  68377. pMem++;
  68378. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  68379. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  68380. assert( pMem->z!=0 );
  68381. pMem->n = sqlite3Strlen30(pMem->z);
  68382. pMem->enc = SQLITE_UTF8;
  68383. pMem++;
  68384. /* When an OP_Program opcode is encounter (the only opcode that has
  68385. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  68386. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  68387. ** has not already been seen.
  68388. */
  68389. if( pOp->p4type==P4_SUBPROGRAM ){
  68390. int nByte = (nSub+1)*sizeof(SubProgram*);
  68391. int j;
  68392. for(j=0; j<nSub; j++){
  68393. if( apSub[j]==pOp->p4.pProgram ) break;
  68394. }
  68395. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  68396. apSub = (SubProgram **)pSub->z;
  68397. apSub[nSub++] = pOp->p4.pProgram;
  68398. pSub->flags |= MEM_Blob;
  68399. pSub->n = nSub*sizeof(SubProgram*);
  68400. }
  68401. }
  68402. }
  68403. pMem->flags = MEM_Int;
  68404. pMem->u.i = pOp->p1; /* P1 */
  68405. pMem++;
  68406. pMem->flags = MEM_Int;
  68407. pMem->u.i = pOp->p2; /* P2 */
  68408. pMem++;
  68409. pMem->flags = MEM_Int;
  68410. pMem->u.i = pOp->p3; /* P3 */
  68411. pMem++;
  68412. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  68413. assert( p->db->mallocFailed );
  68414. return SQLITE_ERROR;
  68415. }
  68416. pMem->flags = MEM_Str|MEM_Term;
  68417. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  68418. if( zP4!=pMem->z ){
  68419. pMem->n = 0;
  68420. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  68421. }else{
  68422. assert( pMem->z!=0 );
  68423. pMem->n = sqlite3Strlen30(pMem->z);
  68424. pMem->enc = SQLITE_UTF8;
  68425. }
  68426. pMem++;
  68427. if( p->explain==1 ){
  68428. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  68429. assert( p->db->mallocFailed );
  68430. return SQLITE_ERROR;
  68431. }
  68432. pMem->flags = MEM_Str|MEM_Term;
  68433. pMem->n = 2;
  68434. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  68435. pMem->enc = SQLITE_UTF8;
  68436. pMem++;
  68437. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  68438. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  68439. assert( p->db->mallocFailed );
  68440. return SQLITE_ERROR;
  68441. }
  68442. pMem->flags = MEM_Str|MEM_Term;
  68443. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  68444. pMem->enc = SQLITE_UTF8;
  68445. #else
  68446. pMem->flags = MEM_Null; /* Comment */
  68447. #endif
  68448. }
  68449. p->nResColumn = 8 - 4*(p->explain-1);
  68450. p->pResultSet = &p->aMem[1];
  68451. p->rc = SQLITE_OK;
  68452. rc = SQLITE_ROW;
  68453. }
  68454. return rc;
  68455. }
  68456. #endif /* SQLITE_OMIT_EXPLAIN */
  68457. #ifdef SQLITE_DEBUG
  68458. /*
  68459. ** Print the SQL that was used to generate a VDBE program.
  68460. */
  68461. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  68462. const char *z = 0;
  68463. if( p->zSql ){
  68464. z = p->zSql;
  68465. }else if( p->nOp>=1 ){
  68466. const VdbeOp *pOp = &p->aOp[0];
  68467. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  68468. z = pOp->p4.z;
  68469. while( sqlite3Isspace(*z) ) z++;
  68470. }
  68471. }
  68472. if( z ) printf("SQL: [%s]\n", z);
  68473. }
  68474. #endif
  68475. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  68476. /*
  68477. ** Print an IOTRACE message showing SQL content.
  68478. */
  68479. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  68480. int nOp = p->nOp;
  68481. VdbeOp *pOp;
  68482. if( sqlite3IoTrace==0 ) return;
  68483. if( nOp<1 ) return;
  68484. pOp = &p->aOp[0];
  68485. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  68486. int i, j;
  68487. char z[1000];
  68488. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  68489. for(i=0; sqlite3Isspace(z[i]); i++){}
  68490. for(j=0; z[i]; i++){
  68491. if( sqlite3Isspace(z[i]) ){
  68492. if( z[i-1]!=' ' ){
  68493. z[j++] = ' ';
  68494. }
  68495. }else{
  68496. z[j++] = z[i];
  68497. }
  68498. }
  68499. z[j] = 0;
  68500. sqlite3IoTrace("SQL %s\n", z);
  68501. }
  68502. }
  68503. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  68504. /* An instance of this object describes bulk memory available for use
  68505. ** by subcomponents of a prepared statement. Space is allocated out
  68506. ** of a ReusableSpace object by the allocSpace() routine below.
  68507. */
  68508. struct ReusableSpace {
  68509. u8 *pSpace; /* Available memory */
  68510. int nFree; /* Bytes of available memory */
  68511. int nNeeded; /* Total bytes that could not be allocated */
  68512. };
  68513. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  68514. ** from the ReusableSpace object. Return a pointer to the allocated
  68515. ** memory on success. If insufficient memory is available in the
  68516. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  68517. ** value by the amount needed and return NULL.
  68518. **
  68519. ** If pBuf is not initially NULL, that means that the memory has already
  68520. ** been allocated by a prior call to this routine, so just return a copy
  68521. ** of pBuf and leave ReusableSpace unchanged.
  68522. **
  68523. ** This allocator is employed to repurpose unused slots at the end of the
  68524. ** opcode array of prepared state for other memory needs of the prepared
  68525. ** statement.
  68526. */
  68527. static void *allocSpace(
  68528. struct ReusableSpace *p, /* Bulk memory available for allocation */
  68529. void *pBuf, /* Pointer to a prior allocation */
  68530. int nByte /* Bytes of memory needed */
  68531. ){
  68532. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  68533. if( pBuf==0 ){
  68534. nByte = ROUND8(nByte);
  68535. if( nByte <= p->nFree ){
  68536. p->nFree -= nByte;
  68537. pBuf = &p->pSpace[p->nFree];
  68538. }else{
  68539. p->nNeeded += nByte;
  68540. }
  68541. }
  68542. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  68543. return pBuf;
  68544. }
  68545. /*
  68546. ** Rewind the VDBE back to the beginning in preparation for
  68547. ** running it.
  68548. */
  68549. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  68550. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  68551. int i;
  68552. #endif
  68553. assert( p!=0 );
  68554. assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
  68555. /* There should be at least one opcode.
  68556. */
  68557. assert( p->nOp>0 );
  68558. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  68559. p->magic = VDBE_MAGIC_RUN;
  68560. #ifdef SQLITE_DEBUG
  68561. for(i=0; i<p->nMem; i++){
  68562. assert( p->aMem[i].db==p->db );
  68563. }
  68564. #endif
  68565. p->pc = -1;
  68566. p->rc = SQLITE_OK;
  68567. p->errorAction = OE_Abort;
  68568. p->nChange = 0;
  68569. p->cacheCtr = 1;
  68570. p->minWriteFileFormat = 255;
  68571. p->iStatement = 0;
  68572. p->nFkConstraint = 0;
  68573. #ifdef VDBE_PROFILE
  68574. for(i=0; i<p->nOp; i++){
  68575. p->aOp[i].cnt = 0;
  68576. p->aOp[i].cycles = 0;
  68577. }
  68578. #endif
  68579. }
  68580. /*
  68581. ** Prepare a virtual machine for execution for the first time after
  68582. ** creating the virtual machine. This involves things such
  68583. ** as allocating registers and initializing the program counter.
  68584. ** After the VDBE has be prepped, it can be executed by one or more
  68585. ** calls to sqlite3VdbeExec().
  68586. **
  68587. ** This function may be called exactly once on each virtual machine.
  68588. ** After this routine is called the VM has been "packaged" and is ready
  68589. ** to run. After this routine is called, further calls to
  68590. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  68591. ** the Vdbe from the Parse object that helped generate it so that the
  68592. ** the Vdbe becomes an independent entity and the Parse object can be
  68593. ** destroyed.
  68594. **
  68595. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  68596. ** to its initial state after it has been run.
  68597. */
  68598. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  68599. Vdbe *p, /* The VDBE */
  68600. Parse *pParse /* Parsing context */
  68601. ){
  68602. sqlite3 *db; /* The database connection */
  68603. int nVar; /* Number of parameters */
  68604. int nMem; /* Number of VM memory registers */
  68605. int nCursor; /* Number of cursors required */
  68606. int nArg; /* Number of arguments in subprograms */
  68607. int n; /* Loop counter */
  68608. struct ReusableSpace x; /* Reusable bulk memory */
  68609. assert( p!=0 );
  68610. assert( p->nOp>0 );
  68611. assert( pParse!=0 );
  68612. assert( p->magic==VDBE_MAGIC_INIT );
  68613. assert( pParse==p->pParse );
  68614. db = p->db;
  68615. assert( db->mallocFailed==0 );
  68616. nVar = pParse->nVar;
  68617. nMem = pParse->nMem;
  68618. nCursor = pParse->nTab;
  68619. nArg = pParse->nMaxArg;
  68620. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  68621. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  68622. ** space at the end of aMem[] for cursors 1 and greater.
  68623. ** See also: allocateCursor().
  68624. */
  68625. nMem += nCursor;
  68626. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  68627. /* Figure out how much reusable memory is available at the end of the
  68628. ** opcode array. This extra memory will be reallocated for other elements
  68629. ** of the prepared statement.
  68630. */
  68631. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  68632. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  68633. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  68634. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  68635. assert( x.nFree>=0 );
  68636. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  68637. resolveP2Values(p, &nArg);
  68638. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  68639. if( pParse->explain && nMem<10 ){
  68640. nMem = 10;
  68641. }
  68642. p->expired = 0;
  68643. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  68644. ** passes. On the first pass, we try to reuse unused memory at the
  68645. ** end of the opcode array. If we are unable to satisfy all memory
  68646. ** requirements by reusing the opcode array tail, then the second
  68647. ** pass will fill in the remainder using a fresh memory allocation.
  68648. **
  68649. ** This two-pass approach that reuses as much memory as possible from
  68650. ** the leftover memory at the end of the opcode array. This can significantly
  68651. ** reduce the amount of memory held by a prepared statement.
  68652. */
  68653. do {
  68654. x.nNeeded = 0;
  68655. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  68656. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  68657. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  68658. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  68659. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  68660. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  68661. #endif
  68662. if( x.nNeeded==0 ) break;
  68663. x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
  68664. x.nFree = x.nNeeded;
  68665. }while( !db->mallocFailed );
  68666. p->pVList = pParse->pVList;
  68667. pParse->pVList = 0;
  68668. p->explain = pParse->explain;
  68669. if( db->mallocFailed ){
  68670. p->nVar = 0;
  68671. p->nCursor = 0;
  68672. p->nMem = 0;
  68673. }else{
  68674. p->nCursor = nCursor;
  68675. p->nVar = (ynVar)nVar;
  68676. initMemArray(p->aVar, nVar, db, MEM_Null);
  68677. p->nMem = nMem;
  68678. initMemArray(p->aMem, nMem, db, MEM_Undefined);
  68679. memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
  68680. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  68681. memset(p->anExec, 0, p->nOp*sizeof(i64));
  68682. #endif
  68683. }
  68684. sqlite3VdbeRewind(p);
  68685. }
  68686. /*
  68687. ** Close a VDBE cursor and release all the resources that cursor
  68688. ** happens to hold.
  68689. */
  68690. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  68691. if( pCx==0 ){
  68692. return;
  68693. }
  68694. assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
  68695. switch( pCx->eCurType ){
  68696. case CURTYPE_SORTER: {
  68697. sqlite3VdbeSorterClose(p->db, pCx);
  68698. break;
  68699. }
  68700. case CURTYPE_BTREE: {
  68701. if( pCx->isEphemeral ){
  68702. if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
  68703. /* The pCx->pCursor will be close automatically, if it exists, by
  68704. ** the call above. */
  68705. }else{
  68706. assert( pCx->uc.pCursor!=0 );
  68707. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  68708. }
  68709. break;
  68710. }
  68711. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68712. case CURTYPE_VTAB: {
  68713. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  68714. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  68715. assert( pVCur->pVtab->nRef>0 );
  68716. pVCur->pVtab->nRef--;
  68717. pModule->xClose(pVCur);
  68718. break;
  68719. }
  68720. #endif
  68721. }
  68722. }
  68723. /*
  68724. ** Close all cursors in the current frame.
  68725. */
  68726. static void closeCursorsInFrame(Vdbe *p){
  68727. if( p->apCsr ){
  68728. int i;
  68729. for(i=0; i<p->nCursor; i++){
  68730. VdbeCursor *pC = p->apCsr[i];
  68731. if( pC ){
  68732. sqlite3VdbeFreeCursor(p, pC);
  68733. p->apCsr[i] = 0;
  68734. }
  68735. }
  68736. }
  68737. }
  68738. /*
  68739. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  68740. ** is used, for example, when a trigger sub-program is halted to restore
  68741. ** control to the main program.
  68742. */
  68743. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  68744. Vdbe *v = pFrame->v;
  68745. closeCursorsInFrame(v);
  68746. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  68747. v->anExec = pFrame->anExec;
  68748. #endif
  68749. v->aOp = pFrame->aOp;
  68750. v->nOp = pFrame->nOp;
  68751. v->aMem = pFrame->aMem;
  68752. v->nMem = pFrame->nMem;
  68753. v->apCsr = pFrame->apCsr;
  68754. v->nCursor = pFrame->nCursor;
  68755. v->db->lastRowid = pFrame->lastRowid;
  68756. v->nChange = pFrame->nChange;
  68757. v->db->nChange = pFrame->nDbChange;
  68758. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  68759. v->pAuxData = pFrame->pAuxData;
  68760. pFrame->pAuxData = 0;
  68761. return pFrame->pc;
  68762. }
  68763. /*
  68764. ** Close all cursors.
  68765. **
  68766. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  68767. ** cell array. This is necessary as the memory cell array may contain
  68768. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  68769. ** open cursors.
  68770. */
  68771. static void closeAllCursors(Vdbe *p){
  68772. if( p->pFrame ){
  68773. VdbeFrame *pFrame;
  68774. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  68775. sqlite3VdbeFrameRestore(pFrame);
  68776. p->pFrame = 0;
  68777. p->nFrame = 0;
  68778. }
  68779. assert( p->nFrame==0 );
  68780. closeCursorsInFrame(p);
  68781. if( p->aMem ){
  68782. releaseMemArray(p->aMem, p->nMem);
  68783. }
  68784. while( p->pDelFrame ){
  68785. VdbeFrame *pDel = p->pDelFrame;
  68786. p->pDelFrame = pDel->pParent;
  68787. sqlite3VdbeFrameDelete(pDel);
  68788. }
  68789. /* Delete any auxdata allocations made by the VM */
  68790. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  68791. assert( p->pAuxData==0 );
  68792. }
  68793. /*
  68794. ** Clean up the VM after a single run.
  68795. */
  68796. static void Cleanup(Vdbe *p){
  68797. sqlite3 *db = p->db;
  68798. #ifdef SQLITE_DEBUG
  68799. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  68800. ** Vdbe.aMem[] arrays have already been cleaned up. */
  68801. int i;
  68802. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  68803. if( p->aMem ){
  68804. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  68805. }
  68806. #endif
  68807. sqlite3DbFree(db, p->zErrMsg);
  68808. p->zErrMsg = 0;
  68809. p->pResultSet = 0;
  68810. }
  68811. /*
  68812. ** Set the number of result columns that will be returned by this SQL
  68813. ** statement. This is now set at compile time, rather than during
  68814. ** execution of the vdbe program so that sqlite3_column_count() can
  68815. ** be called on an SQL statement before sqlite3_step().
  68816. */
  68817. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  68818. Mem *pColName;
  68819. int n;
  68820. sqlite3 *db = p->db;
  68821. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  68822. sqlite3DbFree(db, p->aColName);
  68823. n = nResColumn*COLNAME_N;
  68824. p->nResColumn = (u16)nResColumn;
  68825. p->aColName = pColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
  68826. if( p->aColName==0 ) return;
  68827. initMemArray(p->aColName, n, p->db, MEM_Null);
  68828. }
  68829. /*
  68830. ** Set the name of the idx'th column to be returned by the SQL statement.
  68831. ** zName must be a pointer to a nul terminated string.
  68832. **
  68833. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  68834. **
  68835. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  68836. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  68837. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  68838. */
  68839. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  68840. Vdbe *p, /* Vdbe being configured */
  68841. int idx, /* Index of column zName applies to */
  68842. int var, /* One of the COLNAME_* constants */
  68843. const char *zName, /* Pointer to buffer containing name */
  68844. void (*xDel)(void*) /* Memory management strategy for zName */
  68845. ){
  68846. int rc;
  68847. Mem *pColName;
  68848. assert( idx<p->nResColumn );
  68849. assert( var<COLNAME_N );
  68850. if( p->db->mallocFailed ){
  68851. assert( !zName || xDel!=SQLITE_DYNAMIC );
  68852. return SQLITE_NOMEM_BKPT;
  68853. }
  68854. assert( p->aColName!=0 );
  68855. pColName = &(p->aColName[idx+var*p->nResColumn]);
  68856. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  68857. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  68858. return rc;
  68859. }
  68860. /*
  68861. ** A read or write transaction may or may not be active on database handle
  68862. ** db. If a transaction is active, commit it. If there is a
  68863. ** write-transaction spanning more than one database file, this routine
  68864. ** takes care of the master journal trickery.
  68865. */
  68866. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  68867. int i;
  68868. int nTrans = 0; /* Number of databases with an active write-transaction
  68869. ** that are candidates for a two-phase commit using a
  68870. ** master-journal */
  68871. int rc = SQLITE_OK;
  68872. int needXcommit = 0;
  68873. #ifdef SQLITE_OMIT_VIRTUALTABLE
  68874. /* With this option, sqlite3VtabSync() is defined to be simply
  68875. ** SQLITE_OK so p is not used.
  68876. */
  68877. UNUSED_PARAMETER(p);
  68878. #endif
  68879. /* Before doing anything else, call the xSync() callback for any
  68880. ** virtual module tables written in this transaction. This has to
  68881. ** be done before determining whether a master journal file is
  68882. ** required, as an xSync() callback may add an attached database
  68883. ** to the transaction.
  68884. */
  68885. rc = sqlite3VtabSync(db, p);
  68886. /* This loop determines (a) if the commit hook should be invoked and
  68887. ** (b) how many database files have open write transactions, not
  68888. ** including the temp database. (b) is important because if more than
  68889. ** one database file has an open write transaction, a master journal
  68890. ** file is required for an atomic commit.
  68891. */
  68892. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  68893. Btree *pBt = db->aDb[i].pBt;
  68894. if( sqlite3BtreeIsInTrans(pBt) ){
  68895. /* Whether or not a database might need a master journal depends upon
  68896. ** its journal mode (among other things). This matrix determines which
  68897. ** journal modes use a master journal and which do not */
  68898. static const u8 aMJNeeded[] = {
  68899. /* DELETE */ 1,
  68900. /* PERSIST */ 1,
  68901. /* OFF */ 0,
  68902. /* TRUNCATE */ 1,
  68903. /* MEMORY */ 0,
  68904. /* WAL */ 0
  68905. };
  68906. Pager *pPager; /* Pager associated with pBt */
  68907. needXcommit = 1;
  68908. sqlite3BtreeEnter(pBt);
  68909. pPager = sqlite3BtreePager(pBt);
  68910. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  68911. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  68912. ){
  68913. assert( i!=1 );
  68914. nTrans++;
  68915. }
  68916. rc = sqlite3PagerExclusiveLock(pPager);
  68917. sqlite3BtreeLeave(pBt);
  68918. }
  68919. }
  68920. if( rc!=SQLITE_OK ){
  68921. return rc;
  68922. }
  68923. /* If there are any write-transactions at all, invoke the commit hook */
  68924. if( needXcommit && db->xCommitCallback ){
  68925. rc = db->xCommitCallback(db->pCommitArg);
  68926. if( rc ){
  68927. return SQLITE_CONSTRAINT_COMMITHOOK;
  68928. }
  68929. }
  68930. /* The simple case - no more than one database file (not counting the
  68931. ** TEMP database) has a transaction active. There is no need for the
  68932. ** master-journal.
  68933. **
  68934. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  68935. ** string, it means the main database is :memory: or a temp file. In
  68936. ** that case we do not support atomic multi-file commits, so use the
  68937. ** simple case then too.
  68938. */
  68939. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  68940. || nTrans<=1
  68941. ){
  68942. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  68943. Btree *pBt = db->aDb[i].pBt;
  68944. if( pBt ){
  68945. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  68946. }
  68947. }
  68948. /* Do the commit only if all databases successfully complete phase 1.
  68949. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  68950. ** IO error while deleting or truncating a journal file. It is unlikely,
  68951. ** but could happen. In this case abandon processing and return the error.
  68952. */
  68953. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  68954. Btree *pBt = db->aDb[i].pBt;
  68955. if( pBt ){
  68956. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  68957. }
  68958. }
  68959. if( rc==SQLITE_OK ){
  68960. sqlite3VtabCommit(db);
  68961. }
  68962. }
  68963. /* The complex case - There is a multi-file write-transaction active.
  68964. ** This requires a master journal file to ensure the transaction is
  68965. ** committed atomically.
  68966. */
  68967. #ifndef SQLITE_OMIT_DISKIO
  68968. else{
  68969. sqlite3_vfs *pVfs = db->pVfs;
  68970. char *zMaster = 0; /* File-name for the master journal */
  68971. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  68972. sqlite3_file *pMaster = 0;
  68973. i64 offset = 0;
  68974. int res;
  68975. int retryCount = 0;
  68976. int nMainFile;
  68977. /* Select a master journal file name */
  68978. nMainFile = sqlite3Strlen30(zMainFile);
  68979. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  68980. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  68981. do {
  68982. u32 iRandom;
  68983. if( retryCount ){
  68984. if( retryCount>100 ){
  68985. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  68986. sqlite3OsDelete(pVfs, zMaster, 0);
  68987. break;
  68988. }else if( retryCount==1 ){
  68989. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  68990. }
  68991. }
  68992. retryCount++;
  68993. sqlite3_randomness(sizeof(iRandom), &iRandom);
  68994. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  68995. (iRandom>>8)&0xffffff, iRandom&0xff);
  68996. /* The antipenultimate character of the master journal name must
  68997. ** be "9" to avoid name collisions when using 8+3 filenames. */
  68998. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  68999. sqlite3FileSuffix3(zMainFile, zMaster);
  69000. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  69001. }while( rc==SQLITE_OK && res );
  69002. if( rc==SQLITE_OK ){
  69003. /* Open the master journal. */
  69004. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  69005. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  69006. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  69007. );
  69008. }
  69009. if( rc!=SQLITE_OK ){
  69010. sqlite3DbFree(db, zMaster);
  69011. return rc;
  69012. }
  69013. /* Write the name of each database file in the transaction into the new
  69014. ** master journal file. If an error occurs at this point close
  69015. ** and delete the master journal file. All the individual journal files
  69016. ** still have 'null' as the master journal pointer, so they will roll
  69017. ** back independently if a failure occurs.
  69018. */
  69019. for(i=0; i<db->nDb; i++){
  69020. Btree *pBt = db->aDb[i].pBt;
  69021. if( sqlite3BtreeIsInTrans(pBt) ){
  69022. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  69023. if( zFile==0 ){
  69024. continue; /* Ignore TEMP and :memory: databases */
  69025. }
  69026. assert( zFile[0]!=0 );
  69027. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  69028. offset += sqlite3Strlen30(zFile)+1;
  69029. if( rc!=SQLITE_OK ){
  69030. sqlite3OsCloseFree(pMaster);
  69031. sqlite3OsDelete(pVfs, zMaster, 0);
  69032. sqlite3DbFree(db, zMaster);
  69033. return rc;
  69034. }
  69035. }
  69036. }
  69037. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  69038. ** flag is set this is not required.
  69039. */
  69040. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  69041. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  69042. ){
  69043. sqlite3OsCloseFree(pMaster);
  69044. sqlite3OsDelete(pVfs, zMaster, 0);
  69045. sqlite3DbFree(db, zMaster);
  69046. return rc;
  69047. }
  69048. /* Sync all the db files involved in the transaction. The same call
  69049. ** sets the master journal pointer in each individual journal. If
  69050. ** an error occurs here, do not delete the master journal file.
  69051. **
  69052. ** If the error occurs during the first call to
  69053. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  69054. ** master journal file will be orphaned. But we cannot delete it,
  69055. ** in case the master journal file name was written into the journal
  69056. ** file before the failure occurred.
  69057. */
  69058. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  69059. Btree *pBt = db->aDb[i].pBt;
  69060. if( pBt ){
  69061. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  69062. }
  69063. }
  69064. sqlite3OsCloseFree(pMaster);
  69065. assert( rc!=SQLITE_BUSY );
  69066. if( rc!=SQLITE_OK ){
  69067. sqlite3DbFree(db, zMaster);
  69068. return rc;
  69069. }
  69070. /* Delete the master journal file. This commits the transaction. After
  69071. ** doing this the directory is synced again before any individual
  69072. ** transaction files are deleted.
  69073. */
  69074. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  69075. sqlite3DbFree(db, zMaster);
  69076. zMaster = 0;
  69077. if( rc ){
  69078. return rc;
  69079. }
  69080. /* All files and directories have already been synced, so the following
  69081. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  69082. ** deleting or truncating journals. If something goes wrong while
  69083. ** this is happening we don't really care. The integrity of the
  69084. ** transaction is already guaranteed, but some stray 'cold' journals
  69085. ** may be lying around. Returning an error code won't help matters.
  69086. */
  69087. disable_simulated_io_errors();
  69088. sqlite3BeginBenignMalloc();
  69089. for(i=0; i<db->nDb; i++){
  69090. Btree *pBt = db->aDb[i].pBt;
  69091. if( pBt ){
  69092. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  69093. }
  69094. }
  69095. sqlite3EndBenignMalloc();
  69096. enable_simulated_io_errors();
  69097. sqlite3VtabCommit(db);
  69098. }
  69099. #endif
  69100. return rc;
  69101. }
  69102. /*
  69103. ** This routine checks that the sqlite3.nVdbeActive count variable
  69104. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  69105. ** currently active. An assertion fails if the two counts do not match.
  69106. ** This is an internal self-check only - it is not an essential processing
  69107. ** step.
  69108. **
  69109. ** This is a no-op if NDEBUG is defined.
  69110. */
  69111. #ifndef NDEBUG
  69112. static void checkActiveVdbeCnt(sqlite3 *db){
  69113. Vdbe *p;
  69114. int cnt = 0;
  69115. int nWrite = 0;
  69116. int nRead = 0;
  69117. p = db->pVdbe;
  69118. while( p ){
  69119. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  69120. cnt++;
  69121. if( p->readOnly==0 ) nWrite++;
  69122. if( p->bIsReader ) nRead++;
  69123. }
  69124. p = p->pNext;
  69125. }
  69126. assert( cnt==db->nVdbeActive );
  69127. assert( nWrite==db->nVdbeWrite );
  69128. assert( nRead==db->nVdbeRead );
  69129. }
  69130. #else
  69131. #define checkActiveVdbeCnt(x)
  69132. #endif
  69133. /*
  69134. ** If the Vdbe passed as the first argument opened a statement-transaction,
  69135. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  69136. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  69137. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  69138. ** statement transaction is committed.
  69139. **
  69140. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  69141. ** Otherwise SQLITE_OK.
  69142. */
  69143. static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
  69144. sqlite3 *const db = p->db;
  69145. int rc = SQLITE_OK;
  69146. int i;
  69147. const int iSavepoint = p->iStatement-1;
  69148. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  69149. assert( db->nStatement>0 );
  69150. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  69151. for(i=0; i<db->nDb; i++){
  69152. int rc2 = SQLITE_OK;
  69153. Btree *pBt = db->aDb[i].pBt;
  69154. if( pBt ){
  69155. if( eOp==SAVEPOINT_ROLLBACK ){
  69156. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  69157. }
  69158. if( rc2==SQLITE_OK ){
  69159. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  69160. }
  69161. if( rc==SQLITE_OK ){
  69162. rc = rc2;
  69163. }
  69164. }
  69165. }
  69166. db->nStatement--;
  69167. p->iStatement = 0;
  69168. if( rc==SQLITE_OK ){
  69169. if( eOp==SAVEPOINT_ROLLBACK ){
  69170. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  69171. }
  69172. if( rc==SQLITE_OK ){
  69173. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  69174. }
  69175. }
  69176. /* If the statement transaction is being rolled back, also restore the
  69177. ** database handles deferred constraint counter to the value it had when
  69178. ** the statement transaction was opened. */
  69179. if( eOp==SAVEPOINT_ROLLBACK ){
  69180. db->nDeferredCons = p->nStmtDefCons;
  69181. db->nDeferredImmCons = p->nStmtDefImmCons;
  69182. }
  69183. return rc;
  69184. }
  69185. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  69186. if( p->db->nStatement && p->iStatement ){
  69187. return vdbeCloseStatement(p, eOp);
  69188. }
  69189. return SQLITE_OK;
  69190. }
  69191. /*
  69192. ** This function is called when a transaction opened by the database
  69193. ** handle associated with the VM passed as an argument is about to be
  69194. ** committed. If there are outstanding deferred foreign key constraint
  69195. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  69196. **
  69197. ** If there are outstanding FK violations and this function returns
  69198. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  69199. ** and write an error message to it. Then return SQLITE_ERROR.
  69200. */
  69201. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69202. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  69203. sqlite3 *db = p->db;
  69204. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  69205. || (!deferred && p->nFkConstraint>0)
  69206. ){
  69207. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  69208. p->errorAction = OE_Abort;
  69209. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  69210. return SQLITE_ERROR;
  69211. }
  69212. return SQLITE_OK;
  69213. }
  69214. #endif
  69215. /*
  69216. ** This routine is called the when a VDBE tries to halt. If the VDBE
  69217. ** has made changes and is in autocommit mode, then commit those
  69218. ** changes. If a rollback is needed, then do the rollback.
  69219. **
  69220. ** This routine is the only way to move the state of a VM from
  69221. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  69222. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  69223. **
  69224. ** Return an error code. If the commit could not complete because of
  69225. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  69226. ** means the close did not happen and needs to be repeated.
  69227. */
  69228. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  69229. int rc; /* Used to store transient return codes */
  69230. sqlite3 *db = p->db;
  69231. /* This function contains the logic that determines if a statement or
  69232. ** transaction will be committed or rolled back as a result of the
  69233. ** execution of this virtual machine.
  69234. **
  69235. ** If any of the following errors occur:
  69236. **
  69237. ** SQLITE_NOMEM
  69238. ** SQLITE_IOERR
  69239. ** SQLITE_FULL
  69240. ** SQLITE_INTERRUPT
  69241. **
  69242. ** Then the internal cache might have been left in an inconsistent
  69243. ** state. We need to rollback the statement transaction, if there is
  69244. ** one, or the complete transaction if there is no statement transaction.
  69245. */
  69246. if( p->magic!=VDBE_MAGIC_RUN ){
  69247. return SQLITE_OK;
  69248. }
  69249. if( db->mallocFailed ){
  69250. p->rc = SQLITE_NOMEM_BKPT;
  69251. }
  69252. closeAllCursors(p);
  69253. checkActiveVdbeCnt(db);
  69254. /* No commit or rollback needed if the program never started or if the
  69255. ** SQL statement does not read or write a database file. */
  69256. if( p->pc>=0 && p->bIsReader ){
  69257. int mrc; /* Primary error code from p->rc */
  69258. int eStatementOp = 0;
  69259. int isSpecialError; /* Set to true if a 'special' error */
  69260. /* Lock all btrees used by the statement */
  69261. sqlite3VdbeEnter(p);
  69262. /* Check for one of the special errors */
  69263. mrc = p->rc & 0xff;
  69264. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  69265. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  69266. if( isSpecialError ){
  69267. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  69268. ** no rollback is necessary. Otherwise, at least a savepoint
  69269. ** transaction must be rolled back to restore the database to a
  69270. ** consistent state.
  69271. **
  69272. ** Even if the statement is read-only, it is important to perform
  69273. ** a statement or transaction rollback operation. If the error
  69274. ** occurred while writing to the journal, sub-journal or database
  69275. ** file as part of an effort to free up cache space (see function
  69276. ** pagerStress() in pager.c), the rollback is required to restore
  69277. ** the pager to a consistent state.
  69278. */
  69279. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  69280. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  69281. eStatementOp = SAVEPOINT_ROLLBACK;
  69282. }else{
  69283. /* We are forced to roll back the active transaction. Before doing
  69284. ** so, abort any other statements this handle currently has active.
  69285. */
  69286. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  69287. sqlite3CloseSavepoints(db);
  69288. db->autoCommit = 1;
  69289. p->nChange = 0;
  69290. }
  69291. }
  69292. }
  69293. /* Check for immediate foreign key violations. */
  69294. if( p->rc==SQLITE_OK ){
  69295. sqlite3VdbeCheckFk(p, 0);
  69296. }
  69297. /* If the auto-commit flag is set and this is the only active writer
  69298. ** VM, then we do either a commit or rollback of the current transaction.
  69299. **
  69300. ** Note: This block also runs if one of the special errors handled
  69301. ** above has occurred.
  69302. */
  69303. if( !sqlite3VtabInSync(db)
  69304. && db->autoCommit
  69305. && db->nVdbeWrite==(p->readOnly==0)
  69306. ){
  69307. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  69308. rc = sqlite3VdbeCheckFk(p, 1);
  69309. if( rc!=SQLITE_OK ){
  69310. if( NEVER(p->readOnly) ){
  69311. sqlite3VdbeLeave(p);
  69312. return SQLITE_ERROR;
  69313. }
  69314. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  69315. }else{
  69316. /* The auto-commit flag is true, the vdbe program was successful
  69317. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  69318. ** key constraints to hold up the transaction. This means a commit
  69319. ** is required. */
  69320. rc = vdbeCommit(db, p);
  69321. }
  69322. if( rc==SQLITE_BUSY && p->readOnly ){
  69323. sqlite3VdbeLeave(p);
  69324. return SQLITE_BUSY;
  69325. }else if( rc!=SQLITE_OK ){
  69326. p->rc = rc;
  69327. sqlite3RollbackAll(db, SQLITE_OK);
  69328. p->nChange = 0;
  69329. }else{
  69330. db->nDeferredCons = 0;
  69331. db->nDeferredImmCons = 0;
  69332. db->flags &= ~SQLITE_DeferFKs;
  69333. sqlite3CommitInternalChanges(db);
  69334. }
  69335. }else{
  69336. sqlite3RollbackAll(db, SQLITE_OK);
  69337. p->nChange = 0;
  69338. }
  69339. db->nStatement = 0;
  69340. }else if( eStatementOp==0 ){
  69341. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  69342. eStatementOp = SAVEPOINT_RELEASE;
  69343. }else if( p->errorAction==OE_Abort ){
  69344. eStatementOp = SAVEPOINT_ROLLBACK;
  69345. }else{
  69346. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  69347. sqlite3CloseSavepoints(db);
  69348. db->autoCommit = 1;
  69349. p->nChange = 0;
  69350. }
  69351. }
  69352. /* If eStatementOp is non-zero, then a statement transaction needs to
  69353. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  69354. ** do so. If this operation returns an error, and the current statement
  69355. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  69356. ** current statement error code.
  69357. */
  69358. if( eStatementOp ){
  69359. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  69360. if( rc ){
  69361. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  69362. p->rc = rc;
  69363. sqlite3DbFree(db, p->zErrMsg);
  69364. p->zErrMsg = 0;
  69365. }
  69366. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  69367. sqlite3CloseSavepoints(db);
  69368. db->autoCommit = 1;
  69369. p->nChange = 0;
  69370. }
  69371. }
  69372. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  69373. ** has been rolled back, update the database connection change-counter.
  69374. */
  69375. if( p->changeCntOn ){
  69376. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  69377. sqlite3VdbeSetChanges(db, p->nChange);
  69378. }else{
  69379. sqlite3VdbeSetChanges(db, 0);
  69380. }
  69381. p->nChange = 0;
  69382. }
  69383. /* Release the locks */
  69384. sqlite3VdbeLeave(p);
  69385. }
  69386. /* We have successfully halted and closed the VM. Record this fact. */
  69387. if( p->pc>=0 ){
  69388. db->nVdbeActive--;
  69389. if( !p->readOnly ) db->nVdbeWrite--;
  69390. if( p->bIsReader ) db->nVdbeRead--;
  69391. assert( db->nVdbeActive>=db->nVdbeRead );
  69392. assert( db->nVdbeRead>=db->nVdbeWrite );
  69393. assert( db->nVdbeWrite>=0 );
  69394. }
  69395. p->magic = VDBE_MAGIC_HALT;
  69396. checkActiveVdbeCnt(db);
  69397. if( db->mallocFailed ){
  69398. p->rc = SQLITE_NOMEM_BKPT;
  69399. }
  69400. /* If the auto-commit flag is set to true, then any locks that were held
  69401. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  69402. ** to invoke any required unlock-notify callbacks.
  69403. */
  69404. if( db->autoCommit ){
  69405. sqlite3ConnectionUnlocked(db);
  69406. }
  69407. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  69408. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  69409. }
  69410. /*
  69411. ** Each VDBE holds the result of the most recent sqlite3_step() call
  69412. ** in p->rc. This routine sets that result back to SQLITE_OK.
  69413. */
  69414. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  69415. p->rc = SQLITE_OK;
  69416. }
  69417. /*
  69418. ** Copy the error code and error message belonging to the VDBE passed
  69419. ** as the first argument to its database handle (so that they will be
  69420. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  69421. **
  69422. ** This function does not clear the VDBE error code or message, just
  69423. ** copies them to the database handle.
  69424. */
  69425. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  69426. sqlite3 *db = p->db;
  69427. int rc = p->rc;
  69428. if( p->zErrMsg ){
  69429. db->bBenignMalloc++;
  69430. sqlite3BeginBenignMalloc();
  69431. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  69432. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  69433. sqlite3EndBenignMalloc();
  69434. db->bBenignMalloc--;
  69435. db->errCode = rc;
  69436. }else{
  69437. sqlite3Error(db, rc);
  69438. }
  69439. return rc;
  69440. }
  69441. #ifdef SQLITE_ENABLE_SQLLOG
  69442. /*
  69443. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  69444. ** invoke it.
  69445. */
  69446. static void vdbeInvokeSqllog(Vdbe *v){
  69447. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  69448. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  69449. assert( v->db->init.busy==0 );
  69450. if( zExpanded ){
  69451. sqlite3GlobalConfig.xSqllog(
  69452. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  69453. );
  69454. sqlite3DbFree(v->db, zExpanded);
  69455. }
  69456. }
  69457. }
  69458. #else
  69459. # define vdbeInvokeSqllog(x)
  69460. #endif
  69461. /*
  69462. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  69463. ** Write any error messages into *pzErrMsg. Return the result code.
  69464. **
  69465. ** After this routine is run, the VDBE should be ready to be executed
  69466. ** again.
  69467. **
  69468. ** To look at it another way, this routine resets the state of the
  69469. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  69470. ** VDBE_MAGIC_INIT.
  69471. */
  69472. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  69473. sqlite3 *db;
  69474. db = p->db;
  69475. /* If the VM did not run to completion or if it encountered an
  69476. ** error, then it might not have been halted properly. So halt
  69477. ** it now.
  69478. */
  69479. sqlite3VdbeHalt(p);
  69480. /* If the VDBE has be run even partially, then transfer the error code
  69481. ** and error message from the VDBE into the main database structure. But
  69482. ** if the VDBE has just been set to run but has not actually executed any
  69483. ** instructions yet, leave the main database error information unchanged.
  69484. */
  69485. if( p->pc>=0 ){
  69486. vdbeInvokeSqllog(p);
  69487. sqlite3VdbeTransferError(p);
  69488. sqlite3DbFree(db, p->zErrMsg);
  69489. p->zErrMsg = 0;
  69490. if( p->runOnlyOnce ) p->expired = 1;
  69491. }else if( p->rc && p->expired ){
  69492. /* The expired flag was set on the VDBE before the first call
  69493. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  69494. ** called), set the database error in this case as well.
  69495. */
  69496. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  69497. sqlite3DbFree(db, p->zErrMsg);
  69498. p->zErrMsg = 0;
  69499. }
  69500. /* Reclaim all memory used by the VDBE
  69501. */
  69502. Cleanup(p);
  69503. /* Save profiling information from this VDBE run.
  69504. */
  69505. #ifdef VDBE_PROFILE
  69506. {
  69507. FILE *out = fopen("vdbe_profile.out", "a");
  69508. if( out ){
  69509. int i;
  69510. fprintf(out, "---- ");
  69511. for(i=0; i<p->nOp; i++){
  69512. fprintf(out, "%02x", p->aOp[i].opcode);
  69513. }
  69514. fprintf(out, "\n");
  69515. if( p->zSql ){
  69516. char c, pc = 0;
  69517. fprintf(out, "-- ");
  69518. for(i=0; (c = p->zSql[i])!=0; i++){
  69519. if( pc=='\n' ) fprintf(out, "-- ");
  69520. putc(c, out);
  69521. pc = c;
  69522. }
  69523. if( pc!='\n' ) fprintf(out, "\n");
  69524. }
  69525. for(i=0; i<p->nOp; i++){
  69526. char zHdr[100];
  69527. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  69528. p->aOp[i].cnt,
  69529. p->aOp[i].cycles,
  69530. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  69531. );
  69532. fprintf(out, "%s", zHdr);
  69533. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  69534. }
  69535. fclose(out);
  69536. }
  69537. }
  69538. #endif
  69539. p->magic = VDBE_MAGIC_RESET;
  69540. return p->rc & db->errMask;
  69541. }
  69542. /*
  69543. ** Clean up and delete a VDBE after execution. Return an integer which is
  69544. ** the result code. Write any error message text into *pzErrMsg.
  69545. */
  69546. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  69547. int rc = SQLITE_OK;
  69548. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  69549. rc = sqlite3VdbeReset(p);
  69550. assert( (rc & p->db->errMask)==rc );
  69551. }
  69552. sqlite3VdbeDelete(p);
  69553. return rc;
  69554. }
  69555. /*
  69556. ** If parameter iOp is less than zero, then invoke the destructor for
  69557. ** all auxiliary data pointers currently cached by the VM passed as
  69558. ** the first argument.
  69559. **
  69560. ** Or, if iOp is greater than or equal to zero, then the destructor is
  69561. ** only invoked for those auxiliary data pointers created by the user
  69562. ** function invoked by the OP_Function opcode at instruction iOp of
  69563. ** VM pVdbe, and only then if:
  69564. **
  69565. ** * the associated function parameter is the 32nd or later (counting
  69566. ** from left to right), or
  69567. **
  69568. ** * the corresponding bit in argument mask is clear (where the first
  69569. ** function parameter corresponds to bit 0 etc.).
  69570. */
  69571. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  69572. while( *pp ){
  69573. AuxData *pAux = *pp;
  69574. if( (iOp<0)
  69575. || (pAux->iAuxOp==iOp
  69576. && pAux->iAuxArg>=0
  69577. && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
  69578. ){
  69579. testcase( pAux->iAuxArg==31 );
  69580. if( pAux->xDeleteAux ){
  69581. pAux->xDeleteAux(pAux->pAux);
  69582. }
  69583. *pp = pAux->pNextAux;
  69584. sqlite3DbFree(db, pAux);
  69585. }else{
  69586. pp= &pAux->pNextAux;
  69587. }
  69588. }
  69589. }
  69590. /*
  69591. ** Free all memory associated with the Vdbe passed as the second argument,
  69592. ** except for object itself, which is preserved.
  69593. **
  69594. ** The difference between this function and sqlite3VdbeDelete() is that
  69595. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  69596. ** the database connection and frees the object itself.
  69597. */
  69598. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  69599. SubProgram *pSub, *pNext;
  69600. assert( p->db==0 || p->db==db );
  69601. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  69602. for(pSub=p->pProgram; pSub; pSub=pNext){
  69603. pNext = pSub->pNext;
  69604. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  69605. sqlite3DbFree(db, pSub);
  69606. }
  69607. if( p->magic!=VDBE_MAGIC_INIT ){
  69608. releaseMemArray(p->aVar, p->nVar);
  69609. sqlite3DbFree(db, p->pVList);
  69610. sqlite3DbFree(db, p->pFree);
  69611. }
  69612. vdbeFreeOpArray(db, p->aOp, p->nOp);
  69613. sqlite3DbFree(db, p->aColName);
  69614. sqlite3DbFree(db, p->zSql);
  69615. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  69616. {
  69617. int i;
  69618. for(i=0; i<p->nScan; i++){
  69619. sqlite3DbFree(db, p->aScan[i].zName);
  69620. }
  69621. sqlite3DbFree(db, p->aScan);
  69622. }
  69623. #endif
  69624. }
  69625. /*
  69626. ** Delete an entire VDBE.
  69627. */
  69628. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  69629. sqlite3 *db;
  69630. if( NEVER(p==0) ) return;
  69631. db = p->db;
  69632. assert( sqlite3_mutex_held(db->mutex) );
  69633. sqlite3VdbeClearObject(db, p);
  69634. if( p->pPrev ){
  69635. p->pPrev->pNext = p->pNext;
  69636. }else{
  69637. assert( db->pVdbe==p );
  69638. db->pVdbe = p->pNext;
  69639. }
  69640. if( p->pNext ){
  69641. p->pNext->pPrev = p->pPrev;
  69642. }
  69643. p->magic = VDBE_MAGIC_DEAD;
  69644. p->db = 0;
  69645. sqlite3DbFreeNN(db, p);
  69646. }
  69647. /*
  69648. ** The cursor "p" has a pending seek operation that has not yet been
  69649. ** carried out. Seek the cursor now. If an error occurs, return
  69650. ** the appropriate error code.
  69651. */
  69652. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  69653. int res, rc;
  69654. #ifdef SQLITE_TEST
  69655. extern int sqlite3_search_count;
  69656. #endif
  69657. assert( p->deferredMoveto );
  69658. assert( p->isTable );
  69659. assert( p->eCurType==CURTYPE_BTREE );
  69660. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  69661. if( rc ) return rc;
  69662. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  69663. #ifdef SQLITE_TEST
  69664. sqlite3_search_count++;
  69665. #endif
  69666. p->deferredMoveto = 0;
  69667. p->cacheStatus = CACHE_STALE;
  69668. return SQLITE_OK;
  69669. }
  69670. /*
  69671. ** Something has moved cursor "p" out of place. Maybe the row it was
  69672. ** pointed to was deleted out from under it. Or maybe the btree was
  69673. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  69674. ** is supposed to be pointing. If the row was deleted out from under the
  69675. ** cursor, set the cursor to point to a NULL row.
  69676. */
  69677. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  69678. int isDifferentRow, rc;
  69679. assert( p->eCurType==CURTYPE_BTREE );
  69680. assert( p->uc.pCursor!=0 );
  69681. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  69682. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  69683. p->cacheStatus = CACHE_STALE;
  69684. if( isDifferentRow ) p->nullRow = 1;
  69685. return rc;
  69686. }
  69687. /*
  69688. ** Check to ensure that the cursor is valid. Restore the cursor
  69689. ** if need be. Return any I/O error from the restore operation.
  69690. */
  69691. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  69692. assert( p->eCurType==CURTYPE_BTREE );
  69693. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  69694. return handleMovedCursor(p);
  69695. }
  69696. return SQLITE_OK;
  69697. }
  69698. /*
  69699. ** Make sure the cursor p is ready to read or write the row to which it
  69700. ** was last positioned. Return an error code if an OOM fault or I/O error
  69701. ** prevents us from positioning the cursor to its correct position.
  69702. **
  69703. ** If a MoveTo operation is pending on the given cursor, then do that
  69704. ** MoveTo now. If no move is pending, check to see if the row has been
  69705. ** deleted out from under the cursor and if it has, mark the row as
  69706. ** a NULL row.
  69707. **
  69708. ** If the cursor is already pointing to the correct row and that row has
  69709. ** not been deleted out from under the cursor, then this routine is a no-op.
  69710. */
  69711. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  69712. VdbeCursor *p = *pp;
  69713. if( p->eCurType==CURTYPE_BTREE ){
  69714. if( p->deferredMoveto ){
  69715. int iMap;
  69716. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
  69717. *pp = p->pAltCursor;
  69718. *piCol = iMap - 1;
  69719. return SQLITE_OK;
  69720. }
  69721. return handleDeferredMoveto(p);
  69722. }
  69723. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  69724. return handleMovedCursor(p);
  69725. }
  69726. }
  69727. return SQLITE_OK;
  69728. }
  69729. /*
  69730. ** The following functions:
  69731. **
  69732. ** sqlite3VdbeSerialType()
  69733. ** sqlite3VdbeSerialTypeLen()
  69734. ** sqlite3VdbeSerialLen()
  69735. ** sqlite3VdbeSerialPut()
  69736. ** sqlite3VdbeSerialGet()
  69737. **
  69738. ** encapsulate the code that serializes values for storage in SQLite
  69739. ** data and index records. Each serialized value consists of a
  69740. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  69741. ** integer, stored as a varint.
  69742. **
  69743. ** In an SQLite index record, the serial type is stored directly before
  69744. ** the blob of data that it corresponds to. In a table record, all serial
  69745. ** types are stored at the start of the record, and the blobs of data at
  69746. ** the end. Hence these functions allow the caller to handle the
  69747. ** serial-type and data blob separately.
  69748. **
  69749. ** The following table describes the various storage classes for data:
  69750. **
  69751. ** serial type bytes of data type
  69752. ** -------------- --------------- ---------------
  69753. ** 0 0 NULL
  69754. ** 1 1 signed integer
  69755. ** 2 2 signed integer
  69756. ** 3 3 signed integer
  69757. ** 4 4 signed integer
  69758. ** 5 6 signed integer
  69759. ** 6 8 signed integer
  69760. ** 7 8 IEEE float
  69761. ** 8 0 Integer constant 0
  69762. ** 9 0 Integer constant 1
  69763. ** 10,11 reserved for expansion
  69764. ** N>=12 and even (N-12)/2 BLOB
  69765. ** N>=13 and odd (N-13)/2 text
  69766. **
  69767. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  69768. ** of SQLite will not understand those serial types.
  69769. */
  69770. /*
  69771. ** Return the serial-type for the value stored in pMem.
  69772. */
  69773. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  69774. int flags = pMem->flags;
  69775. u32 n;
  69776. assert( pLen!=0 );
  69777. if( flags&MEM_Null ){
  69778. *pLen = 0;
  69779. return 0;
  69780. }
  69781. if( flags&MEM_Int ){
  69782. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  69783. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  69784. i64 i = pMem->u.i;
  69785. u64 u;
  69786. if( i<0 ){
  69787. u = ~i;
  69788. }else{
  69789. u = i;
  69790. }
  69791. if( u<=127 ){
  69792. if( (i&1)==i && file_format>=4 ){
  69793. *pLen = 0;
  69794. return 8+(u32)u;
  69795. }else{
  69796. *pLen = 1;
  69797. return 1;
  69798. }
  69799. }
  69800. if( u<=32767 ){ *pLen = 2; return 2; }
  69801. if( u<=8388607 ){ *pLen = 3; return 3; }
  69802. if( u<=2147483647 ){ *pLen = 4; return 4; }
  69803. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  69804. *pLen = 8;
  69805. return 6;
  69806. }
  69807. if( flags&MEM_Real ){
  69808. *pLen = 8;
  69809. return 7;
  69810. }
  69811. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  69812. assert( pMem->n>=0 );
  69813. n = (u32)pMem->n;
  69814. if( flags & MEM_Zero ){
  69815. n += pMem->u.nZero;
  69816. }
  69817. *pLen = n;
  69818. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  69819. }
  69820. /*
  69821. ** The sizes for serial types less than 128
  69822. */
  69823. static const u8 sqlite3SmallTypeSizes[] = {
  69824. /* 0 1 2 3 4 5 6 7 8 9 */
  69825. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  69826. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  69827. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  69828. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  69829. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  69830. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  69831. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  69832. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  69833. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  69834. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  69835. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  69836. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  69837. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  69838. };
  69839. /*
  69840. ** Return the length of the data corresponding to the supplied serial-type.
  69841. */
  69842. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  69843. if( serial_type>=128 ){
  69844. return (serial_type-12)/2;
  69845. }else{
  69846. assert( serial_type<12
  69847. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  69848. return sqlite3SmallTypeSizes[serial_type];
  69849. }
  69850. }
  69851. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  69852. assert( serial_type<128 );
  69853. return sqlite3SmallTypeSizes[serial_type];
  69854. }
  69855. /*
  69856. ** If we are on an architecture with mixed-endian floating
  69857. ** points (ex: ARM7) then swap the lower 4 bytes with the
  69858. ** upper 4 bytes. Return the result.
  69859. **
  69860. ** For most architectures, this is a no-op.
  69861. **
  69862. ** (later): It is reported to me that the mixed-endian problem
  69863. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  69864. ** that early versions of GCC stored the two words of a 64-bit
  69865. ** float in the wrong order. And that error has been propagated
  69866. ** ever since. The blame is not necessarily with GCC, though.
  69867. ** GCC might have just copying the problem from a prior compiler.
  69868. ** I am also told that newer versions of GCC that follow a different
  69869. ** ABI get the byte order right.
  69870. **
  69871. ** Developers using SQLite on an ARM7 should compile and run their
  69872. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  69873. ** enabled, some asserts below will ensure that the byte order of
  69874. ** floating point values is correct.
  69875. **
  69876. ** (2007-08-30) Frank van Vugt has studied this problem closely
  69877. ** and has send his findings to the SQLite developers. Frank
  69878. ** writes that some Linux kernels offer floating point hardware
  69879. ** emulation that uses only 32-bit mantissas instead of a full
  69880. ** 48-bits as required by the IEEE standard. (This is the
  69881. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  69882. ** byte swapping becomes very complicated. To avoid problems,
  69883. ** the necessary byte swapping is carried out using a 64-bit integer
  69884. ** rather than a 64-bit float. Frank assures us that the code here
  69885. ** works for him. We, the developers, have no way to independently
  69886. ** verify this, but Frank seems to know what he is talking about
  69887. ** so we trust him.
  69888. */
  69889. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  69890. static u64 floatSwap(u64 in){
  69891. union {
  69892. u64 r;
  69893. u32 i[2];
  69894. } u;
  69895. u32 t;
  69896. u.r = in;
  69897. t = u.i[0];
  69898. u.i[0] = u.i[1];
  69899. u.i[1] = t;
  69900. return u.r;
  69901. }
  69902. # define swapMixedEndianFloat(X) X = floatSwap(X)
  69903. #else
  69904. # define swapMixedEndianFloat(X)
  69905. #endif
  69906. /*
  69907. ** Write the serialized data blob for the value stored in pMem into
  69908. ** buf. It is assumed that the caller has allocated sufficient space.
  69909. ** Return the number of bytes written.
  69910. **
  69911. ** nBuf is the amount of space left in buf[]. The caller is responsible
  69912. ** for allocating enough space to buf[] to hold the entire field, exclusive
  69913. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  69914. **
  69915. ** Return the number of bytes actually written into buf[]. The number
  69916. ** of bytes in the zero-filled tail is included in the return value only
  69917. ** if those bytes were zeroed in buf[].
  69918. */
  69919. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  69920. u32 len;
  69921. /* Integer and Real */
  69922. if( serial_type<=7 && serial_type>0 ){
  69923. u64 v;
  69924. u32 i;
  69925. if( serial_type==7 ){
  69926. assert( sizeof(v)==sizeof(pMem->u.r) );
  69927. memcpy(&v, &pMem->u.r, sizeof(v));
  69928. swapMixedEndianFloat(v);
  69929. }else{
  69930. v = pMem->u.i;
  69931. }
  69932. len = i = sqlite3SmallTypeSizes[serial_type];
  69933. assert( i>0 );
  69934. do{
  69935. buf[--i] = (u8)(v&0xFF);
  69936. v >>= 8;
  69937. }while( i );
  69938. return len;
  69939. }
  69940. /* String or blob */
  69941. if( serial_type>=12 ){
  69942. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  69943. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  69944. len = pMem->n;
  69945. if( len>0 ) memcpy(buf, pMem->z, len);
  69946. return len;
  69947. }
  69948. /* NULL or constants 0 or 1 */
  69949. return 0;
  69950. }
  69951. /* Input "x" is a sequence of unsigned characters that represent a
  69952. ** big-endian integer. Return the equivalent native integer
  69953. */
  69954. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  69955. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  69956. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  69957. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  69958. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  69959. /*
  69960. ** Deserialize the data blob pointed to by buf as serial type serial_type
  69961. ** and store the result in pMem. Return the number of bytes read.
  69962. **
  69963. ** This function is implemented as two separate routines for performance.
  69964. ** The few cases that require local variables are broken out into a separate
  69965. ** routine so that in most cases the overhead of moving the stack pointer
  69966. ** is avoided.
  69967. */
  69968. static u32 SQLITE_NOINLINE serialGet(
  69969. const unsigned char *buf, /* Buffer to deserialize from */
  69970. u32 serial_type, /* Serial type to deserialize */
  69971. Mem *pMem /* Memory cell to write value into */
  69972. ){
  69973. u64 x = FOUR_BYTE_UINT(buf);
  69974. u32 y = FOUR_BYTE_UINT(buf+4);
  69975. x = (x<<32) + y;
  69976. if( serial_type==6 ){
  69977. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  69978. ** twos-complement integer. */
  69979. pMem->u.i = *(i64*)&x;
  69980. pMem->flags = MEM_Int;
  69981. testcase( pMem->u.i<0 );
  69982. }else{
  69983. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  69984. ** floating point number. */
  69985. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  69986. /* Verify that integers and floating point values use the same
  69987. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  69988. ** defined that 64-bit floating point values really are mixed
  69989. ** endian.
  69990. */
  69991. static const u64 t1 = ((u64)0x3ff00000)<<32;
  69992. static const double r1 = 1.0;
  69993. u64 t2 = t1;
  69994. swapMixedEndianFloat(t2);
  69995. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  69996. #endif
  69997. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  69998. swapMixedEndianFloat(x);
  69999. memcpy(&pMem->u.r, &x, sizeof(x));
  70000. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  70001. }
  70002. return 8;
  70003. }
  70004. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  70005. const unsigned char *buf, /* Buffer to deserialize from */
  70006. u32 serial_type, /* Serial type to deserialize */
  70007. Mem *pMem /* Memory cell to write value into */
  70008. ){
  70009. switch( serial_type ){
  70010. case 10: /* Reserved for future use */
  70011. case 11: /* Reserved for future use */
  70012. case 0: { /* Null */
  70013. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  70014. pMem->flags = MEM_Null;
  70015. break;
  70016. }
  70017. case 1: {
  70018. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  70019. ** integer. */
  70020. pMem->u.i = ONE_BYTE_INT(buf);
  70021. pMem->flags = MEM_Int;
  70022. testcase( pMem->u.i<0 );
  70023. return 1;
  70024. }
  70025. case 2: { /* 2-byte signed integer */
  70026. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  70027. ** twos-complement integer. */
  70028. pMem->u.i = TWO_BYTE_INT(buf);
  70029. pMem->flags = MEM_Int;
  70030. testcase( pMem->u.i<0 );
  70031. return 2;
  70032. }
  70033. case 3: { /* 3-byte signed integer */
  70034. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  70035. ** twos-complement integer. */
  70036. pMem->u.i = THREE_BYTE_INT(buf);
  70037. pMem->flags = MEM_Int;
  70038. testcase( pMem->u.i<0 );
  70039. return 3;
  70040. }
  70041. case 4: { /* 4-byte signed integer */
  70042. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  70043. ** twos-complement integer. */
  70044. pMem->u.i = FOUR_BYTE_INT(buf);
  70045. #ifdef __HP_cc
  70046. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  70047. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  70048. #endif
  70049. pMem->flags = MEM_Int;
  70050. testcase( pMem->u.i<0 );
  70051. return 4;
  70052. }
  70053. case 5: { /* 6-byte signed integer */
  70054. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  70055. ** twos-complement integer. */
  70056. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  70057. pMem->flags = MEM_Int;
  70058. testcase( pMem->u.i<0 );
  70059. return 6;
  70060. }
  70061. case 6: /* 8-byte signed integer */
  70062. case 7: { /* IEEE floating point */
  70063. /* These use local variables, so do them in a separate routine
  70064. ** to avoid having to move the frame pointer in the common case */
  70065. return serialGet(buf,serial_type,pMem);
  70066. }
  70067. case 8: /* Integer 0 */
  70068. case 9: { /* Integer 1 */
  70069. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  70070. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  70071. pMem->u.i = serial_type-8;
  70072. pMem->flags = MEM_Int;
  70073. return 0;
  70074. }
  70075. default: {
  70076. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  70077. ** length.
  70078. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  70079. ** (N-13)/2 bytes in length. */
  70080. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  70081. pMem->z = (char *)buf;
  70082. pMem->n = (serial_type-12)/2;
  70083. pMem->flags = aFlag[serial_type&1];
  70084. return pMem->n;
  70085. }
  70086. }
  70087. return 0;
  70088. }
  70089. /*
  70090. ** This routine is used to allocate sufficient space for an UnpackedRecord
  70091. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  70092. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  70093. **
  70094. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  70095. ** the unaligned buffer passed via the second and third arguments (presumably
  70096. ** stack space). If the former, then *ppFree is set to a pointer that should
  70097. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  70098. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  70099. ** before returning.
  70100. **
  70101. ** If an OOM error occurs, NULL is returned.
  70102. */
  70103. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  70104. KeyInfo *pKeyInfo /* Description of the record */
  70105. ){
  70106. UnpackedRecord *p; /* Unpacked record to return */
  70107. int nByte; /* Number of bytes required for *p */
  70108. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  70109. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  70110. if( !p ) return 0;
  70111. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  70112. assert( pKeyInfo->aSortOrder!=0 );
  70113. p->pKeyInfo = pKeyInfo;
  70114. p->nField = pKeyInfo->nField + 1;
  70115. return p;
  70116. }
  70117. /*
  70118. ** Given the nKey-byte encoding of a record in pKey[], populate the
  70119. ** UnpackedRecord structure indicated by the fourth argument with the
  70120. ** contents of the decoded record.
  70121. */
  70122. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  70123. KeyInfo *pKeyInfo, /* Information about the record format */
  70124. int nKey, /* Size of the binary record */
  70125. const void *pKey, /* The binary record */
  70126. UnpackedRecord *p /* Populate this structure before returning. */
  70127. ){
  70128. const unsigned char *aKey = (const unsigned char *)pKey;
  70129. int d;
  70130. u32 idx; /* Offset in aKey[] to read from */
  70131. u16 u; /* Unsigned loop counter */
  70132. u32 szHdr;
  70133. Mem *pMem = p->aMem;
  70134. p->default_rc = 0;
  70135. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70136. idx = getVarint32(aKey, szHdr);
  70137. d = szHdr;
  70138. u = 0;
  70139. while( idx<szHdr && d<=nKey ){
  70140. u32 serial_type;
  70141. idx += getVarint32(&aKey[idx], serial_type);
  70142. pMem->enc = pKeyInfo->enc;
  70143. pMem->db = pKeyInfo->db;
  70144. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  70145. pMem->szMalloc = 0;
  70146. pMem->z = 0;
  70147. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  70148. pMem++;
  70149. if( (++u)>=p->nField ) break;
  70150. }
  70151. assert( u<=pKeyInfo->nField + 1 );
  70152. p->nField = u;
  70153. }
  70154. #ifdef SQLITE_DEBUG
  70155. /*
  70156. ** This function compares two index or table record keys in the same way
  70157. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  70158. ** this function deserializes and compares values using the
  70159. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  70160. ** in assert() statements to ensure that the optimized code in
  70161. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  70162. **
  70163. ** Return true if the result of comparison is equivalent to desiredResult.
  70164. ** Return false if there is a disagreement.
  70165. */
  70166. static int vdbeRecordCompareDebug(
  70167. int nKey1, const void *pKey1, /* Left key */
  70168. const UnpackedRecord *pPKey2, /* Right key */
  70169. int desiredResult /* Correct answer */
  70170. ){
  70171. u32 d1; /* Offset into aKey[] of next data element */
  70172. u32 idx1; /* Offset into aKey[] of next header element */
  70173. u32 szHdr1; /* Number of bytes in header */
  70174. int i = 0;
  70175. int rc = 0;
  70176. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  70177. KeyInfo *pKeyInfo;
  70178. Mem mem1;
  70179. pKeyInfo = pPKey2->pKeyInfo;
  70180. if( pKeyInfo->db==0 ) return 1;
  70181. mem1.enc = pKeyInfo->enc;
  70182. mem1.db = pKeyInfo->db;
  70183. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  70184. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  70185. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  70186. ** We could initialize it, as shown here, to silence those complaints.
  70187. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  70188. ** the unnecessary initialization has a measurable negative performance
  70189. ** impact, since this routine is a very high runner. And so, we choose
  70190. ** to ignore the compiler warnings and leave this variable uninitialized.
  70191. */
  70192. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  70193. idx1 = getVarint32(aKey1, szHdr1);
  70194. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  70195. d1 = szHdr1;
  70196. assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
  70197. assert( pKeyInfo->aSortOrder!=0 );
  70198. assert( pKeyInfo->nField>0 );
  70199. assert( idx1<=szHdr1 || CORRUPT_DB );
  70200. do{
  70201. u32 serial_type1;
  70202. /* Read the serial types for the next element in each key. */
  70203. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  70204. /* Verify that there is enough key space remaining to avoid
  70205. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  70206. ** always be greater than or equal to the amount of required key space.
  70207. ** Use that approximation to avoid the more expensive call to
  70208. ** sqlite3VdbeSerialTypeLen() in the common case.
  70209. */
  70210. if( d1+serial_type1+2>(u32)nKey1
  70211. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  70212. ){
  70213. break;
  70214. }
  70215. /* Extract the values to be compared.
  70216. */
  70217. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  70218. /* Do the comparison
  70219. */
  70220. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  70221. if( rc!=0 ){
  70222. assert( mem1.szMalloc==0 ); /* See comment below */
  70223. if( pKeyInfo->aSortOrder[i] ){
  70224. rc = -rc; /* Invert the result for DESC sort order. */
  70225. }
  70226. goto debugCompareEnd;
  70227. }
  70228. i++;
  70229. }while( idx1<szHdr1 && i<pPKey2->nField );
  70230. /* No memory allocation is ever used on mem1. Prove this using
  70231. ** the following assert(). If the assert() fails, it indicates a
  70232. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  70233. */
  70234. assert( mem1.szMalloc==0 );
  70235. /* rc==0 here means that one of the keys ran out of fields and
  70236. ** all the fields up to that point were equal. Return the default_rc
  70237. ** value. */
  70238. rc = pPKey2->default_rc;
  70239. debugCompareEnd:
  70240. if( desiredResult==0 && rc==0 ) return 1;
  70241. if( desiredResult<0 && rc<0 ) return 1;
  70242. if( desiredResult>0 && rc>0 ) return 1;
  70243. if( CORRUPT_DB ) return 1;
  70244. if( pKeyInfo->db->mallocFailed ) return 1;
  70245. return 0;
  70246. }
  70247. #endif
  70248. #ifdef SQLITE_DEBUG
  70249. /*
  70250. ** Count the number of fields (a.k.a. columns) in the record given by
  70251. ** pKey,nKey. The verify that this count is less than or equal to the
  70252. ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
  70253. **
  70254. ** If this constraint is not satisfied, it means that the high-speed
  70255. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  70256. ** not work correctly. If this assert() ever fires, it probably means
  70257. ** that the KeyInfo.nField or KeyInfo.nXField values were computed
  70258. ** incorrectly.
  70259. */
  70260. static void vdbeAssertFieldCountWithinLimits(
  70261. int nKey, const void *pKey, /* The record to verify */
  70262. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  70263. ){
  70264. int nField = 0;
  70265. u32 szHdr;
  70266. u32 idx;
  70267. u32 notUsed;
  70268. const unsigned char *aKey = (const unsigned char*)pKey;
  70269. if( CORRUPT_DB ) return;
  70270. idx = getVarint32(aKey, szHdr);
  70271. assert( nKey>=0 );
  70272. assert( szHdr<=(u32)nKey );
  70273. while( idx<szHdr ){
  70274. idx += getVarint32(aKey+idx, notUsed);
  70275. nField++;
  70276. }
  70277. assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
  70278. }
  70279. #else
  70280. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  70281. #endif
  70282. /*
  70283. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  70284. ** using the collation sequence pColl. As usual, return a negative , zero
  70285. ** or positive value if *pMem1 is less than, equal to or greater than
  70286. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  70287. */
  70288. static int vdbeCompareMemString(
  70289. const Mem *pMem1,
  70290. const Mem *pMem2,
  70291. const CollSeq *pColl,
  70292. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  70293. ){
  70294. if( pMem1->enc==pColl->enc ){
  70295. /* The strings are already in the correct encoding. Call the
  70296. ** comparison function directly */
  70297. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  70298. }else{
  70299. int rc;
  70300. const void *v1, *v2;
  70301. int n1, n2;
  70302. Mem c1;
  70303. Mem c2;
  70304. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  70305. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  70306. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  70307. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  70308. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  70309. n1 = v1==0 ? 0 : c1.n;
  70310. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  70311. n2 = v2==0 ? 0 : c2.n;
  70312. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  70313. if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  70314. sqlite3VdbeMemRelease(&c1);
  70315. sqlite3VdbeMemRelease(&c2);
  70316. return rc;
  70317. }
  70318. }
  70319. /*
  70320. ** The input pBlob is guaranteed to be a Blob that is not marked
  70321. ** with MEM_Zero. Return true if it could be a zero-blob.
  70322. */
  70323. static int isAllZero(const char *z, int n){
  70324. int i;
  70325. for(i=0; i<n; i++){
  70326. if( z[i] ) return 0;
  70327. }
  70328. return 1;
  70329. }
  70330. /*
  70331. ** Compare two blobs. Return negative, zero, or positive if the first
  70332. ** is less than, equal to, or greater than the second, respectively.
  70333. ** If one blob is a prefix of the other, then the shorter is the lessor.
  70334. */
  70335. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  70336. int c;
  70337. int n1 = pB1->n;
  70338. int n2 = pB2->n;
  70339. /* It is possible to have a Blob value that has some non-zero content
  70340. ** followed by zero content. But that only comes up for Blobs formed
  70341. ** by the OP_MakeRecord opcode, and such Blobs never get passed into
  70342. ** sqlite3MemCompare(). */
  70343. assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
  70344. assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
  70345. if( (pB1->flags|pB2->flags) & MEM_Zero ){
  70346. if( pB1->flags & pB2->flags & MEM_Zero ){
  70347. return pB1->u.nZero - pB2->u.nZero;
  70348. }else if( pB1->flags & MEM_Zero ){
  70349. if( !isAllZero(pB2->z, pB2->n) ) return -1;
  70350. return pB1->u.nZero - n2;
  70351. }else{
  70352. if( !isAllZero(pB1->z, pB1->n) ) return +1;
  70353. return n1 - pB2->u.nZero;
  70354. }
  70355. }
  70356. c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
  70357. if( c ) return c;
  70358. return n1 - n2;
  70359. }
  70360. /*
  70361. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  70362. ** number. Return negative, zero, or positive if the first (i64) is less than,
  70363. ** equal to, or greater than the second (double).
  70364. */
  70365. static int sqlite3IntFloatCompare(i64 i, double r){
  70366. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  70367. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  70368. if( x<r ) return -1;
  70369. if( x>r ) return +1;
  70370. return 0;
  70371. }else{
  70372. i64 y;
  70373. double s;
  70374. if( r<-9223372036854775808.0 ) return +1;
  70375. if( r>9223372036854775807.0 ) return -1;
  70376. y = (i64)r;
  70377. if( i<y ) return -1;
  70378. if( i>y ){
  70379. if( y==SMALLEST_INT64 && r>0.0 ) return -1;
  70380. return +1;
  70381. }
  70382. s = (double)i;
  70383. if( s<r ) return -1;
  70384. if( s>r ) return +1;
  70385. return 0;
  70386. }
  70387. }
  70388. /*
  70389. ** Compare the values contained by the two memory cells, returning
  70390. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  70391. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  70392. ** and reals) sorted numerically, followed by text ordered by the collating
  70393. ** sequence pColl and finally blob's ordered by memcmp().
  70394. **
  70395. ** Two NULL values are considered equal by this function.
  70396. */
  70397. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  70398. int f1, f2;
  70399. int combined_flags;
  70400. f1 = pMem1->flags;
  70401. f2 = pMem2->flags;
  70402. combined_flags = f1|f2;
  70403. assert( (combined_flags & MEM_RowSet)==0 );
  70404. /* If one value is NULL, it is less than the other. If both values
  70405. ** are NULL, return 0.
  70406. */
  70407. if( combined_flags&MEM_Null ){
  70408. return (f2&MEM_Null) - (f1&MEM_Null);
  70409. }
  70410. /* At least one of the two values is a number
  70411. */
  70412. if( combined_flags&(MEM_Int|MEM_Real) ){
  70413. if( (f1 & f2 & MEM_Int)!=0 ){
  70414. if( pMem1->u.i < pMem2->u.i ) return -1;
  70415. if( pMem1->u.i > pMem2->u.i ) return +1;
  70416. return 0;
  70417. }
  70418. if( (f1 & f2 & MEM_Real)!=0 ){
  70419. if( pMem1->u.r < pMem2->u.r ) return -1;
  70420. if( pMem1->u.r > pMem2->u.r ) return +1;
  70421. return 0;
  70422. }
  70423. if( (f1&MEM_Int)!=0 ){
  70424. if( (f2&MEM_Real)!=0 ){
  70425. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  70426. }else{
  70427. return -1;
  70428. }
  70429. }
  70430. if( (f1&MEM_Real)!=0 ){
  70431. if( (f2&MEM_Int)!=0 ){
  70432. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  70433. }else{
  70434. return -1;
  70435. }
  70436. }
  70437. return +1;
  70438. }
  70439. /* If one value is a string and the other is a blob, the string is less.
  70440. ** If both are strings, compare using the collating functions.
  70441. */
  70442. if( combined_flags&MEM_Str ){
  70443. if( (f1 & MEM_Str)==0 ){
  70444. return 1;
  70445. }
  70446. if( (f2 & MEM_Str)==0 ){
  70447. return -1;
  70448. }
  70449. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  70450. assert( pMem1->enc==SQLITE_UTF8 ||
  70451. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  70452. /* The collation sequence must be defined at this point, even if
  70453. ** the user deletes the collation sequence after the vdbe program is
  70454. ** compiled (this was not always the case).
  70455. */
  70456. assert( !pColl || pColl->xCmp );
  70457. if( pColl ){
  70458. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  70459. }
  70460. /* If a NULL pointer was passed as the collate function, fall through
  70461. ** to the blob case and use memcmp(). */
  70462. }
  70463. /* Both values must be blobs. Compare using memcmp(). */
  70464. return sqlite3BlobCompare(pMem1, pMem2);
  70465. }
  70466. /*
  70467. ** The first argument passed to this function is a serial-type that
  70468. ** corresponds to an integer - all values between 1 and 9 inclusive
  70469. ** except 7. The second points to a buffer containing an integer value
  70470. ** serialized according to serial_type. This function deserializes
  70471. ** and returns the value.
  70472. */
  70473. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  70474. u32 y;
  70475. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  70476. switch( serial_type ){
  70477. case 0:
  70478. case 1:
  70479. testcase( aKey[0]&0x80 );
  70480. return ONE_BYTE_INT(aKey);
  70481. case 2:
  70482. testcase( aKey[0]&0x80 );
  70483. return TWO_BYTE_INT(aKey);
  70484. case 3:
  70485. testcase( aKey[0]&0x80 );
  70486. return THREE_BYTE_INT(aKey);
  70487. case 4: {
  70488. testcase( aKey[0]&0x80 );
  70489. y = FOUR_BYTE_UINT(aKey);
  70490. return (i64)*(int*)&y;
  70491. }
  70492. case 5: {
  70493. testcase( aKey[0]&0x80 );
  70494. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  70495. }
  70496. case 6: {
  70497. u64 x = FOUR_BYTE_UINT(aKey);
  70498. testcase( aKey[0]&0x80 );
  70499. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  70500. return (i64)*(i64*)&x;
  70501. }
  70502. }
  70503. return (serial_type - 8);
  70504. }
  70505. /*
  70506. ** This function compares the two table rows or index records
  70507. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  70508. ** or positive integer if key1 is less than, equal to or
  70509. ** greater than key2. The {nKey1, pKey1} key must be a blob
  70510. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  70511. ** key must be a parsed key such as obtained from
  70512. ** sqlite3VdbeParseRecord.
  70513. **
  70514. ** If argument bSkip is non-zero, it is assumed that the caller has already
  70515. ** determined that the first fields of the keys are equal.
  70516. **
  70517. ** Key1 and Key2 do not have to contain the same number of fields. If all
  70518. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  70519. ** returned.
  70520. **
  70521. ** If database corruption is discovered, set pPKey2->errCode to
  70522. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  70523. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  70524. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  70525. */
  70526. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  70527. int nKey1, const void *pKey1, /* Left key */
  70528. UnpackedRecord *pPKey2, /* Right key */
  70529. int bSkip /* If true, skip the first field */
  70530. ){
  70531. u32 d1; /* Offset into aKey[] of next data element */
  70532. int i; /* Index of next field to compare */
  70533. u32 szHdr1; /* Size of record header in bytes */
  70534. u32 idx1; /* Offset of first type in header */
  70535. int rc = 0; /* Return value */
  70536. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  70537. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  70538. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  70539. Mem mem1;
  70540. /* If bSkip is true, then the caller has already determined that the first
  70541. ** two elements in the keys are equal. Fix the various stack variables so
  70542. ** that this routine begins comparing at the second field. */
  70543. if( bSkip ){
  70544. u32 s1;
  70545. idx1 = 1 + getVarint32(&aKey1[1], s1);
  70546. szHdr1 = aKey1[0];
  70547. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  70548. i = 1;
  70549. pRhs++;
  70550. }else{
  70551. idx1 = getVarint32(aKey1, szHdr1);
  70552. d1 = szHdr1;
  70553. if( d1>(unsigned)nKey1 ){
  70554. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  70555. return 0; /* Corruption */
  70556. }
  70557. i = 0;
  70558. }
  70559. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  70560. assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
  70561. || CORRUPT_DB );
  70562. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  70563. assert( pPKey2->pKeyInfo->nField>0 );
  70564. assert( idx1<=szHdr1 || CORRUPT_DB );
  70565. do{
  70566. u32 serial_type;
  70567. /* RHS is an integer */
  70568. if( pRhs->flags & MEM_Int ){
  70569. serial_type = aKey1[idx1];
  70570. testcase( serial_type==12 );
  70571. if( serial_type>=10 ){
  70572. rc = +1;
  70573. }else if( serial_type==0 ){
  70574. rc = -1;
  70575. }else if( serial_type==7 ){
  70576. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  70577. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  70578. }else{
  70579. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  70580. i64 rhs = pRhs->u.i;
  70581. if( lhs<rhs ){
  70582. rc = -1;
  70583. }else if( lhs>rhs ){
  70584. rc = +1;
  70585. }
  70586. }
  70587. }
  70588. /* RHS is real */
  70589. else if( pRhs->flags & MEM_Real ){
  70590. serial_type = aKey1[idx1];
  70591. if( serial_type>=10 ){
  70592. /* Serial types 12 or greater are strings and blobs (greater than
  70593. ** numbers). Types 10 and 11 are currently "reserved for future
  70594. ** use", so it doesn't really matter what the results of comparing
  70595. ** them to numberic values are. */
  70596. rc = +1;
  70597. }else if( serial_type==0 ){
  70598. rc = -1;
  70599. }else{
  70600. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  70601. if( serial_type==7 ){
  70602. if( mem1.u.r<pRhs->u.r ){
  70603. rc = -1;
  70604. }else if( mem1.u.r>pRhs->u.r ){
  70605. rc = +1;
  70606. }
  70607. }else{
  70608. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  70609. }
  70610. }
  70611. }
  70612. /* RHS is a string */
  70613. else if( pRhs->flags & MEM_Str ){
  70614. getVarint32(&aKey1[idx1], serial_type);
  70615. testcase( serial_type==12 );
  70616. if( serial_type<12 ){
  70617. rc = -1;
  70618. }else if( !(serial_type & 0x01) ){
  70619. rc = +1;
  70620. }else{
  70621. mem1.n = (serial_type - 12) / 2;
  70622. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  70623. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  70624. if( (d1+mem1.n) > (unsigned)nKey1 ){
  70625. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  70626. return 0; /* Corruption */
  70627. }else if( pKeyInfo->aColl[i] ){
  70628. mem1.enc = pKeyInfo->enc;
  70629. mem1.db = pKeyInfo->db;
  70630. mem1.flags = MEM_Str;
  70631. mem1.z = (char*)&aKey1[d1];
  70632. rc = vdbeCompareMemString(
  70633. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  70634. );
  70635. }else{
  70636. int nCmp = MIN(mem1.n, pRhs->n);
  70637. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  70638. if( rc==0 ) rc = mem1.n - pRhs->n;
  70639. }
  70640. }
  70641. }
  70642. /* RHS is a blob */
  70643. else if( pRhs->flags & MEM_Blob ){
  70644. assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
  70645. getVarint32(&aKey1[idx1], serial_type);
  70646. testcase( serial_type==12 );
  70647. if( serial_type<12 || (serial_type & 0x01) ){
  70648. rc = -1;
  70649. }else{
  70650. int nStr = (serial_type - 12) / 2;
  70651. testcase( (d1+nStr)==(unsigned)nKey1 );
  70652. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  70653. if( (d1+nStr) > (unsigned)nKey1 ){
  70654. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  70655. return 0; /* Corruption */
  70656. }else if( pRhs->flags & MEM_Zero ){
  70657. if( !isAllZero((const char*)&aKey1[d1],nStr) ){
  70658. rc = 1;
  70659. }else{
  70660. rc = nStr - pRhs->u.nZero;
  70661. }
  70662. }else{
  70663. int nCmp = MIN(nStr, pRhs->n);
  70664. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  70665. if( rc==0 ) rc = nStr - pRhs->n;
  70666. }
  70667. }
  70668. }
  70669. /* RHS is null */
  70670. else{
  70671. serial_type = aKey1[idx1];
  70672. rc = (serial_type!=0);
  70673. }
  70674. if( rc!=0 ){
  70675. if( pKeyInfo->aSortOrder[i] ){
  70676. rc = -rc;
  70677. }
  70678. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  70679. assert( mem1.szMalloc==0 ); /* See comment below */
  70680. return rc;
  70681. }
  70682. i++;
  70683. pRhs++;
  70684. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  70685. idx1 += sqlite3VarintLen(serial_type);
  70686. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  70687. /* No memory allocation is ever used on mem1. Prove this using
  70688. ** the following assert(). If the assert() fails, it indicates a
  70689. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  70690. assert( mem1.szMalloc==0 );
  70691. /* rc==0 here means that one or both of the keys ran out of fields and
  70692. ** all the fields up to that point were equal. Return the default_rc
  70693. ** value. */
  70694. assert( CORRUPT_DB
  70695. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  70696. || pKeyInfo->db->mallocFailed
  70697. );
  70698. pPKey2->eqSeen = 1;
  70699. return pPKey2->default_rc;
  70700. }
  70701. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  70702. int nKey1, const void *pKey1, /* Left key */
  70703. UnpackedRecord *pPKey2 /* Right key */
  70704. ){
  70705. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  70706. }
  70707. /*
  70708. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  70709. ** that (a) the first field of pPKey2 is an integer, and (b) the
  70710. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  70711. ** byte (i.e. is less than 128).
  70712. **
  70713. ** To avoid concerns about buffer overreads, this routine is only used
  70714. ** on schemas where the maximum valid header size is 63 bytes or less.
  70715. */
  70716. static int vdbeRecordCompareInt(
  70717. int nKey1, const void *pKey1, /* Left key */
  70718. UnpackedRecord *pPKey2 /* Right key */
  70719. ){
  70720. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  70721. int serial_type = ((const u8*)pKey1)[1];
  70722. int res;
  70723. u32 y;
  70724. u64 x;
  70725. i64 v;
  70726. i64 lhs;
  70727. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  70728. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  70729. switch( serial_type ){
  70730. case 1: { /* 1-byte signed integer */
  70731. lhs = ONE_BYTE_INT(aKey);
  70732. testcase( lhs<0 );
  70733. break;
  70734. }
  70735. case 2: { /* 2-byte signed integer */
  70736. lhs = TWO_BYTE_INT(aKey);
  70737. testcase( lhs<0 );
  70738. break;
  70739. }
  70740. case 3: { /* 3-byte signed integer */
  70741. lhs = THREE_BYTE_INT(aKey);
  70742. testcase( lhs<0 );
  70743. break;
  70744. }
  70745. case 4: { /* 4-byte signed integer */
  70746. y = FOUR_BYTE_UINT(aKey);
  70747. lhs = (i64)*(int*)&y;
  70748. testcase( lhs<0 );
  70749. break;
  70750. }
  70751. case 5: { /* 6-byte signed integer */
  70752. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  70753. testcase( lhs<0 );
  70754. break;
  70755. }
  70756. case 6: { /* 8-byte signed integer */
  70757. x = FOUR_BYTE_UINT(aKey);
  70758. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  70759. lhs = *(i64*)&x;
  70760. testcase( lhs<0 );
  70761. break;
  70762. }
  70763. case 8:
  70764. lhs = 0;
  70765. break;
  70766. case 9:
  70767. lhs = 1;
  70768. break;
  70769. /* This case could be removed without changing the results of running
  70770. ** this code. Including it causes gcc to generate a faster switch
  70771. ** statement (since the range of switch targets now starts at zero and
  70772. ** is contiguous) but does not cause any duplicate code to be generated
  70773. ** (as gcc is clever enough to combine the two like cases). Other
  70774. ** compilers might be similar. */
  70775. case 0: case 7:
  70776. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  70777. default:
  70778. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  70779. }
  70780. v = pPKey2->aMem[0].u.i;
  70781. if( v>lhs ){
  70782. res = pPKey2->r1;
  70783. }else if( v<lhs ){
  70784. res = pPKey2->r2;
  70785. }else if( pPKey2->nField>1 ){
  70786. /* The first fields of the two keys are equal. Compare the trailing
  70787. ** fields. */
  70788. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  70789. }else{
  70790. /* The first fields of the two keys are equal and there are no trailing
  70791. ** fields. Return pPKey2->default_rc in this case. */
  70792. res = pPKey2->default_rc;
  70793. pPKey2->eqSeen = 1;
  70794. }
  70795. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  70796. return res;
  70797. }
  70798. /*
  70799. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  70800. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  70801. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  70802. ** at the start of (pKey1/nKey1) fits in a single byte.
  70803. */
  70804. static int vdbeRecordCompareString(
  70805. int nKey1, const void *pKey1, /* Left key */
  70806. UnpackedRecord *pPKey2 /* Right key */
  70807. ){
  70808. const u8 *aKey1 = (const u8*)pKey1;
  70809. int serial_type;
  70810. int res;
  70811. assert( pPKey2->aMem[0].flags & MEM_Str );
  70812. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  70813. getVarint32(&aKey1[1], serial_type);
  70814. if( serial_type<12 ){
  70815. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  70816. }else if( !(serial_type & 0x01) ){
  70817. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  70818. }else{
  70819. int nCmp;
  70820. int nStr;
  70821. int szHdr = aKey1[0];
  70822. nStr = (serial_type-12) / 2;
  70823. if( (szHdr + nStr) > nKey1 ){
  70824. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  70825. return 0; /* Corruption */
  70826. }
  70827. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  70828. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  70829. if( res==0 ){
  70830. res = nStr - pPKey2->aMem[0].n;
  70831. if( res==0 ){
  70832. if( pPKey2->nField>1 ){
  70833. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  70834. }else{
  70835. res = pPKey2->default_rc;
  70836. pPKey2->eqSeen = 1;
  70837. }
  70838. }else if( res>0 ){
  70839. res = pPKey2->r2;
  70840. }else{
  70841. res = pPKey2->r1;
  70842. }
  70843. }else if( res>0 ){
  70844. res = pPKey2->r2;
  70845. }else{
  70846. res = pPKey2->r1;
  70847. }
  70848. }
  70849. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  70850. || CORRUPT_DB
  70851. || pPKey2->pKeyInfo->db->mallocFailed
  70852. );
  70853. return res;
  70854. }
  70855. /*
  70856. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  70857. ** suitable for comparing serialized records to the unpacked record passed
  70858. ** as the only argument.
  70859. */
  70860. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  70861. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  70862. ** that the size-of-header varint that occurs at the start of each record
  70863. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  70864. ** also assumes that it is safe to overread a buffer by at least the
  70865. ** maximum possible legal header size plus 8 bytes. Because there is
  70866. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  70867. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  70868. ** limit the size of the header to 64 bytes in cases where the first field
  70869. ** is an integer.
  70870. **
  70871. ** The easiest way to enforce this limit is to consider only records with
  70872. ** 13 fields or less. If the first field is an integer, the maximum legal
  70873. ** header size is (12*5 + 1 + 1) bytes. */
  70874. if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
  70875. int flags = p->aMem[0].flags;
  70876. if( p->pKeyInfo->aSortOrder[0] ){
  70877. p->r1 = 1;
  70878. p->r2 = -1;
  70879. }else{
  70880. p->r1 = -1;
  70881. p->r2 = 1;
  70882. }
  70883. if( (flags & MEM_Int) ){
  70884. return vdbeRecordCompareInt;
  70885. }
  70886. testcase( flags & MEM_Real );
  70887. testcase( flags & MEM_Null );
  70888. testcase( flags & MEM_Blob );
  70889. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  70890. assert( flags & MEM_Str );
  70891. return vdbeRecordCompareString;
  70892. }
  70893. }
  70894. return sqlite3VdbeRecordCompare;
  70895. }
  70896. /*
  70897. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  70898. ** Read the rowid (the last field in the record) and store it in *rowid.
  70899. ** Return SQLITE_OK if everything works, or an error code otherwise.
  70900. **
  70901. ** pCur might be pointing to text obtained from a corrupt database file.
  70902. ** So the content cannot be trusted. Do appropriate checks on the content.
  70903. */
  70904. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  70905. i64 nCellKey = 0;
  70906. int rc;
  70907. u32 szHdr; /* Size of the header */
  70908. u32 typeRowid; /* Serial type of the rowid */
  70909. u32 lenRowid; /* Size of the rowid */
  70910. Mem m, v;
  70911. /* Get the size of the index entry. Only indices entries of less
  70912. ** than 2GiB are support - anything large must be database corruption.
  70913. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  70914. ** this code can safely assume that nCellKey is 32-bits
  70915. */
  70916. assert( sqlite3BtreeCursorIsValid(pCur) );
  70917. nCellKey = sqlite3BtreePayloadSize(pCur);
  70918. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  70919. /* Read in the complete content of the index entry */
  70920. sqlite3VdbeMemInit(&m, db, 0);
  70921. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  70922. if( rc ){
  70923. return rc;
  70924. }
  70925. /* The index entry must begin with a header size */
  70926. (void)getVarint32((u8*)m.z, szHdr);
  70927. testcase( szHdr==3 );
  70928. testcase( szHdr==m.n );
  70929. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  70930. goto idx_rowid_corruption;
  70931. }
  70932. /* The last field of the index should be an integer - the ROWID.
  70933. ** Verify that the last entry really is an integer. */
  70934. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  70935. testcase( typeRowid==1 );
  70936. testcase( typeRowid==2 );
  70937. testcase( typeRowid==3 );
  70938. testcase( typeRowid==4 );
  70939. testcase( typeRowid==5 );
  70940. testcase( typeRowid==6 );
  70941. testcase( typeRowid==8 );
  70942. testcase( typeRowid==9 );
  70943. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  70944. goto idx_rowid_corruption;
  70945. }
  70946. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  70947. testcase( (u32)m.n==szHdr+lenRowid );
  70948. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  70949. goto idx_rowid_corruption;
  70950. }
  70951. /* Fetch the integer off the end of the index record */
  70952. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  70953. *rowid = v.u.i;
  70954. sqlite3VdbeMemRelease(&m);
  70955. return SQLITE_OK;
  70956. /* Jump here if database corruption is detected after m has been
  70957. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  70958. idx_rowid_corruption:
  70959. testcase( m.szMalloc!=0 );
  70960. sqlite3VdbeMemRelease(&m);
  70961. return SQLITE_CORRUPT_BKPT;
  70962. }
  70963. /*
  70964. ** Compare the key of the index entry that cursor pC is pointing to against
  70965. ** the key string in pUnpacked. Write into *pRes a number
  70966. ** that is negative, zero, or positive if pC is less than, equal to,
  70967. ** or greater than pUnpacked. Return SQLITE_OK on success.
  70968. **
  70969. ** pUnpacked is either created without a rowid or is truncated so that it
  70970. ** omits the rowid at the end. The rowid at the end of the index entry
  70971. ** is ignored as well. Hence, this routine only compares the prefixes
  70972. ** of the keys prior to the final rowid, not the entire key.
  70973. */
  70974. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  70975. sqlite3 *db, /* Database connection */
  70976. VdbeCursor *pC, /* The cursor to compare against */
  70977. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  70978. int *res /* Write the comparison result here */
  70979. ){
  70980. i64 nCellKey = 0;
  70981. int rc;
  70982. BtCursor *pCur;
  70983. Mem m;
  70984. assert( pC->eCurType==CURTYPE_BTREE );
  70985. pCur = pC->uc.pCursor;
  70986. assert( sqlite3BtreeCursorIsValid(pCur) );
  70987. nCellKey = sqlite3BtreePayloadSize(pCur);
  70988. /* nCellKey will always be between 0 and 0xffffffff because of the way
  70989. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  70990. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  70991. *res = 0;
  70992. return SQLITE_CORRUPT_BKPT;
  70993. }
  70994. sqlite3VdbeMemInit(&m, db, 0);
  70995. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  70996. if( rc ){
  70997. return rc;
  70998. }
  70999. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  71000. sqlite3VdbeMemRelease(&m);
  71001. return SQLITE_OK;
  71002. }
  71003. /*
  71004. ** This routine sets the value to be returned by subsequent calls to
  71005. ** sqlite3_changes() on the database handle 'db'.
  71006. */
  71007. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  71008. assert( sqlite3_mutex_held(db->mutex) );
  71009. db->nChange = nChange;
  71010. db->nTotalChange += nChange;
  71011. }
  71012. /*
  71013. ** Set a flag in the vdbe to update the change counter when it is finalised
  71014. ** or reset.
  71015. */
  71016. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  71017. v->changeCntOn = 1;
  71018. }
  71019. /*
  71020. ** Mark every prepared statement associated with a database connection
  71021. ** as expired.
  71022. **
  71023. ** An expired statement means that recompilation of the statement is
  71024. ** recommend. Statements expire when things happen that make their
  71025. ** programs obsolete. Removing user-defined functions or collating
  71026. ** sequences, or changing an authorization function are the types of
  71027. ** things that make prepared statements obsolete.
  71028. */
  71029. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  71030. Vdbe *p;
  71031. for(p = db->pVdbe; p; p=p->pNext){
  71032. p->expired = 1;
  71033. }
  71034. }
  71035. /*
  71036. ** Return the database associated with the Vdbe.
  71037. */
  71038. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  71039. return v->db;
  71040. }
  71041. /*
  71042. ** Return a pointer to an sqlite3_value structure containing the value bound
  71043. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  71044. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  71045. ** constants) to the value before returning it.
  71046. **
  71047. ** The returned value must be freed by the caller using sqlite3ValueFree().
  71048. */
  71049. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  71050. assert( iVar>0 );
  71051. if( v ){
  71052. Mem *pMem = &v->aVar[iVar-1];
  71053. if( 0==(pMem->flags & MEM_Null) ){
  71054. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  71055. if( pRet ){
  71056. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  71057. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  71058. }
  71059. return pRet;
  71060. }
  71061. }
  71062. return 0;
  71063. }
  71064. /*
  71065. ** Configure SQL variable iVar so that binding a new value to it signals
  71066. ** to sqlite3_reoptimize() that re-preparing the statement may result
  71067. ** in a better query plan.
  71068. */
  71069. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  71070. assert( iVar>0 );
  71071. if( iVar>=32 ){
  71072. v->expmask |= 0x80000000;
  71073. }else{
  71074. v->expmask |= ((u32)1 << (iVar-1));
  71075. }
  71076. }
  71077. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71078. /*
  71079. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  71080. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  71081. ** in memory obtained from sqlite3DbMalloc).
  71082. */
  71083. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  71084. if( pVtab->zErrMsg ){
  71085. sqlite3 *db = p->db;
  71086. sqlite3DbFree(db, p->zErrMsg);
  71087. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  71088. sqlite3_free(pVtab->zErrMsg);
  71089. pVtab->zErrMsg = 0;
  71090. }
  71091. }
  71092. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  71093. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  71094. /*
  71095. ** If the second argument is not NULL, release any allocations associated
  71096. ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
  71097. ** structure itself, using sqlite3DbFree().
  71098. **
  71099. ** This function is used to free UnpackedRecord structures allocated by
  71100. ** the vdbeUnpackRecord() function found in vdbeapi.c.
  71101. */
  71102. static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
  71103. if( p ){
  71104. int i;
  71105. for(i=0; i<nField; i++){
  71106. Mem *pMem = &p->aMem[i];
  71107. if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
  71108. }
  71109. sqlite3DbFreeNN(db, p);
  71110. }
  71111. }
  71112. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  71113. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  71114. /*
  71115. ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
  71116. ** then cursor passed as the second argument should point to the row about
  71117. ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
  71118. ** the required value will be read from the row the cursor points to.
  71119. */
  71120. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
  71121. Vdbe *v, /* Vdbe pre-update hook is invoked by */
  71122. VdbeCursor *pCsr, /* Cursor to grab old.* values from */
  71123. int op, /* SQLITE_INSERT, UPDATE or DELETE */
  71124. const char *zDb, /* Database name */
  71125. Table *pTab, /* Modified table */
  71126. i64 iKey1, /* Initial key value */
  71127. int iReg /* Register for new.* record */
  71128. ){
  71129. sqlite3 *db = v->db;
  71130. i64 iKey2;
  71131. PreUpdate preupdate;
  71132. const char *zTbl = pTab->zName;
  71133. static const u8 fakeSortOrder = 0;
  71134. assert( db->pPreUpdate==0 );
  71135. memset(&preupdate, 0, sizeof(PreUpdate));
  71136. if( HasRowid(pTab)==0 ){
  71137. iKey1 = iKey2 = 0;
  71138. preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  71139. }else{
  71140. if( op==SQLITE_UPDATE ){
  71141. iKey2 = v->aMem[iReg].u.i;
  71142. }else{
  71143. iKey2 = iKey1;
  71144. }
  71145. }
  71146. assert( pCsr->nField==pTab->nCol
  71147. || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  71148. );
  71149. preupdate.v = v;
  71150. preupdate.pCsr = pCsr;
  71151. preupdate.op = op;
  71152. preupdate.iNewReg = iReg;
  71153. preupdate.keyinfo.db = db;
  71154. preupdate.keyinfo.enc = ENC(db);
  71155. preupdate.keyinfo.nField = pTab->nCol;
  71156. preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
  71157. preupdate.iKey1 = iKey1;
  71158. preupdate.iKey2 = iKey2;
  71159. preupdate.pTab = pTab;
  71160. db->pPreUpdate = &preupdate;
  71161. db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
  71162. db->pPreUpdate = 0;
  71163. sqlite3DbFree(db, preupdate.aRecord);
  71164. vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pUnpacked);
  71165. vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pNewUnpacked);
  71166. if( preupdate.aNew ){
  71167. int i;
  71168. for(i=0; i<pCsr->nField; i++){
  71169. sqlite3VdbeMemRelease(&preupdate.aNew[i]);
  71170. }
  71171. sqlite3DbFreeNN(db, preupdate.aNew);
  71172. }
  71173. }
  71174. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  71175. /************** End of vdbeaux.c *********************************************/
  71176. /************** Begin file vdbeapi.c *****************************************/
  71177. /*
  71178. ** 2004 May 26
  71179. **
  71180. ** The author disclaims copyright to this source code. In place of
  71181. ** a legal notice, here is a blessing:
  71182. **
  71183. ** May you do good and not evil.
  71184. ** May you find forgiveness for yourself and forgive others.
  71185. ** May you share freely, never taking more than you give.
  71186. **
  71187. *************************************************************************
  71188. **
  71189. ** This file contains code use to implement APIs that are part of the
  71190. ** VDBE.
  71191. */
  71192. /* #include "sqliteInt.h" */
  71193. /* #include "vdbeInt.h" */
  71194. #ifndef SQLITE_OMIT_DEPRECATED
  71195. /*
  71196. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  71197. ** to be recompiled. A statement needs to be recompiled whenever the
  71198. ** execution environment changes in a way that would alter the program
  71199. ** that sqlite3_prepare() generates. For example, if new functions or
  71200. ** collating sequences are registered or if an authorizer function is
  71201. ** added or changed.
  71202. */
  71203. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  71204. Vdbe *p = (Vdbe*)pStmt;
  71205. return p==0 || p->expired;
  71206. }
  71207. #endif
  71208. /*
  71209. ** Check on a Vdbe to make sure it has not been finalized. Log
  71210. ** an error and return true if it has been finalized (or is otherwise
  71211. ** invalid). Return false if it is ok.
  71212. */
  71213. static int vdbeSafety(Vdbe *p){
  71214. if( p->db==0 ){
  71215. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  71216. return 1;
  71217. }else{
  71218. return 0;
  71219. }
  71220. }
  71221. static int vdbeSafetyNotNull(Vdbe *p){
  71222. if( p==0 ){
  71223. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  71224. return 1;
  71225. }else{
  71226. return vdbeSafety(p);
  71227. }
  71228. }
  71229. #ifndef SQLITE_OMIT_TRACE
  71230. /*
  71231. ** Invoke the profile callback. This routine is only called if we already
  71232. ** know that the profile callback is defined and needs to be invoked.
  71233. */
  71234. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  71235. sqlite3_int64 iNow;
  71236. sqlite3_int64 iElapse;
  71237. assert( p->startTime>0 );
  71238. assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
  71239. assert( db->init.busy==0 );
  71240. assert( p->zSql!=0 );
  71241. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  71242. iElapse = (iNow - p->startTime)*1000000;
  71243. if( db->xProfile ){
  71244. db->xProfile(db->pProfileArg, p->zSql, iElapse);
  71245. }
  71246. if( db->mTrace & SQLITE_TRACE_PROFILE ){
  71247. db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
  71248. }
  71249. p->startTime = 0;
  71250. }
  71251. /*
  71252. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  71253. ** is needed, and it invokes the callback if it is needed.
  71254. */
  71255. # define checkProfileCallback(DB,P) \
  71256. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  71257. #else
  71258. # define checkProfileCallback(DB,P) /*no-op*/
  71259. #endif
  71260. /*
  71261. ** The following routine destroys a virtual machine that is created by
  71262. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  71263. ** success/failure code that describes the result of executing the virtual
  71264. ** machine.
  71265. **
  71266. ** This routine sets the error code and string returned by
  71267. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  71268. */
  71269. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  71270. int rc;
  71271. if( pStmt==0 ){
  71272. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  71273. ** pointer is a harmless no-op. */
  71274. rc = SQLITE_OK;
  71275. }else{
  71276. Vdbe *v = (Vdbe*)pStmt;
  71277. sqlite3 *db = v->db;
  71278. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  71279. sqlite3_mutex_enter(db->mutex);
  71280. checkProfileCallback(db, v);
  71281. rc = sqlite3VdbeFinalize(v);
  71282. rc = sqlite3ApiExit(db, rc);
  71283. sqlite3LeaveMutexAndCloseZombie(db);
  71284. }
  71285. return rc;
  71286. }
  71287. /*
  71288. ** Terminate the current execution of an SQL statement and reset it
  71289. ** back to its starting state so that it can be reused. A success code from
  71290. ** the prior execution is returned.
  71291. **
  71292. ** This routine sets the error code and string returned by
  71293. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  71294. */
  71295. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  71296. int rc;
  71297. if( pStmt==0 ){
  71298. rc = SQLITE_OK;
  71299. }else{
  71300. Vdbe *v = (Vdbe*)pStmt;
  71301. sqlite3 *db = v->db;
  71302. sqlite3_mutex_enter(db->mutex);
  71303. checkProfileCallback(db, v);
  71304. rc = sqlite3VdbeReset(v);
  71305. sqlite3VdbeRewind(v);
  71306. assert( (rc & (db->errMask))==rc );
  71307. rc = sqlite3ApiExit(db, rc);
  71308. sqlite3_mutex_leave(db->mutex);
  71309. }
  71310. return rc;
  71311. }
  71312. /*
  71313. ** Set all the parameters in the compiled SQL statement to NULL.
  71314. */
  71315. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  71316. int i;
  71317. int rc = SQLITE_OK;
  71318. Vdbe *p = (Vdbe*)pStmt;
  71319. #if SQLITE_THREADSAFE
  71320. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  71321. #endif
  71322. sqlite3_mutex_enter(mutex);
  71323. for(i=0; i<p->nVar; i++){
  71324. sqlite3VdbeMemRelease(&p->aVar[i]);
  71325. p->aVar[i].flags = MEM_Null;
  71326. }
  71327. assert( p->isPrepareV2 || p->expmask==0 );
  71328. if( p->expmask ){
  71329. p->expired = 1;
  71330. }
  71331. sqlite3_mutex_leave(mutex);
  71332. return rc;
  71333. }
  71334. /**************************** sqlite3_value_ *******************************
  71335. ** The following routines extract information from a Mem or sqlite3_value
  71336. ** structure.
  71337. */
  71338. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  71339. Mem *p = (Mem*)pVal;
  71340. if( p->flags & (MEM_Blob|MEM_Str) ){
  71341. if( ExpandBlob(p)!=SQLITE_OK ){
  71342. assert( p->flags==MEM_Null && p->z==0 );
  71343. return 0;
  71344. }
  71345. p->flags |= MEM_Blob;
  71346. return p->n ? p->z : 0;
  71347. }else{
  71348. return sqlite3_value_text(pVal);
  71349. }
  71350. }
  71351. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  71352. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  71353. }
  71354. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  71355. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  71356. }
  71357. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  71358. return sqlite3VdbeRealValue((Mem*)pVal);
  71359. }
  71360. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  71361. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  71362. }
  71363. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  71364. return sqlite3VdbeIntValue((Mem*)pVal);
  71365. }
  71366. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
  71367. Mem *pMem = (Mem*)pVal;
  71368. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  71369. }
  71370. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  71371. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  71372. }
  71373. #ifndef SQLITE_OMIT_UTF16
  71374. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  71375. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  71376. }
  71377. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  71378. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  71379. }
  71380. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  71381. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  71382. }
  71383. #endif /* SQLITE_OMIT_UTF16 */
  71384. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  71385. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  71386. ** point number string BLOB NULL
  71387. */
  71388. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  71389. static const u8 aType[] = {
  71390. SQLITE_BLOB, /* 0x00 */
  71391. SQLITE_NULL, /* 0x01 */
  71392. SQLITE_TEXT, /* 0x02 */
  71393. SQLITE_NULL, /* 0x03 */
  71394. SQLITE_INTEGER, /* 0x04 */
  71395. SQLITE_NULL, /* 0x05 */
  71396. SQLITE_INTEGER, /* 0x06 */
  71397. SQLITE_NULL, /* 0x07 */
  71398. SQLITE_FLOAT, /* 0x08 */
  71399. SQLITE_NULL, /* 0x09 */
  71400. SQLITE_FLOAT, /* 0x0a */
  71401. SQLITE_NULL, /* 0x0b */
  71402. SQLITE_INTEGER, /* 0x0c */
  71403. SQLITE_NULL, /* 0x0d */
  71404. SQLITE_INTEGER, /* 0x0e */
  71405. SQLITE_NULL, /* 0x0f */
  71406. SQLITE_BLOB, /* 0x10 */
  71407. SQLITE_NULL, /* 0x11 */
  71408. SQLITE_TEXT, /* 0x12 */
  71409. SQLITE_NULL, /* 0x13 */
  71410. SQLITE_INTEGER, /* 0x14 */
  71411. SQLITE_NULL, /* 0x15 */
  71412. SQLITE_INTEGER, /* 0x16 */
  71413. SQLITE_NULL, /* 0x17 */
  71414. SQLITE_FLOAT, /* 0x18 */
  71415. SQLITE_NULL, /* 0x19 */
  71416. SQLITE_FLOAT, /* 0x1a */
  71417. SQLITE_NULL, /* 0x1b */
  71418. SQLITE_INTEGER, /* 0x1c */
  71419. SQLITE_NULL, /* 0x1d */
  71420. SQLITE_INTEGER, /* 0x1e */
  71421. SQLITE_NULL, /* 0x1f */
  71422. };
  71423. return aType[pVal->flags&MEM_AffMask];
  71424. }
  71425. /* Make a copy of an sqlite3_value object
  71426. */
  71427. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
  71428. sqlite3_value *pNew;
  71429. if( pOrig==0 ) return 0;
  71430. pNew = sqlite3_malloc( sizeof(*pNew) );
  71431. if( pNew==0 ) return 0;
  71432. memset(pNew, 0, sizeof(*pNew));
  71433. memcpy(pNew, pOrig, MEMCELLSIZE);
  71434. pNew->flags &= ~MEM_Dyn;
  71435. pNew->db = 0;
  71436. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  71437. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  71438. pNew->flags |= MEM_Ephem;
  71439. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  71440. sqlite3ValueFree(pNew);
  71441. pNew = 0;
  71442. }
  71443. }
  71444. return pNew;
  71445. }
  71446. /* Destroy an sqlite3_value object previously obtained from
  71447. ** sqlite3_value_dup().
  71448. */
  71449. SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
  71450. sqlite3ValueFree(pOld);
  71451. }
  71452. /**************************** sqlite3_result_ *******************************
  71453. ** The following routines are used by user-defined functions to specify
  71454. ** the function result.
  71455. **
  71456. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  71457. ** result as a string or blob but if the string or blob is too large, it
  71458. ** then sets the error code to SQLITE_TOOBIG
  71459. **
  71460. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  71461. ** on value P is not going to be used and need to be destroyed.
  71462. */
  71463. static void setResultStrOrError(
  71464. sqlite3_context *pCtx, /* Function context */
  71465. const char *z, /* String pointer */
  71466. int n, /* Bytes in string, or negative */
  71467. u8 enc, /* Encoding of z. 0 for BLOBs */
  71468. void (*xDel)(void*) /* Destructor function */
  71469. ){
  71470. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  71471. sqlite3_result_error_toobig(pCtx);
  71472. }
  71473. }
  71474. static int invokeValueDestructor(
  71475. const void *p, /* Value to destroy */
  71476. void (*xDel)(void*), /* The destructor */
  71477. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  71478. ){
  71479. assert( xDel!=SQLITE_DYNAMIC );
  71480. if( xDel==0 ){
  71481. /* noop */
  71482. }else if( xDel==SQLITE_TRANSIENT ){
  71483. /* noop */
  71484. }else{
  71485. xDel((void*)p);
  71486. }
  71487. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  71488. return SQLITE_TOOBIG;
  71489. }
  71490. SQLITE_API void sqlite3_result_blob(
  71491. sqlite3_context *pCtx,
  71492. const void *z,
  71493. int n,
  71494. void (*xDel)(void *)
  71495. ){
  71496. assert( n>=0 );
  71497. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71498. setResultStrOrError(pCtx, z, n, 0, xDel);
  71499. }
  71500. SQLITE_API void sqlite3_result_blob64(
  71501. sqlite3_context *pCtx,
  71502. const void *z,
  71503. sqlite3_uint64 n,
  71504. void (*xDel)(void *)
  71505. ){
  71506. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71507. assert( xDel!=SQLITE_DYNAMIC );
  71508. if( n>0x7fffffff ){
  71509. (void)invokeValueDestructor(z, xDel, pCtx);
  71510. }else{
  71511. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  71512. }
  71513. }
  71514. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  71515. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71516. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  71517. }
  71518. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  71519. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71520. pCtx->isError = SQLITE_ERROR;
  71521. pCtx->fErrorOrAux = 1;
  71522. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  71523. }
  71524. #ifndef SQLITE_OMIT_UTF16
  71525. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  71526. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71527. pCtx->isError = SQLITE_ERROR;
  71528. pCtx->fErrorOrAux = 1;
  71529. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  71530. }
  71531. #endif
  71532. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  71533. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71534. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  71535. }
  71536. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  71537. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71538. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  71539. }
  71540. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  71541. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71542. sqlite3VdbeMemSetNull(pCtx->pOut);
  71543. }
  71544. SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  71545. Mem *pOut = pCtx->pOut;
  71546. assert( sqlite3_mutex_held(pOut->db->mutex) );
  71547. pOut->eSubtype = eSubtype & 0xff;
  71548. pOut->flags |= MEM_Subtype;
  71549. }
  71550. SQLITE_API void sqlite3_result_text(
  71551. sqlite3_context *pCtx,
  71552. const char *z,
  71553. int n,
  71554. void (*xDel)(void *)
  71555. ){
  71556. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71557. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  71558. }
  71559. SQLITE_API void sqlite3_result_text64(
  71560. sqlite3_context *pCtx,
  71561. const char *z,
  71562. sqlite3_uint64 n,
  71563. void (*xDel)(void *),
  71564. unsigned char enc
  71565. ){
  71566. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71567. assert( xDel!=SQLITE_DYNAMIC );
  71568. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  71569. if( n>0x7fffffff ){
  71570. (void)invokeValueDestructor(z, xDel, pCtx);
  71571. }else{
  71572. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  71573. }
  71574. }
  71575. #ifndef SQLITE_OMIT_UTF16
  71576. SQLITE_API void sqlite3_result_text16(
  71577. sqlite3_context *pCtx,
  71578. const void *z,
  71579. int n,
  71580. void (*xDel)(void *)
  71581. ){
  71582. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71583. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  71584. }
  71585. SQLITE_API void sqlite3_result_text16be(
  71586. sqlite3_context *pCtx,
  71587. const void *z,
  71588. int n,
  71589. void (*xDel)(void *)
  71590. ){
  71591. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71592. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  71593. }
  71594. SQLITE_API void sqlite3_result_text16le(
  71595. sqlite3_context *pCtx,
  71596. const void *z,
  71597. int n,
  71598. void (*xDel)(void *)
  71599. ){
  71600. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71601. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  71602. }
  71603. #endif /* SQLITE_OMIT_UTF16 */
  71604. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  71605. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71606. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  71607. }
  71608. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  71609. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71610. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  71611. }
  71612. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  71613. Mem *pOut = pCtx->pOut;
  71614. assert( sqlite3_mutex_held(pOut->db->mutex) );
  71615. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  71616. return SQLITE_TOOBIG;
  71617. }
  71618. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  71619. return SQLITE_OK;
  71620. }
  71621. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  71622. pCtx->isError = errCode;
  71623. pCtx->fErrorOrAux = 1;
  71624. #ifdef SQLITE_DEBUG
  71625. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  71626. #endif
  71627. if( pCtx->pOut->flags & MEM_Null ){
  71628. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  71629. SQLITE_UTF8, SQLITE_STATIC);
  71630. }
  71631. }
  71632. /* Force an SQLITE_TOOBIG error. */
  71633. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  71634. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71635. pCtx->isError = SQLITE_TOOBIG;
  71636. pCtx->fErrorOrAux = 1;
  71637. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  71638. SQLITE_UTF8, SQLITE_STATIC);
  71639. }
  71640. /* An SQLITE_NOMEM error. */
  71641. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  71642. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71643. sqlite3VdbeMemSetNull(pCtx->pOut);
  71644. pCtx->isError = SQLITE_NOMEM_BKPT;
  71645. pCtx->fErrorOrAux = 1;
  71646. sqlite3OomFault(pCtx->pOut->db);
  71647. }
  71648. /*
  71649. ** This function is called after a transaction has been committed. It
  71650. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  71651. */
  71652. static int doWalCallbacks(sqlite3 *db){
  71653. int rc = SQLITE_OK;
  71654. #ifndef SQLITE_OMIT_WAL
  71655. int i;
  71656. for(i=0; i<db->nDb; i++){
  71657. Btree *pBt = db->aDb[i].pBt;
  71658. if( pBt ){
  71659. int nEntry;
  71660. sqlite3BtreeEnter(pBt);
  71661. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  71662. sqlite3BtreeLeave(pBt);
  71663. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  71664. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
  71665. }
  71666. }
  71667. }
  71668. #endif
  71669. return rc;
  71670. }
  71671. /*
  71672. ** Execute the statement pStmt, either until a row of data is ready, the
  71673. ** statement is completely executed or an error occurs.
  71674. **
  71675. ** This routine implements the bulk of the logic behind the sqlite_step()
  71676. ** API. The only thing omitted is the automatic recompile if a
  71677. ** schema change has occurred. That detail is handled by the
  71678. ** outer sqlite3_step() wrapper procedure.
  71679. */
  71680. static int sqlite3Step(Vdbe *p){
  71681. sqlite3 *db;
  71682. int rc;
  71683. assert(p);
  71684. if( p->magic!=VDBE_MAGIC_RUN ){
  71685. /* We used to require that sqlite3_reset() be called before retrying
  71686. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  71687. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  71688. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  71689. ** This "automatic-reset" change is not technically an incompatibility,
  71690. ** since any application that receives an SQLITE_MISUSE is broken by
  71691. ** definition.
  71692. **
  71693. ** Nevertheless, some published applications that were originally written
  71694. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  71695. ** returns, and those were broken by the automatic-reset change. As a
  71696. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  71697. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  71698. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  71699. ** or SQLITE_BUSY error.
  71700. */
  71701. #ifdef SQLITE_OMIT_AUTORESET
  71702. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  71703. sqlite3_reset((sqlite3_stmt*)p);
  71704. }else{
  71705. return SQLITE_MISUSE_BKPT;
  71706. }
  71707. #else
  71708. sqlite3_reset((sqlite3_stmt*)p);
  71709. #endif
  71710. }
  71711. /* Check that malloc() has not failed. If it has, return early. */
  71712. db = p->db;
  71713. if( db->mallocFailed ){
  71714. p->rc = SQLITE_NOMEM;
  71715. return SQLITE_NOMEM_BKPT;
  71716. }
  71717. if( p->pc<=0 && p->expired ){
  71718. p->rc = SQLITE_SCHEMA;
  71719. rc = SQLITE_ERROR;
  71720. goto end_of_step;
  71721. }
  71722. if( p->pc<0 ){
  71723. /* If there are no other statements currently running, then
  71724. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  71725. ** from interrupting a statement that has not yet started.
  71726. */
  71727. if( db->nVdbeActive==0 ){
  71728. db->u1.isInterrupted = 0;
  71729. }
  71730. assert( db->nVdbeWrite>0 || db->autoCommit==0
  71731. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  71732. );
  71733. #ifndef SQLITE_OMIT_TRACE
  71734. if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
  71735. && !db->init.busy && p->zSql ){
  71736. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  71737. }else{
  71738. assert( p->startTime==0 );
  71739. }
  71740. #endif
  71741. db->nVdbeActive++;
  71742. if( p->readOnly==0 ) db->nVdbeWrite++;
  71743. if( p->bIsReader ) db->nVdbeRead++;
  71744. p->pc = 0;
  71745. }
  71746. #ifdef SQLITE_DEBUG
  71747. p->rcApp = SQLITE_OK;
  71748. #endif
  71749. #ifndef SQLITE_OMIT_EXPLAIN
  71750. if( p->explain ){
  71751. rc = sqlite3VdbeList(p);
  71752. }else
  71753. #endif /* SQLITE_OMIT_EXPLAIN */
  71754. {
  71755. db->nVdbeExec++;
  71756. rc = sqlite3VdbeExec(p);
  71757. db->nVdbeExec--;
  71758. }
  71759. #ifndef SQLITE_OMIT_TRACE
  71760. /* If the statement completed successfully, invoke the profile callback */
  71761. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  71762. #endif
  71763. if( rc==SQLITE_DONE ){
  71764. assert( p->rc==SQLITE_OK );
  71765. p->rc = doWalCallbacks(db);
  71766. if( p->rc!=SQLITE_OK ){
  71767. rc = SQLITE_ERROR;
  71768. }
  71769. }
  71770. db->errCode = rc;
  71771. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  71772. p->rc = SQLITE_NOMEM_BKPT;
  71773. }
  71774. end_of_step:
  71775. /* At this point local variable rc holds the value that should be
  71776. ** returned if this statement was compiled using the legacy
  71777. ** sqlite3_prepare() interface. According to the docs, this can only
  71778. ** be one of the values in the first assert() below. Variable p->rc
  71779. ** contains the value that would be returned if sqlite3_finalize()
  71780. ** were called on statement p.
  71781. */
  71782. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  71783. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  71784. );
  71785. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  71786. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  71787. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  71788. ** error has occurred, then return the error code in p->rc to the
  71789. ** caller. Set the error code in the database handle to the same value.
  71790. */
  71791. rc = sqlite3VdbeTransferError(p);
  71792. }
  71793. return (rc&db->errMask);
  71794. }
  71795. /*
  71796. ** This is the top-level implementation of sqlite3_step(). Call
  71797. ** sqlite3Step() to do most of the work. If a schema error occurs,
  71798. ** call sqlite3Reprepare() and try again.
  71799. */
  71800. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  71801. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  71802. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  71803. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  71804. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  71805. sqlite3 *db; /* The database connection */
  71806. if( vdbeSafetyNotNull(v) ){
  71807. return SQLITE_MISUSE_BKPT;
  71808. }
  71809. db = v->db;
  71810. sqlite3_mutex_enter(db->mutex);
  71811. v->doingRerun = 0;
  71812. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  71813. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  71814. int savedPc = v->pc;
  71815. rc2 = rc = sqlite3Reprepare(v);
  71816. if( rc!=SQLITE_OK) break;
  71817. sqlite3_reset(pStmt);
  71818. if( savedPc>=0 ) v->doingRerun = 1;
  71819. assert( v->expired==0 );
  71820. }
  71821. if( rc2!=SQLITE_OK ){
  71822. /* This case occurs after failing to recompile an sql statement.
  71823. ** The error message from the SQL compiler has already been loaded
  71824. ** into the database handle. This block copies the error message
  71825. ** from the database handle into the statement and sets the statement
  71826. ** program counter to 0 to ensure that when the statement is
  71827. ** finalized or reset the parser error message is available via
  71828. ** sqlite3_errmsg() and sqlite3_errcode().
  71829. */
  71830. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  71831. sqlite3DbFree(db, v->zErrMsg);
  71832. if( !db->mallocFailed ){
  71833. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  71834. v->rc = rc2;
  71835. } else {
  71836. v->zErrMsg = 0;
  71837. v->rc = rc = SQLITE_NOMEM_BKPT;
  71838. }
  71839. }
  71840. rc = sqlite3ApiExit(db, rc);
  71841. sqlite3_mutex_leave(db->mutex);
  71842. return rc;
  71843. }
  71844. /*
  71845. ** Extract the user data from a sqlite3_context structure and return a
  71846. ** pointer to it.
  71847. */
  71848. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  71849. assert( p && p->pFunc );
  71850. return p->pFunc->pUserData;
  71851. }
  71852. /*
  71853. ** Extract the user data from a sqlite3_context structure and return a
  71854. ** pointer to it.
  71855. **
  71856. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  71857. ** returns a copy of the pointer to the database connection (the 1st
  71858. ** parameter) of the sqlite3_create_function() and
  71859. ** sqlite3_create_function16() routines that originally registered the
  71860. ** application defined function.
  71861. */
  71862. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  71863. assert( p && p->pOut );
  71864. return p->pOut->db;
  71865. }
  71866. /*
  71867. ** Return the current time for a statement. If the current time
  71868. ** is requested more than once within the same run of a single prepared
  71869. ** statement, the exact same time is returned for each invocation regardless
  71870. ** of the amount of time that elapses between invocations. In other words,
  71871. ** the time returned is always the time of the first call.
  71872. */
  71873. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  71874. int rc;
  71875. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  71876. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  71877. assert( p->pVdbe!=0 );
  71878. #else
  71879. sqlite3_int64 iTime = 0;
  71880. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  71881. #endif
  71882. if( *piTime==0 ){
  71883. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  71884. if( rc ) *piTime = 0;
  71885. }
  71886. return *piTime;
  71887. }
  71888. /*
  71889. ** The following is the implementation of an SQL function that always
  71890. ** fails with an error message stating that the function is used in the
  71891. ** wrong context. The sqlite3_overload_function() API might construct
  71892. ** SQL function that use this routine so that the functions will exist
  71893. ** for name resolution but are actually overloaded by the xFindFunction
  71894. ** method of virtual tables.
  71895. */
  71896. SQLITE_PRIVATE void sqlite3InvalidFunction(
  71897. sqlite3_context *context, /* The function calling context */
  71898. int NotUsed, /* Number of arguments to the function */
  71899. sqlite3_value **NotUsed2 /* Value of each argument */
  71900. ){
  71901. const char *zName = context->pFunc->zName;
  71902. char *zErr;
  71903. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  71904. zErr = sqlite3_mprintf(
  71905. "unable to use function %s in the requested context", zName);
  71906. sqlite3_result_error(context, zErr, -1);
  71907. sqlite3_free(zErr);
  71908. }
  71909. /*
  71910. ** Create a new aggregate context for p and return a pointer to
  71911. ** its pMem->z element.
  71912. */
  71913. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  71914. Mem *pMem = p->pMem;
  71915. assert( (pMem->flags & MEM_Agg)==0 );
  71916. if( nByte<=0 ){
  71917. sqlite3VdbeMemSetNull(pMem);
  71918. pMem->z = 0;
  71919. }else{
  71920. sqlite3VdbeMemClearAndResize(pMem, nByte);
  71921. pMem->flags = MEM_Agg;
  71922. pMem->u.pDef = p->pFunc;
  71923. if( pMem->z ){
  71924. memset(pMem->z, 0, nByte);
  71925. }
  71926. }
  71927. return (void*)pMem->z;
  71928. }
  71929. /*
  71930. ** Allocate or return the aggregate context for a user function. A new
  71931. ** context is allocated on the first call. Subsequent calls return the
  71932. ** same context that was returned on prior calls.
  71933. */
  71934. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  71935. assert( p && p->pFunc && p->pFunc->xFinalize );
  71936. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  71937. testcase( nByte<0 );
  71938. if( (p->pMem->flags & MEM_Agg)==0 ){
  71939. return createAggContext(p, nByte);
  71940. }else{
  71941. return (void*)p->pMem->z;
  71942. }
  71943. }
  71944. /*
  71945. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  71946. ** the user-function defined by pCtx.
  71947. **
  71948. ** The left-most argument is 0.
  71949. **
  71950. ** Undocumented behavior: If iArg is negative then access a cache of
  71951. ** auxiliary data pointers that is available to all functions within a
  71952. ** single prepared statement. The iArg values must match.
  71953. */
  71954. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  71955. AuxData *pAuxData;
  71956. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71957. #if SQLITE_ENABLE_STAT3_OR_STAT4
  71958. if( pCtx->pVdbe==0 ) return 0;
  71959. #else
  71960. assert( pCtx->pVdbe!=0 );
  71961. #endif
  71962. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  71963. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  71964. return pAuxData->pAux;
  71965. }
  71966. }
  71967. return 0;
  71968. }
  71969. /*
  71970. ** Set the auxiliary data pointer and delete function, for the iArg'th
  71971. ** argument to the user-function defined by pCtx. Any previous value is
  71972. ** deleted by calling the delete function specified when it was set.
  71973. **
  71974. ** The left-most argument is 0.
  71975. **
  71976. ** Undocumented behavior: If iArg is negative then make the data available
  71977. ** to all functions within the current prepared statement using iArg as an
  71978. ** access code.
  71979. */
  71980. SQLITE_API void sqlite3_set_auxdata(
  71981. sqlite3_context *pCtx,
  71982. int iArg,
  71983. void *pAux,
  71984. void (*xDelete)(void*)
  71985. ){
  71986. AuxData *pAuxData;
  71987. Vdbe *pVdbe = pCtx->pVdbe;
  71988. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71989. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71990. if( pVdbe==0 ) goto failed;
  71991. #else
  71992. assert( pVdbe!=0 );
  71993. #endif
  71994. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  71995. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  71996. break;
  71997. }
  71998. }
  71999. if( pAuxData==0 ){
  72000. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  72001. if( !pAuxData ) goto failed;
  72002. pAuxData->iAuxOp = pCtx->iOp;
  72003. pAuxData->iAuxArg = iArg;
  72004. pAuxData->pNextAux = pVdbe->pAuxData;
  72005. pVdbe->pAuxData = pAuxData;
  72006. if( pCtx->fErrorOrAux==0 ){
  72007. pCtx->isError = 0;
  72008. pCtx->fErrorOrAux = 1;
  72009. }
  72010. }else if( pAuxData->xDeleteAux ){
  72011. pAuxData->xDeleteAux(pAuxData->pAux);
  72012. }
  72013. pAuxData->pAux = pAux;
  72014. pAuxData->xDeleteAux = xDelete;
  72015. return;
  72016. failed:
  72017. if( xDelete ){
  72018. xDelete(pAux);
  72019. }
  72020. }
  72021. #ifndef SQLITE_OMIT_DEPRECATED
  72022. /*
  72023. ** Return the number of times the Step function of an aggregate has been
  72024. ** called.
  72025. **
  72026. ** This function is deprecated. Do not use it for new code. It is
  72027. ** provide only to avoid breaking legacy code. New aggregate function
  72028. ** implementations should keep their own counts within their aggregate
  72029. ** context.
  72030. */
  72031. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  72032. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  72033. return p->pMem->n;
  72034. }
  72035. #endif
  72036. /*
  72037. ** Return the number of columns in the result set for the statement pStmt.
  72038. */
  72039. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  72040. Vdbe *pVm = (Vdbe *)pStmt;
  72041. return pVm ? pVm->nResColumn : 0;
  72042. }
  72043. /*
  72044. ** Return the number of values available from the current row of the
  72045. ** currently executing statement pStmt.
  72046. */
  72047. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  72048. Vdbe *pVm = (Vdbe *)pStmt;
  72049. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  72050. return pVm->nResColumn;
  72051. }
  72052. /*
  72053. ** Return a pointer to static memory containing an SQL NULL value.
  72054. */
  72055. static const Mem *columnNullValue(void){
  72056. /* Even though the Mem structure contains an element
  72057. ** of type i64, on certain architectures (x86) with certain compiler
  72058. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  72059. ** instead of an 8-byte one. This all works fine, except that when
  72060. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  72061. ** that a Mem structure is located on an 8-byte boundary. To prevent
  72062. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  72063. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  72064. ** __attribute__((aligned(8))) macro. */
  72065. static const Mem nullMem
  72066. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  72067. __attribute__((aligned(8)))
  72068. #endif
  72069. = {
  72070. /* .u = */ {0},
  72071. /* .flags = */ (u16)MEM_Null,
  72072. /* .enc = */ (u8)0,
  72073. /* .eSubtype = */ (u8)0,
  72074. /* .n = */ (int)0,
  72075. /* .z = */ (char*)0,
  72076. /* .zMalloc = */ (char*)0,
  72077. /* .szMalloc = */ (int)0,
  72078. /* .uTemp = */ (u32)0,
  72079. /* .db = */ (sqlite3*)0,
  72080. /* .xDel = */ (void(*)(void*))0,
  72081. #ifdef SQLITE_DEBUG
  72082. /* .pScopyFrom = */ (Mem*)0,
  72083. /* .pFiller = */ (void*)0,
  72084. #endif
  72085. };
  72086. return &nullMem;
  72087. }
  72088. /*
  72089. ** Check to see if column iCol of the given statement is valid. If
  72090. ** it is, return a pointer to the Mem for the value of that column.
  72091. ** If iCol is not valid, return a pointer to a Mem which has a value
  72092. ** of NULL.
  72093. */
  72094. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  72095. Vdbe *pVm;
  72096. Mem *pOut;
  72097. pVm = (Vdbe *)pStmt;
  72098. if( pVm==0 ) return (Mem*)columnNullValue();
  72099. assert( pVm->db );
  72100. sqlite3_mutex_enter(pVm->db->mutex);
  72101. if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  72102. pOut = &pVm->pResultSet[i];
  72103. }else{
  72104. sqlite3Error(pVm->db, SQLITE_RANGE);
  72105. pOut = (Mem*)columnNullValue();
  72106. }
  72107. return pOut;
  72108. }
  72109. /*
  72110. ** This function is called after invoking an sqlite3_value_XXX function on a
  72111. ** column value (i.e. a value returned by evaluating an SQL expression in the
  72112. ** select list of a SELECT statement) that may cause a malloc() failure. If
  72113. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  72114. ** code of statement pStmt set to SQLITE_NOMEM.
  72115. **
  72116. ** Specifically, this is called from within:
  72117. **
  72118. ** sqlite3_column_int()
  72119. ** sqlite3_column_int64()
  72120. ** sqlite3_column_text()
  72121. ** sqlite3_column_text16()
  72122. ** sqlite3_column_real()
  72123. ** sqlite3_column_bytes()
  72124. ** sqlite3_column_bytes16()
  72125. ** sqiite3_column_blob()
  72126. */
  72127. static void columnMallocFailure(sqlite3_stmt *pStmt)
  72128. {
  72129. /* If malloc() failed during an encoding conversion within an
  72130. ** sqlite3_column_XXX API, then set the return code of the statement to
  72131. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  72132. ** and _finalize() will return NOMEM.
  72133. */
  72134. Vdbe *p = (Vdbe *)pStmt;
  72135. if( p ){
  72136. assert( p->db!=0 );
  72137. assert( sqlite3_mutex_held(p->db->mutex) );
  72138. p->rc = sqlite3ApiExit(p->db, p->rc);
  72139. sqlite3_mutex_leave(p->db->mutex);
  72140. }
  72141. }
  72142. /**************************** sqlite3_column_ *******************************
  72143. ** The following routines are used to access elements of the current row
  72144. ** in the result set.
  72145. */
  72146. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  72147. const void *val;
  72148. val = sqlite3_value_blob( columnMem(pStmt,i) );
  72149. /* Even though there is no encoding conversion, value_blob() might
  72150. ** need to call malloc() to expand the result of a zeroblob()
  72151. ** expression.
  72152. */
  72153. columnMallocFailure(pStmt);
  72154. return val;
  72155. }
  72156. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  72157. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  72158. columnMallocFailure(pStmt);
  72159. return val;
  72160. }
  72161. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  72162. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  72163. columnMallocFailure(pStmt);
  72164. return val;
  72165. }
  72166. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  72167. double val = sqlite3_value_double( columnMem(pStmt,i) );
  72168. columnMallocFailure(pStmt);
  72169. return val;
  72170. }
  72171. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  72172. int val = sqlite3_value_int( columnMem(pStmt,i) );
  72173. columnMallocFailure(pStmt);
  72174. return val;
  72175. }
  72176. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  72177. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  72178. columnMallocFailure(pStmt);
  72179. return val;
  72180. }
  72181. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  72182. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  72183. columnMallocFailure(pStmt);
  72184. return val;
  72185. }
  72186. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  72187. Mem *pOut = columnMem(pStmt, i);
  72188. if( pOut->flags&MEM_Static ){
  72189. pOut->flags &= ~MEM_Static;
  72190. pOut->flags |= MEM_Ephem;
  72191. }
  72192. columnMallocFailure(pStmt);
  72193. return (sqlite3_value *)pOut;
  72194. }
  72195. #ifndef SQLITE_OMIT_UTF16
  72196. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  72197. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  72198. columnMallocFailure(pStmt);
  72199. return val;
  72200. }
  72201. #endif /* SQLITE_OMIT_UTF16 */
  72202. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  72203. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  72204. columnMallocFailure(pStmt);
  72205. return iType;
  72206. }
  72207. /*
  72208. ** Convert the N-th element of pStmt->pColName[] into a string using
  72209. ** xFunc() then return that string. If N is out of range, return 0.
  72210. **
  72211. ** There are up to 5 names for each column. useType determines which
  72212. ** name is returned. Here are the names:
  72213. **
  72214. ** 0 The column name as it should be displayed for output
  72215. ** 1 The datatype name for the column
  72216. ** 2 The name of the database that the column derives from
  72217. ** 3 The name of the table that the column derives from
  72218. ** 4 The name of the table column that the result column derives from
  72219. **
  72220. ** If the result is not a simple column reference (if it is an expression
  72221. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  72222. */
  72223. static const void *columnName(
  72224. sqlite3_stmt *pStmt,
  72225. int N,
  72226. const void *(*xFunc)(Mem*),
  72227. int useType
  72228. ){
  72229. const void *ret;
  72230. Vdbe *p;
  72231. int n;
  72232. sqlite3 *db;
  72233. #ifdef SQLITE_ENABLE_API_ARMOR
  72234. if( pStmt==0 ){
  72235. (void)SQLITE_MISUSE_BKPT;
  72236. return 0;
  72237. }
  72238. #endif
  72239. ret = 0;
  72240. p = (Vdbe *)pStmt;
  72241. db = p->db;
  72242. assert( db!=0 );
  72243. n = sqlite3_column_count(pStmt);
  72244. if( N<n && N>=0 ){
  72245. N += useType*n;
  72246. sqlite3_mutex_enter(db->mutex);
  72247. assert( db->mallocFailed==0 );
  72248. ret = xFunc(&p->aColName[N]);
  72249. /* A malloc may have failed inside of the xFunc() call. If this
  72250. ** is the case, clear the mallocFailed flag and return NULL.
  72251. */
  72252. if( db->mallocFailed ){
  72253. sqlite3OomClear(db);
  72254. ret = 0;
  72255. }
  72256. sqlite3_mutex_leave(db->mutex);
  72257. }
  72258. return ret;
  72259. }
  72260. /*
  72261. ** Return the name of the Nth column of the result set returned by SQL
  72262. ** statement pStmt.
  72263. */
  72264. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  72265. return columnName(
  72266. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  72267. }
  72268. #ifndef SQLITE_OMIT_UTF16
  72269. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  72270. return columnName(
  72271. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  72272. }
  72273. #endif
  72274. /*
  72275. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  72276. ** not define OMIT_DECLTYPE.
  72277. */
  72278. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  72279. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  72280. and SQLITE_ENABLE_COLUMN_METADATA"
  72281. #endif
  72282. #ifndef SQLITE_OMIT_DECLTYPE
  72283. /*
  72284. ** Return the column declaration type (if applicable) of the 'i'th column
  72285. ** of the result set of SQL statement pStmt.
  72286. */
  72287. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  72288. return columnName(
  72289. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  72290. }
  72291. #ifndef SQLITE_OMIT_UTF16
  72292. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  72293. return columnName(
  72294. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  72295. }
  72296. #endif /* SQLITE_OMIT_UTF16 */
  72297. #endif /* SQLITE_OMIT_DECLTYPE */
  72298. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  72299. /*
  72300. ** Return the name of the database from which a result column derives.
  72301. ** NULL is returned if the result column is an expression or constant or
  72302. ** anything else which is not an unambiguous reference to a database column.
  72303. */
  72304. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  72305. return columnName(
  72306. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  72307. }
  72308. #ifndef SQLITE_OMIT_UTF16
  72309. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  72310. return columnName(
  72311. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  72312. }
  72313. #endif /* SQLITE_OMIT_UTF16 */
  72314. /*
  72315. ** Return the name of the table from which a result column derives.
  72316. ** NULL is returned if the result column is an expression or constant or
  72317. ** anything else which is not an unambiguous reference to a database column.
  72318. */
  72319. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  72320. return columnName(
  72321. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  72322. }
  72323. #ifndef SQLITE_OMIT_UTF16
  72324. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  72325. return columnName(
  72326. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  72327. }
  72328. #endif /* SQLITE_OMIT_UTF16 */
  72329. /*
  72330. ** Return the name of the table column from which a result column derives.
  72331. ** NULL is returned if the result column is an expression or constant or
  72332. ** anything else which is not an unambiguous reference to a database column.
  72333. */
  72334. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  72335. return columnName(
  72336. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  72337. }
  72338. #ifndef SQLITE_OMIT_UTF16
  72339. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  72340. return columnName(
  72341. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  72342. }
  72343. #endif /* SQLITE_OMIT_UTF16 */
  72344. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  72345. /******************************* sqlite3_bind_ ***************************
  72346. **
  72347. ** Routines used to attach values to wildcards in a compiled SQL statement.
  72348. */
  72349. /*
  72350. ** Unbind the value bound to variable i in virtual machine p. This is the
  72351. ** the same as binding a NULL value to the column. If the "i" parameter is
  72352. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  72353. **
  72354. ** A successful evaluation of this routine acquires the mutex on p.
  72355. ** the mutex is released if any kind of error occurs.
  72356. **
  72357. ** The error code stored in database p->db is overwritten with the return
  72358. ** value in any case.
  72359. */
  72360. static int vdbeUnbind(Vdbe *p, int i){
  72361. Mem *pVar;
  72362. if( vdbeSafetyNotNull(p) ){
  72363. return SQLITE_MISUSE_BKPT;
  72364. }
  72365. sqlite3_mutex_enter(p->db->mutex);
  72366. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  72367. sqlite3Error(p->db, SQLITE_MISUSE);
  72368. sqlite3_mutex_leave(p->db->mutex);
  72369. sqlite3_log(SQLITE_MISUSE,
  72370. "bind on a busy prepared statement: [%s]", p->zSql);
  72371. return SQLITE_MISUSE_BKPT;
  72372. }
  72373. if( i<1 || i>p->nVar ){
  72374. sqlite3Error(p->db, SQLITE_RANGE);
  72375. sqlite3_mutex_leave(p->db->mutex);
  72376. return SQLITE_RANGE;
  72377. }
  72378. i--;
  72379. pVar = &p->aVar[i];
  72380. sqlite3VdbeMemRelease(pVar);
  72381. pVar->flags = MEM_Null;
  72382. sqlite3Error(p->db, SQLITE_OK);
  72383. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  72384. ** binding a new value to this variable invalidates the current query plan.
  72385. **
  72386. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  72387. ** parameter in the WHERE clause might influence the choice of query plan
  72388. ** for a statement, then the statement will be automatically recompiled,
  72389. ** as if there had been a schema change, on the first sqlite3_step() call
  72390. ** following any change to the bindings of that parameter.
  72391. */
  72392. assert( p->isPrepareV2 || p->expmask==0 );
  72393. if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
  72394. p->expired = 1;
  72395. }
  72396. return SQLITE_OK;
  72397. }
  72398. /*
  72399. ** Bind a text or BLOB value.
  72400. */
  72401. static int bindText(
  72402. sqlite3_stmt *pStmt, /* The statement to bind against */
  72403. int i, /* Index of the parameter to bind */
  72404. const void *zData, /* Pointer to the data to be bound */
  72405. int nData, /* Number of bytes of data to be bound */
  72406. void (*xDel)(void*), /* Destructor for the data */
  72407. u8 encoding /* Encoding for the data */
  72408. ){
  72409. Vdbe *p = (Vdbe *)pStmt;
  72410. Mem *pVar;
  72411. int rc;
  72412. rc = vdbeUnbind(p, i);
  72413. if( rc==SQLITE_OK ){
  72414. if( zData!=0 ){
  72415. pVar = &p->aVar[i-1];
  72416. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  72417. if( rc==SQLITE_OK && encoding!=0 ){
  72418. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  72419. }
  72420. sqlite3Error(p->db, rc);
  72421. rc = sqlite3ApiExit(p->db, rc);
  72422. }
  72423. sqlite3_mutex_leave(p->db->mutex);
  72424. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  72425. xDel((void*)zData);
  72426. }
  72427. return rc;
  72428. }
  72429. /*
  72430. ** Bind a blob value to an SQL statement variable.
  72431. */
  72432. SQLITE_API int sqlite3_bind_blob(
  72433. sqlite3_stmt *pStmt,
  72434. int i,
  72435. const void *zData,
  72436. int nData,
  72437. void (*xDel)(void*)
  72438. ){
  72439. #ifdef SQLITE_ENABLE_API_ARMOR
  72440. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  72441. #endif
  72442. return bindText(pStmt, i, zData, nData, xDel, 0);
  72443. }
  72444. SQLITE_API int sqlite3_bind_blob64(
  72445. sqlite3_stmt *pStmt,
  72446. int i,
  72447. const void *zData,
  72448. sqlite3_uint64 nData,
  72449. void (*xDel)(void*)
  72450. ){
  72451. assert( xDel!=SQLITE_DYNAMIC );
  72452. if( nData>0x7fffffff ){
  72453. return invokeValueDestructor(zData, xDel, 0);
  72454. }else{
  72455. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  72456. }
  72457. }
  72458. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  72459. int rc;
  72460. Vdbe *p = (Vdbe *)pStmt;
  72461. rc = vdbeUnbind(p, i);
  72462. if( rc==SQLITE_OK ){
  72463. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  72464. sqlite3_mutex_leave(p->db->mutex);
  72465. }
  72466. return rc;
  72467. }
  72468. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  72469. return sqlite3_bind_int64(p, i, (i64)iValue);
  72470. }
  72471. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  72472. int rc;
  72473. Vdbe *p = (Vdbe *)pStmt;
  72474. rc = vdbeUnbind(p, i);
  72475. if( rc==SQLITE_OK ){
  72476. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  72477. sqlite3_mutex_leave(p->db->mutex);
  72478. }
  72479. return rc;
  72480. }
  72481. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  72482. int rc;
  72483. Vdbe *p = (Vdbe*)pStmt;
  72484. rc = vdbeUnbind(p, i);
  72485. if( rc==SQLITE_OK ){
  72486. sqlite3_mutex_leave(p->db->mutex);
  72487. }
  72488. return rc;
  72489. }
  72490. SQLITE_API int sqlite3_bind_text(
  72491. sqlite3_stmt *pStmt,
  72492. int i,
  72493. const char *zData,
  72494. int nData,
  72495. void (*xDel)(void*)
  72496. ){
  72497. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  72498. }
  72499. SQLITE_API int sqlite3_bind_text64(
  72500. sqlite3_stmt *pStmt,
  72501. int i,
  72502. const char *zData,
  72503. sqlite3_uint64 nData,
  72504. void (*xDel)(void*),
  72505. unsigned char enc
  72506. ){
  72507. assert( xDel!=SQLITE_DYNAMIC );
  72508. if( nData>0x7fffffff ){
  72509. return invokeValueDestructor(zData, xDel, 0);
  72510. }else{
  72511. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  72512. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  72513. }
  72514. }
  72515. #ifndef SQLITE_OMIT_UTF16
  72516. SQLITE_API int sqlite3_bind_text16(
  72517. sqlite3_stmt *pStmt,
  72518. int i,
  72519. const void *zData,
  72520. int nData,
  72521. void (*xDel)(void*)
  72522. ){
  72523. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  72524. }
  72525. #endif /* SQLITE_OMIT_UTF16 */
  72526. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  72527. int rc;
  72528. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  72529. case SQLITE_INTEGER: {
  72530. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  72531. break;
  72532. }
  72533. case SQLITE_FLOAT: {
  72534. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  72535. break;
  72536. }
  72537. case SQLITE_BLOB: {
  72538. if( pValue->flags & MEM_Zero ){
  72539. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  72540. }else{
  72541. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  72542. }
  72543. break;
  72544. }
  72545. case SQLITE_TEXT: {
  72546. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  72547. pValue->enc);
  72548. break;
  72549. }
  72550. default: {
  72551. rc = sqlite3_bind_null(pStmt, i);
  72552. break;
  72553. }
  72554. }
  72555. return rc;
  72556. }
  72557. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  72558. int rc;
  72559. Vdbe *p = (Vdbe *)pStmt;
  72560. rc = vdbeUnbind(p, i);
  72561. if( rc==SQLITE_OK ){
  72562. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  72563. sqlite3_mutex_leave(p->db->mutex);
  72564. }
  72565. return rc;
  72566. }
  72567. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  72568. int rc;
  72569. Vdbe *p = (Vdbe *)pStmt;
  72570. sqlite3_mutex_enter(p->db->mutex);
  72571. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  72572. rc = SQLITE_TOOBIG;
  72573. }else{
  72574. assert( (n & 0x7FFFFFFF)==n );
  72575. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  72576. }
  72577. rc = sqlite3ApiExit(p->db, rc);
  72578. sqlite3_mutex_leave(p->db->mutex);
  72579. return rc;
  72580. }
  72581. /*
  72582. ** Return the number of wildcards that can be potentially bound to.
  72583. ** This routine is added to support DBD::SQLite.
  72584. */
  72585. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  72586. Vdbe *p = (Vdbe*)pStmt;
  72587. return p ? p->nVar : 0;
  72588. }
  72589. /*
  72590. ** Return the name of a wildcard parameter. Return NULL if the index
  72591. ** is out of range or if the wildcard is unnamed.
  72592. **
  72593. ** The result is always UTF-8.
  72594. */
  72595. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  72596. Vdbe *p = (Vdbe*)pStmt;
  72597. if( p==0 ) return 0;
  72598. return sqlite3VListNumToName(p->pVList, i);
  72599. }
  72600. /*
  72601. ** Given a wildcard parameter name, return the index of the variable
  72602. ** with that name. If there is no variable with the given name,
  72603. ** return 0.
  72604. */
  72605. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  72606. if( p==0 || zName==0 ) return 0;
  72607. return sqlite3VListNameToNum(p->pVList, zName, nName);
  72608. }
  72609. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  72610. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  72611. }
  72612. /*
  72613. ** Transfer all bindings from the first statement over to the second.
  72614. */
  72615. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  72616. Vdbe *pFrom = (Vdbe*)pFromStmt;
  72617. Vdbe *pTo = (Vdbe*)pToStmt;
  72618. int i;
  72619. assert( pTo->db==pFrom->db );
  72620. assert( pTo->nVar==pFrom->nVar );
  72621. sqlite3_mutex_enter(pTo->db->mutex);
  72622. for(i=0; i<pFrom->nVar; i++){
  72623. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  72624. }
  72625. sqlite3_mutex_leave(pTo->db->mutex);
  72626. return SQLITE_OK;
  72627. }
  72628. #ifndef SQLITE_OMIT_DEPRECATED
  72629. /*
  72630. ** Deprecated external interface. Internal/core SQLite code
  72631. ** should call sqlite3TransferBindings.
  72632. **
  72633. ** It is misuse to call this routine with statements from different
  72634. ** database connections. But as this is a deprecated interface, we
  72635. ** will not bother to check for that condition.
  72636. **
  72637. ** If the two statements contain a different number of bindings, then
  72638. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  72639. ** SQLITE_OK is returned.
  72640. */
  72641. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  72642. Vdbe *pFrom = (Vdbe*)pFromStmt;
  72643. Vdbe *pTo = (Vdbe*)pToStmt;
  72644. if( pFrom->nVar!=pTo->nVar ){
  72645. return SQLITE_ERROR;
  72646. }
  72647. assert( pTo->isPrepareV2 || pTo->expmask==0 );
  72648. if( pTo->expmask ){
  72649. pTo->expired = 1;
  72650. }
  72651. assert( pFrom->isPrepareV2 || pFrom->expmask==0 );
  72652. if( pFrom->expmask ){
  72653. pFrom->expired = 1;
  72654. }
  72655. return sqlite3TransferBindings(pFromStmt, pToStmt);
  72656. }
  72657. #endif
  72658. /*
  72659. ** Return the sqlite3* database handle to which the prepared statement given
  72660. ** in the argument belongs. This is the same database handle that was
  72661. ** the first argument to the sqlite3_prepare() that was used to create
  72662. ** the statement in the first place.
  72663. */
  72664. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  72665. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  72666. }
  72667. /*
  72668. ** Return true if the prepared statement is guaranteed to not modify the
  72669. ** database.
  72670. */
  72671. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  72672. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  72673. }
  72674. /*
  72675. ** Return true if the prepared statement is in need of being reset.
  72676. */
  72677. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  72678. Vdbe *v = (Vdbe*)pStmt;
  72679. return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
  72680. }
  72681. /*
  72682. ** Return a pointer to the next prepared statement after pStmt associated
  72683. ** with database connection pDb. If pStmt is NULL, return the first
  72684. ** prepared statement for the database connection. Return NULL if there
  72685. ** are no more.
  72686. */
  72687. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  72688. sqlite3_stmt *pNext;
  72689. #ifdef SQLITE_ENABLE_API_ARMOR
  72690. if( !sqlite3SafetyCheckOk(pDb) ){
  72691. (void)SQLITE_MISUSE_BKPT;
  72692. return 0;
  72693. }
  72694. #endif
  72695. sqlite3_mutex_enter(pDb->mutex);
  72696. if( pStmt==0 ){
  72697. pNext = (sqlite3_stmt*)pDb->pVdbe;
  72698. }else{
  72699. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  72700. }
  72701. sqlite3_mutex_leave(pDb->mutex);
  72702. return pNext;
  72703. }
  72704. /*
  72705. ** Return the value of a status counter for a prepared statement
  72706. */
  72707. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  72708. Vdbe *pVdbe = (Vdbe*)pStmt;
  72709. u32 v;
  72710. #ifdef SQLITE_ENABLE_API_ARMOR
  72711. if( !pStmt ){
  72712. (void)SQLITE_MISUSE_BKPT;
  72713. return 0;
  72714. }
  72715. #endif
  72716. v = pVdbe->aCounter[op];
  72717. if( resetFlag ) pVdbe->aCounter[op] = 0;
  72718. return (int)v;
  72719. }
  72720. /*
  72721. ** Return the SQL associated with a prepared statement
  72722. */
  72723. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  72724. Vdbe *p = (Vdbe *)pStmt;
  72725. return p ? p->zSql : 0;
  72726. }
  72727. /*
  72728. ** Return the SQL associated with a prepared statement with
  72729. ** bound parameters expanded. Space to hold the returned string is
  72730. ** obtained from sqlite3_malloc(). The caller is responsible for
  72731. ** freeing the returned string by passing it to sqlite3_free().
  72732. **
  72733. ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
  72734. ** expanded bound parameters.
  72735. */
  72736. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
  72737. #ifdef SQLITE_OMIT_TRACE
  72738. return 0;
  72739. #else
  72740. char *z = 0;
  72741. const char *zSql = sqlite3_sql(pStmt);
  72742. if( zSql ){
  72743. Vdbe *p = (Vdbe *)pStmt;
  72744. sqlite3_mutex_enter(p->db->mutex);
  72745. z = sqlite3VdbeExpandSql(p, zSql);
  72746. sqlite3_mutex_leave(p->db->mutex);
  72747. }
  72748. return z;
  72749. #endif
  72750. }
  72751. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  72752. /*
  72753. ** Allocate and populate an UnpackedRecord structure based on the serialized
  72754. ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
  72755. ** if successful, or a NULL pointer if an OOM error is encountered.
  72756. */
  72757. static UnpackedRecord *vdbeUnpackRecord(
  72758. KeyInfo *pKeyInfo,
  72759. int nKey,
  72760. const void *pKey
  72761. ){
  72762. UnpackedRecord *pRet; /* Return value */
  72763. pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  72764. if( pRet ){
  72765. memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
  72766. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
  72767. }
  72768. return pRet;
  72769. }
  72770. /*
  72771. ** This function is called from within a pre-update callback to retrieve
  72772. ** a field of the row currently being updated or deleted.
  72773. */
  72774. SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  72775. PreUpdate *p = db->pPreUpdate;
  72776. Mem *pMem;
  72777. int rc = SQLITE_OK;
  72778. /* Test that this call is being made from within an SQLITE_DELETE or
  72779. ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  72780. if( !p || p->op==SQLITE_INSERT ){
  72781. rc = SQLITE_MISUSE_BKPT;
  72782. goto preupdate_old_out;
  72783. }
  72784. if( p->pPk ){
  72785. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  72786. }
  72787. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  72788. rc = SQLITE_RANGE;
  72789. goto preupdate_old_out;
  72790. }
  72791. /* If the old.* record has not yet been loaded into memory, do so now. */
  72792. if( p->pUnpacked==0 ){
  72793. u32 nRec;
  72794. u8 *aRec;
  72795. nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
  72796. aRec = sqlite3DbMallocRaw(db, nRec);
  72797. if( !aRec ) goto preupdate_old_out;
  72798. rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
  72799. if( rc==SQLITE_OK ){
  72800. p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
  72801. if( !p->pUnpacked ) rc = SQLITE_NOMEM;
  72802. }
  72803. if( rc!=SQLITE_OK ){
  72804. sqlite3DbFree(db, aRec);
  72805. goto preupdate_old_out;
  72806. }
  72807. p->aRecord = aRec;
  72808. }
  72809. pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
  72810. if( iIdx==p->pTab->iPKey ){
  72811. sqlite3VdbeMemSetInt64(pMem, p->iKey1);
  72812. }else if( iIdx>=p->pUnpacked->nField ){
  72813. *ppValue = (sqlite3_value *)columnNullValue();
  72814. }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
  72815. if( pMem->flags & MEM_Int ){
  72816. sqlite3VdbeMemRealify(pMem);
  72817. }
  72818. }
  72819. preupdate_old_out:
  72820. sqlite3Error(db, rc);
  72821. return sqlite3ApiExit(db, rc);
  72822. }
  72823. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  72824. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  72825. /*
  72826. ** This function is called from within a pre-update callback to retrieve
  72827. ** the number of columns in the row being updated, deleted or inserted.
  72828. */
  72829. SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
  72830. PreUpdate *p = db->pPreUpdate;
  72831. return (p ? p->keyinfo.nField : 0);
  72832. }
  72833. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  72834. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  72835. /*
  72836. ** This function is designed to be called from within a pre-update callback
  72837. ** only. It returns zero if the change that caused the callback was made
  72838. ** immediately by a user SQL statement. Or, if the change was made by a
  72839. ** trigger program, it returns the number of trigger programs currently
  72840. ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
  72841. ** top-level trigger etc.).
  72842. **
  72843. ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
  72844. ** or SET DEFAULT action is considered a trigger.
  72845. */
  72846. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
  72847. PreUpdate *p = db->pPreUpdate;
  72848. return (p ? p->v->nFrame : 0);
  72849. }
  72850. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  72851. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  72852. /*
  72853. ** This function is called from within a pre-update callback to retrieve
  72854. ** a field of the row currently being updated or inserted.
  72855. */
  72856. SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  72857. PreUpdate *p = db->pPreUpdate;
  72858. int rc = SQLITE_OK;
  72859. Mem *pMem;
  72860. if( !p || p->op==SQLITE_DELETE ){
  72861. rc = SQLITE_MISUSE_BKPT;
  72862. goto preupdate_new_out;
  72863. }
  72864. if( p->pPk && p->op!=SQLITE_UPDATE ){
  72865. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  72866. }
  72867. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  72868. rc = SQLITE_RANGE;
  72869. goto preupdate_new_out;
  72870. }
  72871. if( p->op==SQLITE_INSERT ){
  72872. /* For an INSERT, memory cell p->iNewReg contains the serialized record
  72873. ** that is being inserted. Deserialize it. */
  72874. UnpackedRecord *pUnpack = p->pNewUnpacked;
  72875. if( !pUnpack ){
  72876. Mem *pData = &p->v->aMem[p->iNewReg];
  72877. rc = ExpandBlob(pData);
  72878. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  72879. pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
  72880. if( !pUnpack ){
  72881. rc = SQLITE_NOMEM;
  72882. goto preupdate_new_out;
  72883. }
  72884. p->pNewUnpacked = pUnpack;
  72885. }
  72886. pMem = &pUnpack->aMem[iIdx];
  72887. if( iIdx==p->pTab->iPKey ){
  72888. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  72889. }else if( iIdx>=pUnpack->nField ){
  72890. pMem = (sqlite3_value *)columnNullValue();
  72891. }
  72892. }else{
  72893. /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
  72894. ** value. Make a copy of the cell contents and return a pointer to it.
  72895. ** It is not safe to return a pointer to the memory cell itself as the
  72896. ** caller may modify the value text encoding.
  72897. */
  72898. assert( p->op==SQLITE_UPDATE );
  72899. if( !p->aNew ){
  72900. p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
  72901. if( !p->aNew ){
  72902. rc = SQLITE_NOMEM;
  72903. goto preupdate_new_out;
  72904. }
  72905. }
  72906. assert( iIdx>=0 && iIdx<p->pCsr->nField );
  72907. pMem = &p->aNew[iIdx];
  72908. if( pMem->flags==0 ){
  72909. if( iIdx==p->pTab->iPKey ){
  72910. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  72911. }else{
  72912. rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
  72913. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  72914. }
  72915. }
  72916. }
  72917. *ppValue = pMem;
  72918. preupdate_new_out:
  72919. sqlite3Error(db, rc);
  72920. return sqlite3ApiExit(db, rc);
  72921. }
  72922. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  72923. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  72924. /*
  72925. ** Return status data for a single loop within query pStmt.
  72926. */
  72927. SQLITE_API int sqlite3_stmt_scanstatus(
  72928. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  72929. int idx, /* Index of loop to report on */
  72930. int iScanStatusOp, /* Which metric to return */
  72931. void *pOut /* OUT: Write the answer here */
  72932. ){
  72933. Vdbe *p = (Vdbe*)pStmt;
  72934. ScanStatus *pScan;
  72935. if( idx<0 || idx>=p->nScan ) return 1;
  72936. pScan = &p->aScan[idx];
  72937. switch( iScanStatusOp ){
  72938. case SQLITE_SCANSTAT_NLOOP: {
  72939. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  72940. break;
  72941. }
  72942. case SQLITE_SCANSTAT_NVISIT: {
  72943. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  72944. break;
  72945. }
  72946. case SQLITE_SCANSTAT_EST: {
  72947. double r = 1.0;
  72948. LogEst x = pScan->nEst;
  72949. while( x<100 ){
  72950. x += 10;
  72951. r *= 0.5;
  72952. }
  72953. *(double*)pOut = r*sqlite3LogEstToInt(x);
  72954. break;
  72955. }
  72956. case SQLITE_SCANSTAT_NAME: {
  72957. *(const char**)pOut = pScan->zName;
  72958. break;
  72959. }
  72960. case SQLITE_SCANSTAT_EXPLAIN: {
  72961. if( pScan->addrExplain ){
  72962. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  72963. }else{
  72964. *(const char**)pOut = 0;
  72965. }
  72966. break;
  72967. }
  72968. case SQLITE_SCANSTAT_SELECTID: {
  72969. if( pScan->addrExplain ){
  72970. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  72971. }else{
  72972. *(int*)pOut = -1;
  72973. }
  72974. break;
  72975. }
  72976. default: {
  72977. return 1;
  72978. }
  72979. }
  72980. return 0;
  72981. }
  72982. /*
  72983. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  72984. */
  72985. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  72986. Vdbe *p = (Vdbe*)pStmt;
  72987. memset(p->anExec, 0, p->nOp * sizeof(i64));
  72988. }
  72989. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  72990. /************** End of vdbeapi.c *********************************************/
  72991. /************** Begin file vdbetrace.c ***************************************/
  72992. /*
  72993. ** 2009 November 25
  72994. **
  72995. ** The author disclaims copyright to this source code. In place of
  72996. ** a legal notice, here is a blessing:
  72997. **
  72998. ** May you do good and not evil.
  72999. ** May you find forgiveness for yourself and forgive others.
  73000. ** May you share freely, never taking more than you give.
  73001. **
  73002. *************************************************************************
  73003. **
  73004. ** This file contains code used to insert the values of host parameters
  73005. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  73006. **
  73007. ** The Vdbe parse-tree explainer is also found here.
  73008. */
  73009. /* #include "sqliteInt.h" */
  73010. /* #include "vdbeInt.h" */
  73011. #ifndef SQLITE_OMIT_TRACE
  73012. /*
  73013. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  73014. ** bytes in this text up to but excluding the first character in
  73015. ** a host parameter. If the text contains no host parameters, return
  73016. ** the total number of bytes in the text.
  73017. */
  73018. static int findNextHostParameter(const char *zSql, int *pnToken){
  73019. int tokenType;
  73020. int nTotal = 0;
  73021. int n;
  73022. *pnToken = 0;
  73023. while( zSql[0] ){
  73024. n = sqlite3GetToken((u8*)zSql, &tokenType);
  73025. assert( n>0 && tokenType!=TK_ILLEGAL );
  73026. if( tokenType==TK_VARIABLE ){
  73027. *pnToken = n;
  73028. break;
  73029. }
  73030. nTotal += n;
  73031. zSql += n;
  73032. }
  73033. return nTotal;
  73034. }
  73035. /*
  73036. ** This function returns a pointer to a nul-terminated string in memory
  73037. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  73038. ** string contains a copy of zRawSql but with host parameters expanded to
  73039. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  73040. ** then the returned string holds a copy of zRawSql with "-- " prepended
  73041. ** to each line of text.
  73042. **
  73043. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  73044. ** then long strings and blobs are truncated to that many bytes. This
  73045. ** can be used to prevent unreasonably large trace strings when dealing
  73046. ** with large (multi-megabyte) strings and blobs.
  73047. **
  73048. ** The calling function is responsible for making sure the memory returned
  73049. ** is eventually freed.
  73050. **
  73051. ** ALGORITHM: Scan the input string looking for host parameters in any of
  73052. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  73053. ** string literals, quoted identifier names, and comments. For text forms,
  73054. ** the host parameter index is found by scanning the prepared
  73055. ** statement for the corresponding OP_Variable opcode. Once the host
  73056. ** parameter index is known, locate the value in p->aVar[]. Then render
  73057. ** the value as a literal in place of the host parameter name.
  73058. */
  73059. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  73060. Vdbe *p, /* The prepared statement being evaluated */
  73061. const char *zRawSql /* Raw text of the SQL statement */
  73062. ){
  73063. sqlite3 *db; /* The database connection */
  73064. int idx = 0; /* Index of a host parameter */
  73065. int nextIndex = 1; /* Index of next ? host parameter */
  73066. int n; /* Length of a token prefix */
  73067. int nToken; /* Length of the parameter token */
  73068. int i; /* Loop counter */
  73069. Mem *pVar; /* Value of a host parameter */
  73070. StrAccum out; /* Accumulate the output here */
  73071. #ifndef SQLITE_OMIT_UTF16
  73072. Mem utf8; /* Used to convert UTF16 parameters into UTF8 for display */
  73073. #endif
  73074. char zBase[100]; /* Initial working space */
  73075. db = p->db;
  73076. sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
  73077. db->aLimit[SQLITE_LIMIT_LENGTH]);
  73078. if( db->nVdbeExec>1 ){
  73079. while( *zRawSql ){
  73080. const char *zStart = zRawSql;
  73081. while( *(zRawSql++)!='\n' && *zRawSql );
  73082. sqlite3StrAccumAppend(&out, "-- ", 3);
  73083. assert( (zRawSql - zStart) > 0 );
  73084. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  73085. }
  73086. }else if( p->nVar==0 ){
  73087. sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
  73088. }else{
  73089. while( zRawSql[0] ){
  73090. n = findNextHostParameter(zRawSql, &nToken);
  73091. assert( n>0 );
  73092. sqlite3StrAccumAppend(&out, zRawSql, n);
  73093. zRawSql += n;
  73094. assert( zRawSql[0] || nToken==0 );
  73095. if( nToken==0 ) break;
  73096. if( zRawSql[0]=='?' ){
  73097. if( nToken>1 ){
  73098. assert( sqlite3Isdigit(zRawSql[1]) );
  73099. sqlite3GetInt32(&zRawSql[1], &idx);
  73100. }else{
  73101. idx = nextIndex;
  73102. }
  73103. }else{
  73104. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  73105. zRawSql[0]=='@' || zRawSql[0]=='#' );
  73106. testcase( zRawSql[0]==':' );
  73107. testcase( zRawSql[0]=='$' );
  73108. testcase( zRawSql[0]=='@' );
  73109. testcase( zRawSql[0]=='#' );
  73110. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  73111. assert( idx>0 );
  73112. }
  73113. zRawSql += nToken;
  73114. nextIndex = idx + 1;
  73115. assert( idx>0 && idx<=p->nVar );
  73116. pVar = &p->aVar[idx-1];
  73117. if( pVar->flags & MEM_Null ){
  73118. sqlite3StrAccumAppend(&out, "NULL", 4);
  73119. }else if( pVar->flags & MEM_Int ){
  73120. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  73121. }else if( pVar->flags & MEM_Real ){
  73122. sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
  73123. }else if( pVar->flags & MEM_Str ){
  73124. int nOut; /* Number of bytes of the string text to include in output */
  73125. #ifndef SQLITE_OMIT_UTF16
  73126. u8 enc = ENC(db);
  73127. if( enc!=SQLITE_UTF8 ){
  73128. memset(&utf8, 0, sizeof(utf8));
  73129. utf8.db = db;
  73130. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  73131. if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
  73132. out.accError = STRACCUM_NOMEM;
  73133. out.nAlloc = 0;
  73134. }
  73135. pVar = &utf8;
  73136. }
  73137. #endif
  73138. nOut = pVar->n;
  73139. #ifdef SQLITE_TRACE_SIZE_LIMIT
  73140. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  73141. nOut = SQLITE_TRACE_SIZE_LIMIT;
  73142. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  73143. }
  73144. #endif
  73145. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  73146. #ifdef SQLITE_TRACE_SIZE_LIMIT
  73147. if( nOut<pVar->n ){
  73148. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  73149. }
  73150. #endif
  73151. #ifndef SQLITE_OMIT_UTF16
  73152. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  73153. #endif
  73154. }else if( pVar->flags & MEM_Zero ){
  73155. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  73156. }else{
  73157. int nOut; /* Number of bytes of the blob to include in output */
  73158. assert( pVar->flags & MEM_Blob );
  73159. sqlite3StrAccumAppend(&out, "x'", 2);
  73160. nOut = pVar->n;
  73161. #ifdef SQLITE_TRACE_SIZE_LIMIT
  73162. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  73163. #endif
  73164. for(i=0; i<nOut; i++){
  73165. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  73166. }
  73167. sqlite3StrAccumAppend(&out, "'", 1);
  73168. #ifdef SQLITE_TRACE_SIZE_LIMIT
  73169. if( nOut<pVar->n ){
  73170. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  73171. }
  73172. #endif
  73173. }
  73174. }
  73175. }
  73176. if( out.accError ) sqlite3StrAccumReset(&out);
  73177. return sqlite3StrAccumFinish(&out);
  73178. }
  73179. #endif /* #ifndef SQLITE_OMIT_TRACE */
  73180. /************** End of vdbetrace.c *******************************************/
  73181. /************** Begin file vdbe.c ********************************************/
  73182. /*
  73183. ** 2001 September 15
  73184. **
  73185. ** The author disclaims copyright to this source code. In place of
  73186. ** a legal notice, here is a blessing:
  73187. **
  73188. ** May you do good and not evil.
  73189. ** May you find forgiveness for yourself and forgive others.
  73190. ** May you share freely, never taking more than you give.
  73191. **
  73192. *************************************************************************
  73193. ** The code in this file implements the function that runs the
  73194. ** bytecode of a prepared statement.
  73195. **
  73196. ** Various scripts scan this source file in order to generate HTML
  73197. ** documentation, headers files, or other derived files. The formatting
  73198. ** of the code in this file is, therefore, important. See other comments
  73199. ** in this file for details. If in doubt, do not deviate from existing
  73200. ** commenting and indentation practices when changing or adding code.
  73201. */
  73202. /* #include "sqliteInt.h" */
  73203. /* #include "vdbeInt.h" */
  73204. /*
  73205. ** Invoke this macro on memory cells just prior to changing the
  73206. ** value of the cell. This macro verifies that shallow copies are
  73207. ** not misused. A shallow copy of a string or blob just copies a
  73208. ** pointer to the string or blob, not the content. If the original
  73209. ** is changed while the copy is still in use, the string or blob might
  73210. ** be changed out from under the copy. This macro verifies that nothing
  73211. ** like that ever happens.
  73212. */
  73213. #ifdef SQLITE_DEBUG
  73214. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  73215. #else
  73216. # define memAboutToChange(P,M)
  73217. #endif
  73218. /*
  73219. ** The following global variable is incremented every time a cursor
  73220. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  73221. ** procedures use this information to make sure that indices are
  73222. ** working correctly. This variable has no function other than to
  73223. ** help verify the correct operation of the library.
  73224. */
  73225. #ifdef SQLITE_TEST
  73226. SQLITE_API int sqlite3_search_count = 0;
  73227. #endif
  73228. /*
  73229. ** When this global variable is positive, it gets decremented once before
  73230. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  73231. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  73232. **
  73233. ** This facility is used for testing purposes only. It does not function
  73234. ** in an ordinary build.
  73235. */
  73236. #ifdef SQLITE_TEST
  73237. SQLITE_API int sqlite3_interrupt_count = 0;
  73238. #endif
  73239. /*
  73240. ** The next global variable is incremented each type the OP_Sort opcode
  73241. ** is executed. The test procedures use this information to make sure that
  73242. ** sorting is occurring or not occurring at appropriate times. This variable
  73243. ** has no function other than to help verify the correct operation of the
  73244. ** library.
  73245. */
  73246. #ifdef SQLITE_TEST
  73247. SQLITE_API int sqlite3_sort_count = 0;
  73248. #endif
  73249. /*
  73250. ** The next global variable records the size of the largest MEM_Blob
  73251. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  73252. ** use this information to make sure that the zero-blob functionality
  73253. ** is working correctly. This variable has no function other than to
  73254. ** help verify the correct operation of the library.
  73255. */
  73256. #ifdef SQLITE_TEST
  73257. SQLITE_API int sqlite3_max_blobsize = 0;
  73258. static void updateMaxBlobsize(Mem *p){
  73259. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  73260. sqlite3_max_blobsize = p->n;
  73261. }
  73262. }
  73263. #endif
  73264. /*
  73265. ** This macro evaluates to true if either the update hook or the preupdate
  73266. ** hook are enabled for database connect DB.
  73267. */
  73268. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  73269. # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
  73270. #else
  73271. # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
  73272. #endif
  73273. /*
  73274. ** The next global variable is incremented each time the OP_Found opcode
  73275. ** is executed. This is used to test whether or not the foreign key
  73276. ** operation implemented using OP_FkIsZero is working. This variable
  73277. ** has no function other than to help verify the correct operation of the
  73278. ** library.
  73279. */
  73280. #ifdef SQLITE_TEST
  73281. SQLITE_API int sqlite3_found_count = 0;
  73282. #endif
  73283. /*
  73284. ** Test a register to see if it exceeds the current maximum blob size.
  73285. ** If it does, record the new maximum blob size.
  73286. */
  73287. #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
  73288. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  73289. #else
  73290. # define UPDATE_MAX_BLOBSIZE(P)
  73291. #endif
  73292. /*
  73293. ** Invoke the VDBE coverage callback, if that callback is defined. This
  73294. ** feature is used for test suite validation only and does not appear an
  73295. ** production builds.
  73296. **
  73297. ** M is an integer, 2 or 3, that indices how many different ways the
  73298. ** branch can go. It is usually 2. "I" is the direction the branch
  73299. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  73300. ** second alternative branch is taken.
  73301. **
  73302. ** iSrcLine is the source code line (from the __LINE__ macro) that
  73303. ** generated the VDBE instruction. This instrumentation assumes that all
  73304. ** source code is in a single file (the amalgamation). Special values 1
  73305. ** and 2 for the iSrcLine parameter mean that this particular branch is
  73306. ** always taken or never taken, respectively.
  73307. */
  73308. #if !defined(SQLITE_VDBE_COVERAGE)
  73309. # define VdbeBranchTaken(I,M)
  73310. #else
  73311. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  73312. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  73313. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  73314. M = iSrcLine;
  73315. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  73316. ** VdbeCoverageNeverTaken() */
  73317. assert( (M & I)==I );
  73318. }else{
  73319. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  73320. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  73321. iSrcLine,I,M);
  73322. }
  73323. }
  73324. #endif
  73325. /*
  73326. ** Convert the given register into a string if it isn't one
  73327. ** already. Return non-zero if a malloc() fails.
  73328. */
  73329. #define Stringify(P, enc) \
  73330. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  73331. { goto no_mem; }
  73332. /*
  73333. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  73334. ** a pointer to a dynamically allocated string where some other entity
  73335. ** is responsible for deallocating that string. Because the register
  73336. ** does not control the string, it might be deleted without the register
  73337. ** knowing it.
  73338. **
  73339. ** This routine converts an ephemeral string into a dynamically allocated
  73340. ** string that the register itself controls. In other words, it
  73341. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  73342. */
  73343. #define Deephemeralize(P) \
  73344. if( ((P)->flags&MEM_Ephem)!=0 \
  73345. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  73346. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  73347. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  73348. /*
  73349. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  73350. ** if we run out of memory.
  73351. */
  73352. static VdbeCursor *allocateCursor(
  73353. Vdbe *p, /* The virtual machine */
  73354. int iCur, /* Index of the new VdbeCursor */
  73355. int nField, /* Number of fields in the table or index */
  73356. int iDb, /* Database the cursor belongs to, or -1 */
  73357. u8 eCurType /* Type of the new cursor */
  73358. ){
  73359. /* Find the memory cell that will be used to store the blob of memory
  73360. ** required for this VdbeCursor structure. It is convenient to use a
  73361. ** vdbe memory cell to manage the memory allocation required for a
  73362. ** VdbeCursor structure for the following reasons:
  73363. **
  73364. ** * Sometimes cursor numbers are used for a couple of different
  73365. ** purposes in a vdbe program. The different uses might require
  73366. ** different sized allocations. Memory cells provide growable
  73367. ** allocations.
  73368. **
  73369. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  73370. ** be freed lazily via the sqlite3_release_memory() API. This
  73371. ** minimizes the number of malloc calls made by the system.
  73372. **
  73373. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  73374. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  73375. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  73376. */
  73377. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  73378. int nByte;
  73379. VdbeCursor *pCx = 0;
  73380. nByte =
  73381. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  73382. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  73383. assert( iCur>=0 && iCur<p->nCursor );
  73384. if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
  73385. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  73386. p->apCsr[iCur] = 0;
  73387. }
  73388. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  73389. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  73390. memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
  73391. pCx->eCurType = eCurType;
  73392. pCx->iDb = iDb;
  73393. pCx->nField = nField;
  73394. pCx->aOffset = &pCx->aType[nField];
  73395. if( eCurType==CURTYPE_BTREE ){
  73396. pCx->uc.pCursor = (BtCursor*)
  73397. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  73398. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  73399. }
  73400. }
  73401. return pCx;
  73402. }
  73403. /*
  73404. ** Try to convert a value into a numeric representation if we can
  73405. ** do so without loss of information. In other words, if the string
  73406. ** looks like a number, convert it into a number. If it does not
  73407. ** look like a number, leave it alone.
  73408. **
  73409. ** If the bTryForInt flag is true, then extra effort is made to give
  73410. ** an integer representation. Strings that look like floating point
  73411. ** values but which have no fractional component (example: '48.00')
  73412. ** will have a MEM_Int representation when bTryForInt is true.
  73413. **
  73414. ** If bTryForInt is false, then if the input string contains a decimal
  73415. ** point or exponential notation, the result is only MEM_Real, even
  73416. ** if there is an exact integer representation of the quantity.
  73417. */
  73418. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  73419. double rValue;
  73420. i64 iValue;
  73421. u8 enc = pRec->enc;
  73422. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  73423. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  73424. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  73425. pRec->u.i = iValue;
  73426. pRec->flags |= MEM_Int;
  73427. }else{
  73428. pRec->u.r = rValue;
  73429. pRec->flags |= MEM_Real;
  73430. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  73431. }
  73432. }
  73433. /*
  73434. ** Processing is determine by the affinity parameter:
  73435. **
  73436. ** SQLITE_AFF_INTEGER:
  73437. ** SQLITE_AFF_REAL:
  73438. ** SQLITE_AFF_NUMERIC:
  73439. ** Try to convert pRec to an integer representation or a
  73440. ** floating-point representation if an integer representation
  73441. ** is not possible. Note that the integer representation is
  73442. ** always preferred, even if the affinity is REAL, because
  73443. ** an integer representation is more space efficient on disk.
  73444. **
  73445. ** SQLITE_AFF_TEXT:
  73446. ** Convert pRec to a text representation.
  73447. **
  73448. ** SQLITE_AFF_BLOB:
  73449. ** No-op. pRec is unchanged.
  73450. */
  73451. static void applyAffinity(
  73452. Mem *pRec, /* The value to apply affinity to */
  73453. char affinity, /* The affinity to be applied */
  73454. u8 enc /* Use this text encoding */
  73455. ){
  73456. if( affinity>=SQLITE_AFF_NUMERIC ){
  73457. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  73458. || affinity==SQLITE_AFF_NUMERIC );
  73459. if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  73460. if( (pRec->flags & MEM_Real)==0 ){
  73461. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  73462. }else{
  73463. sqlite3VdbeIntegerAffinity(pRec);
  73464. }
  73465. }
  73466. }else if( affinity==SQLITE_AFF_TEXT ){
  73467. /* Only attempt the conversion to TEXT if there is an integer or real
  73468. ** representation (blob and NULL do not get converted) but no string
  73469. ** representation. It would be harmless to repeat the conversion if
  73470. ** there is already a string rep, but it is pointless to waste those
  73471. ** CPU cycles. */
  73472. if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
  73473. if( (pRec->flags&(MEM_Real|MEM_Int)) ){
  73474. sqlite3VdbeMemStringify(pRec, enc, 1);
  73475. }
  73476. }
  73477. pRec->flags &= ~(MEM_Real|MEM_Int);
  73478. }
  73479. }
  73480. /*
  73481. ** Try to convert the type of a function argument or a result column
  73482. ** into a numeric representation. Use either INTEGER or REAL whichever
  73483. ** is appropriate. But only do the conversion if it is possible without
  73484. ** loss of information and return the revised type of the argument.
  73485. */
  73486. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  73487. int eType = sqlite3_value_type(pVal);
  73488. if( eType==SQLITE_TEXT ){
  73489. Mem *pMem = (Mem*)pVal;
  73490. applyNumericAffinity(pMem, 0);
  73491. eType = sqlite3_value_type(pVal);
  73492. }
  73493. return eType;
  73494. }
  73495. /*
  73496. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  73497. ** not the internal Mem* type.
  73498. */
  73499. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  73500. sqlite3_value *pVal,
  73501. u8 affinity,
  73502. u8 enc
  73503. ){
  73504. applyAffinity((Mem *)pVal, affinity, enc);
  73505. }
  73506. /*
  73507. ** pMem currently only holds a string type (or maybe a BLOB that we can
  73508. ** interpret as a string if we want to). Compute its corresponding
  73509. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  73510. ** accordingly.
  73511. */
  73512. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  73513. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  73514. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  73515. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  73516. return 0;
  73517. }
  73518. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
  73519. return MEM_Int;
  73520. }
  73521. return MEM_Real;
  73522. }
  73523. /*
  73524. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  73525. ** none.
  73526. **
  73527. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  73528. ** But it does set pMem->u.r and pMem->u.i appropriately.
  73529. */
  73530. static u16 numericType(Mem *pMem){
  73531. if( pMem->flags & (MEM_Int|MEM_Real) ){
  73532. return pMem->flags & (MEM_Int|MEM_Real);
  73533. }
  73534. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  73535. return computeNumericType(pMem);
  73536. }
  73537. return 0;
  73538. }
  73539. #ifdef SQLITE_DEBUG
  73540. /*
  73541. ** Write a nice string representation of the contents of cell pMem
  73542. ** into buffer zBuf, length nBuf.
  73543. */
  73544. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  73545. char *zCsr = zBuf;
  73546. int f = pMem->flags;
  73547. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  73548. if( f&MEM_Blob ){
  73549. int i;
  73550. char c;
  73551. if( f & MEM_Dyn ){
  73552. c = 'z';
  73553. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  73554. }else if( f & MEM_Static ){
  73555. c = 't';
  73556. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  73557. }else if( f & MEM_Ephem ){
  73558. c = 'e';
  73559. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  73560. }else{
  73561. c = 's';
  73562. }
  73563. *(zCsr++) = c;
  73564. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  73565. zCsr += sqlite3Strlen30(zCsr);
  73566. for(i=0; i<16 && i<pMem->n; i++){
  73567. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  73568. zCsr += sqlite3Strlen30(zCsr);
  73569. }
  73570. for(i=0; i<16 && i<pMem->n; i++){
  73571. char z = pMem->z[i];
  73572. if( z<32 || z>126 ) *zCsr++ = '.';
  73573. else *zCsr++ = z;
  73574. }
  73575. *(zCsr++) = ']';
  73576. if( f & MEM_Zero ){
  73577. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  73578. zCsr += sqlite3Strlen30(zCsr);
  73579. }
  73580. *zCsr = '\0';
  73581. }else if( f & MEM_Str ){
  73582. int j, k;
  73583. zBuf[0] = ' ';
  73584. if( f & MEM_Dyn ){
  73585. zBuf[1] = 'z';
  73586. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  73587. }else if( f & MEM_Static ){
  73588. zBuf[1] = 't';
  73589. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  73590. }else if( f & MEM_Ephem ){
  73591. zBuf[1] = 'e';
  73592. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  73593. }else{
  73594. zBuf[1] = 's';
  73595. }
  73596. k = 2;
  73597. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  73598. k += sqlite3Strlen30(&zBuf[k]);
  73599. zBuf[k++] = '[';
  73600. for(j=0; j<15 && j<pMem->n; j++){
  73601. u8 c = pMem->z[j];
  73602. if( c>=0x20 && c<0x7f ){
  73603. zBuf[k++] = c;
  73604. }else{
  73605. zBuf[k++] = '.';
  73606. }
  73607. }
  73608. zBuf[k++] = ']';
  73609. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  73610. k += sqlite3Strlen30(&zBuf[k]);
  73611. zBuf[k++] = 0;
  73612. }
  73613. }
  73614. #endif
  73615. #ifdef SQLITE_DEBUG
  73616. /*
  73617. ** Print the value of a register for tracing purposes:
  73618. */
  73619. static void memTracePrint(Mem *p){
  73620. if( p->flags & MEM_Undefined ){
  73621. printf(" undefined");
  73622. }else if( p->flags & MEM_Null ){
  73623. printf(" NULL");
  73624. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  73625. printf(" si:%lld", p->u.i);
  73626. }else if( p->flags & MEM_Int ){
  73627. printf(" i:%lld", p->u.i);
  73628. #ifndef SQLITE_OMIT_FLOATING_POINT
  73629. }else if( p->flags & MEM_Real ){
  73630. printf(" r:%g", p->u.r);
  73631. #endif
  73632. }else if( p->flags & MEM_RowSet ){
  73633. printf(" (rowset)");
  73634. }else{
  73635. char zBuf[200];
  73636. sqlite3VdbeMemPrettyPrint(p, zBuf);
  73637. printf(" %s", zBuf);
  73638. }
  73639. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  73640. }
  73641. static void registerTrace(int iReg, Mem *p){
  73642. printf("REG[%d] = ", iReg);
  73643. memTracePrint(p);
  73644. printf("\n");
  73645. sqlite3VdbeCheckMemInvariants(p);
  73646. }
  73647. #endif
  73648. #ifdef SQLITE_DEBUG
  73649. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  73650. #else
  73651. # define REGISTER_TRACE(R,M)
  73652. #endif
  73653. #ifdef VDBE_PROFILE
  73654. /*
  73655. ** hwtime.h contains inline assembler code for implementing
  73656. ** high-performance timing routines.
  73657. */
  73658. /************** Include hwtime.h in the middle of vdbe.c *********************/
  73659. /************** Begin file hwtime.h ******************************************/
  73660. /*
  73661. ** 2008 May 27
  73662. **
  73663. ** The author disclaims copyright to this source code. In place of
  73664. ** a legal notice, here is a blessing:
  73665. **
  73666. ** May you do good and not evil.
  73667. ** May you find forgiveness for yourself and forgive others.
  73668. ** May you share freely, never taking more than you give.
  73669. **
  73670. ******************************************************************************
  73671. **
  73672. ** This file contains inline asm code for retrieving "high-performance"
  73673. ** counters for x86 class CPUs.
  73674. */
  73675. #ifndef SQLITE_HWTIME_H
  73676. #define SQLITE_HWTIME_H
  73677. /*
  73678. ** The following routine only works on pentium-class (or newer) processors.
  73679. ** It uses the RDTSC opcode to read the cycle count value out of the
  73680. ** processor and returns that value. This can be used for high-res
  73681. ** profiling.
  73682. */
  73683. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  73684. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  73685. #if defined(__GNUC__)
  73686. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  73687. unsigned int lo, hi;
  73688. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  73689. return (sqlite_uint64)hi << 32 | lo;
  73690. }
  73691. #elif defined(_MSC_VER)
  73692. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  73693. __asm {
  73694. rdtsc
  73695. ret ; return value at EDX:EAX
  73696. }
  73697. }
  73698. #endif
  73699. #elif (defined(__GNUC__) && defined(__x86_64__))
  73700. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  73701. unsigned long val;
  73702. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  73703. return val;
  73704. }
  73705. #elif (defined(__GNUC__) && defined(__ppc__))
  73706. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  73707. unsigned long long retval;
  73708. unsigned long junk;
  73709. __asm__ __volatile__ ("\n\
  73710. 1: mftbu %1\n\
  73711. mftb %L0\n\
  73712. mftbu %0\n\
  73713. cmpw %0,%1\n\
  73714. bne 1b"
  73715. : "=r" (retval), "=r" (junk));
  73716. return retval;
  73717. }
  73718. #else
  73719. #error Need implementation of sqlite3Hwtime() for your platform.
  73720. /*
  73721. ** To compile without implementing sqlite3Hwtime() for your platform,
  73722. ** you can remove the above #error and use the following
  73723. ** stub function. You will lose timing support for many
  73724. ** of the debugging and testing utilities, but it should at
  73725. ** least compile and run.
  73726. */
  73727. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  73728. #endif
  73729. #endif /* !defined(SQLITE_HWTIME_H) */
  73730. /************** End of hwtime.h **********************************************/
  73731. /************** Continuing where we left off in vdbe.c ***********************/
  73732. #endif
  73733. #ifndef NDEBUG
  73734. /*
  73735. ** This function is only called from within an assert() expression. It
  73736. ** checks that the sqlite3.nTransaction variable is correctly set to
  73737. ** the number of non-transaction savepoints currently in the
  73738. ** linked list starting at sqlite3.pSavepoint.
  73739. **
  73740. ** Usage:
  73741. **
  73742. ** assert( checkSavepointCount(db) );
  73743. */
  73744. static int checkSavepointCount(sqlite3 *db){
  73745. int n = 0;
  73746. Savepoint *p;
  73747. for(p=db->pSavepoint; p; p=p->pNext) n++;
  73748. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  73749. return 1;
  73750. }
  73751. #endif
  73752. /*
  73753. ** Return the register of pOp->p2 after first preparing it to be
  73754. ** overwritten with an integer value.
  73755. */
  73756. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  73757. sqlite3VdbeMemSetNull(pOut);
  73758. pOut->flags = MEM_Int;
  73759. return pOut;
  73760. }
  73761. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  73762. Mem *pOut;
  73763. assert( pOp->p2>0 );
  73764. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  73765. pOut = &p->aMem[pOp->p2];
  73766. memAboutToChange(p, pOut);
  73767. if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
  73768. return out2PrereleaseWithClear(pOut);
  73769. }else{
  73770. pOut->flags = MEM_Int;
  73771. return pOut;
  73772. }
  73773. }
  73774. /*
  73775. ** Execute as much of a VDBE program as we can.
  73776. ** This is the core of sqlite3_step().
  73777. */
  73778. SQLITE_PRIVATE int sqlite3VdbeExec(
  73779. Vdbe *p /* The VDBE */
  73780. ){
  73781. Op *aOp = p->aOp; /* Copy of p->aOp */
  73782. Op *pOp = aOp; /* Current operation */
  73783. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  73784. Op *pOrigOp; /* Value of pOp at the top of the loop */
  73785. #endif
  73786. #ifdef SQLITE_DEBUG
  73787. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  73788. #endif
  73789. int rc = SQLITE_OK; /* Value to return */
  73790. sqlite3 *db = p->db; /* The database */
  73791. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  73792. u8 encoding = ENC(db); /* The database encoding */
  73793. int iCompare = 0; /* Result of last comparison */
  73794. unsigned nVmStep = 0; /* Number of virtual machine steps */
  73795. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  73796. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  73797. #endif
  73798. Mem *aMem = p->aMem; /* Copy of p->aMem */
  73799. Mem *pIn1 = 0; /* 1st input operand */
  73800. Mem *pIn2 = 0; /* 2nd input operand */
  73801. Mem *pIn3 = 0; /* 3rd input operand */
  73802. Mem *pOut = 0; /* Output operand */
  73803. #ifdef VDBE_PROFILE
  73804. u64 start; /* CPU clock count at start of opcode */
  73805. #endif
  73806. /*** INSERT STACK UNION HERE ***/
  73807. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  73808. sqlite3VdbeEnter(p);
  73809. if( p->rc==SQLITE_NOMEM ){
  73810. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  73811. ** sqlite3_column_text16() failed. */
  73812. goto no_mem;
  73813. }
  73814. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  73815. assert( p->bIsReader || p->readOnly!=0 );
  73816. p->iCurrentTime = 0;
  73817. assert( p->explain==0 );
  73818. p->pResultSet = 0;
  73819. db->busyHandler.nBusy = 0;
  73820. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  73821. sqlite3VdbeIOTraceSql(p);
  73822. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  73823. if( db->xProgress ){
  73824. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  73825. assert( 0 < db->nProgressOps );
  73826. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  73827. }
  73828. #endif
  73829. #ifdef SQLITE_DEBUG
  73830. sqlite3BeginBenignMalloc();
  73831. if( p->pc==0
  73832. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  73833. ){
  73834. int i;
  73835. int once = 1;
  73836. sqlite3VdbePrintSql(p);
  73837. if( p->db->flags & SQLITE_VdbeListing ){
  73838. printf("VDBE Program Listing:\n");
  73839. for(i=0; i<p->nOp; i++){
  73840. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  73841. }
  73842. }
  73843. if( p->db->flags & SQLITE_VdbeEQP ){
  73844. for(i=0; i<p->nOp; i++){
  73845. if( aOp[i].opcode==OP_Explain ){
  73846. if( once ) printf("VDBE Query Plan:\n");
  73847. printf("%s\n", aOp[i].p4.z);
  73848. once = 0;
  73849. }
  73850. }
  73851. }
  73852. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  73853. }
  73854. sqlite3EndBenignMalloc();
  73855. #endif
  73856. for(pOp=&aOp[p->pc]; 1; pOp++){
  73857. /* Errors are detected by individual opcodes, with an immediate
  73858. ** jumps to abort_due_to_error. */
  73859. assert( rc==SQLITE_OK );
  73860. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  73861. #ifdef VDBE_PROFILE
  73862. start = sqlite3Hwtime();
  73863. #endif
  73864. nVmStep++;
  73865. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73866. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  73867. #endif
  73868. /* Only allow tracing if SQLITE_DEBUG is defined.
  73869. */
  73870. #ifdef SQLITE_DEBUG
  73871. if( db->flags & SQLITE_VdbeTrace ){
  73872. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  73873. }
  73874. #endif
  73875. /* Check to see if we need to simulate an interrupt. This only happens
  73876. ** if we have a special test build.
  73877. */
  73878. #ifdef SQLITE_TEST
  73879. if( sqlite3_interrupt_count>0 ){
  73880. sqlite3_interrupt_count--;
  73881. if( sqlite3_interrupt_count==0 ){
  73882. sqlite3_interrupt(db);
  73883. }
  73884. }
  73885. #endif
  73886. /* Sanity checking on other operands */
  73887. #ifdef SQLITE_DEBUG
  73888. {
  73889. u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
  73890. if( (opProperty & OPFLG_IN1)!=0 ){
  73891. assert( pOp->p1>0 );
  73892. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  73893. assert( memIsValid(&aMem[pOp->p1]) );
  73894. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  73895. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  73896. }
  73897. if( (opProperty & OPFLG_IN2)!=0 ){
  73898. assert( pOp->p2>0 );
  73899. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  73900. assert( memIsValid(&aMem[pOp->p2]) );
  73901. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  73902. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  73903. }
  73904. if( (opProperty & OPFLG_IN3)!=0 ){
  73905. assert( pOp->p3>0 );
  73906. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  73907. assert( memIsValid(&aMem[pOp->p3]) );
  73908. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  73909. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  73910. }
  73911. if( (opProperty & OPFLG_OUT2)!=0 ){
  73912. assert( pOp->p2>0 );
  73913. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  73914. memAboutToChange(p, &aMem[pOp->p2]);
  73915. }
  73916. if( (opProperty & OPFLG_OUT3)!=0 ){
  73917. assert( pOp->p3>0 );
  73918. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  73919. memAboutToChange(p, &aMem[pOp->p3]);
  73920. }
  73921. }
  73922. #endif
  73923. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  73924. pOrigOp = pOp;
  73925. #endif
  73926. switch( pOp->opcode ){
  73927. /*****************************************************************************
  73928. ** What follows is a massive switch statement where each case implements a
  73929. ** separate instruction in the virtual machine. If we follow the usual
  73930. ** indentation conventions, each case should be indented by 6 spaces. But
  73931. ** that is a lot of wasted space on the left margin. So the code within
  73932. ** the switch statement will break with convention and be flush-left. Another
  73933. ** big comment (similar to this one) will mark the point in the code where
  73934. ** we transition back to normal indentation.
  73935. **
  73936. ** The formatting of each case is important. The makefile for SQLite
  73937. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  73938. ** file looking for lines that begin with "case OP_". The opcodes.h files
  73939. ** will be filled with #defines that give unique integer values to each
  73940. ** opcode and the opcodes.c file is filled with an array of strings where
  73941. ** each string is the symbolic name for the corresponding opcode. If the
  73942. ** case statement is followed by a comment of the form "/# same as ... #/"
  73943. ** that comment is used to determine the particular value of the opcode.
  73944. **
  73945. ** Other keywords in the comment that follows each case are used to
  73946. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  73947. ** Keywords include: in1, in2, in3, out2, out3. See
  73948. ** the mkopcodeh.awk script for additional information.
  73949. **
  73950. ** Documentation about VDBE opcodes is generated by scanning this file
  73951. ** for lines of that contain "Opcode:". That line and all subsequent
  73952. ** comment lines are used in the generation of the opcode.html documentation
  73953. ** file.
  73954. **
  73955. ** SUMMARY:
  73956. **
  73957. ** Formatting is important to scripts that scan this file.
  73958. ** Do not deviate from the formatting style currently in use.
  73959. **
  73960. *****************************************************************************/
  73961. /* Opcode: Goto * P2 * * *
  73962. **
  73963. ** An unconditional jump to address P2.
  73964. ** The next instruction executed will be
  73965. ** the one at index P2 from the beginning of
  73966. ** the program.
  73967. **
  73968. ** The P1 parameter is not actually used by this opcode. However, it
  73969. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  73970. ** that this Goto is the bottom of a loop and that the lines from P2 down
  73971. ** to the current line should be indented for EXPLAIN output.
  73972. */
  73973. case OP_Goto: { /* jump */
  73974. jump_to_p2_and_check_for_interrupt:
  73975. pOp = &aOp[pOp->p2 - 1];
  73976. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  73977. ** OP_VNext, or OP_SorterNext) all jump here upon
  73978. ** completion. Check to see if sqlite3_interrupt() has been called
  73979. ** or if the progress callback needs to be invoked.
  73980. **
  73981. ** This code uses unstructured "goto" statements and does not look clean.
  73982. ** But that is not due to sloppy coding habits. The code is written this
  73983. ** way for performance, to avoid having to run the interrupt and progress
  73984. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  73985. ** faster according to "valgrind --tool=cachegrind" */
  73986. check_for_interrupt:
  73987. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  73988. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  73989. /* Call the progress callback if it is configured and the required number
  73990. ** of VDBE ops have been executed (either since this invocation of
  73991. ** sqlite3VdbeExec() or since last time the progress callback was called).
  73992. ** If the progress callback returns non-zero, exit the virtual machine with
  73993. ** a return code SQLITE_ABORT.
  73994. */
  73995. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  73996. assert( db->nProgressOps!=0 );
  73997. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  73998. if( db->xProgress(db->pProgressArg) ){
  73999. rc = SQLITE_INTERRUPT;
  74000. goto abort_due_to_error;
  74001. }
  74002. }
  74003. #endif
  74004. break;
  74005. }
  74006. /* Opcode: Gosub P1 P2 * * *
  74007. **
  74008. ** Write the current address onto register P1
  74009. ** and then jump to address P2.
  74010. */
  74011. case OP_Gosub: { /* jump */
  74012. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  74013. pIn1 = &aMem[pOp->p1];
  74014. assert( VdbeMemDynamic(pIn1)==0 );
  74015. memAboutToChange(p, pIn1);
  74016. pIn1->flags = MEM_Int;
  74017. pIn1->u.i = (int)(pOp-aOp);
  74018. REGISTER_TRACE(pOp->p1, pIn1);
  74019. /* Most jump operations do a goto to this spot in order to update
  74020. ** the pOp pointer. */
  74021. jump_to_p2:
  74022. pOp = &aOp[pOp->p2 - 1];
  74023. break;
  74024. }
  74025. /* Opcode: Return P1 * * * *
  74026. **
  74027. ** Jump to the next instruction after the address in register P1. After
  74028. ** the jump, register P1 becomes undefined.
  74029. */
  74030. case OP_Return: { /* in1 */
  74031. pIn1 = &aMem[pOp->p1];
  74032. assert( pIn1->flags==MEM_Int );
  74033. pOp = &aOp[pIn1->u.i];
  74034. pIn1->flags = MEM_Undefined;
  74035. break;
  74036. }
  74037. /* Opcode: InitCoroutine P1 P2 P3 * *
  74038. **
  74039. ** Set up register P1 so that it will Yield to the coroutine
  74040. ** located at address P3.
  74041. **
  74042. ** If P2!=0 then the coroutine implementation immediately follows
  74043. ** this opcode. So jump over the coroutine implementation to
  74044. ** address P2.
  74045. **
  74046. ** See also: EndCoroutine
  74047. */
  74048. case OP_InitCoroutine: { /* jump */
  74049. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  74050. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  74051. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  74052. pOut = &aMem[pOp->p1];
  74053. assert( !VdbeMemDynamic(pOut) );
  74054. pOut->u.i = pOp->p3 - 1;
  74055. pOut->flags = MEM_Int;
  74056. if( pOp->p2 ) goto jump_to_p2;
  74057. break;
  74058. }
  74059. /* Opcode: EndCoroutine P1 * * * *
  74060. **
  74061. ** The instruction at the address in register P1 is a Yield.
  74062. ** Jump to the P2 parameter of that Yield.
  74063. ** After the jump, register P1 becomes undefined.
  74064. **
  74065. ** See also: InitCoroutine
  74066. */
  74067. case OP_EndCoroutine: { /* in1 */
  74068. VdbeOp *pCaller;
  74069. pIn1 = &aMem[pOp->p1];
  74070. assert( pIn1->flags==MEM_Int );
  74071. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  74072. pCaller = &aOp[pIn1->u.i];
  74073. assert( pCaller->opcode==OP_Yield );
  74074. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  74075. pOp = &aOp[pCaller->p2 - 1];
  74076. pIn1->flags = MEM_Undefined;
  74077. break;
  74078. }
  74079. /* Opcode: Yield P1 P2 * * *
  74080. **
  74081. ** Swap the program counter with the value in register P1. This
  74082. ** has the effect of yielding to a coroutine.
  74083. **
  74084. ** If the coroutine that is launched by this instruction ends with
  74085. ** Yield or Return then continue to the next instruction. But if
  74086. ** the coroutine launched by this instruction ends with
  74087. ** EndCoroutine, then jump to P2 rather than continuing with the
  74088. ** next instruction.
  74089. **
  74090. ** See also: InitCoroutine
  74091. */
  74092. case OP_Yield: { /* in1, jump */
  74093. int pcDest;
  74094. pIn1 = &aMem[pOp->p1];
  74095. assert( VdbeMemDynamic(pIn1)==0 );
  74096. pIn1->flags = MEM_Int;
  74097. pcDest = (int)pIn1->u.i;
  74098. pIn1->u.i = (int)(pOp - aOp);
  74099. REGISTER_TRACE(pOp->p1, pIn1);
  74100. pOp = &aOp[pcDest];
  74101. break;
  74102. }
  74103. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  74104. ** Synopsis: if r[P3]=null halt
  74105. **
  74106. ** Check the value in register P3. If it is NULL then Halt using
  74107. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  74108. ** value in register P3 is not NULL, then this routine is a no-op.
  74109. ** The P5 parameter should be 1.
  74110. */
  74111. case OP_HaltIfNull: { /* in3 */
  74112. pIn3 = &aMem[pOp->p3];
  74113. if( (pIn3->flags & MEM_Null)==0 ) break;
  74114. /* Fall through into OP_Halt */
  74115. }
  74116. /* Opcode: Halt P1 P2 * P4 P5
  74117. **
  74118. ** Exit immediately. All open cursors, etc are closed
  74119. ** automatically.
  74120. **
  74121. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  74122. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  74123. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  74124. ** whether or not to rollback the current transaction. Do not rollback
  74125. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  74126. ** then back out all changes that have occurred during this execution of the
  74127. ** VDBE, but do not rollback the transaction.
  74128. **
  74129. ** If P4 is not null then it is an error message string.
  74130. **
  74131. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  74132. **
  74133. ** 0: (no change)
  74134. ** 1: NOT NULL contraint failed: P4
  74135. ** 2: UNIQUE constraint failed: P4
  74136. ** 3: CHECK constraint failed: P4
  74137. ** 4: FOREIGN KEY constraint failed: P4
  74138. **
  74139. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  74140. ** omitted.
  74141. **
  74142. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  74143. ** every program. So a jump past the last instruction of the program
  74144. ** is the same as executing Halt.
  74145. */
  74146. case OP_Halt: {
  74147. VdbeFrame *pFrame;
  74148. int pcx;
  74149. pcx = (int)(pOp - aOp);
  74150. if( pOp->p1==SQLITE_OK && p->pFrame ){
  74151. /* Halt the sub-program. Return control to the parent frame. */
  74152. pFrame = p->pFrame;
  74153. p->pFrame = pFrame->pParent;
  74154. p->nFrame--;
  74155. sqlite3VdbeSetChanges(db, p->nChange);
  74156. pcx = sqlite3VdbeFrameRestore(pFrame);
  74157. if( pOp->p2==OE_Ignore ){
  74158. /* Instruction pcx is the OP_Program that invoked the sub-program
  74159. ** currently being halted. If the p2 instruction of this OP_Halt
  74160. ** instruction is set to OE_Ignore, then the sub-program is throwing
  74161. ** an IGNORE exception. In this case jump to the address specified
  74162. ** as the p2 of the calling OP_Program. */
  74163. pcx = p->aOp[pcx].p2-1;
  74164. }
  74165. aOp = p->aOp;
  74166. aMem = p->aMem;
  74167. pOp = &aOp[pcx];
  74168. break;
  74169. }
  74170. p->rc = pOp->p1;
  74171. p->errorAction = (u8)pOp->p2;
  74172. p->pc = pcx;
  74173. assert( pOp->p5<=4 );
  74174. if( p->rc ){
  74175. if( pOp->p5 ){
  74176. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  74177. "FOREIGN KEY" };
  74178. testcase( pOp->p5==1 );
  74179. testcase( pOp->p5==2 );
  74180. testcase( pOp->p5==3 );
  74181. testcase( pOp->p5==4 );
  74182. sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
  74183. if( pOp->p4.z ){
  74184. p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
  74185. }
  74186. }else{
  74187. sqlite3VdbeError(p, "%s", pOp->p4.z);
  74188. }
  74189. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
  74190. }
  74191. rc = sqlite3VdbeHalt(p);
  74192. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  74193. if( rc==SQLITE_BUSY ){
  74194. p->rc = SQLITE_BUSY;
  74195. }else{
  74196. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  74197. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  74198. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  74199. }
  74200. goto vdbe_return;
  74201. }
  74202. /* Opcode: Integer P1 P2 * * *
  74203. ** Synopsis: r[P2]=P1
  74204. **
  74205. ** The 32-bit integer value P1 is written into register P2.
  74206. */
  74207. case OP_Integer: { /* out2 */
  74208. pOut = out2Prerelease(p, pOp);
  74209. pOut->u.i = pOp->p1;
  74210. break;
  74211. }
  74212. /* Opcode: Int64 * P2 * P4 *
  74213. ** Synopsis: r[P2]=P4
  74214. **
  74215. ** P4 is a pointer to a 64-bit integer value.
  74216. ** Write that value into register P2.
  74217. */
  74218. case OP_Int64: { /* out2 */
  74219. pOut = out2Prerelease(p, pOp);
  74220. assert( pOp->p4.pI64!=0 );
  74221. pOut->u.i = *pOp->p4.pI64;
  74222. break;
  74223. }
  74224. #ifndef SQLITE_OMIT_FLOATING_POINT
  74225. /* Opcode: Real * P2 * P4 *
  74226. ** Synopsis: r[P2]=P4
  74227. **
  74228. ** P4 is a pointer to a 64-bit floating point value.
  74229. ** Write that value into register P2.
  74230. */
  74231. case OP_Real: { /* same as TK_FLOAT, out2 */
  74232. pOut = out2Prerelease(p, pOp);
  74233. pOut->flags = MEM_Real;
  74234. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  74235. pOut->u.r = *pOp->p4.pReal;
  74236. break;
  74237. }
  74238. #endif
  74239. /* Opcode: String8 * P2 * P4 *
  74240. ** Synopsis: r[P2]='P4'
  74241. **
  74242. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  74243. ** into a String opcode before it is executed for the first time. During
  74244. ** this transformation, the length of string P4 is computed and stored
  74245. ** as the P1 parameter.
  74246. */
  74247. case OP_String8: { /* same as TK_STRING, out2 */
  74248. assert( pOp->p4.z!=0 );
  74249. pOut = out2Prerelease(p, pOp);
  74250. pOp->opcode = OP_String;
  74251. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  74252. #ifndef SQLITE_OMIT_UTF16
  74253. if( encoding!=SQLITE_UTF8 ){
  74254. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  74255. assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
  74256. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  74257. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  74258. assert( VdbeMemDynamic(pOut)==0 );
  74259. pOut->szMalloc = 0;
  74260. pOut->flags |= MEM_Static;
  74261. if( pOp->p4type==P4_DYNAMIC ){
  74262. sqlite3DbFree(db, pOp->p4.z);
  74263. }
  74264. pOp->p4type = P4_DYNAMIC;
  74265. pOp->p4.z = pOut->z;
  74266. pOp->p1 = pOut->n;
  74267. }
  74268. testcase( rc==SQLITE_TOOBIG );
  74269. #endif
  74270. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  74271. goto too_big;
  74272. }
  74273. assert( rc==SQLITE_OK );
  74274. /* Fall through to the next case, OP_String */
  74275. }
  74276. /* Opcode: String P1 P2 P3 P4 P5
  74277. ** Synopsis: r[P2]='P4' (len=P1)
  74278. **
  74279. ** The string value P4 of length P1 (bytes) is stored in register P2.
  74280. **
  74281. ** If P3 is not zero and the content of register P3 is equal to P5, then
  74282. ** the datatype of the register P2 is converted to BLOB. The content is
  74283. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  74284. ** of a string, as if it had been CAST. In other words:
  74285. **
  74286. ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
  74287. */
  74288. case OP_String: { /* out2 */
  74289. assert( pOp->p4.z!=0 );
  74290. pOut = out2Prerelease(p, pOp);
  74291. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  74292. pOut->z = pOp->p4.z;
  74293. pOut->n = pOp->p1;
  74294. pOut->enc = encoding;
  74295. UPDATE_MAX_BLOBSIZE(pOut);
  74296. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  74297. if( pOp->p3>0 ){
  74298. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  74299. pIn3 = &aMem[pOp->p3];
  74300. assert( pIn3->flags & MEM_Int );
  74301. if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  74302. }
  74303. #endif
  74304. break;
  74305. }
  74306. /* Opcode: Null P1 P2 P3 * *
  74307. ** Synopsis: r[P2..P3]=NULL
  74308. **
  74309. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  74310. ** NULL into register P3 and every register in between P2 and P3. If P3
  74311. ** is less than P2 (typically P3 is zero) then only register P2 is
  74312. ** set to NULL.
  74313. **
  74314. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  74315. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  74316. ** OP_Ne or OP_Eq.
  74317. */
  74318. case OP_Null: { /* out2 */
  74319. int cnt;
  74320. u16 nullFlag;
  74321. pOut = out2Prerelease(p, pOp);
  74322. cnt = pOp->p3-pOp->p2;
  74323. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  74324. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  74325. pOut->n = 0;
  74326. while( cnt>0 ){
  74327. pOut++;
  74328. memAboutToChange(p, pOut);
  74329. sqlite3VdbeMemSetNull(pOut);
  74330. pOut->flags = nullFlag;
  74331. pOut->n = 0;
  74332. cnt--;
  74333. }
  74334. break;
  74335. }
  74336. /* Opcode: SoftNull P1 * * * *
  74337. ** Synopsis: r[P1]=NULL
  74338. **
  74339. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  74340. ** instruction, but do not free any string or blob memory associated with
  74341. ** the register, so that if the value was a string or blob that was
  74342. ** previously copied using OP_SCopy, the copies will continue to be valid.
  74343. */
  74344. case OP_SoftNull: {
  74345. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  74346. pOut = &aMem[pOp->p1];
  74347. pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
  74348. break;
  74349. }
  74350. /* Opcode: Blob P1 P2 * P4 *
  74351. ** Synopsis: r[P2]=P4 (len=P1)
  74352. **
  74353. ** P4 points to a blob of data P1 bytes long. Store this
  74354. ** blob in register P2.
  74355. */
  74356. case OP_Blob: { /* out2 */
  74357. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  74358. pOut = out2Prerelease(p, pOp);
  74359. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  74360. pOut->enc = encoding;
  74361. UPDATE_MAX_BLOBSIZE(pOut);
  74362. break;
  74363. }
  74364. /* Opcode: Variable P1 P2 * P4 *
  74365. ** Synopsis: r[P2]=parameter(P1,P4)
  74366. **
  74367. ** Transfer the values of bound parameter P1 into register P2
  74368. **
  74369. ** If the parameter is named, then its name appears in P4.
  74370. ** The P4 value is used by sqlite3_bind_parameter_name().
  74371. */
  74372. case OP_Variable: { /* out2 */
  74373. Mem *pVar; /* Value being transferred */
  74374. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  74375. assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
  74376. pVar = &p->aVar[pOp->p1 - 1];
  74377. if( sqlite3VdbeMemTooBig(pVar) ){
  74378. goto too_big;
  74379. }
  74380. pOut = &aMem[pOp->p2];
  74381. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  74382. UPDATE_MAX_BLOBSIZE(pOut);
  74383. break;
  74384. }
  74385. /* Opcode: Move P1 P2 P3 * *
  74386. ** Synopsis: r[P2@P3]=r[P1@P3]
  74387. **
  74388. ** Move the P3 values in register P1..P1+P3-1 over into
  74389. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  74390. ** left holding a NULL. It is an error for register ranges
  74391. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  74392. ** for P3 to be less than 1.
  74393. */
  74394. case OP_Move: {
  74395. int n; /* Number of registers left to copy */
  74396. int p1; /* Register to copy from */
  74397. int p2; /* Register to copy to */
  74398. n = pOp->p3;
  74399. p1 = pOp->p1;
  74400. p2 = pOp->p2;
  74401. assert( n>0 && p1>0 && p2>0 );
  74402. assert( p1+n<=p2 || p2+n<=p1 );
  74403. pIn1 = &aMem[p1];
  74404. pOut = &aMem[p2];
  74405. do{
  74406. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  74407. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  74408. assert( memIsValid(pIn1) );
  74409. memAboutToChange(p, pOut);
  74410. sqlite3VdbeMemMove(pOut, pIn1);
  74411. #ifdef SQLITE_DEBUG
  74412. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  74413. pOut->pScopyFrom += pOp->p2 - p1;
  74414. }
  74415. #endif
  74416. Deephemeralize(pOut);
  74417. REGISTER_TRACE(p2++, pOut);
  74418. pIn1++;
  74419. pOut++;
  74420. }while( --n );
  74421. break;
  74422. }
  74423. /* Opcode: Copy P1 P2 P3 * *
  74424. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  74425. **
  74426. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  74427. **
  74428. ** This instruction makes a deep copy of the value. A duplicate
  74429. ** is made of any string or blob constant. See also OP_SCopy.
  74430. */
  74431. case OP_Copy: {
  74432. int n;
  74433. n = pOp->p3;
  74434. pIn1 = &aMem[pOp->p1];
  74435. pOut = &aMem[pOp->p2];
  74436. assert( pOut!=pIn1 );
  74437. while( 1 ){
  74438. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  74439. Deephemeralize(pOut);
  74440. #ifdef SQLITE_DEBUG
  74441. pOut->pScopyFrom = 0;
  74442. #endif
  74443. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  74444. if( (n--)==0 ) break;
  74445. pOut++;
  74446. pIn1++;
  74447. }
  74448. break;
  74449. }
  74450. /* Opcode: SCopy P1 P2 * * *
  74451. ** Synopsis: r[P2]=r[P1]
  74452. **
  74453. ** Make a shallow copy of register P1 into register P2.
  74454. **
  74455. ** This instruction makes a shallow copy of the value. If the value
  74456. ** is a string or blob, then the copy is only a pointer to the
  74457. ** original and hence if the original changes so will the copy.
  74458. ** Worse, if the original is deallocated, the copy becomes invalid.
  74459. ** Thus the program must guarantee that the original will not change
  74460. ** during the lifetime of the copy. Use OP_Copy to make a complete
  74461. ** copy.
  74462. */
  74463. case OP_SCopy: { /* out2 */
  74464. pIn1 = &aMem[pOp->p1];
  74465. pOut = &aMem[pOp->p2];
  74466. assert( pOut!=pIn1 );
  74467. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  74468. #ifdef SQLITE_DEBUG
  74469. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  74470. #endif
  74471. break;
  74472. }
  74473. /* Opcode: IntCopy P1 P2 * * *
  74474. ** Synopsis: r[P2]=r[P1]
  74475. **
  74476. ** Transfer the integer value held in register P1 into register P2.
  74477. **
  74478. ** This is an optimized version of SCopy that works only for integer
  74479. ** values.
  74480. */
  74481. case OP_IntCopy: { /* out2 */
  74482. pIn1 = &aMem[pOp->p1];
  74483. assert( (pIn1->flags & MEM_Int)!=0 );
  74484. pOut = &aMem[pOp->p2];
  74485. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  74486. break;
  74487. }
  74488. /* Opcode: ResultRow P1 P2 * * *
  74489. ** Synopsis: output=r[P1@P2]
  74490. **
  74491. ** The registers P1 through P1+P2-1 contain a single row of
  74492. ** results. This opcode causes the sqlite3_step() call to terminate
  74493. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  74494. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  74495. ** the result row.
  74496. */
  74497. case OP_ResultRow: {
  74498. Mem *pMem;
  74499. int i;
  74500. assert( p->nResColumn==pOp->p2 );
  74501. assert( pOp->p1>0 );
  74502. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  74503. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  74504. /* Run the progress counter just before returning.
  74505. */
  74506. if( db->xProgress!=0
  74507. && nVmStep>=nProgressLimit
  74508. && db->xProgress(db->pProgressArg)!=0
  74509. ){
  74510. rc = SQLITE_INTERRUPT;
  74511. goto abort_due_to_error;
  74512. }
  74513. #endif
  74514. /* If this statement has violated immediate foreign key constraints, do
  74515. ** not return the number of rows modified. And do not RELEASE the statement
  74516. ** transaction. It needs to be rolled back. */
  74517. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  74518. assert( db->flags&SQLITE_CountRows );
  74519. assert( p->usesStmtJournal );
  74520. goto abort_due_to_error;
  74521. }
  74522. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  74523. ** DML statements invoke this opcode to return the number of rows
  74524. ** modified to the user. This is the only way that a VM that
  74525. ** opens a statement transaction may invoke this opcode.
  74526. **
  74527. ** In case this is such a statement, close any statement transaction
  74528. ** opened by this VM before returning control to the user. This is to
  74529. ** ensure that statement-transactions are always nested, not overlapping.
  74530. ** If the open statement-transaction is not closed here, then the user
  74531. ** may step another VM that opens its own statement transaction. This
  74532. ** may lead to overlapping statement transactions.
  74533. **
  74534. ** The statement transaction is never a top-level transaction. Hence
  74535. ** the RELEASE call below can never fail.
  74536. */
  74537. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  74538. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  74539. assert( rc==SQLITE_OK );
  74540. /* Invalidate all ephemeral cursor row caches */
  74541. p->cacheCtr = (p->cacheCtr + 2)|1;
  74542. /* Make sure the results of the current row are \000 terminated
  74543. ** and have an assigned type. The results are de-ephemeralized as
  74544. ** a side effect.
  74545. */
  74546. pMem = p->pResultSet = &aMem[pOp->p1];
  74547. for(i=0; i<pOp->p2; i++){
  74548. assert( memIsValid(&pMem[i]) );
  74549. Deephemeralize(&pMem[i]);
  74550. assert( (pMem[i].flags & MEM_Ephem)==0
  74551. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  74552. sqlite3VdbeMemNulTerminate(&pMem[i]);
  74553. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  74554. }
  74555. if( db->mallocFailed ) goto no_mem;
  74556. if( db->mTrace & SQLITE_TRACE_ROW ){
  74557. db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
  74558. }
  74559. /* Return SQLITE_ROW
  74560. */
  74561. p->pc = (int)(pOp - aOp) + 1;
  74562. rc = SQLITE_ROW;
  74563. goto vdbe_return;
  74564. }
  74565. /* Opcode: Concat P1 P2 P3 * *
  74566. ** Synopsis: r[P3]=r[P2]+r[P1]
  74567. **
  74568. ** Add the text in register P1 onto the end of the text in
  74569. ** register P2 and store the result in register P3.
  74570. ** If either the P1 or P2 text are NULL then store NULL in P3.
  74571. **
  74572. ** P3 = P2 || P1
  74573. **
  74574. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  74575. ** if P3 is the same register as P2, the implementation is able
  74576. ** to avoid a memcpy().
  74577. */
  74578. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  74579. i64 nByte;
  74580. pIn1 = &aMem[pOp->p1];
  74581. pIn2 = &aMem[pOp->p2];
  74582. pOut = &aMem[pOp->p3];
  74583. assert( pIn1!=pOut );
  74584. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  74585. sqlite3VdbeMemSetNull(pOut);
  74586. break;
  74587. }
  74588. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  74589. Stringify(pIn1, encoding);
  74590. Stringify(pIn2, encoding);
  74591. nByte = pIn1->n + pIn2->n;
  74592. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  74593. goto too_big;
  74594. }
  74595. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  74596. goto no_mem;
  74597. }
  74598. MemSetTypeFlag(pOut, MEM_Str);
  74599. if( pOut!=pIn2 ){
  74600. memcpy(pOut->z, pIn2->z, pIn2->n);
  74601. }
  74602. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  74603. pOut->z[nByte]=0;
  74604. pOut->z[nByte+1] = 0;
  74605. pOut->flags |= MEM_Term;
  74606. pOut->n = (int)nByte;
  74607. pOut->enc = encoding;
  74608. UPDATE_MAX_BLOBSIZE(pOut);
  74609. break;
  74610. }
  74611. /* Opcode: Add P1 P2 P3 * *
  74612. ** Synopsis: r[P3]=r[P1]+r[P2]
  74613. **
  74614. ** Add the value in register P1 to the value in register P2
  74615. ** and store the result in register P3.
  74616. ** If either input is NULL, the result is NULL.
  74617. */
  74618. /* Opcode: Multiply P1 P2 P3 * *
  74619. ** Synopsis: r[P3]=r[P1]*r[P2]
  74620. **
  74621. **
  74622. ** Multiply the value in register P1 by the value in register P2
  74623. ** and store the result in register P3.
  74624. ** If either input is NULL, the result is NULL.
  74625. */
  74626. /* Opcode: Subtract P1 P2 P3 * *
  74627. ** Synopsis: r[P3]=r[P2]-r[P1]
  74628. **
  74629. ** Subtract the value in register P1 from the value in register P2
  74630. ** and store the result in register P3.
  74631. ** If either input is NULL, the result is NULL.
  74632. */
  74633. /* Opcode: Divide P1 P2 P3 * *
  74634. ** Synopsis: r[P3]=r[P2]/r[P1]
  74635. **
  74636. ** Divide the value in register P1 by the value in register P2
  74637. ** and store the result in register P3 (P3=P2/P1). If the value in
  74638. ** register P1 is zero, then the result is NULL. If either input is
  74639. ** NULL, the result is NULL.
  74640. */
  74641. /* Opcode: Remainder P1 P2 P3 * *
  74642. ** Synopsis: r[P3]=r[P2]%r[P1]
  74643. **
  74644. ** Compute the remainder after integer register P2 is divided by
  74645. ** register P1 and store the result in register P3.
  74646. ** If the value in register P1 is zero the result is NULL.
  74647. ** If either operand is NULL, the result is NULL.
  74648. */
  74649. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  74650. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  74651. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  74652. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  74653. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  74654. char bIntint; /* Started out as two integer operands */
  74655. u16 flags; /* Combined MEM_* flags from both inputs */
  74656. u16 type1; /* Numeric type of left operand */
  74657. u16 type2; /* Numeric type of right operand */
  74658. i64 iA; /* Integer value of left operand */
  74659. i64 iB; /* Integer value of right operand */
  74660. double rA; /* Real value of left operand */
  74661. double rB; /* Real value of right operand */
  74662. pIn1 = &aMem[pOp->p1];
  74663. type1 = numericType(pIn1);
  74664. pIn2 = &aMem[pOp->p2];
  74665. type2 = numericType(pIn2);
  74666. pOut = &aMem[pOp->p3];
  74667. flags = pIn1->flags | pIn2->flags;
  74668. if( (type1 & type2 & MEM_Int)!=0 ){
  74669. iA = pIn1->u.i;
  74670. iB = pIn2->u.i;
  74671. bIntint = 1;
  74672. switch( pOp->opcode ){
  74673. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  74674. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  74675. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  74676. case OP_Divide: {
  74677. if( iA==0 ) goto arithmetic_result_is_null;
  74678. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  74679. iB /= iA;
  74680. break;
  74681. }
  74682. default: {
  74683. if( iA==0 ) goto arithmetic_result_is_null;
  74684. if( iA==-1 ) iA = 1;
  74685. iB %= iA;
  74686. break;
  74687. }
  74688. }
  74689. pOut->u.i = iB;
  74690. MemSetTypeFlag(pOut, MEM_Int);
  74691. }else if( (flags & MEM_Null)!=0 ){
  74692. goto arithmetic_result_is_null;
  74693. }else{
  74694. bIntint = 0;
  74695. fp_math:
  74696. rA = sqlite3VdbeRealValue(pIn1);
  74697. rB = sqlite3VdbeRealValue(pIn2);
  74698. switch( pOp->opcode ){
  74699. case OP_Add: rB += rA; break;
  74700. case OP_Subtract: rB -= rA; break;
  74701. case OP_Multiply: rB *= rA; break;
  74702. case OP_Divide: {
  74703. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  74704. if( rA==(double)0 ) goto arithmetic_result_is_null;
  74705. rB /= rA;
  74706. break;
  74707. }
  74708. default: {
  74709. iA = (i64)rA;
  74710. iB = (i64)rB;
  74711. if( iA==0 ) goto arithmetic_result_is_null;
  74712. if( iA==-1 ) iA = 1;
  74713. rB = (double)(iB % iA);
  74714. break;
  74715. }
  74716. }
  74717. #ifdef SQLITE_OMIT_FLOATING_POINT
  74718. pOut->u.i = rB;
  74719. MemSetTypeFlag(pOut, MEM_Int);
  74720. #else
  74721. if( sqlite3IsNaN(rB) ){
  74722. goto arithmetic_result_is_null;
  74723. }
  74724. pOut->u.r = rB;
  74725. MemSetTypeFlag(pOut, MEM_Real);
  74726. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  74727. sqlite3VdbeIntegerAffinity(pOut);
  74728. }
  74729. #endif
  74730. }
  74731. break;
  74732. arithmetic_result_is_null:
  74733. sqlite3VdbeMemSetNull(pOut);
  74734. break;
  74735. }
  74736. /* Opcode: CollSeq P1 * * P4
  74737. **
  74738. ** P4 is a pointer to a CollSeq object. If the next call to a user function
  74739. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  74740. ** be returned. This is used by the built-in min(), max() and nullif()
  74741. ** functions.
  74742. **
  74743. ** If P1 is not zero, then it is a register that a subsequent min() or
  74744. ** max() aggregate will set to 1 if the current row is not the minimum or
  74745. ** maximum. The P1 register is initialized to 0 by this instruction.
  74746. **
  74747. ** The interface used by the implementation of the aforementioned functions
  74748. ** to retrieve the collation sequence set by this opcode is not available
  74749. ** publicly. Only built-in functions have access to this feature.
  74750. */
  74751. case OP_CollSeq: {
  74752. assert( pOp->p4type==P4_COLLSEQ );
  74753. if( pOp->p1 ){
  74754. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  74755. }
  74756. break;
  74757. }
  74758. /* Opcode: Function0 P1 P2 P3 P4 P5
  74759. ** Synopsis: r[P3]=func(r[P2@P5])
  74760. **
  74761. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  74762. ** defines the function) with P5 arguments taken from register P2 and
  74763. ** successors. The result of the function is stored in register P3.
  74764. ** Register P3 must not be one of the function inputs.
  74765. **
  74766. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  74767. ** function was determined to be constant at compile time. If the first
  74768. ** argument was constant then bit 0 of P1 is set. This is used to determine
  74769. ** whether meta data associated with a user function argument using the
  74770. ** sqlite3_set_auxdata() API may be safely retained until the next
  74771. ** invocation of this opcode.
  74772. **
  74773. ** See also: Function, AggStep, AggFinal
  74774. */
  74775. /* Opcode: Function P1 P2 P3 P4 P5
  74776. ** Synopsis: r[P3]=func(r[P2@P5])
  74777. **
  74778. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  74779. ** contains a pointer to the function to be run) with P5 arguments taken
  74780. ** from register P2 and successors. The result of the function is stored
  74781. ** in register P3. Register P3 must not be one of the function inputs.
  74782. **
  74783. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  74784. ** function was determined to be constant at compile time. If the first
  74785. ** argument was constant then bit 0 of P1 is set. This is used to determine
  74786. ** whether meta data associated with a user function argument using the
  74787. ** sqlite3_set_auxdata() API may be safely retained until the next
  74788. ** invocation of this opcode.
  74789. **
  74790. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  74791. ** to a FuncDef object. But on first evaluation, the P4 operand is
  74792. ** automatically converted into an sqlite3_context object and the operation
  74793. ** changed to this OP_Function opcode. In this way, the initialization of
  74794. ** the sqlite3_context object occurs only once, rather than once for each
  74795. ** evaluation of the function.
  74796. **
  74797. ** See also: Function0, AggStep, AggFinal
  74798. */
  74799. case OP_Function0: {
  74800. int n;
  74801. sqlite3_context *pCtx;
  74802. assert( pOp->p4type==P4_FUNCDEF );
  74803. n = pOp->p5;
  74804. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  74805. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  74806. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  74807. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  74808. if( pCtx==0 ) goto no_mem;
  74809. pCtx->pOut = 0;
  74810. pCtx->pFunc = pOp->p4.pFunc;
  74811. pCtx->iOp = (int)(pOp - aOp);
  74812. pCtx->pVdbe = p;
  74813. pCtx->argc = n;
  74814. pOp->p4type = P4_FUNCCTX;
  74815. pOp->p4.pCtx = pCtx;
  74816. pOp->opcode = OP_Function;
  74817. /* Fall through into OP_Function */
  74818. }
  74819. case OP_Function: {
  74820. int i;
  74821. sqlite3_context *pCtx;
  74822. assert( pOp->p4type==P4_FUNCCTX );
  74823. pCtx = pOp->p4.pCtx;
  74824. /* If this function is inside of a trigger, the register array in aMem[]
  74825. ** might change from one evaluation to the next. The next block of code
  74826. ** checks to see if the register array has changed, and if so it
  74827. ** reinitializes the relavant parts of the sqlite3_context object */
  74828. pOut = &aMem[pOp->p3];
  74829. if( pCtx->pOut != pOut ){
  74830. pCtx->pOut = pOut;
  74831. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  74832. }
  74833. memAboutToChange(p, pOut);
  74834. #ifdef SQLITE_DEBUG
  74835. for(i=0; i<pCtx->argc; i++){
  74836. assert( memIsValid(pCtx->argv[i]) );
  74837. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  74838. }
  74839. #endif
  74840. MemSetTypeFlag(pOut, MEM_Null);
  74841. pCtx->fErrorOrAux = 0;
  74842. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  74843. /* If the function returned an error, throw an exception */
  74844. if( pCtx->fErrorOrAux ){
  74845. if( pCtx->isError ){
  74846. sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
  74847. rc = pCtx->isError;
  74848. }
  74849. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  74850. if( rc ) goto abort_due_to_error;
  74851. }
  74852. /* Copy the result of the function into register P3 */
  74853. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  74854. sqlite3VdbeChangeEncoding(pOut, encoding);
  74855. if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
  74856. }
  74857. REGISTER_TRACE(pOp->p3, pOut);
  74858. UPDATE_MAX_BLOBSIZE(pOut);
  74859. break;
  74860. }
  74861. /* Opcode: BitAnd P1 P2 P3 * *
  74862. ** Synopsis: r[P3]=r[P1]&r[P2]
  74863. **
  74864. ** Take the bit-wise AND of the values in register P1 and P2 and
  74865. ** store the result in register P3.
  74866. ** If either input is NULL, the result is NULL.
  74867. */
  74868. /* Opcode: BitOr P1 P2 P3 * *
  74869. ** Synopsis: r[P3]=r[P1]|r[P2]
  74870. **
  74871. ** Take the bit-wise OR of the values in register P1 and P2 and
  74872. ** store the result in register P3.
  74873. ** If either input is NULL, the result is NULL.
  74874. */
  74875. /* Opcode: ShiftLeft P1 P2 P3 * *
  74876. ** Synopsis: r[P3]=r[P2]<<r[P1]
  74877. **
  74878. ** Shift the integer value in register P2 to the left by the
  74879. ** number of bits specified by the integer in register P1.
  74880. ** Store the result in register P3.
  74881. ** If either input is NULL, the result is NULL.
  74882. */
  74883. /* Opcode: ShiftRight P1 P2 P3 * *
  74884. ** Synopsis: r[P3]=r[P2]>>r[P1]
  74885. **
  74886. ** Shift the integer value in register P2 to the right by the
  74887. ** number of bits specified by the integer in register P1.
  74888. ** Store the result in register P3.
  74889. ** If either input is NULL, the result is NULL.
  74890. */
  74891. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  74892. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  74893. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  74894. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  74895. i64 iA;
  74896. u64 uA;
  74897. i64 iB;
  74898. u8 op;
  74899. pIn1 = &aMem[pOp->p1];
  74900. pIn2 = &aMem[pOp->p2];
  74901. pOut = &aMem[pOp->p3];
  74902. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  74903. sqlite3VdbeMemSetNull(pOut);
  74904. break;
  74905. }
  74906. iA = sqlite3VdbeIntValue(pIn2);
  74907. iB = sqlite3VdbeIntValue(pIn1);
  74908. op = pOp->opcode;
  74909. if( op==OP_BitAnd ){
  74910. iA &= iB;
  74911. }else if( op==OP_BitOr ){
  74912. iA |= iB;
  74913. }else if( iB!=0 ){
  74914. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  74915. /* If shifting by a negative amount, shift in the other direction */
  74916. if( iB<0 ){
  74917. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  74918. op = 2*OP_ShiftLeft + 1 - op;
  74919. iB = iB>(-64) ? -iB : 64;
  74920. }
  74921. if( iB>=64 ){
  74922. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  74923. }else{
  74924. memcpy(&uA, &iA, sizeof(uA));
  74925. if( op==OP_ShiftLeft ){
  74926. uA <<= iB;
  74927. }else{
  74928. uA >>= iB;
  74929. /* Sign-extend on a right shift of a negative number */
  74930. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  74931. }
  74932. memcpy(&iA, &uA, sizeof(iA));
  74933. }
  74934. }
  74935. pOut->u.i = iA;
  74936. MemSetTypeFlag(pOut, MEM_Int);
  74937. break;
  74938. }
  74939. /* Opcode: AddImm P1 P2 * * *
  74940. ** Synopsis: r[P1]=r[P1]+P2
  74941. **
  74942. ** Add the constant P2 to the value in register P1.
  74943. ** The result is always an integer.
  74944. **
  74945. ** To force any register to be an integer, just add 0.
  74946. */
  74947. case OP_AddImm: { /* in1 */
  74948. pIn1 = &aMem[pOp->p1];
  74949. memAboutToChange(p, pIn1);
  74950. sqlite3VdbeMemIntegerify(pIn1);
  74951. pIn1->u.i += pOp->p2;
  74952. break;
  74953. }
  74954. /* Opcode: MustBeInt P1 P2 * * *
  74955. **
  74956. ** Force the value in register P1 to be an integer. If the value
  74957. ** in P1 is not an integer and cannot be converted into an integer
  74958. ** without data loss, then jump immediately to P2, or if P2==0
  74959. ** raise an SQLITE_MISMATCH exception.
  74960. */
  74961. case OP_MustBeInt: { /* jump, in1 */
  74962. pIn1 = &aMem[pOp->p1];
  74963. if( (pIn1->flags & MEM_Int)==0 ){
  74964. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  74965. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  74966. if( (pIn1->flags & MEM_Int)==0 ){
  74967. if( pOp->p2==0 ){
  74968. rc = SQLITE_MISMATCH;
  74969. goto abort_due_to_error;
  74970. }else{
  74971. goto jump_to_p2;
  74972. }
  74973. }
  74974. }
  74975. MemSetTypeFlag(pIn1, MEM_Int);
  74976. break;
  74977. }
  74978. #ifndef SQLITE_OMIT_FLOATING_POINT
  74979. /* Opcode: RealAffinity P1 * * * *
  74980. **
  74981. ** If register P1 holds an integer convert it to a real value.
  74982. **
  74983. ** This opcode is used when extracting information from a column that
  74984. ** has REAL affinity. Such column values may still be stored as
  74985. ** integers, for space efficiency, but after extraction we want them
  74986. ** to have only a real value.
  74987. */
  74988. case OP_RealAffinity: { /* in1 */
  74989. pIn1 = &aMem[pOp->p1];
  74990. if( pIn1->flags & MEM_Int ){
  74991. sqlite3VdbeMemRealify(pIn1);
  74992. }
  74993. break;
  74994. }
  74995. #endif
  74996. #ifndef SQLITE_OMIT_CAST
  74997. /* Opcode: Cast P1 P2 * * *
  74998. ** Synopsis: affinity(r[P1])
  74999. **
  75000. ** Force the value in register P1 to be the type defined by P2.
  75001. **
  75002. ** <ul>
  75003. ** <li> P2=='A' &rarr; BLOB
  75004. ** <li> P2=='B' &rarr; TEXT
  75005. ** <li> P2=='C' &rarr; NUMERIC
  75006. ** <li> P2=='D' &rarr; INTEGER
  75007. ** <li> P2=='E' &rarr; REAL
  75008. ** </ul>
  75009. **
  75010. ** A NULL value is not changed by this routine. It remains NULL.
  75011. */
  75012. case OP_Cast: { /* in1 */
  75013. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  75014. testcase( pOp->p2==SQLITE_AFF_TEXT );
  75015. testcase( pOp->p2==SQLITE_AFF_BLOB );
  75016. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  75017. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  75018. testcase( pOp->p2==SQLITE_AFF_REAL );
  75019. pIn1 = &aMem[pOp->p1];
  75020. memAboutToChange(p, pIn1);
  75021. rc = ExpandBlob(pIn1);
  75022. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  75023. UPDATE_MAX_BLOBSIZE(pIn1);
  75024. if( rc ) goto abort_due_to_error;
  75025. break;
  75026. }
  75027. #endif /* SQLITE_OMIT_CAST */
  75028. /* Opcode: Eq P1 P2 P3 P4 P5
  75029. ** Synopsis: IF r[P3]==r[P1]
  75030. **
  75031. ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
  75032. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
  75033. ** store the result of comparison in register P2.
  75034. **
  75035. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  75036. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  75037. ** to coerce both inputs according to this affinity before the
  75038. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  75039. ** affinity is used. Note that the affinity conversions are stored
  75040. ** back into the input registers P1 and P3. So this opcode can cause
  75041. ** persistent changes to registers P1 and P3.
  75042. **
  75043. ** Once any conversions have taken place, and neither value is NULL,
  75044. ** the values are compared. If both values are blobs then memcmp() is
  75045. ** used to determine the results of the comparison. If both values
  75046. ** are text, then the appropriate collating function specified in
  75047. ** P4 is used to do the comparison. If P4 is not specified then
  75048. ** memcmp() is used to compare text string. If both values are
  75049. ** numeric, then a numeric comparison is used. If the two values
  75050. ** are of different types, then numbers are considered less than
  75051. ** strings and strings are considered less than blobs.
  75052. **
  75053. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  75054. ** true or false and is never NULL. If both operands are NULL then the result
  75055. ** of comparison is true. If either operand is NULL then the result is false.
  75056. ** If neither operand is NULL the result is the same as it would be if
  75057. ** the SQLITE_NULLEQ flag were omitted from P5.
  75058. **
  75059. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  75060. ** content of r[P2] is only changed if the new value is NULL or 0 (false).
  75061. ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
  75062. */
  75063. /* Opcode: Ne P1 P2 P3 P4 P5
  75064. ** Synopsis: IF r[P3]!=r[P1]
  75065. **
  75066. ** This works just like the Eq opcode except that the jump is taken if
  75067. ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
  75068. ** additional information.
  75069. **
  75070. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  75071. ** content of r[P2] is only changed if the new value is NULL or 1 (true).
  75072. ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
  75073. */
  75074. /* Opcode: Lt P1 P2 P3 P4 P5
  75075. ** Synopsis: IF r[P3]<r[P1]
  75076. **
  75077. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  75078. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
  75079. ** the result of comparison (0 or 1 or NULL) into register P2.
  75080. **
  75081. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  75082. ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
  75083. ** bit is clear then fall through if either operand is NULL.
  75084. **
  75085. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  75086. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  75087. ** to coerce both inputs according to this affinity before the
  75088. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  75089. ** affinity is used. Note that the affinity conversions are stored
  75090. ** back into the input registers P1 and P3. So this opcode can cause
  75091. ** persistent changes to registers P1 and P3.
  75092. **
  75093. ** Once any conversions have taken place, and neither value is NULL,
  75094. ** the values are compared. If both values are blobs then memcmp() is
  75095. ** used to determine the results of the comparison. If both values
  75096. ** are text, then the appropriate collating function specified in
  75097. ** P4 is used to do the comparison. If P4 is not specified then
  75098. ** memcmp() is used to compare text string. If both values are
  75099. ** numeric, then a numeric comparison is used. If the two values
  75100. ** are of different types, then numbers are considered less than
  75101. ** strings and strings are considered less than blobs.
  75102. */
  75103. /* Opcode: Le P1 P2 P3 P4 P5
  75104. ** Synopsis: IF r[P3]<=r[P1]
  75105. **
  75106. ** This works just like the Lt opcode except that the jump is taken if
  75107. ** the content of register P3 is less than or equal to the content of
  75108. ** register P1. See the Lt opcode for additional information.
  75109. */
  75110. /* Opcode: Gt P1 P2 P3 P4 P5
  75111. ** Synopsis: IF r[P3]>r[P1]
  75112. **
  75113. ** This works just like the Lt opcode except that the jump is taken if
  75114. ** the content of register P3 is greater than the content of
  75115. ** register P1. See the Lt opcode for additional information.
  75116. */
  75117. /* Opcode: Ge P1 P2 P3 P4 P5
  75118. ** Synopsis: IF r[P3]>=r[P1]
  75119. **
  75120. ** This works just like the Lt opcode except that the jump is taken if
  75121. ** the content of register P3 is greater than or equal to the content of
  75122. ** register P1. See the Lt opcode for additional information.
  75123. */
  75124. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  75125. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  75126. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  75127. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  75128. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  75129. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  75130. int res, res2; /* Result of the comparison of pIn1 against pIn3 */
  75131. char affinity; /* Affinity to use for comparison */
  75132. u16 flags1; /* Copy of initial value of pIn1->flags */
  75133. u16 flags3; /* Copy of initial value of pIn3->flags */
  75134. pIn1 = &aMem[pOp->p1];
  75135. pIn3 = &aMem[pOp->p3];
  75136. flags1 = pIn1->flags;
  75137. flags3 = pIn3->flags;
  75138. if( (flags1 | flags3)&MEM_Null ){
  75139. /* One or both operands are NULL */
  75140. if( pOp->p5 & SQLITE_NULLEQ ){
  75141. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  75142. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  75143. ** or not both operands are null.
  75144. */
  75145. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  75146. assert( (flags1 & MEM_Cleared)==0 );
  75147. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  75148. if( (flags1&flags3&MEM_Null)!=0
  75149. && (flags3&MEM_Cleared)==0
  75150. ){
  75151. res = 0; /* Operands are equal */
  75152. }else{
  75153. res = 1; /* Operands are not equal */
  75154. }
  75155. }else{
  75156. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  75157. ** then the result is always NULL.
  75158. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  75159. */
  75160. if( pOp->p5 & SQLITE_STOREP2 ){
  75161. pOut = &aMem[pOp->p2];
  75162. iCompare = 1; /* Operands are not equal */
  75163. memAboutToChange(p, pOut);
  75164. MemSetTypeFlag(pOut, MEM_Null);
  75165. REGISTER_TRACE(pOp->p2, pOut);
  75166. }else{
  75167. VdbeBranchTaken(2,3);
  75168. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  75169. goto jump_to_p2;
  75170. }
  75171. }
  75172. break;
  75173. }
  75174. }else{
  75175. /* Neither operand is NULL. Do a comparison. */
  75176. affinity = pOp->p5 & SQLITE_AFF_MASK;
  75177. if( affinity>=SQLITE_AFF_NUMERIC ){
  75178. if( (flags1 | flags3)&MEM_Str ){
  75179. if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  75180. applyNumericAffinity(pIn1,0);
  75181. testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
  75182. flags3 = pIn3->flags;
  75183. }
  75184. if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  75185. applyNumericAffinity(pIn3,0);
  75186. }
  75187. }
  75188. /* Handle the common case of integer comparison here, as an
  75189. ** optimization, to avoid a call to sqlite3MemCompare() */
  75190. if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
  75191. if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
  75192. if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
  75193. res = 0;
  75194. goto compare_op;
  75195. }
  75196. }else if( affinity==SQLITE_AFF_TEXT ){
  75197. if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
  75198. testcase( pIn1->flags & MEM_Int );
  75199. testcase( pIn1->flags & MEM_Real );
  75200. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  75201. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  75202. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  75203. assert( pIn1!=pIn3 );
  75204. }
  75205. if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
  75206. testcase( pIn3->flags & MEM_Int );
  75207. testcase( pIn3->flags & MEM_Real );
  75208. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  75209. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  75210. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  75211. }
  75212. }
  75213. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  75214. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  75215. }
  75216. compare_op:
  75217. switch( pOp->opcode ){
  75218. case OP_Eq: res2 = res==0; break;
  75219. case OP_Ne: res2 = res; break;
  75220. case OP_Lt: res2 = res<0; break;
  75221. case OP_Le: res2 = res<=0; break;
  75222. case OP_Gt: res2 = res>0; break;
  75223. default: res2 = res>=0; break;
  75224. }
  75225. /* Undo any changes made by applyAffinity() to the input registers. */
  75226. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  75227. pIn1->flags = flags1;
  75228. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  75229. pIn3->flags = flags3;
  75230. if( pOp->p5 & SQLITE_STOREP2 ){
  75231. pOut = &aMem[pOp->p2];
  75232. iCompare = res;
  75233. res2 = res2!=0; /* For this path res2 must be exactly 0 or 1 */
  75234. if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
  75235. /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
  75236. ** and prevents OP_Ne from overwriting NULL with 0. This flag
  75237. ** is only used in contexts where either:
  75238. ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
  75239. ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
  75240. ** Therefore it is not necessary to check the content of r[P2] for
  75241. ** NULL. */
  75242. assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
  75243. assert( res2==0 || res2==1 );
  75244. testcase( res2==0 && pOp->opcode==OP_Eq );
  75245. testcase( res2==1 && pOp->opcode==OP_Eq );
  75246. testcase( res2==0 && pOp->opcode==OP_Ne );
  75247. testcase( res2==1 && pOp->opcode==OP_Ne );
  75248. if( (pOp->opcode==OP_Eq)==res2 ) break;
  75249. }
  75250. memAboutToChange(p, pOut);
  75251. MemSetTypeFlag(pOut, MEM_Int);
  75252. pOut->u.i = res2;
  75253. REGISTER_TRACE(pOp->p2, pOut);
  75254. }else{
  75255. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  75256. if( res2 ){
  75257. goto jump_to_p2;
  75258. }
  75259. }
  75260. break;
  75261. }
  75262. /* Opcode: ElseNotEq * P2 * * *
  75263. **
  75264. ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
  75265. ** If result of an OP_Eq comparison on the same two operands
  75266. ** would have be NULL or false (0), then then jump to P2.
  75267. ** If the result of an OP_Eq comparison on the two previous operands
  75268. ** would have been true (1), then fall through.
  75269. */
  75270. case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
  75271. assert( pOp>aOp );
  75272. assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
  75273. assert( pOp[-1].p5 & SQLITE_STOREP2 );
  75274. VdbeBranchTaken(iCompare!=0, 2);
  75275. if( iCompare!=0 ) goto jump_to_p2;
  75276. break;
  75277. }
  75278. /* Opcode: Permutation * * * P4 *
  75279. **
  75280. ** Set the permutation used by the OP_Compare operator in the next
  75281. ** instruction. The permutation is stored in the P4 operand.
  75282. **
  75283. ** The permutation is only valid until the next OP_Compare that has
  75284. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  75285. ** occur immediately prior to the OP_Compare.
  75286. **
  75287. ** The first integer in the P4 integer array is the length of the array
  75288. ** and does not become part of the permutation.
  75289. */
  75290. case OP_Permutation: {
  75291. assert( pOp->p4type==P4_INTARRAY );
  75292. assert( pOp->p4.ai );
  75293. assert( pOp[1].opcode==OP_Compare );
  75294. assert( pOp[1].p5 & OPFLAG_PERMUTE );
  75295. break;
  75296. }
  75297. /* Opcode: Compare P1 P2 P3 P4 P5
  75298. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  75299. **
  75300. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  75301. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  75302. ** the comparison for use by the next OP_Jump instruct.
  75303. **
  75304. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  75305. ** determined by the most recent OP_Permutation operator. If the
  75306. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  75307. ** order.
  75308. **
  75309. ** P4 is a KeyInfo structure that defines collating sequences and sort
  75310. ** orders for the comparison. The permutation applies to registers
  75311. ** only. The KeyInfo elements are used sequentially.
  75312. **
  75313. ** The comparison is a sort comparison, so NULLs compare equal,
  75314. ** NULLs are less than numbers, numbers are less than strings,
  75315. ** and strings are less than blobs.
  75316. */
  75317. case OP_Compare: {
  75318. int n;
  75319. int i;
  75320. int p1;
  75321. int p2;
  75322. const KeyInfo *pKeyInfo;
  75323. int idx;
  75324. CollSeq *pColl; /* Collating sequence to use on this term */
  75325. int bRev; /* True for DESCENDING sort order */
  75326. int *aPermute; /* The permutation */
  75327. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
  75328. aPermute = 0;
  75329. }else{
  75330. assert( pOp>aOp );
  75331. assert( pOp[-1].opcode==OP_Permutation );
  75332. assert( pOp[-1].p4type==P4_INTARRAY );
  75333. aPermute = pOp[-1].p4.ai + 1;
  75334. assert( aPermute!=0 );
  75335. }
  75336. n = pOp->p3;
  75337. pKeyInfo = pOp->p4.pKeyInfo;
  75338. assert( n>0 );
  75339. assert( pKeyInfo!=0 );
  75340. p1 = pOp->p1;
  75341. p2 = pOp->p2;
  75342. #ifdef SQLITE_DEBUG
  75343. if( aPermute ){
  75344. int k, mx = 0;
  75345. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  75346. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  75347. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  75348. }else{
  75349. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  75350. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  75351. }
  75352. #endif /* SQLITE_DEBUG */
  75353. for(i=0; i<n; i++){
  75354. idx = aPermute ? aPermute[i] : i;
  75355. assert( memIsValid(&aMem[p1+idx]) );
  75356. assert( memIsValid(&aMem[p2+idx]) );
  75357. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  75358. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  75359. assert( i<pKeyInfo->nField );
  75360. pColl = pKeyInfo->aColl[i];
  75361. bRev = pKeyInfo->aSortOrder[i];
  75362. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  75363. if( iCompare ){
  75364. if( bRev ) iCompare = -iCompare;
  75365. break;
  75366. }
  75367. }
  75368. break;
  75369. }
  75370. /* Opcode: Jump P1 P2 P3 * *
  75371. **
  75372. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  75373. ** in the most recent OP_Compare instruction the P1 vector was less than
  75374. ** equal to, or greater than the P2 vector, respectively.
  75375. */
  75376. case OP_Jump: { /* jump */
  75377. if( iCompare<0 ){
  75378. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  75379. }else if( iCompare==0 ){
  75380. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  75381. }else{
  75382. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  75383. }
  75384. break;
  75385. }
  75386. /* Opcode: And P1 P2 P3 * *
  75387. ** Synopsis: r[P3]=(r[P1] && r[P2])
  75388. **
  75389. ** Take the logical AND of the values in registers P1 and P2 and
  75390. ** write the result into register P3.
  75391. **
  75392. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  75393. ** the other input is NULL. A NULL and true or two NULLs give
  75394. ** a NULL output.
  75395. */
  75396. /* Opcode: Or P1 P2 P3 * *
  75397. ** Synopsis: r[P3]=(r[P1] || r[P2])
  75398. **
  75399. ** Take the logical OR of the values in register P1 and P2 and
  75400. ** store the answer in register P3.
  75401. **
  75402. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  75403. ** even if the other input is NULL. A NULL and false or two NULLs
  75404. ** give a NULL output.
  75405. */
  75406. case OP_And: /* same as TK_AND, in1, in2, out3 */
  75407. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  75408. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  75409. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  75410. pIn1 = &aMem[pOp->p1];
  75411. if( pIn1->flags & MEM_Null ){
  75412. v1 = 2;
  75413. }else{
  75414. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  75415. }
  75416. pIn2 = &aMem[pOp->p2];
  75417. if( pIn2->flags & MEM_Null ){
  75418. v2 = 2;
  75419. }else{
  75420. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  75421. }
  75422. if( pOp->opcode==OP_And ){
  75423. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  75424. v1 = and_logic[v1*3+v2];
  75425. }else{
  75426. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  75427. v1 = or_logic[v1*3+v2];
  75428. }
  75429. pOut = &aMem[pOp->p3];
  75430. if( v1==2 ){
  75431. MemSetTypeFlag(pOut, MEM_Null);
  75432. }else{
  75433. pOut->u.i = v1;
  75434. MemSetTypeFlag(pOut, MEM_Int);
  75435. }
  75436. break;
  75437. }
  75438. /* Opcode: Not P1 P2 * * *
  75439. ** Synopsis: r[P2]= !r[P1]
  75440. **
  75441. ** Interpret the value in register P1 as a boolean value. Store the
  75442. ** boolean complement in register P2. If the value in register P1 is
  75443. ** NULL, then a NULL is stored in P2.
  75444. */
  75445. case OP_Not: { /* same as TK_NOT, in1, out2 */
  75446. pIn1 = &aMem[pOp->p1];
  75447. pOut = &aMem[pOp->p2];
  75448. sqlite3VdbeMemSetNull(pOut);
  75449. if( (pIn1->flags & MEM_Null)==0 ){
  75450. pOut->flags = MEM_Int;
  75451. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  75452. }
  75453. break;
  75454. }
  75455. /* Opcode: BitNot P1 P2 * * *
  75456. ** Synopsis: r[P1]= ~r[P1]
  75457. **
  75458. ** Interpret the content of register P1 as an integer. Store the
  75459. ** ones-complement of the P1 value into register P2. If P1 holds
  75460. ** a NULL then store a NULL in P2.
  75461. */
  75462. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  75463. pIn1 = &aMem[pOp->p1];
  75464. pOut = &aMem[pOp->p2];
  75465. sqlite3VdbeMemSetNull(pOut);
  75466. if( (pIn1->flags & MEM_Null)==0 ){
  75467. pOut->flags = MEM_Int;
  75468. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  75469. }
  75470. break;
  75471. }
  75472. /* Opcode: Once P1 P2 * * *
  75473. **
  75474. ** Fall through to the next instruction the first time this opcode is
  75475. ** encountered on each invocation of the byte-code program. Jump to P2
  75476. ** on the second and all subsequent encounters during the same invocation.
  75477. **
  75478. ** Top-level programs determine first invocation by comparing the P1
  75479. ** operand against the P1 operand on the OP_Init opcode at the beginning
  75480. ** of the program. If the P1 values differ, then fall through and make
  75481. ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
  75482. ** the same then take the jump.
  75483. **
  75484. ** For subprograms, there is a bitmask in the VdbeFrame that determines
  75485. ** whether or not the jump should be taken. The bitmask is necessary
  75486. ** because the self-altering code trick does not work for recursive
  75487. ** triggers.
  75488. */
  75489. case OP_Once: { /* jump */
  75490. u32 iAddr; /* Address of this instruction */
  75491. assert( p->aOp[0].opcode==OP_Init );
  75492. if( p->pFrame ){
  75493. iAddr = (int)(pOp - p->aOp);
  75494. if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
  75495. VdbeBranchTaken(1, 2);
  75496. goto jump_to_p2;
  75497. }
  75498. p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
  75499. }else{
  75500. if( p->aOp[0].p1==pOp->p1 ){
  75501. VdbeBranchTaken(1, 2);
  75502. goto jump_to_p2;
  75503. }
  75504. }
  75505. VdbeBranchTaken(0, 2);
  75506. pOp->p1 = p->aOp[0].p1;
  75507. break;
  75508. }
  75509. /* Opcode: If P1 P2 P3 * *
  75510. **
  75511. ** Jump to P2 if the value in register P1 is true. The value
  75512. ** is considered true if it is numeric and non-zero. If the value
  75513. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  75514. */
  75515. /* Opcode: IfNot P1 P2 P3 * *
  75516. **
  75517. ** Jump to P2 if the value in register P1 is False. The value
  75518. ** is considered false if it has a numeric value of zero. If the value
  75519. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  75520. */
  75521. case OP_If: /* jump, in1 */
  75522. case OP_IfNot: { /* jump, in1 */
  75523. int c;
  75524. pIn1 = &aMem[pOp->p1];
  75525. if( pIn1->flags & MEM_Null ){
  75526. c = pOp->p3;
  75527. }else{
  75528. #ifdef SQLITE_OMIT_FLOATING_POINT
  75529. c = sqlite3VdbeIntValue(pIn1)!=0;
  75530. #else
  75531. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  75532. #endif
  75533. if( pOp->opcode==OP_IfNot ) c = !c;
  75534. }
  75535. VdbeBranchTaken(c!=0, 2);
  75536. if( c ){
  75537. goto jump_to_p2;
  75538. }
  75539. break;
  75540. }
  75541. /* Opcode: IsNull P1 P2 * * *
  75542. ** Synopsis: if r[P1]==NULL goto P2
  75543. **
  75544. ** Jump to P2 if the value in register P1 is NULL.
  75545. */
  75546. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  75547. pIn1 = &aMem[pOp->p1];
  75548. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  75549. if( (pIn1->flags & MEM_Null)!=0 ){
  75550. goto jump_to_p2;
  75551. }
  75552. break;
  75553. }
  75554. /* Opcode: NotNull P1 P2 * * *
  75555. ** Synopsis: if r[P1]!=NULL goto P2
  75556. **
  75557. ** Jump to P2 if the value in register P1 is not NULL.
  75558. */
  75559. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  75560. pIn1 = &aMem[pOp->p1];
  75561. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  75562. if( (pIn1->flags & MEM_Null)==0 ){
  75563. goto jump_to_p2;
  75564. }
  75565. break;
  75566. }
  75567. /* Opcode: IfNullRow P1 P2 P3 * *
  75568. ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
  75569. **
  75570. ** Check the cursor P1 to see if it is currently pointing at a NULL row.
  75571. ** If it is, then set register P3 to NULL and jump immediately to P2.
  75572. ** If P1 is not on a NULL row, then fall through without making any
  75573. ** changes.
  75574. */
  75575. case OP_IfNullRow: { /* jump */
  75576. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  75577. assert( p->apCsr[pOp->p1]!=0 );
  75578. if( p->apCsr[pOp->p1]->nullRow ){
  75579. sqlite3VdbeMemSetNull(aMem + pOp->p3);
  75580. goto jump_to_p2;
  75581. }
  75582. break;
  75583. }
  75584. /* Opcode: Column P1 P2 P3 P4 P5
  75585. ** Synopsis: r[P3]=PX
  75586. **
  75587. ** Interpret the data that cursor P1 points to as a structure built using
  75588. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  75589. ** information about the format of the data.) Extract the P2-th column
  75590. ** from this record. If there are less that (P2+1)
  75591. ** values in the record, extract a NULL.
  75592. **
  75593. ** The value extracted is stored in register P3.
  75594. **
  75595. ** If the record contains fewer than P2 fields, then extract a NULL. Or,
  75596. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  75597. ** the result.
  75598. **
  75599. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  75600. ** then the cache of the cursor is reset prior to extracting the column.
  75601. ** The first OP_Column against a pseudo-table after the value of the content
  75602. ** register has changed should have this bit set.
  75603. **
  75604. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
  75605. ** the result is guaranteed to only be used as the argument of a length()
  75606. ** or typeof() function, respectively. The loading of large blobs can be
  75607. ** skipped for length() and all content loading can be skipped for typeof().
  75608. */
  75609. case OP_Column: {
  75610. int p2; /* column number to retrieve */
  75611. VdbeCursor *pC; /* The VDBE cursor */
  75612. BtCursor *pCrsr; /* The BTree cursor */
  75613. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  75614. int len; /* The length of the serialized data for the column */
  75615. int i; /* Loop counter */
  75616. Mem *pDest; /* Where to write the extracted value */
  75617. Mem sMem; /* For storing the record being decoded */
  75618. const u8 *zData; /* Part of the record being decoded */
  75619. const u8 *zHdr; /* Next unparsed byte of the header */
  75620. const u8 *zEndHdr; /* Pointer to first byte after the header */
  75621. u32 offset; /* Offset into the data */
  75622. u64 offset64; /* 64-bit offset */
  75623. u32 avail; /* Number of bytes of available data */
  75624. u32 t; /* A type code from the record header */
  75625. Mem *pReg; /* PseudoTable input register */
  75626. pC = p->apCsr[pOp->p1];
  75627. p2 = pOp->p2;
  75628. /* If the cursor cache is stale, bring it up-to-date */
  75629. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  75630. if( rc ) goto abort_due_to_error;
  75631. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  75632. pDest = &aMem[pOp->p3];
  75633. memAboutToChange(p, pDest);
  75634. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  75635. assert( pC!=0 );
  75636. assert( p2<pC->nField );
  75637. aOffset = pC->aOffset;
  75638. assert( pC->eCurType!=CURTYPE_VTAB );
  75639. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  75640. assert( pC->eCurType!=CURTYPE_SORTER );
  75641. if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
  75642. if( pC->nullRow ){
  75643. if( pC->eCurType==CURTYPE_PSEUDO ){
  75644. assert( pC->uc.pseudoTableReg>0 );
  75645. pReg = &aMem[pC->uc.pseudoTableReg];
  75646. assert( pReg->flags & MEM_Blob );
  75647. assert( memIsValid(pReg) );
  75648. pC->payloadSize = pC->szRow = avail = pReg->n;
  75649. pC->aRow = (u8*)pReg->z;
  75650. }else{
  75651. sqlite3VdbeMemSetNull(pDest);
  75652. goto op_column_out;
  75653. }
  75654. }else{
  75655. pCrsr = pC->uc.pCursor;
  75656. assert( pC->eCurType==CURTYPE_BTREE );
  75657. assert( pCrsr );
  75658. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  75659. pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
  75660. pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail);
  75661. assert( avail<=65536 ); /* Maximum page size is 64KiB */
  75662. if( pC->payloadSize <= (u32)avail ){
  75663. pC->szRow = pC->payloadSize;
  75664. }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  75665. goto too_big;
  75666. }else{
  75667. pC->szRow = avail;
  75668. }
  75669. }
  75670. pC->cacheStatus = p->cacheCtr;
  75671. pC->iHdrOffset = getVarint32(pC->aRow, offset);
  75672. pC->nHdrParsed = 0;
  75673. aOffset[0] = offset;
  75674. if( avail<offset ){ /*OPTIMIZATION-IF-FALSE*/
  75675. /* pC->aRow does not have to hold the entire row, but it does at least
  75676. ** need to cover the header of the record. If pC->aRow does not contain
  75677. ** the complete header, then set it to zero, forcing the header to be
  75678. ** dynamically allocated. */
  75679. pC->aRow = 0;
  75680. pC->szRow = 0;
  75681. /* Make sure a corrupt database has not given us an oversize header.
  75682. ** Do this now to avoid an oversize memory allocation.
  75683. **
  75684. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  75685. ** types use so much data space that there can only be 4096 and 32 of
  75686. ** them, respectively. So the maximum header length results from a
  75687. ** 3-byte type for each of the maximum of 32768 columns plus three
  75688. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  75689. */
  75690. if( offset > 98307 || offset > pC->payloadSize ){
  75691. rc = SQLITE_CORRUPT_BKPT;
  75692. goto abort_due_to_error;
  75693. }
  75694. }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/
  75695. /* The following goto is an optimization. It can be omitted and
  75696. ** everything will still work. But OP_Column is measurably faster
  75697. ** by skipping the subsequent conditional, which is always true.
  75698. */
  75699. zData = pC->aRow;
  75700. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  75701. goto op_column_read_header;
  75702. }
  75703. }
  75704. /* Make sure at least the first p2+1 entries of the header have been
  75705. ** parsed and valid information is in aOffset[] and pC->aType[].
  75706. */
  75707. if( pC->nHdrParsed<=p2 ){
  75708. /* If there is more header available for parsing in the record, try
  75709. ** to extract additional fields up through the p2+1-th field
  75710. */
  75711. if( pC->iHdrOffset<aOffset[0] ){
  75712. /* Make sure zData points to enough of the record to cover the header. */
  75713. if( pC->aRow==0 ){
  75714. memset(&sMem, 0, sizeof(sMem));
  75715. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
  75716. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  75717. zData = (u8*)sMem.z;
  75718. }else{
  75719. zData = pC->aRow;
  75720. }
  75721. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  75722. op_column_read_header:
  75723. i = pC->nHdrParsed;
  75724. offset64 = aOffset[i];
  75725. zHdr = zData + pC->iHdrOffset;
  75726. zEndHdr = zData + aOffset[0];
  75727. do{
  75728. if( (t = zHdr[0])<0x80 ){
  75729. zHdr++;
  75730. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  75731. }else{
  75732. zHdr += sqlite3GetVarint32(zHdr, &t);
  75733. offset64 += sqlite3VdbeSerialTypeLen(t);
  75734. }
  75735. pC->aType[i++] = t;
  75736. aOffset[i] = (u32)(offset64 & 0xffffffff);
  75737. }while( i<=p2 && zHdr<zEndHdr );
  75738. /* The record is corrupt if any of the following are true:
  75739. ** (1) the bytes of the header extend past the declared header size
  75740. ** (2) the entire header was used but not all data was used
  75741. ** (3) the end of the data extends beyond the end of the record.
  75742. */
  75743. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  75744. || (offset64 > pC->payloadSize)
  75745. ){
  75746. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  75747. rc = SQLITE_CORRUPT_BKPT;
  75748. goto abort_due_to_error;
  75749. }
  75750. pC->nHdrParsed = i;
  75751. pC->iHdrOffset = (u32)(zHdr - zData);
  75752. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  75753. }else{
  75754. t = 0;
  75755. }
  75756. /* If after trying to extract new entries from the header, nHdrParsed is
  75757. ** still not up to p2, that means that the record has fewer than p2
  75758. ** columns. So the result will be either the default value or a NULL.
  75759. */
  75760. if( pC->nHdrParsed<=p2 ){
  75761. if( pOp->p4type==P4_MEM ){
  75762. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  75763. }else{
  75764. sqlite3VdbeMemSetNull(pDest);
  75765. }
  75766. goto op_column_out;
  75767. }
  75768. }else{
  75769. t = pC->aType[p2];
  75770. }
  75771. /* Extract the content for the p2+1-th column. Control can only
  75772. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  75773. ** all valid.
  75774. */
  75775. assert( p2<pC->nHdrParsed );
  75776. assert( rc==SQLITE_OK );
  75777. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  75778. if( VdbeMemDynamic(pDest) ){
  75779. sqlite3VdbeMemSetNull(pDest);
  75780. }
  75781. assert( t==pC->aType[p2] );
  75782. if( pC->szRow>=aOffset[p2+1] ){
  75783. /* This is the common case where the desired content fits on the original
  75784. ** page - where the content is not on an overflow page */
  75785. zData = pC->aRow + aOffset[p2];
  75786. if( t<12 ){
  75787. sqlite3VdbeSerialGet(zData, t, pDest);
  75788. }else{
  75789. /* If the column value is a string, we need a persistent value, not
  75790. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  75791. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  75792. */
  75793. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  75794. pDest->n = len = (t-12)/2;
  75795. pDest->enc = encoding;
  75796. if( pDest->szMalloc < len+2 ){
  75797. pDest->flags = MEM_Null;
  75798. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  75799. }else{
  75800. pDest->z = pDest->zMalloc;
  75801. }
  75802. memcpy(pDest->z, zData, len);
  75803. pDest->z[len] = 0;
  75804. pDest->z[len+1] = 0;
  75805. pDest->flags = aFlag[t&1];
  75806. }
  75807. }else{
  75808. pDest->enc = encoding;
  75809. /* This branch happens only when content is on overflow pages */
  75810. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  75811. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  75812. || (len = sqlite3VdbeSerialTypeLen(t))==0
  75813. ){
  75814. /* Content is irrelevant for
  75815. ** 1. the typeof() function,
  75816. ** 2. the length(X) function if X is a blob, and
  75817. ** 3. if the content length is zero.
  75818. ** So we might as well use bogus content rather than reading
  75819. ** content from disk.
  75820. **
  75821. ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
  75822. ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
  75823. ** read up to 16. So 16 bytes of bogus content is supplied.
  75824. */
  75825. static u8 aZero[16]; /* This is the bogus content */
  75826. sqlite3VdbeSerialGet(aZero, t, pDest);
  75827. }else{
  75828. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
  75829. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  75830. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  75831. pDest->flags &= ~MEM_Ephem;
  75832. }
  75833. }
  75834. op_column_out:
  75835. UPDATE_MAX_BLOBSIZE(pDest);
  75836. REGISTER_TRACE(pOp->p3, pDest);
  75837. break;
  75838. }
  75839. /* Opcode: Affinity P1 P2 * P4 *
  75840. ** Synopsis: affinity(r[P1@P2])
  75841. **
  75842. ** Apply affinities to a range of P2 registers starting with P1.
  75843. **
  75844. ** P4 is a string that is P2 characters long. The N-th character of the
  75845. ** string indicates the column affinity that should be used for the N-th
  75846. ** memory cell in the range.
  75847. */
  75848. case OP_Affinity: {
  75849. const char *zAffinity; /* The affinity to be applied */
  75850. zAffinity = pOp->p4.z;
  75851. assert( zAffinity!=0 );
  75852. assert( pOp->p2>0 );
  75853. assert( zAffinity[pOp->p2]==0 );
  75854. pIn1 = &aMem[pOp->p1];
  75855. do{
  75856. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  75857. assert( memIsValid(pIn1) );
  75858. applyAffinity(pIn1, *(zAffinity++), encoding);
  75859. pIn1++;
  75860. }while( zAffinity[0] );
  75861. break;
  75862. }
  75863. /* Opcode: MakeRecord P1 P2 P3 P4 *
  75864. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  75865. **
  75866. ** Convert P2 registers beginning with P1 into the [record format]
  75867. ** use as a data record in a database table or as a key
  75868. ** in an index. The OP_Column opcode can decode the record later.
  75869. **
  75870. ** P4 may be a string that is P2 characters long. The N-th character of the
  75871. ** string indicates the column affinity that should be used for the N-th
  75872. ** field of the index key.
  75873. **
  75874. ** The mapping from character to affinity is given by the SQLITE_AFF_
  75875. ** macros defined in sqliteInt.h.
  75876. **
  75877. ** If P4 is NULL then all index fields have the affinity BLOB.
  75878. */
  75879. case OP_MakeRecord: {
  75880. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  75881. Mem *pRec; /* The new record */
  75882. u64 nData; /* Number of bytes of data space */
  75883. int nHdr; /* Number of bytes of header space */
  75884. i64 nByte; /* Data space required for this record */
  75885. i64 nZero; /* Number of zero bytes at the end of the record */
  75886. int nVarint; /* Number of bytes in a varint */
  75887. u32 serial_type; /* Type field */
  75888. Mem *pData0; /* First field to be combined into the record */
  75889. Mem *pLast; /* Last field of the record */
  75890. int nField; /* Number of fields in the record */
  75891. char *zAffinity; /* The affinity string for the record */
  75892. int file_format; /* File format to use for encoding */
  75893. int i; /* Space used in zNewRecord[] header */
  75894. int j; /* Space used in zNewRecord[] content */
  75895. u32 len; /* Length of a field */
  75896. /* Assuming the record contains N fields, the record format looks
  75897. ** like this:
  75898. **
  75899. ** ------------------------------------------------------------------------
  75900. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  75901. ** ------------------------------------------------------------------------
  75902. **
  75903. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  75904. ** and so forth.
  75905. **
  75906. ** Each type field is a varint representing the serial type of the
  75907. ** corresponding data element (see sqlite3VdbeSerialType()). The
  75908. ** hdr-size field is also a varint which is the offset from the beginning
  75909. ** of the record to data0.
  75910. */
  75911. nData = 0; /* Number of bytes of data space */
  75912. nHdr = 0; /* Number of bytes of header space */
  75913. nZero = 0; /* Number of zero bytes at the end of the record */
  75914. nField = pOp->p1;
  75915. zAffinity = pOp->p4.z;
  75916. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  75917. pData0 = &aMem[nField];
  75918. nField = pOp->p2;
  75919. pLast = &pData0[nField-1];
  75920. file_format = p->minWriteFileFormat;
  75921. /* Identify the output register */
  75922. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  75923. pOut = &aMem[pOp->p3];
  75924. memAboutToChange(p, pOut);
  75925. /* Apply the requested affinity to all inputs
  75926. */
  75927. assert( pData0<=pLast );
  75928. if( zAffinity ){
  75929. pRec = pData0;
  75930. do{
  75931. applyAffinity(pRec++, *(zAffinity++), encoding);
  75932. assert( zAffinity[0]==0 || pRec<=pLast );
  75933. }while( zAffinity[0] );
  75934. }
  75935. #ifdef SQLITE_ENABLE_NULL_TRIM
  75936. /* NULLs can be safely trimmed from the end of the record, as long as
  75937. ** as the schema format is 2 or more and none of the omitted columns
  75938. ** have a non-NULL default value. Also, the record must be left with
  75939. ** at least one field. If P5>0 then it will be one more than the
  75940. ** index of the right-most column with a non-NULL default value */
  75941. if( pOp->p5 ){
  75942. while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
  75943. pLast--;
  75944. nField--;
  75945. }
  75946. }
  75947. #endif
  75948. /* Loop through the elements that will make up the record to figure
  75949. ** out how much space is required for the new record.
  75950. */
  75951. pRec = pLast;
  75952. do{
  75953. assert( memIsValid(pRec) );
  75954. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  75955. if( pRec->flags & MEM_Zero ){
  75956. if( nData ){
  75957. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  75958. }else{
  75959. nZero += pRec->u.nZero;
  75960. len -= pRec->u.nZero;
  75961. }
  75962. }
  75963. nData += len;
  75964. testcase( serial_type==127 );
  75965. testcase( serial_type==128 );
  75966. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  75967. if( pRec==pData0 ) break;
  75968. pRec--;
  75969. }while(1);
  75970. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  75971. ** which determines the total number of bytes in the header. The varint
  75972. ** value is the size of the header in bytes including the size varint
  75973. ** itself. */
  75974. testcase( nHdr==126 );
  75975. testcase( nHdr==127 );
  75976. if( nHdr<=126 ){
  75977. /* The common case */
  75978. nHdr += 1;
  75979. }else{
  75980. /* Rare case of a really large header */
  75981. nVarint = sqlite3VarintLen(nHdr);
  75982. nHdr += nVarint;
  75983. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  75984. }
  75985. nByte = nHdr+nData;
  75986. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  75987. goto too_big;
  75988. }
  75989. /* Make sure the output register has a buffer large enough to store
  75990. ** the new record. The output register (pOp->p3) is not allowed to
  75991. ** be one of the input registers (because the following call to
  75992. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  75993. */
  75994. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  75995. goto no_mem;
  75996. }
  75997. zNewRecord = (u8 *)pOut->z;
  75998. /* Write the record */
  75999. i = putVarint32(zNewRecord, nHdr);
  76000. j = nHdr;
  76001. assert( pData0<=pLast );
  76002. pRec = pData0;
  76003. do{
  76004. serial_type = pRec->uTemp;
  76005. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  76006. ** additional varints, one per column. */
  76007. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  76008. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  76009. ** immediately follow the header. */
  76010. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  76011. }while( (++pRec)<=pLast );
  76012. assert( i==nHdr );
  76013. assert( j==nByte );
  76014. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  76015. pOut->n = (int)nByte;
  76016. pOut->flags = MEM_Blob;
  76017. if( nZero ){
  76018. pOut->u.nZero = nZero;
  76019. pOut->flags |= MEM_Zero;
  76020. }
  76021. REGISTER_TRACE(pOp->p3, pOut);
  76022. UPDATE_MAX_BLOBSIZE(pOut);
  76023. break;
  76024. }
  76025. /* Opcode: Count P1 P2 * * *
  76026. ** Synopsis: r[P2]=count()
  76027. **
  76028. ** Store the number of entries (an integer value) in the table or index
  76029. ** opened by cursor P1 in register P2
  76030. */
  76031. #ifndef SQLITE_OMIT_BTREECOUNT
  76032. case OP_Count: { /* out2 */
  76033. i64 nEntry;
  76034. BtCursor *pCrsr;
  76035. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  76036. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  76037. assert( pCrsr );
  76038. nEntry = 0; /* Not needed. Only used to silence a warning. */
  76039. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  76040. if( rc ) goto abort_due_to_error;
  76041. pOut = out2Prerelease(p, pOp);
  76042. pOut->u.i = nEntry;
  76043. break;
  76044. }
  76045. #endif
  76046. /* Opcode: Savepoint P1 * * P4 *
  76047. **
  76048. ** Open, release or rollback the savepoint named by parameter P4, depending
  76049. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  76050. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  76051. */
  76052. case OP_Savepoint: {
  76053. int p1; /* Value of P1 operand */
  76054. char *zName; /* Name of savepoint */
  76055. int nName;
  76056. Savepoint *pNew;
  76057. Savepoint *pSavepoint;
  76058. Savepoint *pTmp;
  76059. int iSavepoint;
  76060. int ii;
  76061. p1 = pOp->p1;
  76062. zName = pOp->p4.z;
  76063. /* Assert that the p1 parameter is valid. Also that if there is no open
  76064. ** transaction, then there cannot be any savepoints.
  76065. */
  76066. assert( db->pSavepoint==0 || db->autoCommit==0 );
  76067. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  76068. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  76069. assert( checkSavepointCount(db) );
  76070. assert( p->bIsReader );
  76071. if( p1==SAVEPOINT_BEGIN ){
  76072. if( db->nVdbeWrite>0 ){
  76073. /* A new savepoint cannot be created if there are active write
  76074. ** statements (i.e. open read/write incremental blob handles).
  76075. */
  76076. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  76077. rc = SQLITE_BUSY;
  76078. }else{
  76079. nName = sqlite3Strlen30(zName);
  76080. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76081. /* This call is Ok even if this savepoint is actually a transaction
  76082. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  76083. ** If this is a transaction savepoint being opened, it is guaranteed
  76084. ** that the db->aVTrans[] array is empty. */
  76085. assert( db->autoCommit==0 || db->nVTrans==0 );
  76086. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  76087. db->nStatement+db->nSavepoint);
  76088. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76089. #endif
  76090. /* Create a new savepoint structure. */
  76091. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  76092. if( pNew ){
  76093. pNew->zName = (char *)&pNew[1];
  76094. memcpy(pNew->zName, zName, nName+1);
  76095. /* If there is no open transaction, then mark this as a special
  76096. ** "transaction savepoint". */
  76097. if( db->autoCommit ){
  76098. db->autoCommit = 0;
  76099. db->isTransactionSavepoint = 1;
  76100. }else{
  76101. db->nSavepoint++;
  76102. }
  76103. /* Link the new savepoint into the database handle's list. */
  76104. pNew->pNext = db->pSavepoint;
  76105. db->pSavepoint = pNew;
  76106. pNew->nDeferredCons = db->nDeferredCons;
  76107. pNew->nDeferredImmCons = db->nDeferredImmCons;
  76108. }
  76109. }
  76110. }else{
  76111. iSavepoint = 0;
  76112. /* Find the named savepoint. If there is no such savepoint, then an
  76113. ** an error is returned to the user. */
  76114. for(
  76115. pSavepoint = db->pSavepoint;
  76116. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  76117. pSavepoint = pSavepoint->pNext
  76118. ){
  76119. iSavepoint++;
  76120. }
  76121. if( !pSavepoint ){
  76122. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  76123. rc = SQLITE_ERROR;
  76124. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  76125. /* It is not possible to release (commit) a savepoint if there are
  76126. ** active write statements.
  76127. */
  76128. sqlite3VdbeError(p, "cannot release savepoint - "
  76129. "SQL statements in progress");
  76130. rc = SQLITE_BUSY;
  76131. }else{
  76132. /* Determine whether or not this is a transaction savepoint. If so,
  76133. ** and this is a RELEASE command, then the current transaction
  76134. ** is committed.
  76135. */
  76136. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  76137. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  76138. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  76139. goto vdbe_return;
  76140. }
  76141. db->autoCommit = 1;
  76142. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  76143. p->pc = (int)(pOp - aOp);
  76144. db->autoCommit = 0;
  76145. p->rc = rc = SQLITE_BUSY;
  76146. goto vdbe_return;
  76147. }
  76148. db->isTransactionSavepoint = 0;
  76149. rc = p->rc;
  76150. }else{
  76151. int isSchemaChange;
  76152. iSavepoint = db->nSavepoint - iSavepoint - 1;
  76153. if( p1==SAVEPOINT_ROLLBACK ){
  76154. isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
  76155. for(ii=0; ii<db->nDb; ii++){
  76156. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  76157. SQLITE_ABORT_ROLLBACK,
  76158. isSchemaChange==0);
  76159. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76160. }
  76161. }else{
  76162. isSchemaChange = 0;
  76163. }
  76164. for(ii=0; ii<db->nDb; ii++){
  76165. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  76166. if( rc!=SQLITE_OK ){
  76167. goto abort_due_to_error;
  76168. }
  76169. }
  76170. if( isSchemaChange ){
  76171. sqlite3ExpirePreparedStatements(db);
  76172. sqlite3ResetAllSchemasOfConnection(db);
  76173. db->flags = (db->flags | SQLITE_InternChanges);
  76174. }
  76175. }
  76176. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  76177. ** savepoints nested inside of the savepoint being operated on. */
  76178. while( db->pSavepoint!=pSavepoint ){
  76179. pTmp = db->pSavepoint;
  76180. db->pSavepoint = pTmp->pNext;
  76181. sqlite3DbFree(db, pTmp);
  76182. db->nSavepoint--;
  76183. }
  76184. /* If it is a RELEASE, then destroy the savepoint being operated on
  76185. ** too. If it is a ROLLBACK TO, then set the number of deferred
  76186. ** constraint violations present in the database to the value stored
  76187. ** when the savepoint was created. */
  76188. if( p1==SAVEPOINT_RELEASE ){
  76189. assert( pSavepoint==db->pSavepoint );
  76190. db->pSavepoint = pSavepoint->pNext;
  76191. sqlite3DbFree(db, pSavepoint);
  76192. if( !isTransaction ){
  76193. db->nSavepoint--;
  76194. }
  76195. }else{
  76196. db->nDeferredCons = pSavepoint->nDeferredCons;
  76197. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  76198. }
  76199. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  76200. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  76201. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76202. }
  76203. }
  76204. }
  76205. if( rc ) goto abort_due_to_error;
  76206. break;
  76207. }
  76208. /* Opcode: AutoCommit P1 P2 * * *
  76209. **
  76210. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  76211. ** back any currently active btree transactions. If there are any active
  76212. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  76213. ** there are active writing VMs or active VMs that use shared cache.
  76214. **
  76215. ** This instruction causes the VM to halt.
  76216. */
  76217. case OP_AutoCommit: {
  76218. int desiredAutoCommit;
  76219. int iRollback;
  76220. desiredAutoCommit = pOp->p1;
  76221. iRollback = pOp->p2;
  76222. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  76223. assert( desiredAutoCommit==1 || iRollback==0 );
  76224. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  76225. assert( p->bIsReader );
  76226. if( desiredAutoCommit!=db->autoCommit ){
  76227. if( iRollback ){
  76228. assert( desiredAutoCommit==1 );
  76229. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  76230. db->autoCommit = 1;
  76231. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  76232. /* If this instruction implements a COMMIT and other VMs are writing
  76233. ** return an error indicating that the other VMs must complete first.
  76234. */
  76235. sqlite3VdbeError(p, "cannot commit transaction - "
  76236. "SQL statements in progress");
  76237. rc = SQLITE_BUSY;
  76238. goto abort_due_to_error;
  76239. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  76240. goto vdbe_return;
  76241. }else{
  76242. db->autoCommit = (u8)desiredAutoCommit;
  76243. }
  76244. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  76245. p->pc = (int)(pOp - aOp);
  76246. db->autoCommit = (u8)(1-desiredAutoCommit);
  76247. p->rc = rc = SQLITE_BUSY;
  76248. goto vdbe_return;
  76249. }
  76250. assert( db->nStatement==0 );
  76251. sqlite3CloseSavepoints(db);
  76252. if( p->rc==SQLITE_OK ){
  76253. rc = SQLITE_DONE;
  76254. }else{
  76255. rc = SQLITE_ERROR;
  76256. }
  76257. goto vdbe_return;
  76258. }else{
  76259. sqlite3VdbeError(p,
  76260. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  76261. (iRollback)?"cannot rollback - no transaction is active":
  76262. "cannot commit - no transaction is active"));
  76263. rc = SQLITE_ERROR;
  76264. goto abort_due_to_error;
  76265. }
  76266. break;
  76267. }
  76268. /* Opcode: Transaction P1 P2 P3 P4 P5
  76269. **
  76270. ** Begin a transaction on database P1 if a transaction is not already
  76271. ** active.
  76272. ** If P2 is non-zero, then a write-transaction is started, or if a
  76273. ** read-transaction is already active, it is upgraded to a write-transaction.
  76274. ** If P2 is zero, then a read-transaction is started.
  76275. **
  76276. ** P1 is the index of the database file on which the transaction is
  76277. ** started. Index 0 is the main database file and index 1 is the
  76278. ** file used for temporary tables. Indices of 2 or more are used for
  76279. ** attached databases.
  76280. **
  76281. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  76282. ** true (this flag is set if the Vdbe may modify more than one row and may
  76283. ** throw an ABORT exception), a statement transaction may also be opened.
  76284. ** More specifically, a statement transaction is opened iff the database
  76285. ** connection is currently not in autocommit mode, or if there are other
  76286. ** active statements. A statement transaction allows the changes made by this
  76287. ** VDBE to be rolled back after an error without having to roll back the
  76288. ** entire transaction. If no error is encountered, the statement transaction
  76289. ** will automatically commit when the VDBE halts.
  76290. **
  76291. ** If P5!=0 then this opcode also checks the schema cookie against P3
  76292. ** and the schema generation counter against P4.
  76293. ** The cookie changes its value whenever the database schema changes.
  76294. ** This operation is used to detect when that the cookie has changed
  76295. ** and that the current process needs to reread the schema. If the schema
  76296. ** cookie in P3 differs from the schema cookie in the database header or
  76297. ** if the schema generation counter in P4 differs from the current
  76298. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  76299. ** halts. The sqlite3_step() wrapper function might then reprepare the
  76300. ** statement and rerun it from the beginning.
  76301. */
  76302. case OP_Transaction: {
  76303. Btree *pBt;
  76304. int iMeta;
  76305. int iGen;
  76306. assert( p->bIsReader );
  76307. assert( p->readOnly==0 || pOp->p2==0 );
  76308. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  76309. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  76310. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  76311. rc = SQLITE_READONLY;
  76312. goto abort_due_to_error;
  76313. }
  76314. pBt = db->aDb[pOp->p1].pBt;
  76315. if( pBt ){
  76316. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  76317. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  76318. testcase( rc==SQLITE_BUSY_RECOVERY );
  76319. if( rc!=SQLITE_OK ){
  76320. if( (rc&0xff)==SQLITE_BUSY ){
  76321. p->pc = (int)(pOp - aOp);
  76322. p->rc = rc;
  76323. goto vdbe_return;
  76324. }
  76325. goto abort_due_to_error;
  76326. }
  76327. if( pOp->p2 && p->usesStmtJournal
  76328. && (db->autoCommit==0 || db->nVdbeRead>1)
  76329. ){
  76330. assert( sqlite3BtreeIsInTrans(pBt) );
  76331. if( p->iStatement==0 ){
  76332. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  76333. db->nStatement++;
  76334. p->iStatement = db->nSavepoint + db->nStatement;
  76335. }
  76336. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  76337. if( rc==SQLITE_OK ){
  76338. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  76339. }
  76340. /* Store the current value of the database handles deferred constraint
  76341. ** counter. If the statement transaction needs to be rolled back,
  76342. ** the value of this counter needs to be restored too. */
  76343. p->nStmtDefCons = db->nDeferredCons;
  76344. p->nStmtDefImmCons = db->nDeferredImmCons;
  76345. }
  76346. /* Gather the schema version number for checking:
  76347. ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
  76348. ** version is checked to ensure that the schema has not changed since the
  76349. ** SQL statement was prepared.
  76350. */
  76351. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  76352. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  76353. }else{
  76354. iGen = iMeta = 0;
  76355. }
  76356. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  76357. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  76358. sqlite3DbFree(db, p->zErrMsg);
  76359. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  76360. /* If the schema-cookie from the database file matches the cookie
  76361. ** stored with the in-memory representation of the schema, do
  76362. ** not reload the schema from the database file.
  76363. **
  76364. ** If virtual-tables are in use, this is not just an optimization.
  76365. ** Often, v-tables store their data in other SQLite tables, which
  76366. ** are queried from within xNext() and other v-table methods using
  76367. ** prepared queries. If such a query is out-of-date, we do not want to
  76368. ** discard the database schema, as the user code implementing the
  76369. ** v-table would have to be ready for the sqlite3_vtab structure itself
  76370. ** to be invalidated whenever sqlite3_step() is called from within
  76371. ** a v-table method.
  76372. */
  76373. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  76374. sqlite3ResetOneSchema(db, pOp->p1);
  76375. }
  76376. p->expired = 1;
  76377. rc = SQLITE_SCHEMA;
  76378. }
  76379. if( rc ) goto abort_due_to_error;
  76380. break;
  76381. }
  76382. /* Opcode: ReadCookie P1 P2 P3 * *
  76383. **
  76384. ** Read cookie number P3 from database P1 and write it into register P2.
  76385. ** P3==1 is the schema version. P3==2 is the database format.
  76386. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  76387. ** the main database file and P1==1 is the database file used to store
  76388. ** temporary tables.
  76389. **
  76390. ** There must be a read-lock on the database (either a transaction
  76391. ** must be started or there must be an open cursor) before
  76392. ** executing this instruction.
  76393. */
  76394. case OP_ReadCookie: { /* out2 */
  76395. int iMeta;
  76396. int iDb;
  76397. int iCookie;
  76398. assert( p->bIsReader );
  76399. iDb = pOp->p1;
  76400. iCookie = pOp->p3;
  76401. assert( pOp->p3<SQLITE_N_BTREE_META );
  76402. assert( iDb>=0 && iDb<db->nDb );
  76403. assert( db->aDb[iDb].pBt!=0 );
  76404. assert( DbMaskTest(p->btreeMask, iDb) );
  76405. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  76406. pOut = out2Prerelease(p, pOp);
  76407. pOut->u.i = iMeta;
  76408. break;
  76409. }
  76410. /* Opcode: SetCookie P1 P2 P3 * *
  76411. **
  76412. ** Write the integer value P3 into cookie number P2 of database P1.
  76413. ** P2==1 is the schema version. P2==2 is the database format.
  76414. ** P2==3 is the recommended pager cache
  76415. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  76416. ** database file used to store temporary tables.
  76417. **
  76418. ** A transaction must be started before executing this opcode.
  76419. */
  76420. case OP_SetCookie: {
  76421. Db *pDb;
  76422. assert( pOp->p2<SQLITE_N_BTREE_META );
  76423. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  76424. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  76425. assert( p->readOnly==0 );
  76426. pDb = &db->aDb[pOp->p1];
  76427. assert( pDb->pBt!=0 );
  76428. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  76429. /* See note about index shifting on OP_ReadCookie */
  76430. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  76431. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  76432. /* When the schema cookie changes, record the new cookie internally */
  76433. pDb->pSchema->schema_cookie = pOp->p3;
  76434. db->flags |= SQLITE_InternChanges;
  76435. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  76436. /* Record changes in the file format */
  76437. pDb->pSchema->file_format = pOp->p3;
  76438. }
  76439. if( pOp->p1==1 ){
  76440. /* Invalidate all prepared statements whenever the TEMP database
  76441. ** schema is changed. Ticket #1644 */
  76442. sqlite3ExpirePreparedStatements(db);
  76443. p->expired = 0;
  76444. }
  76445. if( rc ) goto abort_due_to_error;
  76446. break;
  76447. }
  76448. /* Opcode: OpenRead P1 P2 P3 P4 P5
  76449. ** Synopsis: root=P2 iDb=P3
  76450. **
  76451. ** Open a read-only cursor for the database table whose root page is
  76452. ** P2 in a database file. The database file is determined by P3.
  76453. ** P3==0 means the main database, P3==1 means the database used for
  76454. ** temporary tables, and P3>1 means used the corresponding attached
  76455. ** database. Give the new cursor an identifier of P1. The P1
  76456. ** values need not be contiguous but all P1 values should be small integers.
  76457. ** It is an error for P1 to be negative.
  76458. **
  76459. ** If P5!=0 then use the content of register P2 as the root page, not
  76460. ** the value of P2 itself.
  76461. **
  76462. ** There will be a read lock on the database whenever there is an
  76463. ** open cursor. If the database was unlocked prior to this instruction
  76464. ** then a read lock is acquired as part of this instruction. A read
  76465. ** lock allows other processes to read the database but prohibits
  76466. ** any other process from modifying the database. The read lock is
  76467. ** released when all cursors are closed. If this instruction attempts
  76468. ** to get a read lock but fails, the script terminates with an
  76469. ** SQLITE_BUSY error code.
  76470. **
  76471. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  76472. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  76473. ** structure, then said structure defines the content and collating
  76474. ** sequence of the index being opened. Otherwise, if P4 is an integer
  76475. ** value, it is set to the number of columns in the table.
  76476. **
  76477. ** See also: OpenWrite, ReopenIdx
  76478. */
  76479. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  76480. ** Synopsis: root=P2 iDb=P3
  76481. **
  76482. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  76483. ** checks to see if the cursor on P1 is already open with a root page
  76484. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  76485. ** if the cursor is already open, do not reopen it.
  76486. **
  76487. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  76488. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  76489. ** every other ReopenIdx or OpenRead for the same cursor number.
  76490. **
  76491. ** See the OpenRead opcode documentation for additional information.
  76492. */
  76493. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  76494. ** Synopsis: root=P2 iDb=P3
  76495. **
  76496. ** Open a read/write cursor named P1 on the table or index whose root
  76497. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  76498. ** root page.
  76499. **
  76500. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  76501. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  76502. ** structure, then said structure defines the content and collating
  76503. ** sequence of the index being opened. Otherwise, if P4 is an integer
  76504. ** value, it is set to the number of columns in the table, or to the
  76505. ** largest index of any column of the table that is actually used.
  76506. **
  76507. ** This instruction works just like OpenRead except that it opens the cursor
  76508. ** in read/write mode. For a given table, there can be one or more read-only
  76509. ** cursors or a single read/write cursor but not both.
  76510. **
  76511. ** See also OpenRead.
  76512. */
  76513. case OP_ReopenIdx: {
  76514. int nField;
  76515. KeyInfo *pKeyInfo;
  76516. int p2;
  76517. int iDb;
  76518. int wrFlag;
  76519. Btree *pX;
  76520. VdbeCursor *pCur;
  76521. Db *pDb;
  76522. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  76523. assert( pOp->p4type==P4_KEYINFO );
  76524. pCur = p->apCsr[pOp->p1];
  76525. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  76526. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  76527. goto open_cursor_set_hints;
  76528. }
  76529. /* If the cursor is not currently open or is open on a different
  76530. ** index, then fall through into OP_OpenRead to force a reopen */
  76531. case OP_OpenRead:
  76532. case OP_OpenWrite:
  76533. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  76534. assert( p->bIsReader );
  76535. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  76536. || p->readOnly==0 );
  76537. if( p->expired ){
  76538. rc = SQLITE_ABORT_ROLLBACK;
  76539. goto abort_due_to_error;
  76540. }
  76541. nField = 0;
  76542. pKeyInfo = 0;
  76543. p2 = pOp->p2;
  76544. iDb = pOp->p3;
  76545. assert( iDb>=0 && iDb<db->nDb );
  76546. assert( DbMaskTest(p->btreeMask, iDb) );
  76547. pDb = &db->aDb[iDb];
  76548. pX = pDb->pBt;
  76549. assert( pX!=0 );
  76550. if( pOp->opcode==OP_OpenWrite ){
  76551. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  76552. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  76553. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  76554. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  76555. p->minWriteFileFormat = pDb->pSchema->file_format;
  76556. }
  76557. }else{
  76558. wrFlag = 0;
  76559. }
  76560. if( pOp->p5 & OPFLAG_P2ISREG ){
  76561. assert( p2>0 );
  76562. assert( p2<=(p->nMem+1 - p->nCursor) );
  76563. pIn2 = &aMem[p2];
  76564. assert( memIsValid(pIn2) );
  76565. assert( (pIn2->flags & MEM_Int)!=0 );
  76566. sqlite3VdbeMemIntegerify(pIn2);
  76567. p2 = (int)pIn2->u.i;
  76568. /* The p2 value always comes from a prior OP_CreateTable opcode and
  76569. ** that opcode will always set the p2 value to 2 or more or else fail.
  76570. ** If there were a failure, the prepared statement would have halted
  76571. ** before reaching this instruction. */
  76572. assert( p2>=2 );
  76573. }
  76574. if( pOp->p4type==P4_KEYINFO ){
  76575. pKeyInfo = pOp->p4.pKeyInfo;
  76576. assert( pKeyInfo->enc==ENC(db) );
  76577. assert( pKeyInfo->db==db );
  76578. nField = pKeyInfo->nField+pKeyInfo->nXField;
  76579. }else if( pOp->p4type==P4_INT32 ){
  76580. nField = pOp->p4.i;
  76581. }
  76582. assert( pOp->p1>=0 );
  76583. assert( nField>=0 );
  76584. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  76585. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  76586. if( pCur==0 ) goto no_mem;
  76587. pCur->nullRow = 1;
  76588. pCur->isOrdered = 1;
  76589. pCur->pgnoRoot = p2;
  76590. #ifdef SQLITE_DEBUG
  76591. pCur->wrFlag = wrFlag;
  76592. #endif
  76593. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  76594. pCur->pKeyInfo = pKeyInfo;
  76595. /* Set the VdbeCursor.isTable variable. Previous versions of
  76596. ** SQLite used to check if the root-page flags were sane at this point
  76597. ** and report database corruption if they were not, but this check has
  76598. ** since moved into the btree layer. */
  76599. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  76600. open_cursor_set_hints:
  76601. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  76602. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  76603. testcase( pOp->p5 & OPFLAG_BULKCSR );
  76604. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  76605. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  76606. #endif
  76607. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  76608. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  76609. if( rc ) goto abort_due_to_error;
  76610. break;
  76611. }
  76612. /* Opcode: OpenDup P1 P2 * * *
  76613. **
  76614. ** Open a new cursor P1 that points to the same ephemeral table as
  76615. ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
  76616. ** opcode. Only ephemeral cursors may be duplicated.
  76617. **
  76618. ** Duplicate ephemeral cursors are used for self-joins of materialized views.
  76619. */
  76620. case OP_OpenDup: {
  76621. VdbeCursor *pOrig; /* The original cursor to be duplicated */
  76622. VdbeCursor *pCx; /* The new cursor */
  76623. pOrig = p->apCsr[pOp->p2];
  76624. assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
  76625. pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
  76626. if( pCx==0 ) goto no_mem;
  76627. pCx->nullRow = 1;
  76628. pCx->isEphemeral = 1;
  76629. pCx->pKeyInfo = pOrig->pKeyInfo;
  76630. pCx->isTable = pOrig->isTable;
  76631. rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
  76632. pCx->pKeyInfo, pCx->uc.pCursor);
  76633. /* The sqlite3BtreeCursor() routine can only fail for the first cursor
  76634. ** opened for a database. Since there is already an open cursor when this
  76635. ** opcode is run, the sqlite3BtreeCursor() cannot fail */
  76636. assert( rc==SQLITE_OK );
  76637. break;
  76638. }
  76639. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  76640. ** Synopsis: nColumn=P2
  76641. **
  76642. ** Open a new cursor P1 to a transient table.
  76643. ** The cursor is always opened read/write even if
  76644. ** the main database is read-only. The ephemeral
  76645. ** table is deleted automatically when the cursor is closed.
  76646. **
  76647. ** P2 is the number of columns in the ephemeral table.
  76648. ** The cursor points to a BTree table if P4==0 and to a BTree index
  76649. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  76650. ** that defines the format of keys in the index.
  76651. **
  76652. ** The P5 parameter can be a mask of the BTREE_* flags defined
  76653. ** in btree.h. These flags control aspects of the operation of
  76654. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  76655. ** added automatically.
  76656. */
  76657. /* Opcode: OpenAutoindex P1 P2 * P4 *
  76658. ** Synopsis: nColumn=P2
  76659. **
  76660. ** This opcode works the same as OP_OpenEphemeral. It has a
  76661. ** different name to distinguish its use. Tables created using
  76662. ** by this opcode will be used for automatically created transient
  76663. ** indices in joins.
  76664. */
  76665. case OP_OpenAutoindex:
  76666. case OP_OpenEphemeral: {
  76667. VdbeCursor *pCx;
  76668. KeyInfo *pKeyInfo;
  76669. static const int vfsFlags =
  76670. SQLITE_OPEN_READWRITE |
  76671. SQLITE_OPEN_CREATE |
  76672. SQLITE_OPEN_EXCLUSIVE |
  76673. SQLITE_OPEN_DELETEONCLOSE |
  76674. SQLITE_OPEN_TRANSIENT_DB;
  76675. assert( pOp->p1>=0 );
  76676. assert( pOp->p2>=0 );
  76677. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  76678. if( pCx==0 ) goto no_mem;
  76679. pCx->nullRow = 1;
  76680. pCx->isEphemeral = 1;
  76681. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
  76682. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  76683. if( rc==SQLITE_OK ){
  76684. rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
  76685. }
  76686. if( rc==SQLITE_OK ){
  76687. /* If a transient index is required, create it by calling
  76688. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  76689. ** opening it. If a transient table is required, just use the
  76690. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  76691. */
  76692. if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  76693. int pgno;
  76694. assert( pOp->p4type==P4_KEYINFO );
  76695. rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
  76696. if( rc==SQLITE_OK ){
  76697. assert( pgno==MASTER_ROOT+1 );
  76698. assert( pKeyInfo->db==db );
  76699. assert( pKeyInfo->enc==ENC(db) );
  76700. rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
  76701. pKeyInfo, pCx->uc.pCursor);
  76702. }
  76703. pCx->isTable = 0;
  76704. }else{
  76705. rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
  76706. 0, pCx->uc.pCursor);
  76707. pCx->isTable = 1;
  76708. }
  76709. }
  76710. if( rc ) goto abort_due_to_error;
  76711. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  76712. break;
  76713. }
  76714. /* Opcode: SorterOpen P1 P2 P3 P4 *
  76715. **
  76716. ** This opcode works like OP_OpenEphemeral except that it opens
  76717. ** a transient index that is specifically designed to sort large
  76718. ** tables using an external merge-sort algorithm.
  76719. **
  76720. ** If argument P3 is non-zero, then it indicates that the sorter may
  76721. ** assume that a stable sort considering the first P3 fields of each
  76722. ** key is sufficient to produce the required results.
  76723. */
  76724. case OP_SorterOpen: {
  76725. VdbeCursor *pCx;
  76726. assert( pOp->p1>=0 );
  76727. assert( pOp->p2>=0 );
  76728. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  76729. if( pCx==0 ) goto no_mem;
  76730. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  76731. assert( pCx->pKeyInfo->db==db );
  76732. assert( pCx->pKeyInfo->enc==ENC(db) );
  76733. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  76734. if( rc ) goto abort_due_to_error;
  76735. break;
  76736. }
  76737. /* Opcode: SequenceTest P1 P2 * * *
  76738. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  76739. **
  76740. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  76741. ** to P2. Regardless of whether or not the jump is taken, increment the
  76742. ** the sequence value.
  76743. */
  76744. case OP_SequenceTest: {
  76745. VdbeCursor *pC;
  76746. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  76747. pC = p->apCsr[pOp->p1];
  76748. assert( isSorter(pC) );
  76749. if( (pC->seqCount++)==0 ){
  76750. goto jump_to_p2;
  76751. }
  76752. break;
  76753. }
  76754. /* Opcode: OpenPseudo P1 P2 P3 * *
  76755. ** Synopsis: P3 columns in r[P2]
  76756. **
  76757. ** Open a new cursor that points to a fake table that contains a single
  76758. ** row of data. The content of that one row is the content of memory
  76759. ** register P2. In other words, cursor P1 becomes an alias for the
  76760. ** MEM_Blob content contained in register P2.
  76761. **
  76762. ** A pseudo-table created by this opcode is used to hold a single
  76763. ** row output from the sorter so that the row can be decomposed into
  76764. ** individual columns using the OP_Column opcode. The OP_Column opcode
  76765. ** is the only cursor opcode that works with a pseudo-table.
  76766. **
  76767. ** P3 is the number of fields in the records that will be stored by
  76768. ** the pseudo-table.
  76769. */
  76770. case OP_OpenPseudo: {
  76771. VdbeCursor *pCx;
  76772. assert( pOp->p1>=0 );
  76773. assert( pOp->p3>=0 );
  76774. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  76775. if( pCx==0 ) goto no_mem;
  76776. pCx->nullRow = 1;
  76777. pCx->uc.pseudoTableReg = pOp->p2;
  76778. pCx->isTable = 1;
  76779. assert( pOp->p5==0 );
  76780. break;
  76781. }
  76782. /* Opcode: Close P1 * * * *
  76783. **
  76784. ** Close a cursor previously opened as P1. If P1 is not
  76785. ** currently open, this instruction is a no-op.
  76786. */
  76787. case OP_Close: {
  76788. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  76789. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  76790. p->apCsr[pOp->p1] = 0;
  76791. break;
  76792. }
  76793. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  76794. /* Opcode: ColumnsUsed P1 * * P4 *
  76795. **
  76796. ** This opcode (which only exists if SQLite was compiled with
  76797. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  76798. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  76799. ** (P4_INT64) in which the first 63 bits are one for each of the
  76800. ** first 63 columns of the table or index that are actually used
  76801. ** by the cursor. The high-order bit is set if any column after
  76802. ** the 64th is used.
  76803. */
  76804. case OP_ColumnsUsed: {
  76805. VdbeCursor *pC;
  76806. pC = p->apCsr[pOp->p1];
  76807. assert( pC->eCurType==CURTYPE_BTREE );
  76808. pC->maskUsed = *(u64*)pOp->p4.pI64;
  76809. break;
  76810. }
  76811. #endif
  76812. /* Opcode: SeekGE P1 P2 P3 P4 *
  76813. ** Synopsis: key=r[P3@P4]
  76814. **
  76815. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  76816. ** use the value in register P3 as the key. If cursor P1 refers
  76817. ** to an SQL index, then P3 is the first in an array of P4 registers
  76818. ** that are used as an unpacked index key.
  76819. **
  76820. ** Reposition cursor P1 so that it points to the smallest entry that
  76821. ** is greater than or equal to the key value. If there are no records
  76822. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  76823. **
  76824. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  76825. ** opcode will always land on a record that equally equals the key, or
  76826. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  76827. ** opcode must be followed by an IdxLE opcode with the same arguments.
  76828. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  76829. ** IdxLE opcode will be used on subsequent loop iterations.
  76830. **
  76831. ** This opcode leaves the cursor configured to move in forward order,
  76832. ** from the beginning toward the end. In other words, the cursor is
  76833. ** configured to use Next, not Prev.
  76834. **
  76835. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  76836. */
  76837. /* Opcode: SeekGT 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 a 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 the key value. If there are no records greater than
  76847. ** the key and P2 is not zero, then jump to P2.
  76848. **
  76849. ** This opcode leaves the cursor configured to move in forward order,
  76850. ** from the beginning toward the end. In other words, the cursor is
  76851. ** configured to use Next, not Prev.
  76852. **
  76853. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  76854. */
  76855. /* Opcode: SeekLT P1 P2 P3 P4 *
  76856. ** Synopsis: key=r[P3@P4]
  76857. **
  76858. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  76859. ** use the value in register P3 as a key. If cursor P1 refers
  76860. ** to an SQL index, then P3 is the first in an array of P4 registers
  76861. ** that are used as an unpacked index key.
  76862. **
  76863. ** Reposition cursor P1 so that it points to the largest entry that
  76864. ** is less than the key value. If there are no records less than
  76865. ** the key and P2 is not zero, then jump to P2.
  76866. **
  76867. ** This opcode leaves the cursor configured to move in reverse order,
  76868. ** from the end toward the beginning. In other words, the cursor is
  76869. ** configured to use Prev, not Next.
  76870. **
  76871. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  76872. */
  76873. /* Opcode: SeekLE P1 P2 P3 P4 *
  76874. ** Synopsis: key=r[P3@P4]
  76875. **
  76876. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  76877. ** use the value in register P3 as a key. If cursor P1 refers
  76878. ** to an SQL index, then P3 is the first in an array of P4 registers
  76879. ** that are used as an unpacked index key.
  76880. **
  76881. ** Reposition cursor P1 so that it points to the largest entry that
  76882. ** is less than or equal to the key value. If there are no records
  76883. ** less than or equal to the key and P2 is not zero, then jump to P2.
  76884. **
  76885. ** This opcode leaves the cursor configured to move in reverse order,
  76886. ** from the end toward the beginning. In other words, the cursor is
  76887. ** configured to use Prev, not Next.
  76888. **
  76889. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  76890. ** opcode will always land on a record that equally equals the key, or
  76891. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  76892. ** opcode must be followed by an IdxGE opcode with the same arguments.
  76893. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  76894. ** IdxGE opcode will be used on subsequent loop iterations.
  76895. **
  76896. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  76897. */
  76898. case OP_SeekLT: /* jump, in3 */
  76899. case OP_SeekLE: /* jump, in3 */
  76900. case OP_SeekGE: /* jump, in3 */
  76901. case OP_SeekGT: { /* jump, in3 */
  76902. int res; /* Comparison result */
  76903. int oc; /* Opcode */
  76904. VdbeCursor *pC; /* The cursor to seek */
  76905. UnpackedRecord r; /* The key to seek for */
  76906. int nField; /* Number of columns or fields in the key */
  76907. i64 iKey; /* The rowid we are to seek to */
  76908. int eqOnly; /* Only interested in == results */
  76909. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  76910. assert( pOp->p2!=0 );
  76911. pC = p->apCsr[pOp->p1];
  76912. assert( pC!=0 );
  76913. assert( pC->eCurType==CURTYPE_BTREE );
  76914. assert( OP_SeekLE == OP_SeekLT+1 );
  76915. assert( OP_SeekGE == OP_SeekLT+2 );
  76916. assert( OP_SeekGT == OP_SeekLT+3 );
  76917. assert( pC->isOrdered );
  76918. assert( pC->uc.pCursor!=0 );
  76919. oc = pOp->opcode;
  76920. eqOnly = 0;
  76921. pC->nullRow = 0;
  76922. #ifdef SQLITE_DEBUG
  76923. pC->seekOp = pOp->opcode;
  76924. #endif
  76925. if( pC->isTable ){
  76926. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  76927. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
  76928. || CORRUPT_DB );
  76929. /* The input value in P3 might be of any type: integer, real, string,
  76930. ** blob, or NULL. But it needs to be an integer before we can do
  76931. ** the seek, so convert it. */
  76932. pIn3 = &aMem[pOp->p3];
  76933. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  76934. applyNumericAffinity(pIn3, 0);
  76935. }
  76936. iKey = sqlite3VdbeIntValue(pIn3);
  76937. /* If the P3 value could not be converted into an integer without
  76938. ** loss of information, then special processing is required... */
  76939. if( (pIn3->flags & MEM_Int)==0 ){
  76940. if( (pIn3->flags & MEM_Real)==0 ){
  76941. /* If the P3 value cannot be converted into any kind of a number,
  76942. ** then the seek is not possible, so jump to P2 */
  76943. VdbeBranchTaken(1,2); goto jump_to_p2;
  76944. break;
  76945. }
  76946. /* If the approximation iKey is larger than the actual real search
  76947. ** term, substitute >= for > and < for <=. e.g. if the search term
  76948. ** is 4.9 and the integer approximation 5:
  76949. **
  76950. ** (x > 4.9) -> (x >= 5)
  76951. ** (x <= 4.9) -> (x < 5)
  76952. */
  76953. if( pIn3->u.r<(double)iKey ){
  76954. assert( OP_SeekGE==(OP_SeekGT-1) );
  76955. assert( OP_SeekLT==(OP_SeekLE-1) );
  76956. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  76957. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  76958. }
  76959. /* If the approximation iKey is smaller than the actual real search
  76960. ** term, substitute <= for < and > for >=. */
  76961. else if( pIn3->u.r>(double)iKey ){
  76962. assert( OP_SeekLE==(OP_SeekLT+1) );
  76963. assert( OP_SeekGT==(OP_SeekGE+1) );
  76964. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  76965. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  76966. }
  76967. }
  76968. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  76969. pC->movetoTarget = iKey; /* Used by OP_Delete */
  76970. if( rc!=SQLITE_OK ){
  76971. goto abort_due_to_error;
  76972. }
  76973. }else{
  76974. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  76975. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  76976. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  76977. */
  76978. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  76979. eqOnly = 1;
  76980. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  76981. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  76982. assert( pOp[1].p1==pOp[0].p1 );
  76983. assert( pOp[1].p2==pOp[0].p2 );
  76984. assert( pOp[1].p3==pOp[0].p3 );
  76985. assert( pOp[1].p4.i==pOp[0].p4.i );
  76986. }
  76987. nField = pOp->p4.i;
  76988. assert( pOp->p4type==P4_INT32 );
  76989. assert( nField>0 );
  76990. r.pKeyInfo = pC->pKeyInfo;
  76991. r.nField = (u16)nField;
  76992. /* The next line of code computes as follows, only faster:
  76993. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  76994. ** r.default_rc = -1;
  76995. ** }else{
  76996. ** r.default_rc = +1;
  76997. ** }
  76998. */
  76999. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  77000. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  77001. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  77002. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  77003. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  77004. r.aMem = &aMem[pOp->p3];
  77005. #ifdef SQLITE_DEBUG
  77006. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  77007. #endif
  77008. r.eqSeen = 0;
  77009. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  77010. if( rc!=SQLITE_OK ){
  77011. goto abort_due_to_error;
  77012. }
  77013. if( eqOnly && r.eqSeen==0 ){
  77014. assert( res!=0 );
  77015. goto seek_not_found;
  77016. }
  77017. }
  77018. pC->deferredMoveto = 0;
  77019. pC->cacheStatus = CACHE_STALE;
  77020. #ifdef SQLITE_TEST
  77021. sqlite3_search_count++;
  77022. #endif
  77023. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  77024. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  77025. res = 0;
  77026. rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
  77027. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  77028. }else{
  77029. res = 0;
  77030. }
  77031. }else{
  77032. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  77033. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  77034. res = 0;
  77035. rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
  77036. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  77037. }else{
  77038. /* res might be negative because the table is empty. Check to
  77039. ** see if this is the case.
  77040. */
  77041. res = sqlite3BtreeEof(pC->uc.pCursor);
  77042. }
  77043. }
  77044. seek_not_found:
  77045. assert( pOp->p2>0 );
  77046. VdbeBranchTaken(res!=0,2);
  77047. if( res ){
  77048. goto jump_to_p2;
  77049. }else if( eqOnly ){
  77050. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  77051. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  77052. }
  77053. break;
  77054. }
  77055. /* Opcode: Found P1 P2 P3 P4 *
  77056. ** Synopsis: key=r[P3@P4]
  77057. **
  77058. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  77059. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  77060. ** record.
  77061. **
  77062. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  77063. ** is a prefix of any entry in P1 then a jump is made to P2 and
  77064. ** P1 is left pointing at the matching entry.
  77065. **
  77066. ** This operation leaves the cursor in a state where it can be
  77067. ** advanced in the forward direction. The Next instruction will work,
  77068. ** but not the Prev instruction.
  77069. **
  77070. ** See also: NotFound, NoConflict, NotExists. SeekGe
  77071. */
  77072. /* Opcode: NotFound P1 P2 P3 P4 *
  77073. ** Synopsis: key=r[P3@P4]
  77074. **
  77075. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  77076. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  77077. ** record.
  77078. **
  77079. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  77080. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  77081. ** does contain an entry whose prefix matches the P3/P4 record then control
  77082. ** falls through to the next instruction and P1 is left pointing at the
  77083. ** matching entry.
  77084. **
  77085. ** This operation leaves the cursor in a state where it cannot be
  77086. ** advanced in either direction. In other words, the Next and Prev
  77087. ** opcodes do not work after this operation.
  77088. **
  77089. ** See also: Found, NotExists, NoConflict
  77090. */
  77091. /* Opcode: NoConflict P1 P2 P3 P4 *
  77092. ** Synopsis: key=r[P3@P4]
  77093. **
  77094. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  77095. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  77096. ** record.
  77097. **
  77098. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  77099. ** contains any NULL value, jump immediately to P2. If all terms of the
  77100. ** record are not-NULL then a check is done to determine if any row in the
  77101. ** P1 index btree has a matching key prefix. If there are no matches, jump
  77102. ** immediately to P2. If there is a match, fall through and leave the P1
  77103. ** cursor pointing to the matching row.
  77104. **
  77105. ** This opcode is similar to OP_NotFound with the exceptions that the
  77106. ** branch is always taken if any part of the search key input is NULL.
  77107. **
  77108. ** This operation leaves the cursor in a state where it cannot be
  77109. ** advanced in either direction. In other words, the Next and Prev
  77110. ** opcodes do not work after this operation.
  77111. **
  77112. ** See also: NotFound, Found, NotExists
  77113. */
  77114. case OP_NoConflict: /* jump, in3 */
  77115. case OP_NotFound: /* jump, in3 */
  77116. case OP_Found: { /* jump, in3 */
  77117. int alreadyExists;
  77118. int takeJump;
  77119. int ii;
  77120. VdbeCursor *pC;
  77121. int res;
  77122. UnpackedRecord *pFree;
  77123. UnpackedRecord *pIdxKey;
  77124. UnpackedRecord r;
  77125. #ifdef SQLITE_TEST
  77126. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  77127. #endif
  77128. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77129. assert( pOp->p4type==P4_INT32 );
  77130. pC = p->apCsr[pOp->p1];
  77131. assert( pC!=0 );
  77132. #ifdef SQLITE_DEBUG
  77133. pC->seekOp = pOp->opcode;
  77134. #endif
  77135. pIn3 = &aMem[pOp->p3];
  77136. assert( pC->eCurType==CURTYPE_BTREE );
  77137. assert( pC->uc.pCursor!=0 );
  77138. assert( pC->isTable==0 );
  77139. if( pOp->p4.i>0 ){
  77140. r.pKeyInfo = pC->pKeyInfo;
  77141. r.nField = (u16)pOp->p4.i;
  77142. r.aMem = pIn3;
  77143. #ifdef SQLITE_DEBUG
  77144. for(ii=0; ii<r.nField; ii++){
  77145. assert( memIsValid(&r.aMem[ii]) );
  77146. assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
  77147. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  77148. }
  77149. #endif
  77150. pIdxKey = &r;
  77151. pFree = 0;
  77152. }else{
  77153. assert( pIn3->flags & MEM_Blob );
  77154. rc = ExpandBlob(pIn3);
  77155. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  77156. if( rc ) goto no_mem;
  77157. pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
  77158. if( pIdxKey==0 ) goto no_mem;
  77159. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  77160. }
  77161. pIdxKey->default_rc = 0;
  77162. takeJump = 0;
  77163. if( pOp->opcode==OP_NoConflict ){
  77164. /* For the OP_NoConflict opcode, take the jump if any of the
  77165. ** input fields are NULL, since any key with a NULL will not
  77166. ** conflict */
  77167. for(ii=0; ii<pIdxKey->nField; ii++){
  77168. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  77169. takeJump = 1;
  77170. break;
  77171. }
  77172. }
  77173. }
  77174. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  77175. if( pFree ) sqlite3DbFreeNN(db, pFree);
  77176. if( rc!=SQLITE_OK ){
  77177. goto abort_due_to_error;
  77178. }
  77179. pC->seekResult = res;
  77180. alreadyExists = (res==0);
  77181. pC->nullRow = 1-alreadyExists;
  77182. pC->deferredMoveto = 0;
  77183. pC->cacheStatus = CACHE_STALE;
  77184. if( pOp->opcode==OP_Found ){
  77185. VdbeBranchTaken(alreadyExists!=0,2);
  77186. if( alreadyExists ) goto jump_to_p2;
  77187. }else{
  77188. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  77189. if( takeJump || !alreadyExists ) goto jump_to_p2;
  77190. }
  77191. break;
  77192. }
  77193. /* Opcode: SeekRowid P1 P2 P3 * *
  77194. ** Synopsis: intkey=r[P3]
  77195. **
  77196. ** P1 is the index of a cursor open on an SQL table btree (with integer
  77197. ** keys). If register P3 does not contain an integer or if P1 does not
  77198. ** contain a record with rowid P3 then jump immediately to P2.
  77199. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
  77200. ** a record with rowid P3 then
  77201. ** leave the cursor pointing at that record and fall through to the next
  77202. ** instruction.
  77203. **
  77204. ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
  77205. ** the P3 register must be guaranteed to contain an integer value. With this
  77206. ** opcode, register P3 might not contain an integer.
  77207. **
  77208. ** The OP_NotFound opcode performs the same operation on index btrees
  77209. ** (with arbitrary multi-value keys).
  77210. **
  77211. ** This opcode leaves the cursor in a state where it cannot be advanced
  77212. ** in either direction. In other words, the Next and Prev opcodes will
  77213. ** not work following this opcode.
  77214. **
  77215. ** See also: Found, NotFound, NoConflict, SeekRowid
  77216. */
  77217. /* Opcode: NotExists P1 P2 P3 * *
  77218. ** Synopsis: intkey=r[P3]
  77219. **
  77220. ** P1 is the index of a cursor open on an SQL table btree (with integer
  77221. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  77222. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  77223. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  77224. ** leave the cursor pointing at that record and fall through to the next
  77225. ** instruction.
  77226. **
  77227. ** The OP_SeekRowid opcode performs the same operation but also allows the
  77228. ** P3 register to contain a non-integer value, in which case the jump is
  77229. ** always taken. This opcode requires that P3 always contain an integer.
  77230. **
  77231. ** The OP_NotFound opcode performs the same operation on index btrees
  77232. ** (with arbitrary multi-value keys).
  77233. **
  77234. ** This opcode leaves the cursor in a state where it cannot be advanced
  77235. ** in either direction. In other words, the Next and Prev opcodes will
  77236. ** not work following this opcode.
  77237. **
  77238. ** See also: Found, NotFound, NoConflict, SeekRowid
  77239. */
  77240. case OP_SeekRowid: { /* jump, in3 */
  77241. VdbeCursor *pC;
  77242. BtCursor *pCrsr;
  77243. int res;
  77244. u64 iKey;
  77245. pIn3 = &aMem[pOp->p3];
  77246. if( (pIn3->flags & MEM_Int)==0 ){
  77247. applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
  77248. if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
  77249. }
  77250. /* Fall through into OP_NotExists */
  77251. case OP_NotExists: /* jump, in3 */
  77252. pIn3 = &aMem[pOp->p3];
  77253. assert( pIn3->flags & MEM_Int );
  77254. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77255. pC = p->apCsr[pOp->p1];
  77256. assert( pC!=0 );
  77257. #ifdef SQLITE_DEBUG
  77258. pC->seekOp = 0;
  77259. #endif
  77260. assert( pC->isTable );
  77261. assert( pC->eCurType==CURTYPE_BTREE );
  77262. pCrsr = pC->uc.pCursor;
  77263. assert( pCrsr!=0 );
  77264. res = 0;
  77265. iKey = pIn3->u.i;
  77266. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  77267. assert( rc==SQLITE_OK || res==0 );
  77268. pC->movetoTarget = iKey; /* Used by OP_Delete */
  77269. pC->nullRow = 0;
  77270. pC->cacheStatus = CACHE_STALE;
  77271. pC->deferredMoveto = 0;
  77272. VdbeBranchTaken(res!=0,2);
  77273. pC->seekResult = res;
  77274. if( res!=0 ){
  77275. assert( rc==SQLITE_OK );
  77276. if( pOp->p2==0 ){
  77277. rc = SQLITE_CORRUPT_BKPT;
  77278. }else{
  77279. goto jump_to_p2;
  77280. }
  77281. }
  77282. if( rc ) goto abort_due_to_error;
  77283. break;
  77284. }
  77285. /* Opcode: Sequence P1 P2 * * *
  77286. ** Synopsis: r[P2]=cursor[P1].ctr++
  77287. **
  77288. ** Find the next available sequence number for cursor P1.
  77289. ** Write the sequence number into register P2.
  77290. ** The sequence number on the cursor is incremented after this
  77291. ** instruction.
  77292. */
  77293. case OP_Sequence: { /* out2 */
  77294. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77295. assert( p->apCsr[pOp->p1]!=0 );
  77296. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  77297. pOut = out2Prerelease(p, pOp);
  77298. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  77299. break;
  77300. }
  77301. /* Opcode: NewRowid P1 P2 P3 * *
  77302. ** Synopsis: r[P2]=rowid
  77303. **
  77304. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  77305. ** The record number is not previously used as a key in the database
  77306. ** table that cursor P1 points to. The new record number is written
  77307. ** written to register P2.
  77308. **
  77309. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  77310. ** the largest previously generated record number. No new record numbers are
  77311. ** allowed to be less than this value. When this value reaches its maximum,
  77312. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  77313. ** generated record number. This P3 mechanism is used to help implement the
  77314. ** AUTOINCREMENT feature.
  77315. */
  77316. case OP_NewRowid: { /* out2 */
  77317. i64 v; /* The new rowid */
  77318. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  77319. int res; /* Result of an sqlite3BtreeLast() */
  77320. int cnt; /* Counter to limit the number of searches */
  77321. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  77322. VdbeFrame *pFrame; /* Root frame of VDBE */
  77323. v = 0;
  77324. res = 0;
  77325. pOut = out2Prerelease(p, pOp);
  77326. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77327. pC = p->apCsr[pOp->p1];
  77328. assert( pC!=0 );
  77329. assert( pC->eCurType==CURTYPE_BTREE );
  77330. assert( pC->uc.pCursor!=0 );
  77331. {
  77332. /* The next rowid or record number (different terms for the same
  77333. ** thing) is obtained in a two-step algorithm.
  77334. **
  77335. ** First we attempt to find the largest existing rowid and add one
  77336. ** to that. But if the largest existing rowid is already the maximum
  77337. ** positive integer, we have to fall through to the second
  77338. ** probabilistic algorithm
  77339. **
  77340. ** The second algorithm is to select a rowid at random and see if
  77341. ** it already exists in the table. If it does not exist, we have
  77342. ** succeeded. If the random rowid does exist, we select a new one
  77343. ** and try again, up to 100 times.
  77344. */
  77345. assert( pC->isTable );
  77346. #ifdef SQLITE_32BIT_ROWID
  77347. # define MAX_ROWID 0x7fffffff
  77348. #else
  77349. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  77350. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  77351. ** to provide the constant while making all compilers happy.
  77352. */
  77353. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  77354. #endif
  77355. if( !pC->useRandomRowid ){
  77356. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  77357. if( rc!=SQLITE_OK ){
  77358. goto abort_due_to_error;
  77359. }
  77360. if( res ){
  77361. v = 1; /* IMP: R-61914-48074 */
  77362. }else{
  77363. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  77364. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  77365. if( v>=MAX_ROWID ){
  77366. pC->useRandomRowid = 1;
  77367. }else{
  77368. v++; /* IMP: R-29538-34987 */
  77369. }
  77370. }
  77371. }
  77372. #ifndef SQLITE_OMIT_AUTOINCREMENT
  77373. if( pOp->p3 ){
  77374. /* Assert that P3 is a valid memory cell. */
  77375. assert( pOp->p3>0 );
  77376. if( p->pFrame ){
  77377. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  77378. /* Assert that P3 is a valid memory cell. */
  77379. assert( pOp->p3<=pFrame->nMem );
  77380. pMem = &pFrame->aMem[pOp->p3];
  77381. }else{
  77382. /* Assert that P3 is a valid memory cell. */
  77383. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  77384. pMem = &aMem[pOp->p3];
  77385. memAboutToChange(p, pMem);
  77386. }
  77387. assert( memIsValid(pMem) );
  77388. REGISTER_TRACE(pOp->p3, pMem);
  77389. sqlite3VdbeMemIntegerify(pMem);
  77390. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  77391. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  77392. rc = SQLITE_FULL; /* IMP: R-17817-00630 */
  77393. goto abort_due_to_error;
  77394. }
  77395. if( v<pMem->u.i+1 ){
  77396. v = pMem->u.i + 1;
  77397. }
  77398. pMem->u.i = v;
  77399. }
  77400. #endif
  77401. if( pC->useRandomRowid ){
  77402. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  77403. ** largest possible integer (9223372036854775807) then the database
  77404. ** engine starts picking positive candidate ROWIDs at random until
  77405. ** it finds one that is not previously used. */
  77406. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  77407. ** an AUTOINCREMENT table. */
  77408. cnt = 0;
  77409. do{
  77410. sqlite3_randomness(sizeof(v), &v);
  77411. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  77412. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  77413. 0, &res))==SQLITE_OK)
  77414. && (res==0)
  77415. && (++cnt<100));
  77416. if( rc ) goto abort_due_to_error;
  77417. if( res==0 ){
  77418. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  77419. goto abort_due_to_error;
  77420. }
  77421. assert( v>0 ); /* EV: R-40812-03570 */
  77422. }
  77423. pC->deferredMoveto = 0;
  77424. pC->cacheStatus = CACHE_STALE;
  77425. }
  77426. pOut->u.i = v;
  77427. break;
  77428. }
  77429. /* Opcode: Insert P1 P2 P3 P4 P5
  77430. ** Synopsis: intkey=r[P3] data=r[P2]
  77431. **
  77432. ** Write an entry into the table of cursor P1. A new entry is
  77433. ** created if it doesn't already exist or the data for an existing
  77434. ** entry is overwritten. The data is the value MEM_Blob stored in register
  77435. ** number P2. The key is stored in register P3. The key must
  77436. ** be a MEM_Int.
  77437. **
  77438. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  77439. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  77440. ** then rowid is stored for subsequent return by the
  77441. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  77442. **
  77443. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  77444. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  77445. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  77446. ** seeks on the cursor or if the most recent seek used a key equal to P3.
  77447. **
  77448. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  77449. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  77450. ** is part of an INSERT operation. The difference is only important to
  77451. ** the update hook.
  77452. **
  77453. ** Parameter P4 may point to a Table structure, or may be NULL. If it is
  77454. ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
  77455. ** following a successful insert.
  77456. **
  77457. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  77458. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  77459. ** and register P2 becomes ephemeral. If the cursor is changed, the
  77460. ** value of register P2 will then change. Make sure this does not
  77461. ** cause any problems.)
  77462. **
  77463. ** This instruction only works on tables. The equivalent instruction
  77464. ** for indices is OP_IdxInsert.
  77465. */
  77466. /* Opcode: InsertInt P1 P2 P3 P4 P5
  77467. ** Synopsis: intkey=P3 data=r[P2]
  77468. **
  77469. ** This works exactly like OP_Insert except that the key is the
  77470. ** integer value P3, not the value of the integer stored in register P3.
  77471. */
  77472. case OP_Insert:
  77473. case OP_InsertInt: {
  77474. Mem *pData; /* MEM cell holding data for the record to be inserted */
  77475. Mem *pKey; /* MEM cell holding key for the record */
  77476. VdbeCursor *pC; /* Cursor to table into which insert is written */
  77477. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  77478. const char *zDb; /* database name - used by the update hook */
  77479. Table *pTab; /* Table structure - used by update and pre-update hooks */
  77480. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  77481. BtreePayload x; /* Payload to be inserted */
  77482. op = 0;
  77483. pData = &aMem[pOp->p2];
  77484. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77485. assert( memIsValid(pData) );
  77486. pC = p->apCsr[pOp->p1];
  77487. assert( pC!=0 );
  77488. assert( pC->eCurType==CURTYPE_BTREE );
  77489. assert( pC->uc.pCursor!=0 );
  77490. assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
  77491. assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
  77492. REGISTER_TRACE(pOp->p2, pData);
  77493. if( pOp->opcode==OP_Insert ){
  77494. pKey = &aMem[pOp->p3];
  77495. assert( pKey->flags & MEM_Int );
  77496. assert( memIsValid(pKey) );
  77497. REGISTER_TRACE(pOp->p3, pKey);
  77498. x.nKey = pKey->u.i;
  77499. }else{
  77500. assert( pOp->opcode==OP_InsertInt );
  77501. x.nKey = pOp->p3;
  77502. }
  77503. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  77504. assert( pC->iDb>=0 );
  77505. zDb = db->aDb[pC->iDb].zDbSName;
  77506. pTab = pOp->p4.pTab;
  77507. assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
  77508. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  77509. }else{
  77510. pTab = 0; /* Not needed. Silence a compiler warning. */
  77511. zDb = 0; /* Not needed. Silence a compiler warning. */
  77512. }
  77513. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77514. /* Invoke the pre-update hook, if any */
  77515. if( db->xPreUpdateCallback
  77516. && pOp->p4type==P4_TABLE
  77517. && !(pOp->p5 & OPFLAG_ISUPDATE)
  77518. ){
  77519. sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
  77520. }
  77521. if( pOp->p5 & OPFLAG_ISNOOP ) break;
  77522. #endif
  77523. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  77524. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
  77525. if( pData->flags & MEM_Null ){
  77526. x.pData = 0;
  77527. x.nData = 0;
  77528. }else{
  77529. assert( pData->flags & (MEM_Blob|MEM_Str) );
  77530. x.pData = pData->z;
  77531. x.nData = pData->n;
  77532. }
  77533. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  77534. if( pData->flags & MEM_Zero ){
  77535. x.nZero = pData->u.nZero;
  77536. }else{
  77537. x.nZero = 0;
  77538. }
  77539. x.pKey = 0;
  77540. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  77541. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
  77542. );
  77543. pC->deferredMoveto = 0;
  77544. pC->cacheStatus = CACHE_STALE;
  77545. /* Invoke the update-hook if required. */
  77546. if( rc ) goto abort_due_to_error;
  77547. if( db->xUpdateCallback && op ){
  77548. db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
  77549. }
  77550. break;
  77551. }
  77552. /* Opcode: Delete P1 P2 P3 P4 P5
  77553. **
  77554. ** Delete the record at which the P1 cursor is currently pointing.
  77555. **
  77556. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  77557. ** the cursor will be left pointing at either the next or the previous
  77558. ** record in the table. If it is left pointing at the next record, then
  77559. ** the next Next instruction will be a no-op. As a result, in this case
  77560. ** it is ok to delete a record from within a Next loop. If
  77561. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  77562. ** left in an undefined state.
  77563. **
  77564. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  77565. ** delete one of several associated with deleting a table row and all its
  77566. ** associated index entries. Exactly one of those deletes is the "primary"
  77567. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  77568. ** marked with the AUXDELETE flag.
  77569. **
  77570. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  77571. ** change count is incremented (otherwise not).
  77572. **
  77573. ** P1 must not be pseudo-table. It has to be a real table with
  77574. ** multiple rows.
  77575. **
  77576. ** If P4 is not NULL then it points to a Table object. In this case either
  77577. ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
  77578. ** have been positioned using OP_NotFound prior to invoking this opcode in
  77579. ** this case. Specifically, if one is configured, the pre-update hook is
  77580. ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
  77581. ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
  77582. **
  77583. ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
  77584. ** of the memory cell that contains the value that the rowid of the row will
  77585. ** be set to by the update.
  77586. */
  77587. case OP_Delete: {
  77588. VdbeCursor *pC;
  77589. const char *zDb;
  77590. Table *pTab;
  77591. int opflags;
  77592. opflags = pOp->p2;
  77593. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77594. pC = p->apCsr[pOp->p1];
  77595. assert( pC!=0 );
  77596. assert( pC->eCurType==CURTYPE_BTREE );
  77597. assert( pC->uc.pCursor!=0 );
  77598. assert( pC->deferredMoveto==0 );
  77599. #ifdef SQLITE_DEBUG
  77600. if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
  77601. /* If p5 is zero, the seek operation that positioned the cursor prior to
  77602. ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
  77603. ** the row that is being deleted */
  77604. i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  77605. assert( pC->movetoTarget==iKey );
  77606. }
  77607. #endif
  77608. /* If the update-hook or pre-update-hook will be invoked, set zDb to
  77609. ** the name of the db to pass as to it. Also set local pTab to a copy
  77610. ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  77611. ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
  77612. ** VdbeCursor.movetoTarget to the current rowid. */
  77613. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  77614. assert( pC->iDb>=0 );
  77615. assert( pOp->p4.pTab!=0 );
  77616. zDb = db->aDb[pC->iDb].zDbSName;
  77617. pTab = pOp->p4.pTab;
  77618. if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  77619. pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  77620. }
  77621. }else{
  77622. zDb = 0; /* Not needed. Silence a compiler warning. */
  77623. pTab = 0; /* Not needed. Silence a compiler warning. */
  77624. }
  77625. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77626. /* Invoke the pre-update-hook if required. */
  77627. if( db->xPreUpdateCallback && pOp->p4.pTab ){
  77628. assert( !(opflags & OPFLAG_ISUPDATE)
  77629. || HasRowid(pTab)==0
  77630. || (aMem[pOp->p3].flags & MEM_Int)
  77631. );
  77632. sqlite3VdbePreUpdateHook(p, pC,
  77633. (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
  77634. zDb, pTab, pC->movetoTarget,
  77635. pOp->p3
  77636. );
  77637. }
  77638. if( opflags & OPFLAG_ISNOOP ) break;
  77639. #endif
  77640. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  77641. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  77642. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  77643. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  77644. #ifdef SQLITE_DEBUG
  77645. if( p->pFrame==0 ){
  77646. if( pC->isEphemeral==0
  77647. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  77648. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  77649. ){
  77650. nExtraDelete++;
  77651. }
  77652. if( pOp->p2 & OPFLAG_NCHANGE ){
  77653. nExtraDelete--;
  77654. }
  77655. }
  77656. #endif
  77657. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  77658. pC->cacheStatus = CACHE_STALE;
  77659. pC->seekResult = 0;
  77660. if( rc ) goto abort_due_to_error;
  77661. /* Invoke the update-hook if required. */
  77662. if( opflags & OPFLAG_NCHANGE ){
  77663. p->nChange++;
  77664. if( db->xUpdateCallback && HasRowid(pTab) ){
  77665. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
  77666. pC->movetoTarget);
  77667. assert( pC->iDb>=0 );
  77668. }
  77669. }
  77670. break;
  77671. }
  77672. /* Opcode: ResetCount * * * * *
  77673. **
  77674. ** The value of the change counter is copied to the database handle
  77675. ** change counter (returned by subsequent calls to sqlite3_changes()).
  77676. ** Then the VMs internal change counter resets to 0.
  77677. ** This is used by trigger programs.
  77678. */
  77679. case OP_ResetCount: {
  77680. sqlite3VdbeSetChanges(db, p->nChange);
  77681. p->nChange = 0;
  77682. break;
  77683. }
  77684. /* Opcode: SorterCompare P1 P2 P3 P4
  77685. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  77686. **
  77687. ** P1 is a sorter cursor. This instruction compares a prefix of the
  77688. ** record blob in register P3 against a prefix of the entry that
  77689. ** the sorter cursor currently points to. Only the first P4 fields
  77690. ** of r[P3] and the sorter record are compared.
  77691. **
  77692. ** If either P3 or the sorter contains a NULL in one of their significant
  77693. ** fields (not counting the P4 fields at the end which are ignored) then
  77694. ** the comparison is assumed to be equal.
  77695. **
  77696. ** Fall through to next instruction if the two records compare equal to
  77697. ** each other. Jump to P2 if they are different.
  77698. */
  77699. case OP_SorterCompare: {
  77700. VdbeCursor *pC;
  77701. int res;
  77702. int nKeyCol;
  77703. pC = p->apCsr[pOp->p1];
  77704. assert( isSorter(pC) );
  77705. assert( pOp->p4type==P4_INT32 );
  77706. pIn3 = &aMem[pOp->p3];
  77707. nKeyCol = pOp->p4.i;
  77708. res = 0;
  77709. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  77710. VdbeBranchTaken(res!=0,2);
  77711. if( rc ) goto abort_due_to_error;
  77712. if( res ) goto jump_to_p2;
  77713. break;
  77714. };
  77715. /* Opcode: SorterData P1 P2 P3 * *
  77716. ** Synopsis: r[P2]=data
  77717. **
  77718. ** Write into register P2 the current sorter data for sorter cursor P1.
  77719. ** Then clear the column header cache on cursor P3.
  77720. **
  77721. ** This opcode is normally use to move a record out of the sorter and into
  77722. ** a register that is the source for a pseudo-table cursor created using
  77723. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  77724. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  77725. ** us from having to issue a separate NullRow instruction to clear that cache.
  77726. */
  77727. case OP_SorterData: {
  77728. VdbeCursor *pC;
  77729. pOut = &aMem[pOp->p2];
  77730. pC = p->apCsr[pOp->p1];
  77731. assert( isSorter(pC) );
  77732. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  77733. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  77734. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77735. if( rc ) goto abort_due_to_error;
  77736. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  77737. break;
  77738. }
  77739. /* Opcode: RowData P1 P2 P3 * *
  77740. ** Synopsis: r[P2]=data
  77741. **
  77742. ** Write into register P2 the complete row content for the row at
  77743. ** which cursor P1 is currently pointing.
  77744. ** There is no interpretation of the data.
  77745. ** It is just copied onto the P2 register exactly as
  77746. ** it is found in the database file.
  77747. **
  77748. ** If cursor P1 is an index, then the content is the key of the row.
  77749. ** If cursor P2 is a table, then the content extracted is the data.
  77750. **
  77751. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  77752. ** of a real table, not a pseudo-table.
  77753. **
  77754. ** If P3!=0 then this opcode is allowed to make an ephermeral pointer
  77755. ** into the database page. That means that the content of the output
  77756. ** register will be invalidated as soon as the cursor moves - including
  77757. ** moves caused by other cursors that "save" the the current cursors
  77758. ** position in order that they can write to the same table. If P3==0
  77759. ** then a copy of the data is made into memory. P3!=0 is faster, but
  77760. ** P3==0 is safer.
  77761. **
  77762. ** If P3!=0 then the content of the P2 register is unsuitable for use
  77763. ** in OP_Result and any OP_Result will invalidate the P2 register content.
  77764. ** The P2 register content is invalidated by opcodes like OP_Function or
  77765. ** by any use of another cursor pointing to the same table.
  77766. */
  77767. case OP_RowData: {
  77768. VdbeCursor *pC;
  77769. BtCursor *pCrsr;
  77770. u32 n;
  77771. pOut = out2Prerelease(p, pOp);
  77772. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77773. pC = p->apCsr[pOp->p1];
  77774. assert( pC!=0 );
  77775. assert( pC->eCurType==CURTYPE_BTREE );
  77776. assert( isSorter(pC)==0 );
  77777. assert( pC->nullRow==0 );
  77778. assert( pC->uc.pCursor!=0 );
  77779. pCrsr = pC->uc.pCursor;
  77780. /* The OP_RowData opcodes always follow OP_NotExists or
  77781. ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
  77782. ** that might invalidate the cursor.
  77783. ** If this where not the case, on of the following assert()s
  77784. ** would fail. Should this ever change (because of changes in the code
  77785. ** generator) then the fix would be to insert a call to
  77786. ** sqlite3VdbeCursorMoveto().
  77787. */
  77788. assert( pC->deferredMoveto==0 );
  77789. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  77790. #if 0 /* Not required due to the previous to assert() statements */
  77791. rc = sqlite3VdbeCursorMoveto(pC);
  77792. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  77793. #endif
  77794. n = sqlite3BtreePayloadSize(pCrsr);
  77795. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77796. goto too_big;
  77797. }
  77798. testcase( n==0 );
  77799. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
  77800. if( rc ) goto abort_due_to_error;
  77801. if( !pOp->p3 ) Deephemeralize(pOut);
  77802. UPDATE_MAX_BLOBSIZE(pOut);
  77803. REGISTER_TRACE(pOp->p2, pOut);
  77804. break;
  77805. }
  77806. /* Opcode: Rowid P1 P2 * * *
  77807. ** Synopsis: r[P2]=rowid
  77808. **
  77809. ** Store in register P2 an integer which is the key of the table entry that
  77810. ** P1 is currently point to.
  77811. **
  77812. ** P1 can be either an ordinary table or a virtual table. There used to
  77813. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  77814. ** one opcode now works for both table types.
  77815. */
  77816. case OP_Rowid: { /* out2 */
  77817. VdbeCursor *pC;
  77818. i64 v;
  77819. sqlite3_vtab *pVtab;
  77820. const sqlite3_module *pModule;
  77821. pOut = out2Prerelease(p, pOp);
  77822. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77823. pC = p->apCsr[pOp->p1];
  77824. assert( pC!=0 );
  77825. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  77826. if( pC->nullRow ){
  77827. pOut->flags = MEM_Null;
  77828. break;
  77829. }else if( pC->deferredMoveto ){
  77830. v = pC->movetoTarget;
  77831. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77832. }else if( pC->eCurType==CURTYPE_VTAB ){
  77833. assert( pC->uc.pVCur!=0 );
  77834. pVtab = pC->uc.pVCur->pVtab;
  77835. pModule = pVtab->pModule;
  77836. assert( pModule->xRowid );
  77837. rc = pModule->xRowid(pC->uc.pVCur, &v);
  77838. sqlite3VtabImportErrmsg(p, pVtab);
  77839. if( rc ) goto abort_due_to_error;
  77840. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  77841. }else{
  77842. assert( pC->eCurType==CURTYPE_BTREE );
  77843. assert( pC->uc.pCursor!=0 );
  77844. rc = sqlite3VdbeCursorRestore(pC);
  77845. if( rc ) goto abort_due_to_error;
  77846. if( pC->nullRow ){
  77847. pOut->flags = MEM_Null;
  77848. break;
  77849. }
  77850. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  77851. }
  77852. pOut->u.i = v;
  77853. break;
  77854. }
  77855. /* Opcode: NullRow P1 * * * *
  77856. **
  77857. ** Move the cursor P1 to a null row. Any OP_Column operations
  77858. ** that occur while the cursor is on the null row will always
  77859. ** write a NULL.
  77860. */
  77861. case OP_NullRow: {
  77862. VdbeCursor *pC;
  77863. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77864. pC = p->apCsr[pOp->p1];
  77865. assert( pC!=0 );
  77866. pC->nullRow = 1;
  77867. pC->cacheStatus = CACHE_STALE;
  77868. if( pC->eCurType==CURTYPE_BTREE ){
  77869. assert( pC->uc.pCursor!=0 );
  77870. sqlite3BtreeClearCursor(pC->uc.pCursor);
  77871. }
  77872. break;
  77873. }
  77874. /* Opcode: Last P1 P2 P3 * *
  77875. **
  77876. ** The next use of the Rowid or Column or Prev instruction for P1
  77877. ** will refer to the last entry in the database table or index.
  77878. ** If the table or index is empty and P2>0, then jump immediately to P2.
  77879. ** If P2 is 0 or if the table or index is not empty, fall through
  77880. ** to the following instruction.
  77881. **
  77882. ** This opcode leaves the cursor configured to move in reverse order,
  77883. ** from the end toward the beginning. In other words, the cursor is
  77884. ** configured to use Prev, not Next.
  77885. **
  77886. ** If P3 is -1, then the cursor is positioned at the end of the btree
  77887. ** for the purpose of appending a new entry onto the btree. In that
  77888. ** case P2 must be 0. It is assumed that the cursor is used only for
  77889. ** appending and so if the cursor is valid, then the cursor must already
  77890. ** be pointing at the end of the btree and so no changes are made to
  77891. ** the cursor.
  77892. */
  77893. case OP_Last: { /* jump */
  77894. VdbeCursor *pC;
  77895. BtCursor *pCrsr;
  77896. int res;
  77897. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77898. pC = p->apCsr[pOp->p1];
  77899. assert( pC!=0 );
  77900. assert( pC->eCurType==CURTYPE_BTREE );
  77901. pCrsr = pC->uc.pCursor;
  77902. res = 0;
  77903. assert( pCrsr!=0 );
  77904. pC->seekResult = pOp->p3;
  77905. #ifdef SQLITE_DEBUG
  77906. pC->seekOp = OP_Last;
  77907. #endif
  77908. if( pOp->p3==0 || !sqlite3BtreeCursorIsValidNN(pCrsr) ){
  77909. rc = sqlite3BtreeLast(pCrsr, &res);
  77910. pC->nullRow = (u8)res;
  77911. pC->deferredMoveto = 0;
  77912. pC->cacheStatus = CACHE_STALE;
  77913. if( rc ) goto abort_due_to_error;
  77914. if( pOp->p2>0 ){
  77915. VdbeBranchTaken(res!=0,2);
  77916. if( res ) goto jump_to_p2;
  77917. }
  77918. }else{
  77919. assert( pOp->p2==0 );
  77920. }
  77921. break;
  77922. }
  77923. /* Opcode: IfSmaller P1 P2 P3 * *
  77924. **
  77925. ** Estimate the number of rows in the table P1. Jump to P2 if that
  77926. ** estimate is less than approximately 2**(0.1*P3).
  77927. */
  77928. case OP_IfSmaller: { /* jump */
  77929. VdbeCursor *pC;
  77930. BtCursor *pCrsr;
  77931. int res;
  77932. i64 sz;
  77933. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77934. pC = p->apCsr[pOp->p1];
  77935. assert( pC!=0 );
  77936. pCrsr = pC->uc.pCursor;
  77937. assert( pCrsr );
  77938. rc = sqlite3BtreeFirst(pCrsr, &res);
  77939. if( rc ) goto abort_due_to_error;
  77940. if( res==0 ){
  77941. sz = sqlite3BtreeRowCountEst(pCrsr);
  77942. if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
  77943. }
  77944. VdbeBranchTaken(res!=0,2);
  77945. if( res ) goto jump_to_p2;
  77946. break;
  77947. }
  77948. /* Opcode: SorterSort P1 P2 * * *
  77949. **
  77950. ** After all records have been inserted into the Sorter object
  77951. ** identified by P1, invoke this opcode to actually do the sorting.
  77952. ** Jump to P2 if there are no records to be sorted.
  77953. **
  77954. ** This opcode is an alias for OP_Sort and OP_Rewind that is used
  77955. ** for Sorter objects.
  77956. */
  77957. /* Opcode: Sort P1 P2 * * *
  77958. **
  77959. ** This opcode does exactly the same thing as OP_Rewind except that
  77960. ** it increments an undocumented global variable used for testing.
  77961. **
  77962. ** Sorting is accomplished by writing records into a sorting index,
  77963. ** then rewinding that index and playing it back from beginning to
  77964. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  77965. ** rewinding so that the global variable will be incremented and
  77966. ** regression tests can determine whether or not the optimizer is
  77967. ** correctly optimizing out sorts.
  77968. */
  77969. case OP_SorterSort: /* jump */
  77970. case OP_Sort: { /* jump */
  77971. #ifdef SQLITE_TEST
  77972. sqlite3_sort_count++;
  77973. sqlite3_search_count--;
  77974. #endif
  77975. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  77976. /* Fall through into OP_Rewind */
  77977. }
  77978. /* Opcode: Rewind P1 P2 * * *
  77979. **
  77980. ** The next use of the Rowid or Column or Next instruction for P1
  77981. ** will refer to the first entry in the database table or index.
  77982. ** If the table or index is empty, jump immediately to P2.
  77983. ** If the table or index is not empty, fall through to the following
  77984. ** instruction.
  77985. **
  77986. ** This opcode leaves the cursor configured to move in forward order,
  77987. ** from the beginning toward the end. In other words, the cursor is
  77988. ** configured to use Next, not Prev.
  77989. */
  77990. case OP_Rewind: { /* jump */
  77991. VdbeCursor *pC;
  77992. BtCursor *pCrsr;
  77993. int res;
  77994. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77995. pC = p->apCsr[pOp->p1];
  77996. assert( pC!=0 );
  77997. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  77998. res = 1;
  77999. #ifdef SQLITE_DEBUG
  78000. pC->seekOp = OP_Rewind;
  78001. #endif
  78002. if( isSorter(pC) ){
  78003. rc = sqlite3VdbeSorterRewind(pC, &res);
  78004. }else{
  78005. assert( pC->eCurType==CURTYPE_BTREE );
  78006. pCrsr = pC->uc.pCursor;
  78007. assert( pCrsr );
  78008. rc = sqlite3BtreeFirst(pCrsr, &res);
  78009. pC->deferredMoveto = 0;
  78010. pC->cacheStatus = CACHE_STALE;
  78011. }
  78012. if( rc ) goto abort_due_to_error;
  78013. pC->nullRow = (u8)res;
  78014. assert( pOp->p2>0 && pOp->p2<p->nOp );
  78015. VdbeBranchTaken(res!=0,2);
  78016. if( res ) goto jump_to_p2;
  78017. break;
  78018. }
  78019. /* Opcode: Next P1 P2 P3 P4 P5
  78020. **
  78021. ** Advance cursor P1 so that it points to the next key/data pair in its
  78022. ** table or index. If there are no more key/value pairs then fall through
  78023. ** to the following instruction. But if the cursor advance was successful,
  78024. ** jump immediately to P2.
  78025. **
  78026. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  78027. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  78028. ** to follow SeekLT, SeekLE, or OP_Last.
  78029. **
  78030. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  78031. ** been opened prior to this opcode or the program will segfault.
  78032. **
  78033. ** The P3 value is a hint to the btree implementation. If P3==1, that
  78034. ** means P1 is an SQL index and that this instruction could have been
  78035. ** omitted if that index had been unique. P3 is usually 0. P3 is
  78036. ** always either 0 or 1.
  78037. **
  78038. ** P4 is always of type P4_ADVANCE. The function pointer points to
  78039. ** sqlite3BtreeNext().
  78040. **
  78041. ** If P5 is positive and the jump is taken, then event counter
  78042. ** number P5-1 in the prepared statement is incremented.
  78043. **
  78044. ** See also: Prev, NextIfOpen
  78045. */
  78046. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  78047. **
  78048. ** This opcode works just like Next except that if cursor P1 is not
  78049. ** open it behaves a no-op.
  78050. */
  78051. /* Opcode: Prev P1 P2 P3 P4 P5
  78052. **
  78053. ** Back up cursor P1 so that it points to the previous key/data pair in its
  78054. ** table or index. If there is no previous key/value pairs then fall through
  78055. ** to the following instruction. But if the cursor backup was successful,
  78056. ** jump immediately to P2.
  78057. **
  78058. **
  78059. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  78060. ** OP_Last opcode used to position the cursor. Prev is not allowed
  78061. ** to follow SeekGT, SeekGE, or OP_Rewind.
  78062. **
  78063. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  78064. ** not open then the behavior is undefined.
  78065. **
  78066. ** The P3 value is a hint to the btree implementation. If P3==1, that
  78067. ** means P1 is an SQL index and that this instruction could have been
  78068. ** omitted if that index had been unique. P3 is usually 0. P3 is
  78069. ** always either 0 or 1.
  78070. **
  78071. ** P4 is always of type P4_ADVANCE. The function pointer points to
  78072. ** sqlite3BtreePrevious().
  78073. **
  78074. ** If P5 is positive and the jump is taken, then event counter
  78075. ** number P5-1 in the prepared statement is incremented.
  78076. */
  78077. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  78078. **
  78079. ** This opcode works just like Prev except that if cursor P1 is not
  78080. ** open it behaves a no-op.
  78081. */
  78082. /* Opcode: SorterNext P1 P2 * * P5
  78083. **
  78084. ** This opcode works just like OP_Next except that P1 must be a
  78085. ** sorter object for which the OP_SorterSort opcode has been
  78086. ** invoked. This opcode advances the cursor to the next sorted
  78087. ** record, or jumps to P2 if there are no more sorted records.
  78088. */
  78089. case OP_SorterNext: { /* jump */
  78090. VdbeCursor *pC;
  78091. int res;
  78092. pC = p->apCsr[pOp->p1];
  78093. assert( isSorter(pC) );
  78094. res = 0;
  78095. rc = sqlite3VdbeSorterNext(db, pC, &res);
  78096. goto next_tail;
  78097. case OP_PrevIfOpen: /* jump */
  78098. case OP_NextIfOpen: /* jump */
  78099. if( p->apCsr[pOp->p1]==0 ) break;
  78100. /* Fall through */
  78101. case OP_Prev: /* jump */
  78102. case OP_Next: /* jump */
  78103. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78104. assert( pOp->p5<ArraySize(p->aCounter) );
  78105. pC = p->apCsr[pOp->p1];
  78106. res = pOp->p3;
  78107. assert( pC!=0 );
  78108. assert( pC->deferredMoveto==0 );
  78109. assert( pC->eCurType==CURTYPE_BTREE );
  78110. assert( res==0 || (res==1 && pC->isTable==0) );
  78111. testcase( res==1 );
  78112. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  78113. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  78114. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  78115. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  78116. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  78117. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  78118. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  78119. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  78120. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  78121. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  78122. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  78123. || pC->seekOp==OP_Last );
  78124. rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
  78125. next_tail:
  78126. pC->cacheStatus = CACHE_STALE;
  78127. VdbeBranchTaken(res==0,2);
  78128. if( rc ) goto abort_due_to_error;
  78129. if( res==0 ){
  78130. pC->nullRow = 0;
  78131. p->aCounter[pOp->p5]++;
  78132. #ifdef SQLITE_TEST
  78133. sqlite3_search_count++;
  78134. #endif
  78135. goto jump_to_p2_and_check_for_interrupt;
  78136. }else{
  78137. pC->nullRow = 1;
  78138. }
  78139. goto check_for_interrupt;
  78140. }
  78141. /* Opcode: IdxInsert P1 P2 P3 P4 P5
  78142. ** Synopsis: key=r[P2]
  78143. **
  78144. ** Register P2 holds an SQL index key made using the
  78145. ** MakeRecord instructions. This opcode writes that key
  78146. ** into the index P1. Data for the entry is nil.
  78147. **
  78148. ** If P4 is not zero, then it is the number of values in the unpacked
  78149. ** key of reg(P2). In that case, P3 is the index of the first register
  78150. ** for the unpacked key. The availability of the unpacked key can sometimes
  78151. ** be an optimization.
  78152. **
  78153. ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
  78154. ** that this insert is likely to be an append.
  78155. **
  78156. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  78157. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  78158. ** then the change counter is unchanged.
  78159. **
  78160. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  78161. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  78162. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  78163. ** seeks on the cursor or if the most recent seek used a key equivalent
  78164. ** to P2.
  78165. **
  78166. ** This instruction only works for indices. The equivalent instruction
  78167. ** for tables is OP_Insert.
  78168. */
  78169. /* Opcode: SorterInsert P1 P2 * * *
  78170. ** Synopsis: key=r[P2]
  78171. **
  78172. ** Register P2 holds an SQL index key made using the
  78173. ** MakeRecord instructions. This opcode writes that key
  78174. ** into the sorter P1. Data for the entry is nil.
  78175. */
  78176. case OP_SorterInsert: /* in2 */
  78177. case OP_IdxInsert: { /* in2 */
  78178. VdbeCursor *pC;
  78179. BtreePayload x;
  78180. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78181. pC = p->apCsr[pOp->p1];
  78182. assert( pC!=0 );
  78183. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  78184. pIn2 = &aMem[pOp->p2];
  78185. assert( pIn2->flags & MEM_Blob );
  78186. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  78187. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  78188. assert( pC->isTable==0 );
  78189. rc = ExpandBlob(pIn2);
  78190. if( rc ) goto abort_due_to_error;
  78191. if( pOp->opcode==OP_SorterInsert ){
  78192. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  78193. }else{
  78194. x.nKey = pIn2->n;
  78195. x.pKey = pIn2->z;
  78196. x.aMem = aMem + pOp->p3;
  78197. x.nMem = (u16)pOp->p4.i;
  78198. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  78199. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
  78200. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  78201. );
  78202. assert( pC->deferredMoveto==0 );
  78203. pC->cacheStatus = CACHE_STALE;
  78204. }
  78205. if( rc) goto abort_due_to_error;
  78206. break;
  78207. }
  78208. /* Opcode: IdxDelete P1 P2 P3 * *
  78209. ** Synopsis: key=r[P2@P3]
  78210. **
  78211. ** The content of P3 registers starting at register P2 form
  78212. ** an unpacked index key. This opcode removes that entry from the
  78213. ** index opened by cursor P1.
  78214. */
  78215. case OP_IdxDelete: {
  78216. VdbeCursor *pC;
  78217. BtCursor *pCrsr;
  78218. int res;
  78219. UnpackedRecord r;
  78220. assert( pOp->p3>0 );
  78221. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  78222. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78223. pC = p->apCsr[pOp->p1];
  78224. assert( pC!=0 );
  78225. assert( pC->eCurType==CURTYPE_BTREE );
  78226. pCrsr = pC->uc.pCursor;
  78227. assert( pCrsr!=0 );
  78228. assert( pOp->p5==0 );
  78229. r.pKeyInfo = pC->pKeyInfo;
  78230. r.nField = (u16)pOp->p3;
  78231. r.default_rc = 0;
  78232. r.aMem = &aMem[pOp->p2];
  78233. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  78234. if( rc ) goto abort_due_to_error;
  78235. if( res==0 ){
  78236. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  78237. if( rc ) goto abort_due_to_error;
  78238. }
  78239. assert( pC->deferredMoveto==0 );
  78240. pC->cacheStatus = CACHE_STALE;
  78241. pC->seekResult = 0;
  78242. break;
  78243. }
  78244. /* Opcode: Seek P1 * P3 P4 *
  78245. ** Synopsis: Move P3 to P1.rowid
  78246. **
  78247. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  78248. ** table. This opcode does a deferred seek of the P3 table cursor
  78249. ** to the row that corresponds to the current row of P1.
  78250. **
  78251. ** This is a deferred seek. Nothing actually happens until
  78252. ** the cursor is used to read a record. That way, if no reads
  78253. ** occur, no unnecessary I/O happens.
  78254. **
  78255. ** P4 may be an array of integers (type P4_INTARRAY) containing
  78256. ** one entry for each column in the P3 table. If array entry a(i)
  78257. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  78258. ** equivalent to performing the deferred seek and then reading column i
  78259. ** from P1. This information is stored in P3 and used to redirect
  78260. ** reads against P3 over to P1, thus possibly avoiding the need to
  78261. ** seek and read cursor P3.
  78262. */
  78263. /* Opcode: IdxRowid P1 P2 * * *
  78264. ** Synopsis: r[P2]=rowid
  78265. **
  78266. ** Write into register P2 an integer which is the last entry in the record at
  78267. ** the end of the index key pointed to by cursor P1. This integer should be
  78268. ** the rowid of the table entry to which this index entry points.
  78269. **
  78270. ** See also: Rowid, MakeRecord.
  78271. */
  78272. case OP_Seek:
  78273. case OP_IdxRowid: { /* out2 */
  78274. VdbeCursor *pC; /* The P1 index cursor */
  78275. VdbeCursor *pTabCur; /* The P2 table cursor (OP_Seek only) */
  78276. i64 rowid; /* Rowid that P1 current points to */
  78277. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78278. pC = p->apCsr[pOp->p1];
  78279. assert( pC!=0 );
  78280. assert( pC->eCurType==CURTYPE_BTREE );
  78281. assert( pC->uc.pCursor!=0 );
  78282. assert( pC->isTable==0 );
  78283. assert( pC->deferredMoveto==0 );
  78284. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  78285. /* The IdxRowid and Seek opcodes are combined because of the commonality
  78286. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  78287. rc = sqlite3VdbeCursorRestore(pC);
  78288. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  78289. ** out from under the cursor. That will never happens for an IdxRowid
  78290. ** or Seek opcode */
  78291. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  78292. if( !pC->nullRow ){
  78293. rowid = 0; /* Not needed. Only used to silence a warning. */
  78294. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  78295. if( rc!=SQLITE_OK ){
  78296. goto abort_due_to_error;
  78297. }
  78298. if( pOp->opcode==OP_Seek ){
  78299. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  78300. pTabCur = p->apCsr[pOp->p3];
  78301. assert( pTabCur!=0 );
  78302. assert( pTabCur->eCurType==CURTYPE_BTREE );
  78303. assert( pTabCur->uc.pCursor!=0 );
  78304. assert( pTabCur->isTable );
  78305. pTabCur->nullRow = 0;
  78306. pTabCur->movetoTarget = rowid;
  78307. pTabCur->deferredMoveto = 1;
  78308. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  78309. pTabCur->aAltMap = pOp->p4.ai;
  78310. pTabCur->pAltCursor = pC;
  78311. }else{
  78312. pOut = out2Prerelease(p, pOp);
  78313. pOut->u.i = rowid;
  78314. }
  78315. }else{
  78316. assert( pOp->opcode==OP_IdxRowid );
  78317. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  78318. }
  78319. break;
  78320. }
  78321. /* Opcode: IdxGE P1 P2 P3 P4 P5
  78322. ** Synopsis: key=r[P3@P4]
  78323. **
  78324. ** The P4 register values beginning with P3 form an unpacked index
  78325. ** key that omits the PRIMARY KEY. Compare this key value against the index
  78326. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  78327. ** fields at the end.
  78328. **
  78329. ** If the P1 index entry is greater than or equal to the key value
  78330. ** then jump to P2. Otherwise fall through to the next instruction.
  78331. */
  78332. /* Opcode: IdxGT P1 P2 P3 P4 P5
  78333. ** Synopsis: key=r[P3@P4]
  78334. **
  78335. ** The P4 register values beginning with P3 form an unpacked index
  78336. ** key that omits the PRIMARY KEY. Compare this key value against the index
  78337. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  78338. ** fields at the end.
  78339. **
  78340. ** If the P1 index entry is greater than the key value
  78341. ** then jump to P2. Otherwise fall through to the next instruction.
  78342. */
  78343. /* Opcode: IdxLT P1 P2 P3 P4 P5
  78344. ** Synopsis: key=r[P3@P4]
  78345. **
  78346. ** The P4 register values beginning with P3 form an unpacked index
  78347. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  78348. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  78349. ** ROWID on the P1 index.
  78350. **
  78351. ** If the P1 index entry is less than the key value then jump to P2.
  78352. ** Otherwise fall through to the next instruction.
  78353. */
  78354. /* Opcode: IdxLE P1 P2 P3 P4 P5
  78355. ** Synopsis: key=r[P3@P4]
  78356. **
  78357. ** The P4 register values beginning with P3 form an unpacked index
  78358. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  78359. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  78360. ** ROWID on the P1 index.
  78361. **
  78362. ** If the P1 index entry is less than or equal to the key value then jump
  78363. ** to P2. Otherwise fall through to the next instruction.
  78364. */
  78365. case OP_IdxLE: /* jump */
  78366. case OP_IdxGT: /* jump */
  78367. case OP_IdxLT: /* jump */
  78368. case OP_IdxGE: { /* jump */
  78369. VdbeCursor *pC;
  78370. int res;
  78371. UnpackedRecord r;
  78372. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78373. pC = p->apCsr[pOp->p1];
  78374. assert( pC!=0 );
  78375. assert( pC->isOrdered );
  78376. assert( pC->eCurType==CURTYPE_BTREE );
  78377. assert( pC->uc.pCursor!=0);
  78378. assert( pC->deferredMoveto==0 );
  78379. assert( pOp->p5==0 || pOp->p5==1 );
  78380. assert( pOp->p4type==P4_INT32 );
  78381. r.pKeyInfo = pC->pKeyInfo;
  78382. r.nField = (u16)pOp->p4.i;
  78383. if( pOp->opcode<OP_IdxLT ){
  78384. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  78385. r.default_rc = -1;
  78386. }else{
  78387. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  78388. r.default_rc = 0;
  78389. }
  78390. r.aMem = &aMem[pOp->p3];
  78391. #ifdef SQLITE_DEBUG
  78392. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  78393. #endif
  78394. res = 0; /* Not needed. Only used to silence a warning. */
  78395. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  78396. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  78397. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  78398. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  78399. res = -res;
  78400. }else{
  78401. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  78402. res++;
  78403. }
  78404. VdbeBranchTaken(res>0,2);
  78405. if( rc ) goto abort_due_to_error;
  78406. if( res>0 ) goto jump_to_p2;
  78407. break;
  78408. }
  78409. /* Opcode: Destroy P1 P2 P3 * *
  78410. **
  78411. ** Delete an entire database table or index whose root page in the database
  78412. ** file is given by P1.
  78413. **
  78414. ** The table being destroyed is in the main database file if P3==0. If
  78415. ** P3==1 then the table to be clear is in the auxiliary database file
  78416. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  78417. **
  78418. ** If AUTOVACUUM is enabled then it is possible that another root page
  78419. ** might be moved into the newly deleted root page in order to keep all
  78420. ** root pages contiguous at the beginning of the database. The former
  78421. ** value of the root page that moved - its value before the move occurred -
  78422. ** is stored in register P2. If no page movement was required (because the
  78423. ** table being dropped was already the last one in the database) then a
  78424. ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
  78425. ** is stored in register P2.
  78426. **
  78427. ** This opcode throws an error if there are any active reader VMs when
  78428. ** it is invoked. This is done to avoid the difficulty associated with
  78429. ** updating existing cursors when a root page is moved in an AUTOVACUUM
  78430. ** database. This error is thrown even if the database is not an AUTOVACUUM
  78431. ** db in order to avoid introducing an incompatibility between autovacuum
  78432. ** and non-autovacuum modes.
  78433. **
  78434. ** See also: Clear
  78435. */
  78436. case OP_Destroy: { /* out2 */
  78437. int iMoved;
  78438. int iDb;
  78439. assert( p->readOnly==0 );
  78440. assert( pOp->p1>1 );
  78441. pOut = out2Prerelease(p, pOp);
  78442. pOut->flags = MEM_Null;
  78443. if( db->nVdbeRead > db->nVDestroy+1 ){
  78444. rc = SQLITE_LOCKED;
  78445. p->errorAction = OE_Abort;
  78446. goto abort_due_to_error;
  78447. }else{
  78448. iDb = pOp->p3;
  78449. assert( DbMaskTest(p->btreeMask, iDb) );
  78450. iMoved = 0; /* Not needed. Only to silence a warning. */
  78451. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  78452. pOut->flags = MEM_Int;
  78453. pOut->u.i = iMoved;
  78454. if( rc ) goto abort_due_to_error;
  78455. #ifndef SQLITE_OMIT_AUTOVACUUM
  78456. if( iMoved!=0 ){
  78457. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  78458. /* All OP_Destroy operations occur on the same btree */
  78459. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  78460. resetSchemaOnFault = iDb+1;
  78461. }
  78462. #endif
  78463. }
  78464. break;
  78465. }
  78466. /* Opcode: Clear P1 P2 P3
  78467. **
  78468. ** Delete all contents of the database table or index whose root page
  78469. ** in the database file is given by P1. But, unlike Destroy, do not
  78470. ** remove the table or index from the database file.
  78471. **
  78472. ** The table being clear is in the main database file if P2==0. If
  78473. ** P2==1 then the table to be clear is in the auxiliary database file
  78474. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  78475. **
  78476. ** If the P3 value is non-zero, then the table referred to must be an
  78477. ** intkey table (an SQL table, not an index). In this case the row change
  78478. ** count is incremented by the number of rows in the table being cleared.
  78479. ** If P3 is greater than zero, then the value stored in register P3 is
  78480. ** also incremented by the number of rows in the table being cleared.
  78481. **
  78482. ** See also: Destroy
  78483. */
  78484. case OP_Clear: {
  78485. int nChange;
  78486. nChange = 0;
  78487. assert( p->readOnly==0 );
  78488. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  78489. rc = sqlite3BtreeClearTable(
  78490. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  78491. );
  78492. if( pOp->p3 ){
  78493. p->nChange += nChange;
  78494. if( pOp->p3>0 ){
  78495. assert( memIsValid(&aMem[pOp->p3]) );
  78496. memAboutToChange(p, &aMem[pOp->p3]);
  78497. aMem[pOp->p3].u.i += nChange;
  78498. }
  78499. }
  78500. if( rc ) goto abort_due_to_error;
  78501. break;
  78502. }
  78503. /* Opcode: ResetSorter P1 * * * *
  78504. **
  78505. ** Delete all contents from the ephemeral table or sorter
  78506. ** that is open on cursor P1.
  78507. **
  78508. ** This opcode only works for cursors used for sorting and
  78509. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  78510. */
  78511. case OP_ResetSorter: {
  78512. VdbeCursor *pC;
  78513. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78514. pC = p->apCsr[pOp->p1];
  78515. assert( pC!=0 );
  78516. if( isSorter(pC) ){
  78517. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  78518. }else{
  78519. assert( pC->eCurType==CURTYPE_BTREE );
  78520. assert( pC->isEphemeral );
  78521. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  78522. if( rc ) goto abort_due_to_error;
  78523. }
  78524. break;
  78525. }
  78526. /* Opcode: CreateTable P1 P2 * * *
  78527. ** Synopsis: r[P2]=root iDb=P1
  78528. **
  78529. ** Allocate a new table in the main database file if P1==0 or in the
  78530. ** auxiliary database file if P1==1 or in an attached database if
  78531. ** P1>1. Write the root page number of the new table into
  78532. ** register P2
  78533. **
  78534. ** The difference between a table and an index is this: A table must
  78535. ** have a 4-byte integer key and can have arbitrary data. An index
  78536. ** has an arbitrary key but no data.
  78537. **
  78538. ** See also: CreateIndex
  78539. */
  78540. /* Opcode: CreateIndex P1 P2 * * *
  78541. ** Synopsis: r[P2]=root iDb=P1
  78542. **
  78543. ** Allocate a new index in the main database file if P1==0 or in the
  78544. ** auxiliary database file if P1==1 or in an attached database if
  78545. ** P1>1. Write the root page number of the new table into
  78546. ** register P2.
  78547. **
  78548. ** See documentation on OP_CreateTable for additional information.
  78549. */
  78550. case OP_CreateIndex: /* out2 */
  78551. case OP_CreateTable: { /* out2 */
  78552. int pgno;
  78553. int flags;
  78554. Db *pDb;
  78555. pOut = out2Prerelease(p, pOp);
  78556. pgno = 0;
  78557. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  78558. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  78559. assert( p->readOnly==0 );
  78560. pDb = &db->aDb[pOp->p1];
  78561. assert( pDb->pBt!=0 );
  78562. if( pOp->opcode==OP_CreateTable ){
  78563. /* flags = BTREE_INTKEY; */
  78564. flags = BTREE_INTKEY;
  78565. }else{
  78566. flags = BTREE_BLOBKEY;
  78567. }
  78568. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  78569. if( rc ) goto abort_due_to_error;
  78570. pOut->u.i = pgno;
  78571. break;
  78572. }
  78573. /* Opcode: SqlExec * * * P4 *
  78574. **
  78575. ** Run the SQL statement or statements specified in the P4 string.
  78576. */
  78577. case OP_SqlExec: {
  78578. db->nSqlExec++;
  78579. rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
  78580. db->nSqlExec--;
  78581. if( rc ) goto abort_due_to_error;
  78582. break;
  78583. }
  78584. /* Opcode: ParseSchema P1 * * P4 *
  78585. **
  78586. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  78587. ** that match the WHERE clause P4.
  78588. **
  78589. ** This opcode invokes the parser to create a new virtual machine,
  78590. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  78591. */
  78592. case OP_ParseSchema: {
  78593. int iDb;
  78594. const char *zMaster;
  78595. char *zSql;
  78596. InitData initData;
  78597. /* Any prepared statement that invokes this opcode will hold mutexes
  78598. ** on every btree. This is a prerequisite for invoking
  78599. ** sqlite3InitCallback().
  78600. */
  78601. #ifdef SQLITE_DEBUG
  78602. for(iDb=0; iDb<db->nDb; iDb++){
  78603. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  78604. }
  78605. #endif
  78606. iDb = pOp->p1;
  78607. assert( iDb>=0 && iDb<db->nDb );
  78608. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  78609. /* Used to be a conditional */ {
  78610. zMaster = MASTER_NAME;
  78611. initData.db = db;
  78612. initData.iDb = pOp->p1;
  78613. initData.pzErrMsg = &p->zErrMsg;
  78614. zSql = sqlite3MPrintf(db,
  78615. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  78616. db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  78617. if( zSql==0 ){
  78618. rc = SQLITE_NOMEM_BKPT;
  78619. }else{
  78620. assert( db->init.busy==0 );
  78621. db->init.busy = 1;
  78622. initData.rc = SQLITE_OK;
  78623. assert( !db->mallocFailed );
  78624. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  78625. if( rc==SQLITE_OK ) rc = initData.rc;
  78626. sqlite3DbFreeNN(db, zSql);
  78627. db->init.busy = 0;
  78628. }
  78629. }
  78630. if( rc ){
  78631. sqlite3ResetAllSchemasOfConnection(db);
  78632. if( rc==SQLITE_NOMEM ){
  78633. goto no_mem;
  78634. }
  78635. goto abort_due_to_error;
  78636. }
  78637. break;
  78638. }
  78639. #if !defined(SQLITE_OMIT_ANALYZE)
  78640. /* Opcode: LoadAnalysis P1 * * * *
  78641. **
  78642. ** Read the sqlite_stat1 table for database P1 and load the content
  78643. ** of that table into the internal index hash table. This will cause
  78644. ** the analysis to be used when preparing all subsequent queries.
  78645. */
  78646. case OP_LoadAnalysis: {
  78647. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  78648. rc = sqlite3AnalysisLoad(db, pOp->p1);
  78649. if( rc ) goto abort_due_to_error;
  78650. break;
  78651. }
  78652. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  78653. /* Opcode: DropTable P1 * * P4 *
  78654. **
  78655. ** Remove the internal (in-memory) data structures that describe
  78656. ** the table named P4 in database P1. This is called after a table
  78657. ** is dropped from disk (using the Destroy opcode) in order to keep
  78658. ** the internal representation of the
  78659. ** schema consistent with what is on disk.
  78660. */
  78661. case OP_DropTable: {
  78662. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  78663. break;
  78664. }
  78665. /* Opcode: DropIndex P1 * * P4 *
  78666. **
  78667. ** Remove the internal (in-memory) data structures that describe
  78668. ** the index named P4 in database P1. This is called after an index
  78669. ** is dropped from disk (using the Destroy opcode)
  78670. ** in order to keep the internal representation of the
  78671. ** schema consistent with what is on disk.
  78672. */
  78673. case OP_DropIndex: {
  78674. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  78675. break;
  78676. }
  78677. /* Opcode: DropTrigger P1 * * P4 *
  78678. **
  78679. ** Remove the internal (in-memory) data structures that describe
  78680. ** the trigger named P4 in database P1. This is called after a trigger
  78681. ** is dropped from disk (using the Destroy opcode) in order to keep
  78682. ** the internal representation of the
  78683. ** schema consistent with what is on disk.
  78684. */
  78685. case OP_DropTrigger: {
  78686. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  78687. break;
  78688. }
  78689. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  78690. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  78691. **
  78692. ** Do an analysis of the currently open database. Store in
  78693. ** register P1 the text of an error message describing any problems.
  78694. ** If no problems are found, store a NULL in register P1.
  78695. **
  78696. ** The register P3 contains one less than the maximum number of allowed errors.
  78697. ** At most reg(P3) errors will be reported.
  78698. ** In other words, the analysis stops as soon as reg(P1) errors are
  78699. ** seen. Reg(P1) is updated with the number of errors remaining.
  78700. **
  78701. ** The root page numbers of all tables in the database are integers
  78702. ** stored in P4_INTARRAY argument.
  78703. **
  78704. ** If P5 is not zero, the check is done on the auxiliary database
  78705. ** file, not the main database file.
  78706. **
  78707. ** This opcode is used to implement the integrity_check pragma.
  78708. */
  78709. case OP_IntegrityCk: {
  78710. int nRoot; /* Number of tables to check. (Number of root pages.) */
  78711. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  78712. int nErr; /* Number of errors reported */
  78713. char *z; /* Text of the error report */
  78714. Mem *pnErr; /* Register keeping track of errors remaining */
  78715. assert( p->bIsReader );
  78716. nRoot = pOp->p2;
  78717. aRoot = pOp->p4.ai;
  78718. assert( nRoot>0 );
  78719. assert( aRoot[nRoot]==0 );
  78720. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  78721. pnErr = &aMem[pOp->p3];
  78722. assert( (pnErr->flags & MEM_Int)!=0 );
  78723. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  78724. pIn1 = &aMem[pOp->p1];
  78725. assert( pOp->p5<db->nDb );
  78726. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  78727. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  78728. (int)pnErr->u.i+1, &nErr);
  78729. sqlite3VdbeMemSetNull(pIn1);
  78730. if( nErr==0 ){
  78731. assert( z==0 );
  78732. }else if( z==0 ){
  78733. goto no_mem;
  78734. }else{
  78735. pnErr->u.i -= nErr-1;
  78736. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  78737. }
  78738. UPDATE_MAX_BLOBSIZE(pIn1);
  78739. sqlite3VdbeChangeEncoding(pIn1, encoding);
  78740. break;
  78741. }
  78742. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  78743. /* Opcode: RowSetAdd P1 P2 * * *
  78744. ** Synopsis: rowset(P1)=r[P2]
  78745. **
  78746. ** Insert the integer value held by register P2 into a RowSet object
  78747. ** held in register P1.
  78748. **
  78749. ** An assertion fails if P2 is not an integer.
  78750. */
  78751. case OP_RowSetAdd: { /* in1, in2 */
  78752. pIn1 = &aMem[pOp->p1];
  78753. pIn2 = &aMem[pOp->p2];
  78754. assert( (pIn2->flags & MEM_Int)!=0 );
  78755. if( (pIn1->flags & MEM_RowSet)==0 ){
  78756. sqlite3VdbeMemSetRowSet(pIn1);
  78757. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  78758. }
  78759. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  78760. break;
  78761. }
  78762. /* Opcode: RowSetRead P1 P2 P3 * *
  78763. ** Synopsis: r[P3]=rowset(P1)
  78764. **
  78765. ** Extract the smallest value from the RowSet object in P1
  78766. ** and put that value into register P3.
  78767. ** Or, if RowSet object P1 is initially empty, leave P3
  78768. ** unchanged and jump to instruction P2.
  78769. */
  78770. case OP_RowSetRead: { /* jump, in1, out3 */
  78771. i64 val;
  78772. pIn1 = &aMem[pOp->p1];
  78773. if( (pIn1->flags & MEM_RowSet)==0
  78774. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  78775. ){
  78776. /* The boolean index is empty */
  78777. sqlite3VdbeMemSetNull(pIn1);
  78778. VdbeBranchTaken(1,2);
  78779. goto jump_to_p2_and_check_for_interrupt;
  78780. }else{
  78781. /* A value was pulled from the index */
  78782. VdbeBranchTaken(0,2);
  78783. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  78784. }
  78785. goto check_for_interrupt;
  78786. }
  78787. /* Opcode: RowSetTest P1 P2 P3 P4
  78788. ** Synopsis: if r[P3] in rowset(P1) goto P2
  78789. **
  78790. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  78791. ** contains a RowSet object and that RowSet object contains
  78792. ** the value held in P3, jump to register P2. Otherwise, insert the
  78793. ** integer in P3 into the RowSet and continue on to the
  78794. ** next opcode.
  78795. **
  78796. ** The RowSet object is optimized for the case where sets of integers
  78797. ** are inserted in distinct phases, which each set contains no duplicates.
  78798. ** Each set is identified by a unique P4 value. The first set
  78799. ** must have P4==0, the final set must have P4==-1, and for all other sets
  78800. ** must have P4>0.
  78801. **
  78802. ** This allows optimizations: (a) when P4==0 there is no need to test
  78803. ** the RowSet object for P3, as it is guaranteed not to contain it,
  78804. ** (b) when P4==-1 there is no need to insert the value, as it will
  78805. ** never be tested for, and (c) when a value that is part of set X is
  78806. ** inserted, there is no need to search to see if the same value was
  78807. ** previously inserted as part of set X (only if it was previously
  78808. ** inserted as part of some other set).
  78809. */
  78810. case OP_RowSetTest: { /* jump, in1, in3 */
  78811. int iSet;
  78812. int exists;
  78813. pIn1 = &aMem[pOp->p1];
  78814. pIn3 = &aMem[pOp->p3];
  78815. iSet = pOp->p4.i;
  78816. assert( pIn3->flags&MEM_Int );
  78817. /* If there is anything other than a rowset object in memory cell P1,
  78818. ** delete it now and initialize P1 with an empty rowset
  78819. */
  78820. if( (pIn1->flags & MEM_RowSet)==0 ){
  78821. sqlite3VdbeMemSetRowSet(pIn1);
  78822. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  78823. }
  78824. assert( pOp->p4type==P4_INT32 );
  78825. assert( iSet==-1 || iSet>=0 );
  78826. if( iSet ){
  78827. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  78828. VdbeBranchTaken(exists!=0,2);
  78829. if( exists ) goto jump_to_p2;
  78830. }
  78831. if( iSet>=0 ){
  78832. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  78833. }
  78834. break;
  78835. }
  78836. #ifndef SQLITE_OMIT_TRIGGER
  78837. /* Opcode: Program P1 P2 P3 P4 P5
  78838. **
  78839. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  78840. **
  78841. ** P1 contains the address of the memory cell that contains the first memory
  78842. ** cell in an array of values used as arguments to the sub-program. P2
  78843. ** contains the address to jump to if the sub-program throws an IGNORE
  78844. ** exception using the RAISE() function. Register P3 contains the address
  78845. ** of a memory cell in this (the parent) VM that is used to allocate the
  78846. ** memory required by the sub-vdbe at runtime.
  78847. **
  78848. ** P4 is a pointer to the VM containing the trigger program.
  78849. **
  78850. ** If P5 is non-zero, then recursive program invocation is enabled.
  78851. */
  78852. case OP_Program: { /* jump */
  78853. int nMem; /* Number of memory registers for sub-program */
  78854. int nByte; /* Bytes of runtime space required for sub-program */
  78855. Mem *pRt; /* Register to allocate runtime space */
  78856. Mem *pMem; /* Used to iterate through memory cells */
  78857. Mem *pEnd; /* Last memory cell in new array */
  78858. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  78859. SubProgram *pProgram; /* Sub-program to execute */
  78860. void *t; /* Token identifying trigger */
  78861. pProgram = pOp->p4.pProgram;
  78862. pRt = &aMem[pOp->p3];
  78863. assert( pProgram->nOp>0 );
  78864. /* If the p5 flag is clear, then recursive invocation of triggers is
  78865. ** disabled for backwards compatibility (p5 is set if this sub-program
  78866. ** is really a trigger, not a foreign key action, and the flag set
  78867. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  78868. **
  78869. ** It is recursive invocation of triggers, at the SQL level, that is
  78870. ** disabled. In some cases a single trigger may generate more than one
  78871. ** SubProgram (if the trigger may be executed with more than one different
  78872. ** ON CONFLICT algorithm). SubProgram structures associated with a
  78873. ** single trigger all have the same value for the SubProgram.token
  78874. ** variable. */
  78875. if( pOp->p5 ){
  78876. t = pProgram->token;
  78877. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  78878. if( pFrame ) break;
  78879. }
  78880. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  78881. rc = SQLITE_ERROR;
  78882. sqlite3VdbeError(p, "too many levels of trigger recursion");
  78883. goto abort_due_to_error;
  78884. }
  78885. /* Register pRt is used to store the memory required to save the state
  78886. ** of the current program, and the memory required at runtime to execute
  78887. ** the trigger program. If this trigger has been fired before, then pRt
  78888. ** is already allocated. Otherwise, it must be initialized. */
  78889. if( (pRt->flags&MEM_Frame)==0 ){
  78890. /* SubProgram.nMem is set to the number of memory cells used by the
  78891. ** program stored in SubProgram.aOp. As well as these, one memory
  78892. ** cell is required for each cursor used by the program. Set local
  78893. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  78894. */
  78895. nMem = pProgram->nMem + pProgram->nCsr;
  78896. assert( nMem>0 );
  78897. if( pProgram->nCsr==0 ) nMem++;
  78898. nByte = ROUND8(sizeof(VdbeFrame))
  78899. + nMem * sizeof(Mem)
  78900. + pProgram->nCsr * sizeof(VdbeCursor*)
  78901. + (pProgram->nOp + 7)/8;
  78902. pFrame = sqlite3DbMallocZero(db, nByte);
  78903. if( !pFrame ){
  78904. goto no_mem;
  78905. }
  78906. sqlite3VdbeMemRelease(pRt);
  78907. pRt->flags = MEM_Frame;
  78908. pRt->u.pFrame = pFrame;
  78909. pFrame->v = p;
  78910. pFrame->nChildMem = nMem;
  78911. pFrame->nChildCsr = pProgram->nCsr;
  78912. pFrame->pc = (int)(pOp - aOp);
  78913. pFrame->aMem = p->aMem;
  78914. pFrame->nMem = p->nMem;
  78915. pFrame->apCsr = p->apCsr;
  78916. pFrame->nCursor = p->nCursor;
  78917. pFrame->aOp = p->aOp;
  78918. pFrame->nOp = p->nOp;
  78919. pFrame->token = pProgram->token;
  78920. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  78921. pFrame->anExec = p->anExec;
  78922. #endif
  78923. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  78924. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  78925. pMem->flags = MEM_Undefined;
  78926. pMem->db = db;
  78927. }
  78928. }else{
  78929. pFrame = pRt->u.pFrame;
  78930. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  78931. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  78932. assert( pProgram->nCsr==pFrame->nChildCsr );
  78933. assert( (int)(pOp - aOp)==pFrame->pc );
  78934. }
  78935. p->nFrame++;
  78936. pFrame->pParent = p->pFrame;
  78937. pFrame->lastRowid = db->lastRowid;
  78938. pFrame->nChange = p->nChange;
  78939. pFrame->nDbChange = p->db->nChange;
  78940. assert( pFrame->pAuxData==0 );
  78941. pFrame->pAuxData = p->pAuxData;
  78942. p->pAuxData = 0;
  78943. p->nChange = 0;
  78944. p->pFrame = pFrame;
  78945. p->aMem = aMem = VdbeFrameMem(pFrame);
  78946. p->nMem = pFrame->nChildMem;
  78947. p->nCursor = (u16)pFrame->nChildCsr;
  78948. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  78949. pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
  78950. memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
  78951. p->aOp = aOp = pProgram->aOp;
  78952. p->nOp = pProgram->nOp;
  78953. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  78954. p->anExec = 0;
  78955. #endif
  78956. pOp = &aOp[-1];
  78957. break;
  78958. }
  78959. /* Opcode: Param P1 P2 * * *
  78960. **
  78961. ** This opcode is only ever present in sub-programs called via the
  78962. ** OP_Program instruction. Copy a value currently stored in a memory
  78963. ** cell of the calling (parent) frame to cell P2 in the current frames
  78964. ** address space. This is used by trigger programs to access the new.*
  78965. ** and old.* values.
  78966. **
  78967. ** The address of the cell in the parent frame is determined by adding
  78968. ** the value of the P1 argument to the value of the P1 argument to the
  78969. ** calling OP_Program instruction.
  78970. */
  78971. case OP_Param: { /* out2 */
  78972. VdbeFrame *pFrame;
  78973. Mem *pIn;
  78974. pOut = out2Prerelease(p, pOp);
  78975. pFrame = p->pFrame;
  78976. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  78977. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  78978. break;
  78979. }
  78980. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  78981. #ifndef SQLITE_OMIT_FOREIGN_KEY
  78982. /* Opcode: FkCounter P1 P2 * * *
  78983. ** Synopsis: fkctr[P1]+=P2
  78984. **
  78985. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  78986. ** If P1 is non-zero, the database constraint counter is incremented
  78987. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  78988. ** statement counter is incremented (immediate foreign key constraints).
  78989. */
  78990. case OP_FkCounter: {
  78991. if( db->flags & SQLITE_DeferFKs ){
  78992. db->nDeferredImmCons += pOp->p2;
  78993. }else if( pOp->p1 ){
  78994. db->nDeferredCons += pOp->p2;
  78995. }else{
  78996. p->nFkConstraint += pOp->p2;
  78997. }
  78998. break;
  78999. }
  79000. /* Opcode: FkIfZero P1 P2 * * *
  79001. ** Synopsis: if fkctr[P1]==0 goto P2
  79002. **
  79003. ** This opcode tests if a foreign key constraint-counter is currently zero.
  79004. ** If so, jump to instruction P2. Otherwise, fall through to the next
  79005. ** instruction.
  79006. **
  79007. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  79008. ** is zero (the one that counts deferred constraint violations). If P1 is
  79009. ** zero, the jump is taken if the statement constraint-counter is zero
  79010. ** (immediate foreign key constraint violations).
  79011. */
  79012. case OP_FkIfZero: { /* jump */
  79013. if( pOp->p1 ){
  79014. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  79015. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  79016. }else{
  79017. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  79018. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  79019. }
  79020. break;
  79021. }
  79022. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  79023. #ifndef SQLITE_OMIT_AUTOINCREMENT
  79024. /* Opcode: MemMax P1 P2 * * *
  79025. ** Synopsis: r[P1]=max(r[P1],r[P2])
  79026. **
  79027. ** P1 is a register in the root frame of this VM (the root frame is
  79028. ** different from the current frame if this instruction is being executed
  79029. ** within a sub-program). Set the value of register P1 to the maximum of
  79030. ** its current value and the value in register P2.
  79031. **
  79032. ** This instruction throws an error if the memory cell is not initially
  79033. ** an integer.
  79034. */
  79035. case OP_MemMax: { /* in2 */
  79036. VdbeFrame *pFrame;
  79037. if( p->pFrame ){
  79038. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  79039. pIn1 = &pFrame->aMem[pOp->p1];
  79040. }else{
  79041. pIn1 = &aMem[pOp->p1];
  79042. }
  79043. assert( memIsValid(pIn1) );
  79044. sqlite3VdbeMemIntegerify(pIn1);
  79045. pIn2 = &aMem[pOp->p2];
  79046. sqlite3VdbeMemIntegerify(pIn2);
  79047. if( pIn1->u.i<pIn2->u.i){
  79048. pIn1->u.i = pIn2->u.i;
  79049. }
  79050. break;
  79051. }
  79052. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  79053. /* Opcode: IfPos P1 P2 P3 * *
  79054. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  79055. **
  79056. ** Register P1 must contain an integer.
  79057. ** If the value of register P1 is 1 or greater, subtract P3 from the
  79058. ** value in P1 and jump to P2.
  79059. **
  79060. ** If the initial value of register P1 is less than 1, then the
  79061. ** value is unchanged and control passes through to the next instruction.
  79062. */
  79063. case OP_IfPos: { /* jump, in1 */
  79064. pIn1 = &aMem[pOp->p1];
  79065. assert( pIn1->flags&MEM_Int );
  79066. VdbeBranchTaken( pIn1->u.i>0, 2);
  79067. if( pIn1->u.i>0 ){
  79068. pIn1->u.i -= pOp->p3;
  79069. goto jump_to_p2;
  79070. }
  79071. break;
  79072. }
  79073. /* Opcode: OffsetLimit P1 P2 P3 * *
  79074. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  79075. **
  79076. ** This opcode performs a commonly used computation associated with
  79077. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  79078. ** holds the offset counter. The opcode computes the combined value
  79079. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  79080. ** value computed is the total number of rows that will need to be
  79081. ** visited in order to complete the query.
  79082. **
  79083. ** If r[P3] is zero or negative, that means there is no OFFSET
  79084. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  79085. **
  79086. ** if r[P1] is zero or negative, that means there is no LIMIT
  79087. ** and r[P2] is set to -1.
  79088. **
  79089. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  79090. */
  79091. case OP_OffsetLimit: { /* in1, out2, in3 */
  79092. i64 x;
  79093. pIn1 = &aMem[pOp->p1];
  79094. pIn3 = &aMem[pOp->p3];
  79095. pOut = out2Prerelease(p, pOp);
  79096. assert( pIn1->flags & MEM_Int );
  79097. assert( pIn3->flags & MEM_Int );
  79098. x = pIn1->u.i;
  79099. if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
  79100. /* If the LIMIT is less than or equal to zero, loop forever. This
  79101. ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
  79102. ** also loop forever. This is undocumented. In fact, one could argue
  79103. ** that the loop should terminate. But assuming 1 billion iterations
  79104. ** per second (far exceeding the capabilities of any current hardware)
  79105. ** it would take nearly 300 years to actually reach the limit. So
  79106. ** looping forever is a reasonable approximation. */
  79107. pOut->u.i = -1;
  79108. }else{
  79109. pOut->u.i = x;
  79110. }
  79111. break;
  79112. }
  79113. /* Opcode: IfNotZero P1 P2 * * *
  79114. ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
  79115. **
  79116. ** Register P1 must contain an integer. If the content of register P1 is
  79117. ** initially greater than zero, then decrement the value in register P1.
  79118. ** If it is non-zero (negative or positive) and then also jump to P2.
  79119. ** If register P1 is initially zero, leave it unchanged and fall through.
  79120. */
  79121. case OP_IfNotZero: { /* jump, in1 */
  79122. pIn1 = &aMem[pOp->p1];
  79123. assert( pIn1->flags&MEM_Int );
  79124. VdbeBranchTaken(pIn1->u.i<0, 2);
  79125. if( pIn1->u.i ){
  79126. if( pIn1->u.i>0 ) pIn1->u.i--;
  79127. goto jump_to_p2;
  79128. }
  79129. break;
  79130. }
  79131. /* Opcode: DecrJumpZero P1 P2 * * *
  79132. ** Synopsis: if (--r[P1])==0 goto P2
  79133. **
  79134. ** Register P1 must hold an integer. Decrement the value in P1
  79135. ** and jump to P2 if the new value is exactly zero.
  79136. */
  79137. case OP_DecrJumpZero: { /* jump, in1 */
  79138. pIn1 = &aMem[pOp->p1];
  79139. assert( pIn1->flags&MEM_Int );
  79140. if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
  79141. VdbeBranchTaken(pIn1->u.i==0, 2);
  79142. if( pIn1->u.i==0 ) goto jump_to_p2;
  79143. break;
  79144. }
  79145. /* Opcode: AggStep0 * P2 P3 P4 P5
  79146. ** Synopsis: accum=r[P3] step(r[P2@P5])
  79147. **
  79148. ** Execute the step function for an aggregate. The
  79149. ** function has P5 arguments. P4 is a pointer to the FuncDef
  79150. ** structure that specifies the function. Register P3 is the
  79151. ** accumulator.
  79152. **
  79153. ** The P5 arguments are taken from register P2 and its
  79154. ** successors.
  79155. */
  79156. /* Opcode: AggStep * P2 P3 P4 P5
  79157. ** Synopsis: accum=r[P3] step(r[P2@P5])
  79158. **
  79159. ** Execute the step function for an aggregate. The
  79160. ** function has P5 arguments. P4 is a pointer to an sqlite3_context
  79161. ** object that is used to run the function. Register P3 is
  79162. ** as the accumulator.
  79163. **
  79164. ** The P5 arguments are taken from register P2 and its
  79165. ** successors.
  79166. **
  79167. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  79168. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  79169. ** the opcode is changed. In this way, the initialization of the
  79170. ** sqlite3_context only happens once, instead of on each call to the
  79171. ** step function.
  79172. */
  79173. case OP_AggStep0: {
  79174. int n;
  79175. sqlite3_context *pCtx;
  79176. assert( pOp->p4type==P4_FUNCDEF );
  79177. n = pOp->p5;
  79178. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  79179. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  79180. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  79181. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  79182. if( pCtx==0 ) goto no_mem;
  79183. pCtx->pMem = 0;
  79184. pCtx->pFunc = pOp->p4.pFunc;
  79185. pCtx->iOp = (int)(pOp - aOp);
  79186. pCtx->pVdbe = p;
  79187. pCtx->argc = n;
  79188. pOp->p4type = P4_FUNCCTX;
  79189. pOp->p4.pCtx = pCtx;
  79190. pOp->opcode = OP_AggStep;
  79191. /* Fall through into OP_AggStep */
  79192. }
  79193. case OP_AggStep: {
  79194. int i;
  79195. sqlite3_context *pCtx;
  79196. Mem *pMem;
  79197. Mem t;
  79198. assert( pOp->p4type==P4_FUNCCTX );
  79199. pCtx = pOp->p4.pCtx;
  79200. pMem = &aMem[pOp->p3];
  79201. /* If this function is inside of a trigger, the register array in aMem[]
  79202. ** might change from one evaluation to the next. The next block of code
  79203. ** checks to see if the register array has changed, and if so it
  79204. ** reinitializes the relavant parts of the sqlite3_context object */
  79205. if( pCtx->pMem != pMem ){
  79206. pCtx->pMem = pMem;
  79207. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  79208. }
  79209. #ifdef SQLITE_DEBUG
  79210. for(i=0; i<pCtx->argc; i++){
  79211. assert( memIsValid(pCtx->argv[i]) );
  79212. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  79213. }
  79214. #endif
  79215. pMem->n++;
  79216. sqlite3VdbeMemInit(&t, db, MEM_Null);
  79217. pCtx->pOut = &t;
  79218. pCtx->fErrorOrAux = 0;
  79219. pCtx->skipFlag = 0;
  79220. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  79221. if( pCtx->fErrorOrAux ){
  79222. if( pCtx->isError ){
  79223. sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
  79224. rc = pCtx->isError;
  79225. }
  79226. sqlite3VdbeMemRelease(&t);
  79227. if( rc ) goto abort_due_to_error;
  79228. }else{
  79229. assert( t.flags==MEM_Null );
  79230. }
  79231. if( pCtx->skipFlag ){
  79232. assert( pOp[-1].opcode==OP_CollSeq );
  79233. i = pOp[-1].p1;
  79234. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  79235. }
  79236. break;
  79237. }
  79238. /* Opcode: AggFinal P1 P2 * P4 *
  79239. ** Synopsis: accum=r[P1] N=P2
  79240. **
  79241. ** Execute the finalizer function for an aggregate. P1 is
  79242. ** the memory location that is the accumulator for the aggregate.
  79243. **
  79244. ** P2 is the number of arguments that the step function takes and
  79245. ** P4 is a pointer to the FuncDef for this function. The P2
  79246. ** argument is not used by this opcode. It is only there to disambiguate
  79247. ** functions that can take varying numbers of arguments. The
  79248. ** P4 argument is only needed for the degenerate case where
  79249. ** the step function was not previously called.
  79250. */
  79251. case OP_AggFinal: {
  79252. Mem *pMem;
  79253. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  79254. pMem = &aMem[pOp->p1];
  79255. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  79256. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  79257. if( rc ){
  79258. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  79259. goto abort_due_to_error;
  79260. }
  79261. sqlite3VdbeChangeEncoding(pMem, encoding);
  79262. UPDATE_MAX_BLOBSIZE(pMem);
  79263. if( sqlite3VdbeMemTooBig(pMem) ){
  79264. goto too_big;
  79265. }
  79266. break;
  79267. }
  79268. #ifndef SQLITE_OMIT_WAL
  79269. /* Opcode: Checkpoint P1 P2 P3 * *
  79270. **
  79271. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  79272. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  79273. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  79274. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  79275. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  79276. ** in the WAL that have been checkpointed after the checkpoint
  79277. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  79278. ** mem[P3+2] are initialized to -1.
  79279. */
  79280. case OP_Checkpoint: {
  79281. int i; /* Loop counter */
  79282. int aRes[3]; /* Results */
  79283. Mem *pMem; /* Write results here */
  79284. assert( p->readOnly==0 );
  79285. aRes[0] = 0;
  79286. aRes[1] = aRes[2] = -1;
  79287. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  79288. || pOp->p2==SQLITE_CHECKPOINT_FULL
  79289. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  79290. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  79291. );
  79292. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  79293. if( rc ){
  79294. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  79295. rc = SQLITE_OK;
  79296. aRes[0] = 1;
  79297. }
  79298. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  79299. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  79300. }
  79301. break;
  79302. };
  79303. #endif
  79304. #ifndef SQLITE_OMIT_PRAGMA
  79305. /* Opcode: JournalMode P1 P2 P3 * *
  79306. **
  79307. ** Change the journal mode of database P1 to P3. P3 must be one of the
  79308. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  79309. ** modes (delete, truncate, persist, off and memory), this is a simple
  79310. ** operation. No IO is required.
  79311. **
  79312. ** If changing into or out of WAL mode the procedure is more complicated.
  79313. **
  79314. ** Write a string containing the final journal-mode to register P2.
  79315. */
  79316. case OP_JournalMode: { /* out2 */
  79317. Btree *pBt; /* Btree to change journal mode of */
  79318. Pager *pPager; /* Pager associated with pBt */
  79319. int eNew; /* New journal mode */
  79320. int eOld; /* The old journal mode */
  79321. #ifndef SQLITE_OMIT_WAL
  79322. const char *zFilename; /* Name of database file for pPager */
  79323. #endif
  79324. pOut = out2Prerelease(p, pOp);
  79325. eNew = pOp->p3;
  79326. assert( eNew==PAGER_JOURNALMODE_DELETE
  79327. || eNew==PAGER_JOURNALMODE_TRUNCATE
  79328. || eNew==PAGER_JOURNALMODE_PERSIST
  79329. || eNew==PAGER_JOURNALMODE_OFF
  79330. || eNew==PAGER_JOURNALMODE_MEMORY
  79331. || eNew==PAGER_JOURNALMODE_WAL
  79332. || eNew==PAGER_JOURNALMODE_QUERY
  79333. );
  79334. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79335. assert( p->readOnly==0 );
  79336. pBt = db->aDb[pOp->p1].pBt;
  79337. pPager = sqlite3BtreePager(pBt);
  79338. eOld = sqlite3PagerGetJournalMode(pPager);
  79339. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  79340. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  79341. #ifndef SQLITE_OMIT_WAL
  79342. zFilename = sqlite3PagerFilename(pPager, 1);
  79343. /* Do not allow a transition to journal_mode=WAL for a database
  79344. ** in temporary storage or if the VFS does not support shared memory
  79345. */
  79346. if( eNew==PAGER_JOURNALMODE_WAL
  79347. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  79348. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  79349. ){
  79350. eNew = eOld;
  79351. }
  79352. if( (eNew!=eOld)
  79353. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  79354. ){
  79355. if( !db->autoCommit || db->nVdbeRead>1 ){
  79356. rc = SQLITE_ERROR;
  79357. sqlite3VdbeError(p,
  79358. "cannot change %s wal mode from within a transaction",
  79359. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  79360. );
  79361. goto abort_due_to_error;
  79362. }else{
  79363. if( eOld==PAGER_JOURNALMODE_WAL ){
  79364. /* If leaving WAL mode, close the log file. If successful, the call
  79365. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  79366. ** file. An EXCLUSIVE lock may still be held on the database file
  79367. ** after a successful return.
  79368. */
  79369. rc = sqlite3PagerCloseWal(pPager, db);
  79370. if( rc==SQLITE_OK ){
  79371. sqlite3PagerSetJournalMode(pPager, eNew);
  79372. }
  79373. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  79374. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  79375. ** as an intermediate */
  79376. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  79377. }
  79378. /* Open a transaction on the database file. Regardless of the journal
  79379. ** mode, this transaction always uses a rollback journal.
  79380. */
  79381. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  79382. if( rc==SQLITE_OK ){
  79383. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  79384. }
  79385. }
  79386. }
  79387. #endif /* ifndef SQLITE_OMIT_WAL */
  79388. if( rc ) eNew = eOld;
  79389. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  79390. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  79391. pOut->z = (char *)sqlite3JournalModename(eNew);
  79392. pOut->n = sqlite3Strlen30(pOut->z);
  79393. pOut->enc = SQLITE_UTF8;
  79394. sqlite3VdbeChangeEncoding(pOut, encoding);
  79395. if( rc ) goto abort_due_to_error;
  79396. break;
  79397. };
  79398. #endif /* SQLITE_OMIT_PRAGMA */
  79399. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  79400. /* Opcode: Vacuum P1 * * * *
  79401. **
  79402. ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
  79403. ** for an attached database. The "temp" database may not be vacuumed.
  79404. */
  79405. case OP_Vacuum: {
  79406. assert( p->readOnly==0 );
  79407. rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
  79408. if( rc ) goto abort_due_to_error;
  79409. break;
  79410. }
  79411. #endif
  79412. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  79413. /* Opcode: IncrVacuum P1 P2 * * *
  79414. **
  79415. ** Perform a single step of the incremental vacuum procedure on
  79416. ** the P1 database. If the vacuum has finished, jump to instruction
  79417. ** P2. Otherwise, fall through to the next instruction.
  79418. */
  79419. case OP_IncrVacuum: { /* jump */
  79420. Btree *pBt;
  79421. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79422. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  79423. assert( p->readOnly==0 );
  79424. pBt = db->aDb[pOp->p1].pBt;
  79425. rc = sqlite3BtreeIncrVacuum(pBt);
  79426. VdbeBranchTaken(rc==SQLITE_DONE,2);
  79427. if( rc ){
  79428. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  79429. rc = SQLITE_OK;
  79430. goto jump_to_p2;
  79431. }
  79432. break;
  79433. }
  79434. #endif
  79435. /* Opcode: Expire P1 * * * *
  79436. **
  79437. ** Cause precompiled statements to expire. When an expired statement
  79438. ** is executed using sqlite3_step() it will either automatically
  79439. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  79440. ** or it will fail with SQLITE_SCHEMA.
  79441. **
  79442. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  79443. ** then only the currently executing statement is expired.
  79444. */
  79445. case OP_Expire: {
  79446. if( !pOp->p1 ){
  79447. sqlite3ExpirePreparedStatements(db);
  79448. }else{
  79449. p->expired = 1;
  79450. }
  79451. break;
  79452. }
  79453. #ifndef SQLITE_OMIT_SHARED_CACHE
  79454. /* Opcode: TableLock P1 P2 P3 P4 *
  79455. ** Synopsis: iDb=P1 root=P2 write=P3
  79456. **
  79457. ** Obtain a lock on a particular table. This instruction is only used when
  79458. ** the shared-cache feature is enabled.
  79459. **
  79460. ** P1 is the index of the database in sqlite3.aDb[] of the database
  79461. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  79462. ** a write lock if P3==1.
  79463. **
  79464. ** P2 contains the root-page of the table to lock.
  79465. **
  79466. ** P4 contains a pointer to the name of the table being locked. This is only
  79467. ** used to generate an error message if the lock cannot be obtained.
  79468. */
  79469. case OP_TableLock: {
  79470. u8 isWriteLock = (u8)pOp->p3;
  79471. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  79472. int p1 = pOp->p1;
  79473. assert( p1>=0 && p1<db->nDb );
  79474. assert( DbMaskTest(p->btreeMask, p1) );
  79475. assert( isWriteLock==0 || isWriteLock==1 );
  79476. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  79477. if( rc ){
  79478. if( (rc&0xFF)==SQLITE_LOCKED ){
  79479. const char *z = pOp->p4.z;
  79480. sqlite3VdbeError(p, "database table is locked: %s", z);
  79481. }
  79482. goto abort_due_to_error;
  79483. }
  79484. }
  79485. break;
  79486. }
  79487. #endif /* SQLITE_OMIT_SHARED_CACHE */
  79488. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79489. /* Opcode: VBegin * * * P4 *
  79490. **
  79491. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  79492. ** xBegin method for that table.
  79493. **
  79494. ** Also, whether or not P4 is set, check that this is not being called from
  79495. ** within a callback to a virtual table xSync() method. If it is, the error
  79496. ** code will be set to SQLITE_LOCKED.
  79497. */
  79498. case OP_VBegin: {
  79499. VTable *pVTab;
  79500. pVTab = pOp->p4.pVtab;
  79501. rc = sqlite3VtabBegin(db, pVTab);
  79502. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  79503. if( rc ) goto abort_due_to_error;
  79504. break;
  79505. }
  79506. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79507. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79508. /* Opcode: VCreate P1 P2 * * *
  79509. **
  79510. ** P2 is a register that holds the name of a virtual table in database
  79511. ** P1. Call the xCreate method for that table.
  79512. */
  79513. case OP_VCreate: {
  79514. Mem sMem; /* For storing the record being decoded */
  79515. const char *zTab; /* Name of the virtual table */
  79516. memset(&sMem, 0, sizeof(sMem));
  79517. sMem.db = db;
  79518. /* Because P2 is always a static string, it is impossible for the
  79519. ** sqlite3VdbeMemCopy() to fail */
  79520. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  79521. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  79522. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  79523. assert( rc==SQLITE_OK );
  79524. zTab = (const char*)sqlite3_value_text(&sMem);
  79525. assert( zTab || db->mallocFailed );
  79526. if( zTab ){
  79527. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  79528. }
  79529. sqlite3VdbeMemRelease(&sMem);
  79530. if( rc ) goto abort_due_to_error;
  79531. break;
  79532. }
  79533. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79534. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79535. /* Opcode: VDestroy P1 * * P4 *
  79536. **
  79537. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  79538. ** of that table.
  79539. */
  79540. case OP_VDestroy: {
  79541. db->nVDestroy++;
  79542. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  79543. db->nVDestroy--;
  79544. if( rc ) goto abort_due_to_error;
  79545. break;
  79546. }
  79547. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79548. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79549. /* Opcode: VOpen P1 * * P4 *
  79550. **
  79551. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  79552. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  79553. ** table and stores that cursor in P1.
  79554. */
  79555. case OP_VOpen: {
  79556. VdbeCursor *pCur;
  79557. sqlite3_vtab_cursor *pVCur;
  79558. sqlite3_vtab *pVtab;
  79559. const sqlite3_module *pModule;
  79560. assert( p->bIsReader );
  79561. pCur = 0;
  79562. pVCur = 0;
  79563. pVtab = pOp->p4.pVtab->pVtab;
  79564. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  79565. rc = SQLITE_LOCKED;
  79566. goto abort_due_to_error;
  79567. }
  79568. pModule = pVtab->pModule;
  79569. rc = pModule->xOpen(pVtab, &pVCur);
  79570. sqlite3VtabImportErrmsg(p, pVtab);
  79571. if( rc ) goto abort_due_to_error;
  79572. /* Initialize sqlite3_vtab_cursor base class */
  79573. pVCur->pVtab = pVtab;
  79574. /* Initialize vdbe cursor object */
  79575. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  79576. if( pCur ){
  79577. pCur->uc.pVCur = pVCur;
  79578. pVtab->nRef++;
  79579. }else{
  79580. assert( db->mallocFailed );
  79581. pModule->xClose(pVCur);
  79582. goto no_mem;
  79583. }
  79584. break;
  79585. }
  79586. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79587. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79588. /* Opcode: VFilter P1 P2 P3 P4 *
  79589. ** Synopsis: iplan=r[P3] zplan='P4'
  79590. **
  79591. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  79592. ** the filtered result set is empty.
  79593. **
  79594. ** P4 is either NULL or a string that was generated by the xBestIndex
  79595. ** method of the module. The interpretation of the P4 string is left
  79596. ** to the module implementation.
  79597. **
  79598. ** This opcode invokes the xFilter method on the virtual table specified
  79599. ** by P1. The integer query plan parameter to xFilter is stored in register
  79600. ** P3. Register P3+1 stores the argc parameter to be passed to the
  79601. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  79602. ** additional parameters which are passed to
  79603. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  79604. **
  79605. ** A jump is made to P2 if the result set after filtering would be empty.
  79606. */
  79607. case OP_VFilter: { /* jump */
  79608. int nArg;
  79609. int iQuery;
  79610. const sqlite3_module *pModule;
  79611. Mem *pQuery;
  79612. Mem *pArgc;
  79613. sqlite3_vtab_cursor *pVCur;
  79614. sqlite3_vtab *pVtab;
  79615. VdbeCursor *pCur;
  79616. int res;
  79617. int i;
  79618. Mem **apArg;
  79619. pQuery = &aMem[pOp->p3];
  79620. pArgc = &pQuery[1];
  79621. pCur = p->apCsr[pOp->p1];
  79622. assert( memIsValid(pQuery) );
  79623. REGISTER_TRACE(pOp->p3, pQuery);
  79624. assert( pCur->eCurType==CURTYPE_VTAB );
  79625. pVCur = pCur->uc.pVCur;
  79626. pVtab = pVCur->pVtab;
  79627. pModule = pVtab->pModule;
  79628. /* Grab the index number and argc parameters */
  79629. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  79630. nArg = (int)pArgc->u.i;
  79631. iQuery = (int)pQuery->u.i;
  79632. /* Invoke the xFilter method */
  79633. res = 0;
  79634. apArg = p->apArg;
  79635. for(i = 0; i<nArg; i++){
  79636. apArg[i] = &pArgc[i+1];
  79637. }
  79638. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  79639. sqlite3VtabImportErrmsg(p, pVtab);
  79640. if( rc ) goto abort_due_to_error;
  79641. res = pModule->xEof(pVCur);
  79642. pCur->nullRow = 0;
  79643. VdbeBranchTaken(res!=0,2);
  79644. if( res ) goto jump_to_p2;
  79645. break;
  79646. }
  79647. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79648. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79649. /* Opcode: VColumn P1 P2 P3 * *
  79650. ** Synopsis: r[P3]=vcolumn(P2)
  79651. **
  79652. ** Store the value of the P2-th column of
  79653. ** the row of the virtual-table that the
  79654. ** P1 cursor is pointing to into register P3.
  79655. */
  79656. case OP_VColumn: {
  79657. sqlite3_vtab *pVtab;
  79658. const sqlite3_module *pModule;
  79659. Mem *pDest;
  79660. sqlite3_context sContext;
  79661. VdbeCursor *pCur = p->apCsr[pOp->p1];
  79662. assert( pCur->eCurType==CURTYPE_VTAB );
  79663. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  79664. pDest = &aMem[pOp->p3];
  79665. memAboutToChange(p, pDest);
  79666. if( pCur->nullRow ){
  79667. sqlite3VdbeMemSetNull(pDest);
  79668. break;
  79669. }
  79670. pVtab = pCur->uc.pVCur->pVtab;
  79671. pModule = pVtab->pModule;
  79672. assert( pModule->xColumn );
  79673. memset(&sContext, 0, sizeof(sContext));
  79674. sContext.pOut = pDest;
  79675. MemSetTypeFlag(pDest, MEM_Null);
  79676. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  79677. sqlite3VtabImportErrmsg(p, pVtab);
  79678. if( sContext.isError ){
  79679. rc = sContext.isError;
  79680. }
  79681. sqlite3VdbeChangeEncoding(pDest, encoding);
  79682. REGISTER_TRACE(pOp->p3, pDest);
  79683. UPDATE_MAX_BLOBSIZE(pDest);
  79684. if( sqlite3VdbeMemTooBig(pDest) ){
  79685. goto too_big;
  79686. }
  79687. if( rc ) goto abort_due_to_error;
  79688. break;
  79689. }
  79690. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79691. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79692. /* Opcode: VNext P1 P2 * * *
  79693. **
  79694. ** Advance virtual table P1 to the next row in its result set and
  79695. ** jump to instruction P2. Or, if the virtual table has reached
  79696. ** the end of its result set, then fall through to the next instruction.
  79697. */
  79698. case OP_VNext: { /* jump */
  79699. sqlite3_vtab *pVtab;
  79700. const sqlite3_module *pModule;
  79701. int res;
  79702. VdbeCursor *pCur;
  79703. res = 0;
  79704. pCur = p->apCsr[pOp->p1];
  79705. assert( pCur->eCurType==CURTYPE_VTAB );
  79706. if( pCur->nullRow ){
  79707. break;
  79708. }
  79709. pVtab = pCur->uc.pVCur->pVtab;
  79710. pModule = pVtab->pModule;
  79711. assert( pModule->xNext );
  79712. /* Invoke the xNext() method of the module. There is no way for the
  79713. ** underlying implementation to return an error if one occurs during
  79714. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  79715. ** data is available) and the error code returned when xColumn or
  79716. ** some other method is next invoked on the save virtual table cursor.
  79717. */
  79718. rc = pModule->xNext(pCur->uc.pVCur);
  79719. sqlite3VtabImportErrmsg(p, pVtab);
  79720. if( rc ) goto abort_due_to_error;
  79721. res = pModule->xEof(pCur->uc.pVCur);
  79722. VdbeBranchTaken(!res,2);
  79723. if( !res ){
  79724. /* If there is data, jump to P2 */
  79725. goto jump_to_p2_and_check_for_interrupt;
  79726. }
  79727. goto check_for_interrupt;
  79728. }
  79729. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79730. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79731. /* Opcode: VRename P1 * * P4 *
  79732. **
  79733. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  79734. ** This opcode invokes the corresponding xRename method. The value
  79735. ** in register P1 is passed as the zName argument to the xRename method.
  79736. */
  79737. case OP_VRename: {
  79738. sqlite3_vtab *pVtab;
  79739. Mem *pName;
  79740. pVtab = pOp->p4.pVtab->pVtab;
  79741. pName = &aMem[pOp->p1];
  79742. assert( pVtab->pModule->xRename );
  79743. assert( memIsValid(pName) );
  79744. assert( p->readOnly==0 );
  79745. REGISTER_TRACE(pOp->p1, pName);
  79746. assert( pName->flags & MEM_Str );
  79747. testcase( pName->enc==SQLITE_UTF8 );
  79748. testcase( pName->enc==SQLITE_UTF16BE );
  79749. testcase( pName->enc==SQLITE_UTF16LE );
  79750. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  79751. if( rc ) goto abort_due_to_error;
  79752. rc = pVtab->pModule->xRename(pVtab, pName->z);
  79753. sqlite3VtabImportErrmsg(p, pVtab);
  79754. p->expired = 0;
  79755. if( rc ) goto abort_due_to_error;
  79756. break;
  79757. }
  79758. #endif
  79759. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79760. /* Opcode: VUpdate P1 P2 P3 P4 P5
  79761. ** Synopsis: data=r[P3@P2]
  79762. **
  79763. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  79764. ** This opcode invokes the corresponding xUpdate method. P2 values
  79765. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  79766. ** invocation. The value in register (P3+P2-1) corresponds to the
  79767. ** p2th element of the argv array passed to xUpdate.
  79768. **
  79769. ** The xUpdate method will do a DELETE or an INSERT or both.
  79770. ** The argv[0] element (which corresponds to memory cell P3)
  79771. ** is the rowid of a row to delete. If argv[0] is NULL then no
  79772. ** deletion occurs. The argv[1] element is the rowid of the new
  79773. ** row. This can be NULL to have the virtual table select the new
  79774. ** rowid for itself. The subsequent elements in the array are
  79775. ** the values of columns in the new row.
  79776. **
  79777. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  79778. ** a row to delete.
  79779. **
  79780. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  79781. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  79782. ** is set to the value of the rowid for the row just inserted.
  79783. **
  79784. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  79785. ** apply in the case of a constraint failure on an insert or update.
  79786. */
  79787. case OP_VUpdate: {
  79788. sqlite3_vtab *pVtab;
  79789. const sqlite3_module *pModule;
  79790. int nArg;
  79791. int i;
  79792. sqlite_int64 rowid;
  79793. Mem **apArg;
  79794. Mem *pX;
  79795. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  79796. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  79797. );
  79798. assert( p->readOnly==0 );
  79799. pVtab = pOp->p4.pVtab->pVtab;
  79800. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  79801. rc = SQLITE_LOCKED;
  79802. goto abort_due_to_error;
  79803. }
  79804. pModule = pVtab->pModule;
  79805. nArg = pOp->p2;
  79806. assert( pOp->p4type==P4_VTAB );
  79807. if( ALWAYS(pModule->xUpdate) ){
  79808. u8 vtabOnConflict = db->vtabOnConflict;
  79809. apArg = p->apArg;
  79810. pX = &aMem[pOp->p3];
  79811. for(i=0; i<nArg; i++){
  79812. assert( memIsValid(pX) );
  79813. memAboutToChange(p, pX);
  79814. apArg[i] = pX;
  79815. pX++;
  79816. }
  79817. db->vtabOnConflict = pOp->p5;
  79818. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  79819. db->vtabOnConflict = vtabOnConflict;
  79820. sqlite3VtabImportErrmsg(p, pVtab);
  79821. if( rc==SQLITE_OK && pOp->p1 ){
  79822. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  79823. db->lastRowid = rowid;
  79824. }
  79825. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  79826. if( pOp->p5==OE_Ignore ){
  79827. rc = SQLITE_OK;
  79828. }else{
  79829. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  79830. }
  79831. }else{
  79832. p->nChange++;
  79833. }
  79834. if( rc ) goto abort_due_to_error;
  79835. }
  79836. break;
  79837. }
  79838. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79839. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79840. /* Opcode: Pagecount P1 P2 * * *
  79841. **
  79842. ** Write the current number of pages in database P1 to memory cell P2.
  79843. */
  79844. case OP_Pagecount: { /* out2 */
  79845. pOut = out2Prerelease(p, pOp);
  79846. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  79847. break;
  79848. }
  79849. #endif
  79850. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79851. /* Opcode: MaxPgcnt P1 P2 P3 * *
  79852. **
  79853. ** Try to set the maximum page count for database P1 to the value in P3.
  79854. ** Do not let the maximum page count fall below the current page count and
  79855. ** do not change the maximum page count value if P3==0.
  79856. **
  79857. ** Store the maximum page count after the change in register P2.
  79858. */
  79859. case OP_MaxPgcnt: { /* out2 */
  79860. unsigned int newMax;
  79861. Btree *pBt;
  79862. pOut = out2Prerelease(p, pOp);
  79863. pBt = db->aDb[pOp->p1].pBt;
  79864. newMax = 0;
  79865. if( pOp->p3 ){
  79866. newMax = sqlite3BtreeLastPage(pBt);
  79867. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  79868. }
  79869. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  79870. break;
  79871. }
  79872. #endif
  79873. /* Opcode: Init P1 P2 * P4 *
  79874. ** Synopsis: Start at P2
  79875. **
  79876. ** Programs contain a single instance of this opcode as the very first
  79877. ** opcode.
  79878. **
  79879. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  79880. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  79881. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  79882. **
  79883. ** If P2 is not zero, jump to instruction P2.
  79884. **
  79885. ** Increment the value of P1 so that OP_Once opcodes will jump the
  79886. ** first time they are evaluated for this run.
  79887. */
  79888. case OP_Init: { /* jump */
  79889. char *zTrace;
  79890. int i;
  79891. /* If the P4 argument is not NULL, then it must be an SQL comment string.
  79892. ** The "--" string is broken up to prevent false-positives with srcck1.c.
  79893. **
  79894. ** This assert() provides evidence for:
  79895. ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
  79896. ** would have been returned by the legacy sqlite3_trace() interface by
  79897. ** using the X argument when X begins with "--" and invoking
  79898. ** sqlite3_expanded_sql(P) otherwise.
  79899. */
  79900. assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
  79901. assert( pOp==p->aOp ); /* Always instruction 0 */
  79902. #ifndef SQLITE_OMIT_TRACE
  79903. if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
  79904. && !p->doingRerun
  79905. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  79906. ){
  79907. #ifndef SQLITE_OMIT_DEPRECATED
  79908. if( db->mTrace & SQLITE_TRACE_LEGACY ){
  79909. void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
  79910. char *z = sqlite3VdbeExpandSql(p, zTrace);
  79911. x(db->pTraceArg, z);
  79912. sqlite3_free(z);
  79913. }else
  79914. #endif
  79915. if( db->nVdbeExec>1 ){
  79916. char *z = sqlite3MPrintf(db, "-- %s", zTrace);
  79917. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
  79918. sqlite3DbFree(db, z);
  79919. }else{
  79920. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
  79921. }
  79922. }
  79923. #ifdef SQLITE_USE_FCNTL_TRACE
  79924. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  79925. if( zTrace ){
  79926. int j;
  79927. for(j=0; j<db->nDb; j++){
  79928. if( DbMaskTest(p->btreeMask, j)==0 ) continue;
  79929. sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  79930. }
  79931. }
  79932. #endif /* SQLITE_USE_FCNTL_TRACE */
  79933. #ifdef SQLITE_DEBUG
  79934. if( (db->flags & SQLITE_SqlTrace)!=0
  79935. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  79936. ){
  79937. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  79938. }
  79939. #endif /* SQLITE_DEBUG */
  79940. #endif /* SQLITE_OMIT_TRACE */
  79941. assert( pOp->p2>0 );
  79942. if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
  79943. for(i=1; i<p->nOp; i++){
  79944. if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
  79945. }
  79946. pOp->p1 = 0;
  79947. }
  79948. pOp->p1++;
  79949. goto jump_to_p2;
  79950. }
  79951. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  79952. /* Opcode: CursorHint P1 * * P4 *
  79953. **
  79954. ** Provide a hint to cursor P1 that it only needs to return rows that
  79955. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  79956. ** to values currently held in registers. TK_COLUMN terms in the P4
  79957. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  79958. */
  79959. case OP_CursorHint: {
  79960. VdbeCursor *pC;
  79961. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79962. assert( pOp->p4type==P4_EXPR );
  79963. pC = p->apCsr[pOp->p1];
  79964. if( pC ){
  79965. assert( pC->eCurType==CURTYPE_BTREE );
  79966. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  79967. pOp->p4.pExpr, aMem);
  79968. }
  79969. break;
  79970. }
  79971. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  79972. /* Opcode: Noop * * * * *
  79973. **
  79974. ** Do nothing. This instruction is often useful as a jump
  79975. ** destination.
  79976. */
  79977. /*
  79978. ** The magic Explain opcode are only inserted when explain==2 (which
  79979. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  79980. ** This opcode records information from the optimizer. It is the
  79981. ** the same as a no-op. This opcodesnever appears in a real VM program.
  79982. */
  79983. default: { /* This is really OP_Noop and OP_Explain */
  79984. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  79985. break;
  79986. }
  79987. /*****************************************************************************
  79988. ** The cases of the switch statement above this line should all be indented
  79989. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  79990. ** readability. From this point on down, the normal indentation rules are
  79991. ** restored.
  79992. *****************************************************************************/
  79993. }
  79994. #ifdef VDBE_PROFILE
  79995. {
  79996. u64 endTime = sqlite3Hwtime();
  79997. if( endTime>start ) pOrigOp->cycles += endTime - start;
  79998. pOrigOp->cnt++;
  79999. }
  80000. #endif
  80001. /* The following code adds nothing to the actual functionality
  80002. ** of the program. It is only here for testing and debugging.
  80003. ** On the other hand, it does burn CPU cycles every time through
  80004. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  80005. */
  80006. #ifndef NDEBUG
  80007. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  80008. #ifdef SQLITE_DEBUG
  80009. if( db->flags & SQLITE_VdbeTrace ){
  80010. u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
  80011. if( rc!=0 ) printf("rc=%d\n",rc);
  80012. if( opProperty & (OPFLG_OUT2) ){
  80013. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  80014. }
  80015. if( opProperty & OPFLG_OUT3 ){
  80016. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  80017. }
  80018. }
  80019. #endif /* SQLITE_DEBUG */
  80020. #endif /* NDEBUG */
  80021. } /* The end of the for(;;) loop the loops through opcodes */
  80022. /* If we reach this point, it means that execution is finished with
  80023. ** an error of some kind.
  80024. */
  80025. abort_due_to_error:
  80026. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  80027. assert( rc );
  80028. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  80029. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  80030. }
  80031. p->rc = rc;
  80032. sqlite3SystemError(db, rc);
  80033. testcase( sqlite3GlobalConfig.xLog!=0 );
  80034. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  80035. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  80036. sqlite3VdbeHalt(p);
  80037. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  80038. rc = SQLITE_ERROR;
  80039. if( resetSchemaOnFault>0 ){
  80040. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  80041. }
  80042. /* This is the only way out of this procedure. We have to
  80043. ** release the mutexes on btrees that were acquired at the
  80044. ** top. */
  80045. vdbe_return:
  80046. testcase( nVmStep>0 );
  80047. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  80048. sqlite3VdbeLeave(p);
  80049. assert( rc!=SQLITE_OK || nExtraDelete==0
  80050. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  80051. );
  80052. return rc;
  80053. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  80054. ** is encountered.
  80055. */
  80056. too_big:
  80057. sqlite3VdbeError(p, "string or blob too big");
  80058. rc = SQLITE_TOOBIG;
  80059. goto abort_due_to_error;
  80060. /* Jump to here if a malloc() fails.
  80061. */
  80062. no_mem:
  80063. sqlite3OomFault(db);
  80064. sqlite3VdbeError(p, "out of memory");
  80065. rc = SQLITE_NOMEM_BKPT;
  80066. goto abort_due_to_error;
  80067. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  80068. ** flag.
  80069. */
  80070. abort_due_to_interrupt:
  80071. assert( db->u1.isInterrupted );
  80072. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  80073. p->rc = rc;
  80074. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  80075. goto abort_due_to_error;
  80076. }
  80077. /************** End of vdbe.c ************************************************/
  80078. /************** Begin file vdbeblob.c ****************************************/
  80079. /*
  80080. ** 2007 May 1
  80081. **
  80082. ** The author disclaims copyright to this source code. In place of
  80083. ** a legal notice, here is a blessing:
  80084. **
  80085. ** May you do good and not evil.
  80086. ** May you find forgiveness for yourself and forgive others.
  80087. ** May you share freely, never taking more than you give.
  80088. **
  80089. *************************************************************************
  80090. **
  80091. ** This file contains code used to implement incremental BLOB I/O.
  80092. */
  80093. /* #include "sqliteInt.h" */
  80094. /* #include "vdbeInt.h" */
  80095. #ifndef SQLITE_OMIT_INCRBLOB
  80096. /*
  80097. ** Valid sqlite3_blob* handles point to Incrblob structures.
  80098. */
  80099. typedef struct Incrblob Incrblob;
  80100. struct Incrblob {
  80101. int nByte; /* Size of open blob, in bytes */
  80102. int iOffset; /* Byte offset of blob in cursor data */
  80103. u16 iCol; /* Table column this handle is open on */
  80104. BtCursor *pCsr; /* Cursor pointing at blob row */
  80105. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  80106. sqlite3 *db; /* The associated database */
  80107. char *zDb; /* Database name */
  80108. Table *pTab; /* Table object */
  80109. };
  80110. /*
  80111. ** This function is used by both blob_open() and blob_reopen(). It seeks
  80112. ** the b-tree cursor associated with blob handle p to point to row iRow.
  80113. ** If successful, SQLITE_OK is returned and subsequent calls to
  80114. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  80115. **
  80116. ** If an error occurs, or if the specified row does not exist or does not
  80117. ** contain a value of type TEXT or BLOB in the column nominated when the
  80118. ** blob handle was opened, then an error code is returned and *pzErr may
  80119. ** be set to point to a buffer containing an error message. It is the
  80120. ** responsibility of the caller to free the error message buffer using
  80121. ** sqlite3DbFree().
  80122. **
  80123. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  80124. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  80125. ** immediately return SQLITE_ABORT.
  80126. */
  80127. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  80128. int rc; /* Error code */
  80129. char *zErr = 0; /* Error message */
  80130. Vdbe *v = (Vdbe *)p->pStmt;
  80131. /* Set the value of register r[1] in the SQL statement to integer iRow.
  80132. ** This is done directly as a performance optimization
  80133. */
  80134. v->aMem[1].flags = MEM_Int;
  80135. v->aMem[1].u.i = iRow;
  80136. /* If the statement has been run before (and is paused at the OP_ResultRow)
  80137. ** then back it up to the point where it does the OP_SeekRowid. This could
  80138. ** have been down with an extra OP_Goto, but simply setting the program
  80139. ** counter is faster. */
  80140. if( v->pc>3 ){
  80141. v->pc = 3;
  80142. rc = sqlite3VdbeExec(v);
  80143. }else{
  80144. rc = sqlite3_step(p->pStmt);
  80145. }
  80146. if( rc==SQLITE_ROW ){
  80147. VdbeCursor *pC = v->apCsr[0];
  80148. u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
  80149. testcase( pC->nHdrParsed==p->iCol );
  80150. testcase( pC->nHdrParsed==p->iCol+1 );
  80151. if( type<12 ){
  80152. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  80153. type==0?"null": type==7?"real": "integer"
  80154. );
  80155. rc = SQLITE_ERROR;
  80156. sqlite3_finalize(p->pStmt);
  80157. p->pStmt = 0;
  80158. }else{
  80159. p->iOffset = pC->aType[p->iCol + pC->nField];
  80160. p->nByte = sqlite3VdbeSerialTypeLen(type);
  80161. p->pCsr = pC->uc.pCursor;
  80162. sqlite3BtreeIncrblobCursor(p->pCsr);
  80163. }
  80164. }
  80165. if( rc==SQLITE_ROW ){
  80166. rc = SQLITE_OK;
  80167. }else if( p->pStmt ){
  80168. rc = sqlite3_finalize(p->pStmt);
  80169. p->pStmt = 0;
  80170. if( rc==SQLITE_OK ){
  80171. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  80172. rc = SQLITE_ERROR;
  80173. }else{
  80174. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  80175. }
  80176. }
  80177. assert( rc!=SQLITE_OK || zErr==0 );
  80178. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  80179. *pzErr = zErr;
  80180. return rc;
  80181. }
  80182. /*
  80183. ** Open a blob handle.
  80184. */
  80185. SQLITE_API int sqlite3_blob_open(
  80186. sqlite3* db, /* The database connection */
  80187. const char *zDb, /* The attached database containing the blob */
  80188. const char *zTable, /* The table containing the blob */
  80189. const char *zColumn, /* The column containing the blob */
  80190. sqlite_int64 iRow, /* The row containing the glob */
  80191. int wrFlag, /* True -> read/write access, false -> read-only */
  80192. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  80193. ){
  80194. int nAttempt = 0;
  80195. int iCol; /* Index of zColumn in row-record */
  80196. int rc = SQLITE_OK;
  80197. char *zErr = 0;
  80198. Table *pTab;
  80199. Parse *pParse = 0;
  80200. Incrblob *pBlob = 0;
  80201. #ifdef SQLITE_ENABLE_API_ARMOR
  80202. if( ppBlob==0 ){
  80203. return SQLITE_MISUSE_BKPT;
  80204. }
  80205. #endif
  80206. *ppBlob = 0;
  80207. #ifdef SQLITE_ENABLE_API_ARMOR
  80208. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  80209. return SQLITE_MISUSE_BKPT;
  80210. }
  80211. #endif
  80212. wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
  80213. sqlite3_mutex_enter(db->mutex);
  80214. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  80215. if( !pBlob ) goto blob_open_out;
  80216. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  80217. if( !pParse ) goto blob_open_out;
  80218. do {
  80219. memset(pParse, 0, sizeof(Parse));
  80220. pParse->db = db;
  80221. sqlite3DbFree(db, zErr);
  80222. zErr = 0;
  80223. sqlite3BtreeEnterAll(db);
  80224. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  80225. if( pTab && IsVirtual(pTab) ){
  80226. pTab = 0;
  80227. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  80228. }
  80229. if( pTab && !HasRowid(pTab) ){
  80230. pTab = 0;
  80231. sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
  80232. }
  80233. #ifndef SQLITE_OMIT_VIEW
  80234. if( pTab && pTab->pSelect ){
  80235. pTab = 0;
  80236. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  80237. }
  80238. #endif
  80239. if( !pTab ){
  80240. if( pParse->zErrMsg ){
  80241. sqlite3DbFree(db, zErr);
  80242. zErr = pParse->zErrMsg;
  80243. pParse->zErrMsg = 0;
  80244. }
  80245. rc = SQLITE_ERROR;
  80246. sqlite3BtreeLeaveAll(db);
  80247. goto blob_open_out;
  80248. }
  80249. pBlob->pTab = pTab;
  80250. pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
  80251. /* Now search pTab for the exact column. */
  80252. for(iCol=0; iCol<pTab->nCol; iCol++) {
  80253. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  80254. break;
  80255. }
  80256. }
  80257. if( iCol==pTab->nCol ){
  80258. sqlite3DbFree(db, zErr);
  80259. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  80260. rc = SQLITE_ERROR;
  80261. sqlite3BtreeLeaveAll(db);
  80262. goto blob_open_out;
  80263. }
  80264. /* If the value is being opened for writing, check that the
  80265. ** column is not indexed, and that it is not part of a foreign key.
  80266. */
  80267. if( wrFlag ){
  80268. const char *zFault = 0;
  80269. Index *pIdx;
  80270. #ifndef SQLITE_OMIT_FOREIGN_KEY
  80271. if( db->flags&SQLITE_ForeignKeys ){
  80272. /* Check that the column is not part of an FK child key definition. It
  80273. ** is not necessary to check if it is part of a parent key, as parent
  80274. ** key columns must be indexed. The check below will pick up this
  80275. ** case. */
  80276. FKey *pFKey;
  80277. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  80278. int j;
  80279. for(j=0; j<pFKey->nCol; j++){
  80280. if( pFKey->aCol[j].iFrom==iCol ){
  80281. zFault = "foreign key";
  80282. }
  80283. }
  80284. }
  80285. }
  80286. #endif
  80287. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  80288. int j;
  80289. for(j=0; j<pIdx->nKeyCol; j++){
  80290. /* FIXME: Be smarter about indexes that use expressions */
  80291. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  80292. zFault = "indexed";
  80293. }
  80294. }
  80295. }
  80296. if( zFault ){
  80297. sqlite3DbFree(db, zErr);
  80298. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  80299. rc = SQLITE_ERROR;
  80300. sqlite3BtreeLeaveAll(db);
  80301. goto blob_open_out;
  80302. }
  80303. }
  80304. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
  80305. assert( pBlob->pStmt || db->mallocFailed );
  80306. if( pBlob->pStmt ){
  80307. /* This VDBE program seeks a btree cursor to the identified
  80308. ** db/table/row entry. The reason for using a vdbe program instead
  80309. ** of writing code to use the b-tree layer directly is that the
  80310. ** vdbe program will take advantage of the various transaction,
  80311. ** locking and error handling infrastructure built into the vdbe.
  80312. **
  80313. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  80314. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  80315. ** uses it to implement the blob_read(), blob_write() and
  80316. ** blob_bytes() functions.
  80317. **
  80318. ** The sqlite3_blob_close() function finalizes the vdbe program,
  80319. ** which closes the b-tree cursor and (possibly) commits the
  80320. ** transaction.
  80321. */
  80322. static const int iLn = VDBE_OFFSET_LINENO(2);
  80323. static const VdbeOpList openBlob[] = {
  80324. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  80325. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  80326. /* blobSeekToRow() will initialize r[1] to the desired rowid */
  80327. {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
  80328. {OP_Column, 0, 0, 1}, /* 3 */
  80329. {OP_ResultRow, 1, 0, 0}, /* 4 */
  80330. {OP_Halt, 0, 0, 0}, /* 5 */
  80331. };
  80332. Vdbe *v = (Vdbe *)pBlob->pStmt;
  80333. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  80334. VdbeOp *aOp;
  80335. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
  80336. pTab->pSchema->schema_cookie,
  80337. pTab->pSchema->iGeneration);
  80338. sqlite3VdbeChangeP5(v, 1);
  80339. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  80340. /* Make sure a mutex is held on the table to be accessed */
  80341. sqlite3VdbeUsesBtree(v, iDb);
  80342. if( db->mallocFailed==0 ){
  80343. assert( aOp!=0 );
  80344. /* Configure the OP_TableLock instruction */
  80345. #ifdef SQLITE_OMIT_SHARED_CACHE
  80346. aOp[0].opcode = OP_Noop;
  80347. #else
  80348. aOp[0].p1 = iDb;
  80349. aOp[0].p2 = pTab->tnum;
  80350. aOp[0].p3 = wrFlag;
  80351. sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
  80352. }
  80353. if( db->mallocFailed==0 ){
  80354. #endif
  80355. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  80356. ** parameter of the other to pTab->tnum. */
  80357. if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
  80358. aOp[1].p2 = pTab->tnum;
  80359. aOp[1].p3 = iDb;
  80360. /* Configure the number of columns. Configure the cursor to
  80361. ** think that the table has one more column than it really
  80362. ** does. An OP_Column to retrieve this imaginary column will
  80363. ** always return an SQL NULL. This is useful because it means
  80364. ** we can invoke OP_Column to fill in the vdbe cursors type
  80365. ** and offset cache without causing any IO.
  80366. */
  80367. aOp[1].p4type = P4_INT32;
  80368. aOp[1].p4.i = pTab->nCol+1;
  80369. aOp[3].p2 = pTab->nCol;
  80370. pParse->nVar = 0;
  80371. pParse->nMem = 1;
  80372. pParse->nTab = 1;
  80373. sqlite3VdbeMakeReady(v, pParse);
  80374. }
  80375. }
  80376. pBlob->iCol = iCol;
  80377. pBlob->db = db;
  80378. sqlite3BtreeLeaveAll(db);
  80379. if( db->mallocFailed ){
  80380. goto blob_open_out;
  80381. }
  80382. rc = blobSeekToRow(pBlob, iRow, &zErr);
  80383. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  80384. blob_open_out:
  80385. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  80386. *ppBlob = (sqlite3_blob *)pBlob;
  80387. }else{
  80388. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  80389. sqlite3DbFree(db, pBlob);
  80390. }
  80391. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  80392. sqlite3DbFree(db, zErr);
  80393. sqlite3ParserReset(pParse);
  80394. sqlite3StackFree(db, pParse);
  80395. rc = sqlite3ApiExit(db, rc);
  80396. sqlite3_mutex_leave(db->mutex);
  80397. return rc;
  80398. }
  80399. /*
  80400. ** Close a blob handle that was previously created using
  80401. ** sqlite3_blob_open().
  80402. */
  80403. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  80404. Incrblob *p = (Incrblob *)pBlob;
  80405. int rc;
  80406. sqlite3 *db;
  80407. if( p ){
  80408. db = p->db;
  80409. sqlite3_mutex_enter(db->mutex);
  80410. rc = sqlite3_finalize(p->pStmt);
  80411. sqlite3DbFree(db, p);
  80412. sqlite3_mutex_leave(db->mutex);
  80413. }else{
  80414. rc = SQLITE_OK;
  80415. }
  80416. return rc;
  80417. }
  80418. /*
  80419. ** Perform a read or write operation on a blob
  80420. */
  80421. static int blobReadWrite(
  80422. sqlite3_blob *pBlob,
  80423. void *z,
  80424. int n,
  80425. int iOffset,
  80426. int (*xCall)(BtCursor*, u32, u32, void*)
  80427. ){
  80428. int rc;
  80429. Incrblob *p = (Incrblob *)pBlob;
  80430. Vdbe *v;
  80431. sqlite3 *db;
  80432. if( p==0 ) return SQLITE_MISUSE_BKPT;
  80433. db = p->db;
  80434. sqlite3_mutex_enter(db->mutex);
  80435. v = (Vdbe*)p->pStmt;
  80436. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  80437. /* Request is out of range. Return a transient error. */
  80438. rc = SQLITE_ERROR;
  80439. }else if( v==0 ){
  80440. /* If there is no statement handle, then the blob-handle has
  80441. ** already been invalidated. Return SQLITE_ABORT in this case.
  80442. */
  80443. rc = SQLITE_ABORT;
  80444. }else{
  80445. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  80446. ** returned, clean-up the statement handle.
  80447. */
  80448. assert( db == v->db );
  80449. sqlite3BtreeEnterCursor(p->pCsr);
  80450. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  80451. if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
  80452. /* If a pre-update hook is registered and this is a write cursor,
  80453. ** invoke it here.
  80454. **
  80455. ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
  80456. ** operation should really be an SQLITE_UPDATE. This is probably
  80457. ** incorrect, but is convenient because at this point the new.* values
  80458. ** are not easily obtainable. And for the sessions module, an
  80459. ** SQLITE_UPDATE where the PK columns do not change is handled in the
  80460. ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
  80461. ** slightly more efficient). Since you cannot write to a PK column
  80462. ** using the incremental-blob API, this works. For the sessions module
  80463. ** anyhow.
  80464. */
  80465. sqlite3_int64 iKey;
  80466. iKey = sqlite3BtreeIntegerKey(p->pCsr);
  80467. sqlite3VdbePreUpdateHook(
  80468. v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
  80469. );
  80470. }
  80471. #endif
  80472. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  80473. sqlite3BtreeLeaveCursor(p->pCsr);
  80474. if( rc==SQLITE_ABORT ){
  80475. sqlite3VdbeFinalize(v);
  80476. p->pStmt = 0;
  80477. }else{
  80478. v->rc = rc;
  80479. }
  80480. }
  80481. sqlite3Error(db, rc);
  80482. rc = sqlite3ApiExit(db, rc);
  80483. sqlite3_mutex_leave(db->mutex);
  80484. return rc;
  80485. }
  80486. /*
  80487. ** Read data from a blob handle.
  80488. */
  80489. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  80490. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
  80491. }
  80492. /*
  80493. ** Write data to a blob handle.
  80494. */
  80495. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  80496. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  80497. }
  80498. /*
  80499. ** Query a blob handle for the size of the data.
  80500. **
  80501. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  80502. ** so no mutex is required for access.
  80503. */
  80504. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  80505. Incrblob *p = (Incrblob *)pBlob;
  80506. return (p && p->pStmt) ? p->nByte : 0;
  80507. }
  80508. /*
  80509. ** Move an existing blob handle to point to a different row of the same
  80510. ** database table.
  80511. **
  80512. ** If an error occurs, or if the specified row does not exist or does not
  80513. ** contain a blob or text value, then an error code is returned and the
  80514. ** database handle error code and message set. If this happens, then all
  80515. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  80516. ** immediately return SQLITE_ABORT.
  80517. */
  80518. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  80519. int rc;
  80520. Incrblob *p = (Incrblob *)pBlob;
  80521. sqlite3 *db;
  80522. if( p==0 ) return SQLITE_MISUSE_BKPT;
  80523. db = p->db;
  80524. sqlite3_mutex_enter(db->mutex);
  80525. if( p->pStmt==0 ){
  80526. /* If there is no statement handle, then the blob-handle has
  80527. ** already been invalidated. Return SQLITE_ABORT in this case.
  80528. */
  80529. rc = SQLITE_ABORT;
  80530. }else{
  80531. char *zErr;
  80532. rc = blobSeekToRow(p, iRow, &zErr);
  80533. if( rc!=SQLITE_OK ){
  80534. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  80535. sqlite3DbFree(db, zErr);
  80536. }
  80537. assert( rc!=SQLITE_SCHEMA );
  80538. }
  80539. rc = sqlite3ApiExit(db, rc);
  80540. assert( rc==SQLITE_OK || p->pStmt==0 );
  80541. sqlite3_mutex_leave(db->mutex);
  80542. return rc;
  80543. }
  80544. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  80545. /************** End of vdbeblob.c ********************************************/
  80546. /************** Begin file vdbesort.c ****************************************/
  80547. /*
  80548. ** 2011-07-09
  80549. **
  80550. ** The author disclaims copyright to this source code. In place of
  80551. ** a legal notice, here is a blessing:
  80552. **
  80553. ** May you do good and not evil.
  80554. ** May you find forgiveness for yourself and forgive others.
  80555. ** May you share freely, never taking more than you give.
  80556. **
  80557. *************************************************************************
  80558. ** This file contains code for the VdbeSorter object, used in concert with
  80559. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  80560. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  80561. ** using indexes and without LIMIT clauses.
  80562. **
  80563. ** The VdbeSorter object implements a multi-threaded external merge sort
  80564. ** algorithm that is efficient even if the number of elements being sorted
  80565. ** exceeds the available memory.
  80566. **
  80567. ** Here is the (internal, non-API) interface between this module and the
  80568. ** rest of the SQLite system:
  80569. **
  80570. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  80571. **
  80572. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  80573. ** object. The row is a binary blob in the
  80574. ** OP_MakeRecord format that contains both
  80575. ** the ORDER BY key columns and result columns
  80576. ** in the case of a SELECT w/ ORDER BY, or
  80577. ** the complete record for an index entry
  80578. ** in the case of a CREATE INDEX.
  80579. **
  80580. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  80581. ** Position the read cursor on the
  80582. ** first sorted element.
  80583. **
  80584. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  80585. ** element.
  80586. **
  80587. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  80588. ** row currently under the read cursor.
  80589. **
  80590. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  80591. ** currently under the read cursor against
  80592. ** another binary blob X and report if
  80593. ** X is strictly less than the read cursor.
  80594. ** Used to enforce uniqueness in a
  80595. ** CREATE UNIQUE INDEX statement.
  80596. **
  80597. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  80598. ** all resources.
  80599. **
  80600. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  80601. ** is like Close() followed by Init() only
  80602. ** much faster.
  80603. **
  80604. ** The interfaces above must be called in a particular order. Write() can
  80605. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  80606. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  80607. **
  80608. ** Init()
  80609. ** for each record: Write()
  80610. ** Rewind()
  80611. ** Rowkey()/Compare()
  80612. ** Next()
  80613. ** Close()
  80614. **
  80615. ** Algorithm:
  80616. **
  80617. ** Records passed to the sorter via calls to Write() are initially held
  80618. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  80619. ** a threshold, when Rewind() is called the set of records is sorted using
  80620. ** an in-memory merge sort. In this case, no temporary files are required
  80621. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  80622. ** directly from main memory.
  80623. **
  80624. ** If the amount of space used to store records in main memory exceeds the
  80625. ** threshold, then the set of records currently in memory are sorted and
  80626. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  80627. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  80628. ** of PMAs may be created by merging existing PMAs together - for example
  80629. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  80630. **
  80631. ** The threshold for the amount of main memory to use before flushing
  80632. ** records to a PMA is roughly the same as the limit configured for the
  80633. ** page-cache of the main database. Specifically, the threshold is set to
  80634. ** the value returned by "PRAGMA main.page_size" multipled by
  80635. ** that returned by "PRAGMA main.cache_size", in bytes.
  80636. **
  80637. ** If the sorter is running in single-threaded mode, then all PMAs generated
  80638. ** are appended to a single temporary file. Or, if the sorter is running in
  80639. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  80640. ** N is the configured number of worker threads. In this case, instead of
  80641. ** sorting the records and writing the PMA to a temporary file itself, the
  80642. ** calling thread usually launches a worker thread to do so. Except, if
  80643. ** there are already N worker threads running, the main thread does the work
  80644. ** itself.
  80645. **
  80646. ** The sorter is running in multi-threaded mode if (a) the library was built
  80647. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  80648. ** than zero, and (b) worker threads have been enabled at runtime by calling
  80649. ** "PRAGMA threads=N" with some value of N greater than 0.
  80650. **
  80651. ** When Rewind() is called, any data remaining in memory is flushed to a
  80652. ** final PMA. So at this point the data is stored in some number of sorted
  80653. ** PMAs within temporary files on disk.
  80654. **
  80655. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  80656. ** sorter is running in single-threaded mode, then these PMAs are merged
  80657. ** incrementally as keys are retreived from the sorter by the VDBE. The
  80658. ** MergeEngine object, described in further detail below, performs this
  80659. ** merge.
  80660. **
  80661. ** Or, if running in multi-threaded mode, then a background thread is
  80662. ** launched to merge the existing PMAs. Once the background thread has
  80663. ** merged T bytes of data into a single sorted PMA, the main thread
  80664. ** begins reading keys from that PMA while the background thread proceeds
  80665. ** with merging the next T bytes of data. And so on.
  80666. **
  80667. ** Parameter T is set to half the value of the memory threshold used
  80668. ** by Write() above to determine when to create a new PMA.
  80669. **
  80670. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  80671. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  80672. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  80673. ** disk are merged together. Then T bytes of data from the second set, and
  80674. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  80675. ** PMAs at a time. This done is to improve locality.
  80676. **
  80677. ** If running in multi-threaded mode and there are more than
  80678. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  80679. ** than one background thread may be created. Specifically, there may be
  80680. ** one background thread for each temporary file on disk, and one background
  80681. ** thread to merge the output of each of the others to a single PMA for
  80682. ** the main thread to read from.
  80683. */
  80684. /* #include "sqliteInt.h" */
  80685. /* #include "vdbeInt.h" */
  80686. /*
  80687. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  80688. ** messages to stderr that may be helpful in understanding the performance
  80689. ** characteristics of the sorter in multi-threaded mode.
  80690. */
  80691. #if 0
  80692. # define SQLITE_DEBUG_SORTER_THREADS 1
  80693. #endif
  80694. /*
  80695. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  80696. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  80697. ** overflows. 512MiB.
  80698. */
  80699. #define SQLITE_MAX_PMASZ (1<<29)
  80700. /*
  80701. ** Private objects used by the sorter
  80702. */
  80703. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  80704. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  80705. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  80706. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  80707. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  80708. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  80709. typedef struct SorterList SorterList; /* In-memory list of records */
  80710. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  80711. /*
  80712. ** A container for a temp file handle and the current amount of data
  80713. ** stored in the file.
  80714. */
  80715. struct SorterFile {
  80716. sqlite3_file *pFd; /* File handle */
  80717. i64 iEof; /* Bytes of data stored in pFd */
  80718. };
  80719. /*
  80720. ** An in-memory list of objects to be sorted.
  80721. **
  80722. ** If aMemory==0 then each object is allocated separately and the objects
  80723. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  80724. ** are stored in the aMemory[] bulk memory, one right after the other, and
  80725. ** are connected using SorterRecord.u.iNext.
  80726. */
  80727. struct SorterList {
  80728. SorterRecord *pList; /* Linked list of records */
  80729. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  80730. int szPMA; /* Size of pList as PMA in bytes */
  80731. };
  80732. /*
  80733. ** The MergeEngine object is used to combine two or more smaller PMAs into
  80734. ** one big PMA using a merge operation. Separate PMAs all need to be
  80735. ** combined into one big PMA in order to be able to step through the sorted
  80736. ** records in order.
  80737. **
  80738. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  80739. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  80740. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  80741. ** For the purposes of the paragraphs below, we assume that the array is
  80742. ** actually N elements in size, where N is the smallest power of 2 greater
  80743. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  80744. ** are treated as if they are empty (always at EOF).
  80745. **
  80746. ** The aTree[] array is also N elements in size. The value of N is stored in
  80747. ** the MergeEngine.nTree variable.
  80748. **
  80749. ** The final (N/2) elements of aTree[] contain the results of comparing
  80750. ** pairs of PMA keys together. Element i contains the result of
  80751. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  80752. ** aTree element is set to the index of it.
  80753. **
  80754. ** For the purposes of this comparison, EOF is considered greater than any
  80755. ** other key value. If the keys are equal (only possible with two EOF
  80756. ** values), it doesn't matter which index is stored.
  80757. **
  80758. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  80759. ** above contains the index of the smallest of each block of 4 PmaReaders
  80760. ** And so on. So that aTree[1] contains the index of the PmaReader that
  80761. ** currently points to the smallest key value. aTree[0] is unused.
  80762. **
  80763. ** Example:
  80764. **
  80765. ** aReadr[0] -> Banana
  80766. ** aReadr[1] -> Feijoa
  80767. ** aReadr[2] -> Elderberry
  80768. ** aReadr[3] -> Currant
  80769. ** aReadr[4] -> Grapefruit
  80770. ** aReadr[5] -> Apple
  80771. ** aReadr[6] -> Durian
  80772. ** aReadr[7] -> EOF
  80773. **
  80774. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  80775. **
  80776. ** The current element is "Apple" (the value of the key indicated by
  80777. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  80778. ** be advanced to the next key in its segment. Say the next key is
  80779. ** "Eggplant":
  80780. **
  80781. ** aReadr[5] -> Eggplant
  80782. **
  80783. ** The contents of aTree[] are updated first by comparing the new PmaReader
  80784. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  80785. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  80786. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  80787. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  80788. ** so the value written into element 1 of the array is 0. As follows:
  80789. **
  80790. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  80791. **
  80792. ** In other words, each time we advance to the next sorter element, log2(N)
  80793. ** key comparison operations are required, where N is the number of segments
  80794. ** being merged (rounded up to the next power of 2).
  80795. */
  80796. struct MergeEngine {
  80797. int nTree; /* Used size of aTree/aReadr (power of 2) */
  80798. SortSubtask *pTask; /* Used by this thread only */
  80799. int *aTree; /* Current state of incremental merge */
  80800. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  80801. };
  80802. /*
  80803. ** This object represents a single thread of control in a sort operation.
  80804. ** Exactly VdbeSorter.nTask instances of this object are allocated
  80805. ** as part of each VdbeSorter object. Instances are never allocated any
  80806. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  80807. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  80808. ** single-threaded operation, there is exactly one instance of this object
  80809. ** and for multi-threaded operation there are two or more instances.
  80810. **
  80811. ** Essentially, this structure contains all those fields of the VdbeSorter
  80812. ** structure for which each thread requires a separate instance. For example,
  80813. ** each thread requries its own UnpackedRecord object to unpack records in
  80814. ** as part of comparison operations.
  80815. **
  80816. ** Before a background thread is launched, variable bDone is set to 0. Then,
  80817. ** right before it exits, the thread itself sets bDone to 1. This is used for
  80818. ** two purposes:
  80819. **
  80820. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  80821. ** attempt to select a SortSubtask for which there is not already an
  80822. ** active background thread (since doing so causes the main thread
  80823. ** to block until it finishes).
  80824. **
  80825. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  80826. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  80827. ** block provoke debugging output.
  80828. **
  80829. ** In both cases, the effects of the main thread seeing (bDone==0) even
  80830. ** after the thread has finished are not dire. So we don't worry about
  80831. ** memory barriers and such here.
  80832. */
  80833. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  80834. struct SortSubtask {
  80835. SQLiteThread *pThread; /* Background thread, if any */
  80836. int bDone; /* Set if thread is finished but not joined */
  80837. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  80838. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  80839. SorterList list; /* List for thread to write to a PMA */
  80840. int nPMA; /* Number of PMAs currently in file */
  80841. SorterCompare xCompare; /* Compare function to use */
  80842. SorterFile file; /* Temp file for level-0 PMAs */
  80843. SorterFile file2; /* Space for other PMAs */
  80844. };
  80845. /*
  80846. ** Main sorter structure. A single instance of this is allocated for each
  80847. ** sorter cursor created by the VDBE.
  80848. **
  80849. ** mxKeysize:
  80850. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  80851. ** this variable is updated so as to be set to the size on disk of the
  80852. ** largest record in the sorter.
  80853. */
  80854. struct VdbeSorter {
  80855. int mnPmaSize; /* Minimum PMA size, in bytes */
  80856. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  80857. int mxKeysize; /* Largest serialized key seen so far */
  80858. int pgsz; /* Main database page size */
  80859. PmaReader *pReader; /* Readr data from here after Rewind() */
  80860. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  80861. sqlite3 *db; /* Database connection */
  80862. KeyInfo *pKeyInfo; /* How to compare records */
  80863. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  80864. SorterList list; /* List of in-memory records */
  80865. int iMemory; /* Offset of free space in list.aMemory */
  80866. int nMemory; /* Size of list.aMemory allocation in bytes */
  80867. u8 bUsePMA; /* True if one or more PMAs created */
  80868. u8 bUseThreads; /* True to use background threads */
  80869. u8 iPrev; /* Previous thread used to flush PMA */
  80870. u8 nTask; /* Size of aTask[] array */
  80871. u8 typeMask;
  80872. SortSubtask aTask[1]; /* One or more subtasks */
  80873. };
  80874. #define SORTER_TYPE_INTEGER 0x01
  80875. #define SORTER_TYPE_TEXT 0x02
  80876. /*
  80877. ** An instance of the following object is used to read records out of a
  80878. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  80879. ** aKey might point into aMap or into aBuffer. If neither of those locations
  80880. ** contain a contiguous representation of the key, then aAlloc is allocated
  80881. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  80882. **
  80883. ** pFd==0 at EOF.
  80884. */
  80885. struct PmaReader {
  80886. i64 iReadOff; /* Current read offset */
  80887. i64 iEof; /* 1 byte past EOF for this PmaReader */
  80888. int nAlloc; /* Bytes of space at aAlloc */
  80889. int nKey; /* Number of bytes in key */
  80890. sqlite3_file *pFd; /* File handle we are reading from */
  80891. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  80892. u8 *aKey; /* Pointer to current key */
  80893. u8 *aBuffer; /* Current read buffer */
  80894. int nBuffer; /* Size of read buffer in bytes */
  80895. u8 *aMap; /* Pointer to mapping of entire file */
  80896. IncrMerger *pIncr; /* Incremental merger */
  80897. };
  80898. /*
  80899. ** Normally, a PmaReader object iterates through an existing PMA stored
  80900. ** within a temp file. However, if the PmaReader.pIncr variable points to
  80901. ** an object of the following type, it may be used to iterate/merge through
  80902. ** multiple PMAs simultaneously.
  80903. **
  80904. ** There are two types of IncrMerger object - single (bUseThread==0) and
  80905. ** multi-threaded (bUseThread==1).
  80906. **
  80907. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  80908. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  80909. ** size. When the IncrMerger is initialized, it reads enough data from
  80910. ** pMerger to populate aFile[0]. It then sets variables within the
  80911. ** corresponding PmaReader object to read from that file and kicks off
  80912. ** a background thread to populate aFile[1] with the next mxSz bytes of
  80913. ** sorted record data from pMerger.
  80914. **
  80915. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  80916. ** background thread has finished populating aFile[1]. It then exchanges
  80917. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  80918. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  80919. ** another background thread to populate the new aFile[1]. And so on, until
  80920. ** the contents of pMerger are exhausted.
  80921. **
  80922. ** A single-threaded IncrMerger does not open any temporary files of its
  80923. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  80924. ** at offset iStartOff of file pTask->file2. And instead of using a
  80925. ** background thread to prepare data for the PmaReader, with a single
  80926. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  80927. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  80928. ** of data.
  80929. */
  80930. struct IncrMerger {
  80931. SortSubtask *pTask; /* Task that owns this merger */
  80932. MergeEngine *pMerger; /* Merge engine thread reads data from */
  80933. i64 iStartOff; /* Offset to start writing file at */
  80934. int mxSz; /* Maximum bytes of data to store */
  80935. int bEof; /* Set to true when merge is finished */
  80936. int bUseThread; /* True to use a bg thread for this object */
  80937. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  80938. };
  80939. /*
  80940. ** An instance of this object is used for writing a PMA.
  80941. **
  80942. ** The PMA is written one record at a time. Each record is of an arbitrary
  80943. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  80944. ** each block is aligned on a page boundary. This object caches writes to
  80945. ** the PMA so that aligned, page-size blocks are written.
  80946. */
  80947. struct PmaWriter {
  80948. int eFWErr; /* Non-zero if in an error state */
  80949. u8 *aBuffer; /* Pointer to write buffer */
  80950. int nBuffer; /* Size of write buffer in bytes */
  80951. int iBufStart; /* First byte of buffer to write */
  80952. int iBufEnd; /* Last byte of buffer to write */
  80953. i64 iWriteOff; /* Offset of start of buffer in file */
  80954. sqlite3_file *pFd; /* File handle to write to */
  80955. };
  80956. /*
  80957. ** This object is the header on a single record while that record is being
  80958. ** held in memory and prior to being written out as part of a PMA.
  80959. **
  80960. ** How the linked list is connected depends on how memory is being managed
  80961. ** by this module. If using a separate allocation for each in-memory record
  80962. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  80963. ** SorterRecord.u.pNext pointers.
  80964. **
  80965. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  80966. ** then while records are being accumulated the list is linked using the
  80967. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  80968. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  80969. ** has finished passing records to the sorter, or when the in-memory buffer
  80970. ** is full, the list is sorted. As part of the sorting process, it is
  80971. ** converted to use the SorterRecord.u.pNext pointers. See function
  80972. ** vdbeSorterSort() for details.
  80973. */
  80974. struct SorterRecord {
  80975. int nVal; /* Size of the record in bytes */
  80976. union {
  80977. SorterRecord *pNext; /* Pointer to next record in list */
  80978. int iNext; /* Offset within aMemory of next record */
  80979. } u;
  80980. /* The data for the record immediately follows this header */
  80981. };
  80982. /* Return a pointer to the buffer containing the record data for SorterRecord
  80983. ** object p. Should be used as if:
  80984. **
  80985. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  80986. */
  80987. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  80988. /* Maximum number of PMAs that a single MergeEngine can merge */
  80989. #define SORTER_MAX_MERGE_COUNT 16
  80990. static int vdbeIncrSwap(IncrMerger*);
  80991. static void vdbeIncrFree(IncrMerger *);
  80992. /*
  80993. ** Free all memory belonging to the PmaReader object passed as the
  80994. ** argument. All structure fields are set to zero before returning.
  80995. */
  80996. static void vdbePmaReaderClear(PmaReader *pReadr){
  80997. sqlite3_free(pReadr->aAlloc);
  80998. sqlite3_free(pReadr->aBuffer);
  80999. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  81000. vdbeIncrFree(pReadr->pIncr);
  81001. memset(pReadr, 0, sizeof(PmaReader));
  81002. }
  81003. /*
  81004. ** Read the next nByte bytes of data from the PMA p.
  81005. ** If successful, set *ppOut to point to a buffer containing the data
  81006. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  81007. ** error code.
  81008. **
  81009. ** The buffer returned in *ppOut is only valid until the
  81010. ** next call to this function.
  81011. */
  81012. static int vdbePmaReadBlob(
  81013. PmaReader *p, /* PmaReader from which to take the blob */
  81014. int nByte, /* Bytes of data to read */
  81015. u8 **ppOut /* OUT: Pointer to buffer containing data */
  81016. ){
  81017. int iBuf; /* Offset within buffer to read from */
  81018. int nAvail; /* Bytes of data available in buffer */
  81019. if( p->aMap ){
  81020. *ppOut = &p->aMap[p->iReadOff];
  81021. p->iReadOff += nByte;
  81022. return SQLITE_OK;
  81023. }
  81024. assert( p->aBuffer );
  81025. /* If there is no more data to be read from the buffer, read the next
  81026. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  81027. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  81028. iBuf = p->iReadOff % p->nBuffer;
  81029. if( iBuf==0 ){
  81030. int nRead; /* Bytes to read from disk */
  81031. int rc; /* sqlite3OsRead() return code */
  81032. /* Determine how many bytes of data to read. */
  81033. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  81034. nRead = p->nBuffer;
  81035. }else{
  81036. nRead = (int)(p->iEof - p->iReadOff);
  81037. }
  81038. assert( nRead>0 );
  81039. /* Readr data from the file. Return early if an error occurs. */
  81040. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  81041. assert( rc!=SQLITE_IOERR_SHORT_READ );
  81042. if( rc!=SQLITE_OK ) return rc;
  81043. }
  81044. nAvail = p->nBuffer - iBuf;
  81045. if( nByte<=nAvail ){
  81046. /* The requested data is available in the in-memory buffer. In this
  81047. ** case there is no need to make a copy of the data, just return a
  81048. ** pointer into the buffer to the caller. */
  81049. *ppOut = &p->aBuffer[iBuf];
  81050. p->iReadOff += nByte;
  81051. }else{
  81052. /* The requested data is not all available in the in-memory buffer.
  81053. ** In this case, allocate space at p->aAlloc[] to copy the requested
  81054. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  81055. int nRem; /* Bytes remaining to copy */
  81056. /* Extend the p->aAlloc[] allocation if required. */
  81057. if( p->nAlloc<nByte ){
  81058. u8 *aNew;
  81059. int nNew = MAX(128, p->nAlloc*2);
  81060. while( nByte>nNew ) nNew = nNew*2;
  81061. aNew = sqlite3Realloc(p->aAlloc, nNew);
  81062. if( !aNew ) return SQLITE_NOMEM_BKPT;
  81063. p->nAlloc = nNew;
  81064. p->aAlloc = aNew;
  81065. }
  81066. /* Copy as much data as is available in the buffer into the start of
  81067. ** p->aAlloc[]. */
  81068. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  81069. p->iReadOff += nAvail;
  81070. nRem = nByte - nAvail;
  81071. /* The following loop copies up to p->nBuffer bytes per iteration into
  81072. ** the p->aAlloc[] buffer. */
  81073. while( nRem>0 ){
  81074. int rc; /* vdbePmaReadBlob() return code */
  81075. int nCopy; /* Number of bytes to copy */
  81076. u8 *aNext; /* Pointer to buffer to copy data from */
  81077. nCopy = nRem;
  81078. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  81079. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  81080. if( rc!=SQLITE_OK ) return rc;
  81081. assert( aNext!=p->aAlloc );
  81082. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  81083. nRem -= nCopy;
  81084. }
  81085. *ppOut = p->aAlloc;
  81086. }
  81087. return SQLITE_OK;
  81088. }
  81089. /*
  81090. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  81091. ** the value read.
  81092. */
  81093. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  81094. int iBuf;
  81095. if( p->aMap ){
  81096. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  81097. }else{
  81098. iBuf = p->iReadOff % p->nBuffer;
  81099. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  81100. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  81101. }else{
  81102. u8 aVarint[16], *a;
  81103. int i = 0, rc;
  81104. do{
  81105. rc = vdbePmaReadBlob(p, 1, &a);
  81106. if( rc ) return rc;
  81107. aVarint[(i++)&0xf] = a[0];
  81108. }while( (a[0]&0x80)!=0 );
  81109. sqlite3GetVarint(aVarint, pnOut);
  81110. }
  81111. }
  81112. return SQLITE_OK;
  81113. }
  81114. /*
  81115. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  81116. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  81117. ** (because the file is too large or the VFS layer is configured not to use
  81118. ** mmap), return SQLITE_OK and set *pp to NULL.
  81119. **
  81120. ** Or, if an error occurs, return an SQLite error code. The final value of
  81121. ** *pp is undefined in this case.
  81122. */
  81123. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  81124. int rc = SQLITE_OK;
  81125. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  81126. sqlite3_file *pFd = pFile->pFd;
  81127. if( pFd->pMethods->iVersion>=3 ){
  81128. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  81129. testcase( rc!=SQLITE_OK );
  81130. }
  81131. }
  81132. return rc;
  81133. }
  81134. /*
  81135. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  81136. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  81137. ** if successful, or an SQLite error code if an error occurs.
  81138. */
  81139. static int vdbePmaReaderSeek(
  81140. SortSubtask *pTask, /* Task context */
  81141. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  81142. SorterFile *pFile, /* Sorter file to read from */
  81143. i64 iOff /* Offset in pFile */
  81144. ){
  81145. int rc = SQLITE_OK;
  81146. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  81147. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  81148. if( pReadr->aMap ){
  81149. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  81150. pReadr->aMap = 0;
  81151. }
  81152. pReadr->iReadOff = iOff;
  81153. pReadr->iEof = pFile->iEof;
  81154. pReadr->pFd = pFile->pFd;
  81155. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  81156. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  81157. int pgsz = pTask->pSorter->pgsz;
  81158. int iBuf = pReadr->iReadOff % pgsz;
  81159. if( pReadr->aBuffer==0 ){
  81160. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  81161. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  81162. pReadr->nBuffer = pgsz;
  81163. }
  81164. if( rc==SQLITE_OK && iBuf ){
  81165. int nRead = pgsz - iBuf;
  81166. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  81167. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  81168. }
  81169. rc = sqlite3OsRead(
  81170. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  81171. );
  81172. testcase( rc!=SQLITE_OK );
  81173. }
  81174. }
  81175. return rc;
  81176. }
  81177. /*
  81178. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  81179. ** no error occurs, or an SQLite error code if one does.
  81180. */
  81181. static int vdbePmaReaderNext(PmaReader *pReadr){
  81182. int rc = SQLITE_OK; /* Return Code */
  81183. u64 nRec = 0; /* Size of record in bytes */
  81184. if( pReadr->iReadOff>=pReadr->iEof ){
  81185. IncrMerger *pIncr = pReadr->pIncr;
  81186. int bEof = 1;
  81187. if( pIncr ){
  81188. rc = vdbeIncrSwap(pIncr);
  81189. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  81190. rc = vdbePmaReaderSeek(
  81191. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  81192. );
  81193. bEof = 0;
  81194. }
  81195. }
  81196. if( bEof ){
  81197. /* This is an EOF condition */
  81198. vdbePmaReaderClear(pReadr);
  81199. testcase( rc!=SQLITE_OK );
  81200. return rc;
  81201. }
  81202. }
  81203. if( rc==SQLITE_OK ){
  81204. rc = vdbePmaReadVarint(pReadr, &nRec);
  81205. }
  81206. if( rc==SQLITE_OK ){
  81207. pReadr->nKey = (int)nRec;
  81208. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  81209. testcase( rc!=SQLITE_OK );
  81210. }
  81211. return rc;
  81212. }
  81213. /*
  81214. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  81215. ** starting at offset iStart and ending at offset iEof-1. This function
  81216. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  81217. ** PMA is empty).
  81218. **
  81219. ** If the pnByte parameter is NULL, then it is assumed that the file
  81220. ** contains a single PMA, and that that PMA omits the initial length varint.
  81221. */
  81222. static int vdbePmaReaderInit(
  81223. SortSubtask *pTask, /* Task context */
  81224. SorterFile *pFile, /* Sorter file to read from */
  81225. i64 iStart, /* Start offset in pFile */
  81226. PmaReader *pReadr, /* PmaReader to populate */
  81227. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  81228. ){
  81229. int rc;
  81230. assert( pFile->iEof>iStart );
  81231. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  81232. assert( pReadr->aBuffer==0 );
  81233. assert( pReadr->aMap==0 );
  81234. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  81235. if( rc==SQLITE_OK ){
  81236. u64 nByte = 0; /* Size of PMA in bytes */
  81237. rc = vdbePmaReadVarint(pReadr, &nByte);
  81238. pReadr->iEof = pReadr->iReadOff + nByte;
  81239. *pnByte += nByte;
  81240. }
  81241. if( rc==SQLITE_OK ){
  81242. rc = vdbePmaReaderNext(pReadr);
  81243. }
  81244. return rc;
  81245. }
  81246. /*
  81247. ** A version of vdbeSorterCompare() that assumes that it has already been
  81248. ** determined that the first field of key1 is equal to the first field of
  81249. ** key2.
  81250. */
  81251. static int vdbeSorterCompareTail(
  81252. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  81253. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  81254. const void *pKey1, int nKey1, /* Left side of comparison */
  81255. const void *pKey2, int nKey2 /* Right side of comparison */
  81256. ){
  81257. UnpackedRecord *r2 = pTask->pUnpacked;
  81258. if( *pbKey2Cached==0 ){
  81259. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  81260. *pbKey2Cached = 1;
  81261. }
  81262. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  81263. }
  81264. /*
  81265. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  81266. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  81267. ** used by the comparison. Return the result of the comparison.
  81268. **
  81269. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  81270. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  81271. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  81272. ** version of key2 and *pbKey2Cached set to true before returning.
  81273. **
  81274. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  81275. ** to SQLITE_NOMEM.
  81276. */
  81277. static int vdbeSorterCompare(
  81278. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  81279. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  81280. const void *pKey1, int nKey1, /* Left side of comparison */
  81281. const void *pKey2, int nKey2 /* Right side of comparison */
  81282. ){
  81283. UnpackedRecord *r2 = pTask->pUnpacked;
  81284. if( !*pbKey2Cached ){
  81285. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  81286. *pbKey2Cached = 1;
  81287. }
  81288. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  81289. }
  81290. /*
  81291. ** A specially optimized version of vdbeSorterCompare() that assumes that
  81292. ** the first field of each key is a TEXT value and that the collation
  81293. ** sequence to compare them with is BINARY.
  81294. */
  81295. static int vdbeSorterCompareText(
  81296. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  81297. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  81298. const void *pKey1, int nKey1, /* Left side of comparison */
  81299. const void *pKey2, int nKey2 /* Right side of comparison */
  81300. ){
  81301. const u8 * const p1 = (const u8 * const)pKey1;
  81302. const u8 * const p2 = (const u8 * const)pKey2;
  81303. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  81304. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  81305. int n1;
  81306. int n2;
  81307. int res;
  81308. getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
  81309. getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
  81310. res = memcmp(v1, v2, MIN(n1, n2));
  81311. if( res==0 ){
  81312. res = n1 - n2;
  81313. }
  81314. if( res==0 ){
  81315. if( pTask->pSorter->pKeyInfo->nField>1 ){
  81316. res = vdbeSorterCompareTail(
  81317. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  81318. );
  81319. }
  81320. }else{
  81321. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  81322. res = res * -1;
  81323. }
  81324. }
  81325. return res;
  81326. }
  81327. /*
  81328. ** A specially optimized version of vdbeSorterCompare() that assumes that
  81329. ** the first field of each key is an INTEGER value.
  81330. */
  81331. static int vdbeSorterCompareInt(
  81332. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  81333. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  81334. const void *pKey1, int nKey1, /* Left side of comparison */
  81335. const void *pKey2, int nKey2 /* Right side of comparison */
  81336. ){
  81337. const u8 * const p1 = (const u8 * const)pKey1;
  81338. const u8 * const p2 = (const u8 * const)pKey2;
  81339. const int s1 = p1[1]; /* Left hand serial type */
  81340. const int s2 = p2[1]; /* Right hand serial type */
  81341. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  81342. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  81343. int res; /* Return value */
  81344. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  81345. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  81346. if( s1==s2 ){
  81347. /* The two values have the same sign. Compare using memcmp(). */
  81348. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
  81349. const u8 n = aLen[s1];
  81350. int i;
  81351. res = 0;
  81352. for(i=0; i<n; i++){
  81353. if( (res = v1[i] - v2[i])!=0 ){
  81354. if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
  81355. res = v1[0] & 0x80 ? -1 : +1;
  81356. }
  81357. break;
  81358. }
  81359. }
  81360. }else if( s1>7 && s2>7 ){
  81361. res = s1 - s2;
  81362. }else{
  81363. if( s2>7 ){
  81364. res = +1;
  81365. }else if( s1>7 ){
  81366. res = -1;
  81367. }else{
  81368. res = s1 - s2;
  81369. }
  81370. assert( res!=0 );
  81371. if( res>0 ){
  81372. if( *v1 & 0x80 ) res = -1;
  81373. }else{
  81374. if( *v2 & 0x80 ) res = +1;
  81375. }
  81376. }
  81377. if( res==0 ){
  81378. if( pTask->pSorter->pKeyInfo->nField>1 ){
  81379. res = vdbeSorterCompareTail(
  81380. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  81381. );
  81382. }
  81383. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  81384. res = res * -1;
  81385. }
  81386. return res;
  81387. }
  81388. /*
  81389. ** Initialize the temporary index cursor just opened as a sorter cursor.
  81390. **
  81391. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
  81392. ** to determine the number of fields that should be compared from the
  81393. ** records being sorted. However, if the value passed as argument nField
  81394. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  81395. ** is used instead. This is used when sorting records for a CREATE INDEX
  81396. ** statement. In this case, keys are always delivered to the sorter in
  81397. ** order of the primary key, which happens to be make up the final part
  81398. ** of the records being sorted. So if the sort is stable, there is never
  81399. ** any reason to compare PK fields and they can be ignored for a small
  81400. ** performance boost.
  81401. **
  81402. ** The sorter can guarantee a stable sort when running in single-threaded
  81403. ** mode, but not in multi-threaded mode.
  81404. **
  81405. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  81406. */
  81407. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  81408. sqlite3 *db, /* Database connection (for malloc()) */
  81409. int nField, /* Number of key fields in each record */
  81410. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  81411. ){
  81412. int pgsz; /* Page size of main database */
  81413. int i; /* Used to iterate through aTask[] */
  81414. VdbeSorter *pSorter; /* The new sorter */
  81415. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  81416. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  81417. int sz; /* Size of pSorter in bytes */
  81418. int rc = SQLITE_OK;
  81419. #if SQLITE_MAX_WORKER_THREADS==0
  81420. # define nWorker 0
  81421. #else
  81422. int nWorker;
  81423. #endif
  81424. /* Initialize the upper limit on the number of worker threads */
  81425. #if SQLITE_MAX_WORKER_THREADS>0
  81426. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  81427. nWorker = 0;
  81428. }else{
  81429. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  81430. }
  81431. #endif
  81432. /* Do not allow the total number of threads (main thread + all workers)
  81433. ** to exceed the maximum merge count */
  81434. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  81435. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  81436. nWorker = SORTER_MAX_MERGE_COUNT-1;
  81437. }
  81438. #endif
  81439. assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
  81440. assert( pCsr->eCurType==CURTYPE_SORTER );
  81441. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
  81442. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  81443. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  81444. pCsr->uc.pSorter = pSorter;
  81445. if( pSorter==0 ){
  81446. rc = SQLITE_NOMEM_BKPT;
  81447. }else{
  81448. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  81449. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  81450. pKeyInfo->db = 0;
  81451. if( nField && nWorker==0 ){
  81452. pKeyInfo->nXField += (pKeyInfo->nField - nField);
  81453. pKeyInfo->nField = nField;
  81454. }
  81455. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  81456. pSorter->nTask = nWorker + 1;
  81457. pSorter->iPrev = (u8)(nWorker - 1);
  81458. pSorter->bUseThreads = (pSorter->nTask>1);
  81459. pSorter->db = db;
  81460. for(i=0; i<pSorter->nTask; i++){
  81461. SortSubtask *pTask = &pSorter->aTask[i];
  81462. pTask->pSorter = pSorter;
  81463. }
  81464. if( !sqlite3TempInMemory(db) ){
  81465. i64 mxCache; /* Cache size in bytes*/
  81466. u32 szPma = sqlite3GlobalConfig.szPma;
  81467. pSorter->mnPmaSize = szPma * pgsz;
  81468. mxCache = db->aDb[0].pSchema->cache_size;
  81469. if( mxCache<0 ){
  81470. /* A negative cache-size value C indicates that the cache is abs(C)
  81471. ** KiB in size. */
  81472. mxCache = mxCache * -1024;
  81473. }else{
  81474. mxCache = mxCache * pgsz;
  81475. }
  81476. mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
  81477. pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
  81478. /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
  81479. ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
  81480. ** large heap allocations.
  81481. */
  81482. if( sqlite3GlobalConfig.pScratch==0 ){
  81483. assert( pSorter->iMemory==0 );
  81484. pSorter->nMemory = pgsz;
  81485. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  81486. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  81487. }
  81488. }
  81489. if( (pKeyInfo->nField+pKeyInfo->nXField)<13
  81490. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  81491. ){
  81492. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  81493. }
  81494. }
  81495. return rc;
  81496. }
  81497. #undef nWorker /* Defined at the top of this function */
  81498. /*
  81499. ** Free the list of sorted records starting at pRecord.
  81500. */
  81501. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  81502. SorterRecord *p;
  81503. SorterRecord *pNext;
  81504. for(p=pRecord; p; p=pNext){
  81505. pNext = p->u.pNext;
  81506. sqlite3DbFree(db, p);
  81507. }
  81508. }
  81509. /*
  81510. ** Free all resources owned by the object indicated by argument pTask. All
  81511. ** fields of *pTask are zeroed before returning.
  81512. */
  81513. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  81514. sqlite3DbFree(db, pTask->pUnpacked);
  81515. #if SQLITE_MAX_WORKER_THREADS>0
  81516. /* pTask->list.aMemory can only be non-zero if it was handed memory
  81517. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  81518. if( pTask->list.aMemory ){
  81519. sqlite3_free(pTask->list.aMemory);
  81520. }else
  81521. #endif
  81522. {
  81523. assert( pTask->list.aMemory==0 );
  81524. vdbeSorterRecordFree(0, pTask->list.pList);
  81525. }
  81526. if( pTask->file.pFd ){
  81527. sqlite3OsCloseFree(pTask->file.pFd);
  81528. }
  81529. if( pTask->file2.pFd ){
  81530. sqlite3OsCloseFree(pTask->file2.pFd);
  81531. }
  81532. memset(pTask, 0, sizeof(SortSubtask));
  81533. }
  81534. #ifdef SQLITE_DEBUG_SORTER_THREADS
  81535. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  81536. i64 t;
  81537. int iTask = (pTask - pTask->pSorter->aTask);
  81538. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  81539. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  81540. }
  81541. static void vdbeSorterRewindDebug(const char *zEvent){
  81542. i64 t;
  81543. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  81544. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  81545. }
  81546. static void vdbeSorterPopulateDebug(
  81547. SortSubtask *pTask,
  81548. const char *zEvent
  81549. ){
  81550. i64 t;
  81551. int iTask = (pTask - pTask->pSorter->aTask);
  81552. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  81553. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  81554. }
  81555. static void vdbeSorterBlockDebug(
  81556. SortSubtask *pTask,
  81557. int bBlocked,
  81558. const char *zEvent
  81559. ){
  81560. if( bBlocked ){
  81561. i64 t;
  81562. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  81563. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  81564. }
  81565. }
  81566. #else
  81567. # define vdbeSorterWorkDebug(x,y)
  81568. # define vdbeSorterRewindDebug(y)
  81569. # define vdbeSorterPopulateDebug(x,y)
  81570. # define vdbeSorterBlockDebug(x,y,z)
  81571. #endif
  81572. #if SQLITE_MAX_WORKER_THREADS>0
  81573. /*
  81574. ** Join thread pTask->thread.
  81575. */
  81576. static int vdbeSorterJoinThread(SortSubtask *pTask){
  81577. int rc = SQLITE_OK;
  81578. if( pTask->pThread ){
  81579. #ifdef SQLITE_DEBUG_SORTER_THREADS
  81580. int bDone = pTask->bDone;
  81581. #endif
  81582. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  81583. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  81584. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  81585. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  81586. rc = SQLITE_PTR_TO_INT(pRet);
  81587. assert( pTask->bDone==1 );
  81588. pTask->bDone = 0;
  81589. pTask->pThread = 0;
  81590. }
  81591. return rc;
  81592. }
  81593. /*
  81594. ** Launch a background thread to run xTask(pIn).
  81595. */
  81596. static int vdbeSorterCreateThread(
  81597. SortSubtask *pTask, /* Thread will use this task object */
  81598. void *(*xTask)(void*), /* Routine to run in a separate thread */
  81599. void *pIn /* Argument passed into xTask() */
  81600. ){
  81601. assert( pTask->pThread==0 && pTask->bDone==0 );
  81602. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  81603. }
  81604. /*
  81605. ** Join all outstanding threads launched by SorterWrite() to create
  81606. ** level-0 PMAs.
  81607. */
  81608. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  81609. int rc = rcin;
  81610. int i;
  81611. /* This function is always called by the main user thread.
  81612. **
  81613. ** If this function is being called after SorterRewind() has been called,
  81614. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  81615. ** is currently attempt to join one of the other threads. To avoid a race
  81616. ** condition where this thread also attempts to join the same object, join
  81617. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  81618. for(i=pSorter->nTask-1; i>=0; i--){
  81619. SortSubtask *pTask = &pSorter->aTask[i];
  81620. int rc2 = vdbeSorterJoinThread(pTask);
  81621. if( rc==SQLITE_OK ) rc = rc2;
  81622. }
  81623. return rc;
  81624. }
  81625. #else
  81626. # define vdbeSorterJoinAll(x,rcin) (rcin)
  81627. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  81628. #endif
  81629. /*
  81630. ** Allocate a new MergeEngine object capable of handling up to
  81631. ** nReader PmaReader inputs.
  81632. **
  81633. ** nReader is automatically rounded up to the next power of two.
  81634. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  81635. */
  81636. static MergeEngine *vdbeMergeEngineNew(int nReader){
  81637. int N = 2; /* Smallest power of two >= nReader */
  81638. int nByte; /* Total bytes of space to allocate */
  81639. MergeEngine *pNew; /* Pointer to allocated object to return */
  81640. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  81641. while( N<nReader ) N += N;
  81642. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  81643. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  81644. if( pNew ){
  81645. pNew->nTree = N;
  81646. pNew->pTask = 0;
  81647. pNew->aReadr = (PmaReader*)&pNew[1];
  81648. pNew->aTree = (int*)&pNew->aReadr[N];
  81649. }
  81650. return pNew;
  81651. }
  81652. /*
  81653. ** Free the MergeEngine object passed as the only argument.
  81654. */
  81655. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  81656. int i;
  81657. if( pMerger ){
  81658. for(i=0; i<pMerger->nTree; i++){
  81659. vdbePmaReaderClear(&pMerger->aReadr[i]);
  81660. }
  81661. }
  81662. sqlite3_free(pMerger);
  81663. }
  81664. /*
  81665. ** Free all resources associated with the IncrMerger object indicated by
  81666. ** the first argument.
  81667. */
  81668. static void vdbeIncrFree(IncrMerger *pIncr){
  81669. if( pIncr ){
  81670. #if SQLITE_MAX_WORKER_THREADS>0
  81671. if( pIncr->bUseThread ){
  81672. vdbeSorterJoinThread(pIncr->pTask);
  81673. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  81674. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  81675. }
  81676. #endif
  81677. vdbeMergeEngineFree(pIncr->pMerger);
  81678. sqlite3_free(pIncr);
  81679. }
  81680. }
  81681. /*
  81682. ** Reset a sorting cursor back to its original empty state.
  81683. */
  81684. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  81685. int i;
  81686. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  81687. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  81688. #if SQLITE_MAX_WORKER_THREADS>0
  81689. if( pSorter->pReader ){
  81690. vdbePmaReaderClear(pSorter->pReader);
  81691. sqlite3DbFree(db, pSorter->pReader);
  81692. pSorter->pReader = 0;
  81693. }
  81694. #endif
  81695. vdbeMergeEngineFree(pSorter->pMerger);
  81696. pSorter->pMerger = 0;
  81697. for(i=0; i<pSorter->nTask; i++){
  81698. SortSubtask *pTask = &pSorter->aTask[i];
  81699. vdbeSortSubtaskCleanup(db, pTask);
  81700. pTask->pSorter = pSorter;
  81701. }
  81702. if( pSorter->list.aMemory==0 ){
  81703. vdbeSorterRecordFree(0, pSorter->list.pList);
  81704. }
  81705. pSorter->list.pList = 0;
  81706. pSorter->list.szPMA = 0;
  81707. pSorter->bUsePMA = 0;
  81708. pSorter->iMemory = 0;
  81709. pSorter->mxKeysize = 0;
  81710. sqlite3DbFree(db, pSorter->pUnpacked);
  81711. pSorter->pUnpacked = 0;
  81712. }
  81713. /*
  81714. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  81715. */
  81716. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  81717. VdbeSorter *pSorter;
  81718. assert( pCsr->eCurType==CURTYPE_SORTER );
  81719. pSorter = pCsr->uc.pSorter;
  81720. if( pSorter ){
  81721. sqlite3VdbeSorterReset(db, pSorter);
  81722. sqlite3_free(pSorter->list.aMemory);
  81723. sqlite3DbFree(db, pSorter);
  81724. pCsr->uc.pSorter = 0;
  81725. }
  81726. }
  81727. #if SQLITE_MAX_MMAP_SIZE>0
  81728. /*
  81729. ** The first argument is a file-handle open on a temporary file. The file
  81730. ** is guaranteed to be nByte bytes or smaller in size. This function
  81731. ** attempts to extend the file to nByte bytes in size and to ensure that
  81732. ** the VFS has memory mapped it.
  81733. **
  81734. ** Whether or not the file does end up memory mapped of course depends on
  81735. ** the specific VFS implementation.
  81736. */
  81737. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  81738. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  81739. void *p = 0;
  81740. int chunksize = 4*1024;
  81741. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  81742. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  81743. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  81744. sqlite3OsUnfetch(pFd, 0, p);
  81745. }
  81746. }
  81747. #else
  81748. # define vdbeSorterExtendFile(x,y,z)
  81749. #endif
  81750. /*
  81751. ** Allocate space for a file-handle and open a temporary file. If successful,
  81752. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  81753. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  81754. */
  81755. static int vdbeSorterOpenTempFile(
  81756. sqlite3 *db, /* Database handle doing sort */
  81757. i64 nExtend, /* Attempt to extend file to this size */
  81758. sqlite3_file **ppFd
  81759. ){
  81760. int rc;
  81761. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  81762. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  81763. SQLITE_OPEN_TEMP_JOURNAL |
  81764. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  81765. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  81766. );
  81767. if( rc==SQLITE_OK ){
  81768. i64 max = SQLITE_MAX_MMAP_SIZE;
  81769. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  81770. if( nExtend>0 ){
  81771. vdbeSorterExtendFile(db, *ppFd, nExtend);
  81772. }
  81773. }
  81774. return rc;
  81775. }
  81776. /*
  81777. ** If it has not already been allocated, allocate the UnpackedRecord
  81778. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  81779. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  81780. */
  81781. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  81782. if( pTask->pUnpacked==0 ){
  81783. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
  81784. if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
  81785. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
  81786. pTask->pUnpacked->errCode = 0;
  81787. }
  81788. return SQLITE_OK;
  81789. }
  81790. /*
  81791. ** Merge the two sorted lists p1 and p2 into a single list.
  81792. */
  81793. static SorterRecord *vdbeSorterMerge(
  81794. SortSubtask *pTask, /* Calling thread context */
  81795. SorterRecord *p1, /* First list to merge */
  81796. SorterRecord *p2 /* Second list to merge */
  81797. ){
  81798. SorterRecord *pFinal = 0;
  81799. SorterRecord **pp = &pFinal;
  81800. int bCached = 0;
  81801. assert( p1!=0 && p2!=0 );
  81802. for(;;){
  81803. int res;
  81804. res = pTask->xCompare(
  81805. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  81806. );
  81807. if( res<=0 ){
  81808. *pp = p1;
  81809. pp = &p1->u.pNext;
  81810. p1 = p1->u.pNext;
  81811. if( p1==0 ){
  81812. *pp = p2;
  81813. break;
  81814. }
  81815. }else{
  81816. *pp = p2;
  81817. pp = &p2->u.pNext;
  81818. p2 = p2->u.pNext;
  81819. bCached = 0;
  81820. if( p2==0 ){
  81821. *pp = p1;
  81822. break;
  81823. }
  81824. }
  81825. }
  81826. return pFinal;
  81827. }
  81828. /*
  81829. ** Return the SorterCompare function to compare values collected by the
  81830. ** sorter object passed as the only argument.
  81831. */
  81832. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  81833. if( p->typeMask==SORTER_TYPE_INTEGER ){
  81834. return vdbeSorterCompareInt;
  81835. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  81836. return vdbeSorterCompareText;
  81837. }
  81838. return vdbeSorterCompare;
  81839. }
  81840. /*
  81841. ** Sort the linked list of records headed at pTask->pList. Return
  81842. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  81843. ** an error occurs.
  81844. */
  81845. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  81846. int i;
  81847. SorterRecord **aSlot;
  81848. SorterRecord *p;
  81849. int rc;
  81850. rc = vdbeSortAllocUnpacked(pTask);
  81851. if( rc!=SQLITE_OK ) return rc;
  81852. p = pList->pList;
  81853. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  81854. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  81855. if( !aSlot ){
  81856. return SQLITE_NOMEM_BKPT;
  81857. }
  81858. while( p ){
  81859. SorterRecord *pNext;
  81860. if( pList->aMemory ){
  81861. if( (u8*)p==pList->aMemory ){
  81862. pNext = 0;
  81863. }else{
  81864. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  81865. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  81866. }
  81867. }else{
  81868. pNext = p->u.pNext;
  81869. }
  81870. p->u.pNext = 0;
  81871. for(i=0; aSlot[i]; i++){
  81872. p = vdbeSorterMerge(pTask, p, aSlot[i]);
  81873. aSlot[i] = 0;
  81874. }
  81875. aSlot[i] = p;
  81876. p = pNext;
  81877. }
  81878. p = 0;
  81879. for(i=0; i<64; i++){
  81880. if( aSlot[i]==0 ) continue;
  81881. p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
  81882. }
  81883. pList->pList = p;
  81884. sqlite3_free(aSlot);
  81885. assert( pTask->pUnpacked->errCode==SQLITE_OK
  81886. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  81887. );
  81888. return pTask->pUnpacked->errCode;
  81889. }
  81890. /*
  81891. ** Initialize a PMA-writer object.
  81892. */
  81893. static void vdbePmaWriterInit(
  81894. sqlite3_file *pFd, /* File handle to write to */
  81895. PmaWriter *p, /* Object to populate */
  81896. int nBuf, /* Buffer size */
  81897. i64 iStart /* Offset of pFd to begin writing at */
  81898. ){
  81899. memset(p, 0, sizeof(PmaWriter));
  81900. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  81901. if( !p->aBuffer ){
  81902. p->eFWErr = SQLITE_NOMEM_BKPT;
  81903. }else{
  81904. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  81905. p->iWriteOff = iStart - p->iBufStart;
  81906. p->nBuffer = nBuf;
  81907. p->pFd = pFd;
  81908. }
  81909. }
  81910. /*
  81911. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  81912. ** if successful, or an SQLite error code if an error occurs.
  81913. */
  81914. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  81915. int nRem = nData;
  81916. while( nRem>0 && p->eFWErr==0 ){
  81917. int nCopy = nRem;
  81918. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  81919. nCopy = p->nBuffer - p->iBufEnd;
  81920. }
  81921. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  81922. p->iBufEnd += nCopy;
  81923. if( p->iBufEnd==p->nBuffer ){
  81924. p->eFWErr = sqlite3OsWrite(p->pFd,
  81925. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  81926. p->iWriteOff + p->iBufStart
  81927. );
  81928. p->iBufStart = p->iBufEnd = 0;
  81929. p->iWriteOff += p->nBuffer;
  81930. }
  81931. assert( p->iBufEnd<p->nBuffer );
  81932. nRem -= nCopy;
  81933. }
  81934. }
  81935. /*
  81936. ** Flush any buffered data to disk and clean up the PMA-writer object.
  81937. ** The results of using the PMA-writer after this call are undefined.
  81938. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  81939. ** required. Otherwise, return an SQLite error code.
  81940. **
  81941. ** Before returning, set *piEof to the offset immediately following the
  81942. ** last byte written to the file.
  81943. */
  81944. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  81945. int rc;
  81946. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  81947. p->eFWErr = sqlite3OsWrite(p->pFd,
  81948. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  81949. p->iWriteOff + p->iBufStart
  81950. );
  81951. }
  81952. *piEof = (p->iWriteOff + p->iBufEnd);
  81953. sqlite3_free(p->aBuffer);
  81954. rc = p->eFWErr;
  81955. memset(p, 0, sizeof(PmaWriter));
  81956. return rc;
  81957. }
  81958. /*
  81959. ** Write value iVal encoded as a varint to the PMA. Return
  81960. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  81961. */
  81962. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  81963. int nByte;
  81964. u8 aByte[10];
  81965. nByte = sqlite3PutVarint(aByte, iVal);
  81966. vdbePmaWriteBlob(p, aByte, nByte);
  81967. }
  81968. /*
  81969. ** Write the current contents of in-memory linked-list pList to a level-0
  81970. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  81971. ** successful, or an SQLite error code otherwise.
  81972. **
  81973. ** The format of a PMA is:
  81974. **
  81975. ** * A varint. This varint contains the total number of bytes of content
  81976. ** in the PMA (not including the varint itself).
  81977. **
  81978. ** * One or more records packed end-to-end in order of ascending keys.
  81979. ** Each record consists of a varint followed by a blob of data (the
  81980. ** key). The varint is the number of bytes in the blob of data.
  81981. */
  81982. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  81983. sqlite3 *db = pTask->pSorter->db;
  81984. int rc = SQLITE_OK; /* Return code */
  81985. PmaWriter writer; /* Object used to write to the file */
  81986. #ifdef SQLITE_DEBUG
  81987. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  81988. ** This is used by an assert() statement at the end of this function. */
  81989. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  81990. #endif
  81991. vdbeSorterWorkDebug(pTask, "enter");
  81992. memset(&writer, 0, sizeof(PmaWriter));
  81993. assert( pList->szPMA>0 );
  81994. /* If the first temporary PMA file has not been opened, open it now. */
  81995. if( pTask->file.pFd==0 ){
  81996. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  81997. assert( rc!=SQLITE_OK || pTask->file.pFd );
  81998. assert( pTask->file.iEof==0 );
  81999. assert( pTask->nPMA==0 );
  82000. }
  82001. /* Try to get the file to memory map */
  82002. if( rc==SQLITE_OK ){
  82003. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  82004. }
  82005. /* Sort the list */
  82006. if( rc==SQLITE_OK ){
  82007. rc = vdbeSorterSort(pTask, pList);
  82008. }
  82009. if( rc==SQLITE_OK ){
  82010. SorterRecord *p;
  82011. SorterRecord *pNext = 0;
  82012. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  82013. pTask->file.iEof);
  82014. pTask->nPMA++;
  82015. vdbePmaWriteVarint(&writer, pList->szPMA);
  82016. for(p=pList->pList; p; p=pNext){
  82017. pNext = p->u.pNext;
  82018. vdbePmaWriteVarint(&writer, p->nVal);
  82019. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  82020. if( pList->aMemory==0 ) sqlite3_free(p);
  82021. }
  82022. pList->pList = p;
  82023. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  82024. }
  82025. vdbeSorterWorkDebug(pTask, "exit");
  82026. assert( rc!=SQLITE_OK || pList->pList==0 );
  82027. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  82028. return rc;
  82029. }
  82030. /*
  82031. ** Advance the MergeEngine to its next entry.
  82032. ** Set *pbEof to true there is no next entry because
  82033. ** the MergeEngine has reached the end of all its inputs.
  82034. **
  82035. ** Return SQLITE_OK if successful or an error code if an error occurs.
  82036. */
  82037. static int vdbeMergeEngineStep(
  82038. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  82039. int *pbEof /* Set TRUE at EOF. Set false for more content */
  82040. ){
  82041. int rc;
  82042. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  82043. SortSubtask *pTask = pMerger->pTask;
  82044. /* Advance the current PmaReader */
  82045. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  82046. /* Update contents of aTree[] */
  82047. if( rc==SQLITE_OK ){
  82048. int i; /* Index of aTree[] to recalculate */
  82049. PmaReader *pReadr1; /* First PmaReader to compare */
  82050. PmaReader *pReadr2; /* Second PmaReader to compare */
  82051. int bCached = 0;
  82052. /* Find the first two PmaReaders to compare. The one that was just
  82053. ** advanced (iPrev) and the one next to it in the array. */
  82054. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  82055. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  82056. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  82057. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  82058. int iRes;
  82059. if( pReadr1->pFd==0 ){
  82060. iRes = +1;
  82061. }else if( pReadr2->pFd==0 ){
  82062. iRes = -1;
  82063. }else{
  82064. iRes = pTask->xCompare(pTask, &bCached,
  82065. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  82066. );
  82067. }
  82068. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  82069. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  82070. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  82071. ** pKey2 to point to the record belonging to pReadr2.
  82072. **
  82073. ** Alternatively, if pReadr2 contains the smaller of the two values,
  82074. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  82075. ** was actually called above, then pTask->pUnpacked now contains
  82076. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  82077. ** vdbeSorterCompare() from decoding pReadr2 again.
  82078. **
  82079. ** If the two values were equal, then the value from the oldest
  82080. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  82081. ** is sorted from oldest to newest, so pReadr1 contains older values
  82082. ** than pReadr2 iff (pReadr1<pReadr2). */
  82083. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  82084. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  82085. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  82086. bCached = 0;
  82087. }else{
  82088. if( pReadr1->pFd ) bCached = 0;
  82089. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  82090. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  82091. }
  82092. }
  82093. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  82094. }
  82095. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  82096. }
  82097. #if SQLITE_MAX_WORKER_THREADS>0
  82098. /*
  82099. ** The main routine for background threads that write level-0 PMAs.
  82100. */
  82101. static void *vdbeSorterFlushThread(void *pCtx){
  82102. SortSubtask *pTask = (SortSubtask*)pCtx;
  82103. int rc; /* Return code */
  82104. assert( pTask->bDone==0 );
  82105. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  82106. pTask->bDone = 1;
  82107. return SQLITE_INT_TO_PTR(rc);
  82108. }
  82109. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  82110. /*
  82111. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  82112. ** using a background thread.
  82113. */
  82114. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  82115. #if SQLITE_MAX_WORKER_THREADS==0
  82116. pSorter->bUsePMA = 1;
  82117. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  82118. #else
  82119. int rc = SQLITE_OK;
  82120. int i;
  82121. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  82122. int nWorker = (pSorter->nTask-1);
  82123. /* Set the flag to indicate that at least one PMA has been written.
  82124. ** Or will be, anyhow. */
  82125. pSorter->bUsePMA = 1;
  82126. /* Select a sub-task to sort and flush the current list of in-memory
  82127. ** records to disk. If the sorter is running in multi-threaded mode,
  82128. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  82129. ** the background thread from a sub-tasks previous turn is still running,
  82130. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  82131. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  82132. ** sub-tasks are prefered as they use background threads - the final
  82133. ** sub-task uses the main thread. */
  82134. for(i=0; i<nWorker; i++){
  82135. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  82136. pTask = &pSorter->aTask[iTest];
  82137. if( pTask->bDone ){
  82138. rc = vdbeSorterJoinThread(pTask);
  82139. }
  82140. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  82141. }
  82142. if( rc==SQLITE_OK ){
  82143. if( i==nWorker ){
  82144. /* Use the foreground thread for this operation */
  82145. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  82146. }else{
  82147. /* Launch a background thread for this operation */
  82148. u8 *aMem = pTask->list.aMemory;
  82149. void *pCtx = (void*)pTask;
  82150. assert( pTask->pThread==0 && pTask->bDone==0 );
  82151. assert( pTask->list.pList==0 );
  82152. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  82153. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  82154. pTask->list = pSorter->list;
  82155. pSorter->list.pList = 0;
  82156. pSorter->list.szPMA = 0;
  82157. if( aMem ){
  82158. pSorter->list.aMemory = aMem;
  82159. pSorter->nMemory = sqlite3MallocSize(aMem);
  82160. }else if( pSorter->list.aMemory ){
  82161. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  82162. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  82163. }
  82164. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  82165. }
  82166. }
  82167. return rc;
  82168. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  82169. }
  82170. /*
  82171. ** Add a record to the sorter.
  82172. */
  82173. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  82174. const VdbeCursor *pCsr, /* Sorter cursor */
  82175. Mem *pVal /* Memory cell containing record */
  82176. ){
  82177. VdbeSorter *pSorter;
  82178. int rc = SQLITE_OK; /* Return Code */
  82179. SorterRecord *pNew; /* New list element */
  82180. int bFlush; /* True to flush contents of memory to PMA */
  82181. int nReq; /* Bytes of memory required */
  82182. int nPMA; /* Bytes of PMA space required */
  82183. int t; /* serial type of first record field */
  82184. assert( pCsr->eCurType==CURTYPE_SORTER );
  82185. pSorter = pCsr->uc.pSorter;
  82186. getVarint32((const u8*)&pVal->z[1], t);
  82187. if( t>0 && t<10 && t!=7 ){
  82188. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  82189. }else if( t>10 && (t & 0x01) ){
  82190. pSorter->typeMask &= SORTER_TYPE_TEXT;
  82191. }else{
  82192. pSorter->typeMask = 0;
  82193. }
  82194. assert( pSorter );
  82195. /* Figure out whether or not the current contents of memory should be
  82196. ** flushed to a PMA before continuing. If so, do so.
  82197. **
  82198. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  82199. ** flush the contents of memory to a new PMA if (a) at least one value is
  82200. ** already in memory and (b) the new value will not fit in memory.
  82201. **
  82202. ** Or, if using separate allocations for each record, flush the contents
  82203. ** of memory to a PMA if either of the following are true:
  82204. **
  82205. ** * The total memory allocated for the in-memory list is greater
  82206. ** than (page-size * cache-size), or
  82207. **
  82208. ** * The total memory allocated for the in-memory list is greater
  82209. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  82210. */
  82211. nReq = pVal->n + sizeof(SorterRecord);
  82212. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  82213. if( pSorter->mxPmaSize ){
  82214. if( pSorter->list.aMemory ){
  82215. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  82216. }else{
  82217. bFlush = (
  82218. (pSorter->list.szPMA > pSorter->mxPmaSize)
  82219. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  82220. );
  82221. }
  82222. if( bFlush ){
  82223. rc = vdbeSorterFlushPMA(pSorter);
  82224. pSorter->list.szPMA = 0;
  82225. pSorter->iMemory = 0;
  82226. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  82227. }
  82228. }
  82229. pSorter->list.szPMA += nPMA;
  82230. if( nPMA>pSorter->mxKeysize ){
  82231. pSorter->mxKeysize = nPMA;
  82232. }
  82233. if( pSorter->list.aMemory ){
  82234. int nMin = pSorter->iMemory + nReq;
  82235. if( nMin>pSorter->nMemory ){
  82236. u8 *aNew;
  82237. int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  82238. int nNew = pSorter->nMemory * 2;
  82239. while( nNew < nMin ) nNew = nNew*2;
  82240. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  82241. if( nNew < nMin ) nNew = nMin;
  82242. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  82243. if( !aNew ) return SQLITE_NOMEM_BKPT;
  82244. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  82245. pSorter->list.aMemory = aNew;
  82246. pSorter->nMemory = nNew;
  82247. }
  82248. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  82249. pSorter->iMemory += ROUND8(nReq);
  82250. if( pSorter->list.pList ){
  82251. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  82252. }
  82253. }else{
  82254. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  82255. if( pNew==0 ){
  82256. return SQLITE_NOMEM_BKPT;
  82257. }
  82258. pNew->u.pNext = pSorter->list.pList;
  82259. }
  82260. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  82261. pNew->nVal = pVal->n;
  82262. pSorter->list.pList = pNew;
  82263. return rc;
  82264. }
  82265. /*
  82266. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  82267. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  82268. ** except that the number-of-bytes varint is omitted from the start.
  82269. */
  82270. static int vdbeIncrPopulate(IncrMerger *pIncr){
  82271. int rc = SQLITE_OK;
  82272. int rc2;
  82273. i64 iStart = pIncr->iStartOff;
  82274. SorterFile *pOut = &pIncr->aFile[1];
  82275. SortSubtask *pTask = pIncr->pTask;
  82276. MergeEngine *pMerger = pIncr->pMerger;
  82277. PmaWriter writer;
  82278. assert( pIncr->bEof==0 );
  82279. vdbeSorterPopulateDebug(pTask, "enter");
  82280. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  82281. while( rc==SQLITE_OK ){
  82282. int dummy;
  82283. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  82284. int nKey = pReader->nKey;
  82285. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  82286. /* Check if the output file is full or if the input has been exhausted.
  82287. ** In either case exit the loop. */
  82288. if( pReader->pFd==0 ) break;
  82289. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  82290. /* Write the next key to the output. */
  82291. vdbePmaWriteVarint(&writer, nKey);
  82292. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  82293. assert( pIncr->pMerger->pTask==pTask );
  82294. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  82295. }
  82296. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  82297. if( rc==SQLITE_OK ) rc = rc2;
  82298. vdbeSorterPopulateDebug(pTask, "exit");
  82299. return rc;
  82300. }
  82301. #if SQLITE_MAX_WORKER_THREADS>0
  82302. /*
  82303. ** The main routine for background threads that populate aFile[1] of
  82304. ** multi-threaded IncrMerger objects.
  82305. */
  82306. static void *vdbeIncrPopulateThread(void *pCtx){
  82307. IncrMerger *pIncr = (IncrMerger*)pCtx;
  82308. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  82309. pIncr->pTask->bDone = 1;
  82310. return pRet;
  82311. }
  82312. /*
  82313. ** Launch a background thread to populate aFile[1] of pIncr.
  82314. */
  82315. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  82316. void *p = (void*)pIncr;
  82317. assert( pIncr->bUseThread );
  82318. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  82319. }
  82320. #endif
  82321. /*
  82322. ** This function is called when the PmaReader corresponding to pIncr has
  82323. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  82324. ** aFile[0] such that the PmaReader should start rereading it from the
  82325. ** beginning.
  82326. **
  82327. ** For single-threaded objects, this is accomplished by literally reading
  82328. ** keys from pIncr->pMerger and repopulating aFile[0].
  82329. **
  82330. ** For multi-threaded objects, all that is required is to wait until the
  82331. ** background thread is finished (if it is not already) and then swap
  82332. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  82333. ** been exhausted, this function also launches a new background thread
  82334. ** to populate the new aFile[1].
  82335. **
  82336. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  82337. */
  82338. static int vdbeIncrSwap(IncrMerger *pIncr){
  82339. int rc = SQLITE_OK;
  82340. #if SQLITE_MAX_WORKER_THREADS>0
  82341. if( pIncr->bUseThread ){
  82342. rc = vdbeSorterJoinThread(pIncr->pTask);
  82343. if( rc==SQLITE_OK ){
  82344. SorterFile f0 = pIncr->aFile[0];
  82345. pIncr->aFile[0] = pIncr->aFile[1];
  82346. pIncr->aFile[1] = f0;
  82347. }
  82348. if( rc==SQLITE_OK ){
  82349. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  82350. pIncr->bEof = 1;
  82351. }else{
  82352. rc = vdbeIncrBgPopulate(pIncr);
  82353. }
  82354. }
  82355. }else
  82356. #endif
  82357. {
  82358. rc = vdbeIncrPopulate(pIncr);
  82359. pIncr->aFile[0] = pIncr->aFile[1];
  82360. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  82361. pIncr->bEof = 1;
  82362. }
  82363. }
  82364. return rc;
  82365. }
  82366. /*
  82367. ** Allocate and return a new IncrMerger object to read data from pMerger.
  82368. **
  82369. ** If an OOM condition is encountered, return NULL. In this case free the
  82370. ** pMerger argument before returning.
  82371. */
  82372. static int vdbeIncrMergerNew(
  82373. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  82374. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  82375. IncrMerger **ppOut /* Write the new IncrMerger here */
  82376. ){
  82377. int rc = SQLITE_OK;
  82378. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  82379. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  82380. if( pIncr ){
  82381. pIncr->pMerger = pMerger;
  82382. pIncr->pTask = pTask;
  82383. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  82384. pTask->file2.iEof += pIncr->mxSz;
  82385. }else{
  82386. vdbeMergeEngineFree(pMerger);
  82387. rc = SQLITE_NOMEM_BKPT;
  82388. }
  82389. return rc;
  82390. }
  82391. #if SQLITE_MAX_WORKER_THREADS>0
  82392. /*
  82393. ** Set the "use-threads" flag on object pIncr.
  82394. */
  82395. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  82396. pIncr->bUseThread = 1;
  82397. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  82398. }
  82399. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  82400. /*
  82401. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  82402. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  82403. ** are advanced. This routine merely does the comparison.
  82404. */
  82405. static void vdbeMergeEngineCompare(
  82406. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  82407. int iOut /* Store the result in pMerger->aTree[iOut] */
  82408. ){
  82409. int i1;
  82410. int i2;
  82411. int iRes;
  82412. PmaReader *p1;
  82413. PmaReader *p2;
  82414. assert( iOut<pMerger->nTree && iOut>0 );
  82415. if( iOut>=(pMerger->nTree/2) ){
  82416. i1 = (iOut - pMerger->nTree/2) * 2;
  82417. i2 = i1 + 1;
  82418. }else{
  82419. i1 = pMerger->aTree[iOut*2];
  82420. i2 = pMerger->aTree[iOut*2+1];
  82421. }
  82422. p1 = &pMerger->aReadr[i1];
  82423. p2 = &pMerger->aReadr[i2];
  82424. if( p1->pFd==0 ){
  82425. iRes = i2;
  82426. }else if( p2->pFd==0 ){
  82427. iRes = i1;
  82428. }else{
  82429. SortSubtask *pTask = pMerger->pTask;
  82430. int bCached = 0;
  82431. int res;
  82432. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  82433. res = pTask->xCompare(
  82434. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  82435. );
  82436. if( res<=0 ){
  82437. iRes = i1;
  82438. }else{
  82439. iRes = i2;
  82440. }
  82441. }
  82442. pMerger->aTree[iOut] = iRes;
  82443. }
  82444. /*
  82445. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  82446. ** and vdbePmaReaderIncrMergeInit().
  82447. **
  82448. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  82449. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  82450. ** when there exists one or more separate worker threads.
  82451. */
  82452. #define INCRINIT_NORMAL 0
  82453. #define INCRINIT_TASK 1
  82454. #define INCRINIT_ROOT 2
  82455. /*
  82456. ** Forward reference required as the vdbeIncrMergeInit() and
  82457. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  82458. ** building a merge tree.
  82459. */
  82460. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  82461. /*
  82462. ** Initialize the MergeEngine object passed as the second argument. Once this
  82463. ** function returns, the first key of merged data may be read from the
  82464. ** MergeEngine object in the usual fashion.
  82465. **
  82466. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  82467. ** objects attached to the PmaReader objects that the merger reads from have
  82468. ** already been populated, but that they have not yet populated aFile[0] and
  82469. ** set the PmaReader objects up to read from it. In this case all that is
  82470. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  82471. ** its first key.
  82472. **
  82473. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  82474. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  82475. ** to pMerger.
  82476. **
  82477. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  82478. */
  82479. static int vdbeMergeEngineInit(
  82480. SortSubtask *pTask, /* Thread that will run pMerger */
  82481. MergeEngine *pMerger, /* MergeEngine to initialize */
  82482. int eMode /* One of the INCRINIT_XXX constants */
  82483. ){
  82484. int rc = SQLITE_OK; /* Return code */
  82485. int i; /* For looping over PmaReader objects */
  82486. int nTree = pMerger->nTree;
  82487. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  82488. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  82489. /* Verify that the MergeEngine is assigned to a single thread */
  82490. assert( pMerger->pTask==0 );
  82491. pMerger->pTask = pTask;
  82492. for(i=0; i<nTree; i++){
  82493. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  82494. /* PmaReaders should be normally initialized in order, as if they are
  82495. ** reading from the same temp file this makes for more linear file IO.
  82496. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  82497. ** in use it will block the vdbePmaReaderNext() call while it uses
  82498. ** the main thread to fill its buffer. So calling PmaReaderNext()
  82499. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  82500. ** better advantage of multi-processor hardware. */
  82501. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  82502. }else{
  82503. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  82504. }
  82505. if( rc!=SQLITE_OK ) return rc;
  82506. }
  82507. for(i=pMerger->nTree-1; i>0; i--){
  82508. vdbeMergeEngineCompare(pMerger, i);
  82509. }
  82510. return pTask->pUnpacked->errCode;
  82511. }
  82512. /*
  82513. ** The PmaReader passed as the first argument is guaranteed to be an
  82514. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  82515. ** and/or initialize the temp file related fields of the IncrMerge
  82516. ** object at (pReadr->pIncr).
  82517. **
  82518. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  82519. ** in the sub-tree headed by pReadr are also initialized. Data is then
  82520. ** loaded into the buffers belonging to pReadr and it is set to point to
  82521. ** the first key in its range.
  82522. **
  82523. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  82524. ** to be a multi-threaded PmaReader and this function is being called in a
  82525. ** background thread. In this case all PmaReaders in the sub-tree are
  82526. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  82527. ** pReadr is populated. However, pReadr itself is not set up to point
  82528. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  82529. ** that.
  82530. **
  82531. ** The reason this function does not call vdbePmaReaderNext() immediately
  82532. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  82533. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  82534. ** this entire function is being run by thread (pTask->thread), that will
  82535. ** lead to the current background thread attempting to join itself.
  82536. **
  82537. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  82538. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  82539. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  82540. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  82541. ** the current PmaReader set to point to the first key in its range.
  82542. **
  82543. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  82544. */
  82545. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  82546. int rc = SQLITE_OK;
  82547. IncrMerger *pIncr = pReadr->pIncr;
  82548. SortSubtask *pTask = pIncr->pTask;
  82549. sqlite3 *db = pTask->pSorter->db;
  82550. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  82551. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  82552. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  82553. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  82554. ** requires two temp files to itself, whereas a single-threaded object
  82555. ** only requires a region of pTask->file2. */
  82556. if( rc==SQLITE_OK ){
  82557. int mxSz = pIncr->mxSz;
  82558. #if SQLITE_MAX_WORKER_THREADS>0
  82559. if( pIncr->bUseThread ){
  82560. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  82561. if( rc==SQLITE_OK ){
  82562. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  82563. }
  82564. }else
  82565. #endif
  82566. /*if( !pIncr->bUseThread )*/{
  82567. if( pTask->file2.pFd==0 ){
  82568. assert( pTask->file2.iEof>0 );
  82569. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  82570. pTask->file2.iEof = 0;
  82571. }
  82572. if( rc==SQLITE_OK ){
  82573. pIncr->aFile[1].pFd = pTask->file2.pFd;
  82574. pIncr->iStartOff = pTask->file2.iEof;
  82575. pTask->file2.iEof += mxSz;
  82576. }
  82577. }
  82578. }
  82579. #if SQLITE_MAX_WORKER_THREADS>0
  82580. if( rc==SQLITE_OK && pIncr->bUseThread ){
  82581. /* Use the current thread to populate aFile[1], even though this
  82582. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  82583. ** then this function is already running in background thread
  82584. ** pIncr->pTask->thread.
  82585. **
  82586. ** If this is the INCRINIT_ROOT object, then it is running in the
  82587. ** main VDBE thread. But that is Ok, as that thread cannot return
  82588. ** control to the VDBE or proceed with anything useful until the
  82589. ** first results are ready from this merger object anyway.
  82590. */
  82591. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  82592. rc = vdbeIncrPopulate(pIncr);
  82593. }
  82594. #endif
  82595. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  82596. rc = vdbePmaReaderNext(pReadr);
  82597. }
  82598. return rc;
  82599. }
  82600. #if SQLITE_MAX_WORKER_THREADS>0
  82601. /*
  82602. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  82603. ** background threads.
  82604. */
  82605. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  82606. PmaReader *pReader = (PmaReader*)pCtx;
  82607. void *pRet = SQLITE_INT_TO_PTR(
  82608. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  82609. );
  82610. pReader->pIncr->pTask->bDone = 1;
  82611. return pRet;
  82612. }
  82613. #endif
  82614. /*
  82615. ** If the PmaReader passed as the first argument is not an incremental-reader
  82616. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  82617. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  82618. ** this routine to initialize the incremental merge.
  82619. **
  82620. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  82621. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  82622. ** Or, if the IncrMerger is single threaded, the same function is called
  82623. ** using the current thread.
  82624. */
  82625. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  82626. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  82627. int rc = SQLITE_OK; /* Return code */
  82628. if( pIncr ){
  82629. #if SQLITE_MAX_WORKER_THREADS>0
  82630. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  82631. if( pIncr->bUseThread ){
  82632. void *pCtx = (void*)pReadr;
  82633. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  82634. }else
  82635. #endif
  82636. {
  82637. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  82638. }
  82639. }
  82640. return rc;
  82641. }
  82642. /*
  82643. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  82644. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  82645. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  82646. ** to NULL and return an SQLite error code.
  82647. **
  82648. ** When this function is called, *piOffset is set to the offset of the
  82649. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  82650. ** set to the offset immediately following the last byte of the last
  82651. ** PMA before returning. If an error does occur, then the final value of
  82652. ** *piOffset is undefined.
  82653. */
  82654. static int vdbeMergeEngineLevel0(
  82655. SortSubtask *pTask, /* Sorter task to read from */
  82656. int nPMA, /* Number of PMAs to read */
  82657. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  82658. MergeEngine **ppOut /* OUT: New merge-engine */
  82659. ){
  82660. MergeEngine *pNew; /* Merge engine to return */
  82661. i64 iOff = *piOffset;
  82662. int i;
  82663. int rc = SQLITE_OK;
  82664. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  82665. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  82666. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  82667. i64 nDummy = 0;
  82668. PmaReader *pReadr = &pNew->aReadr[i];
  82669. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  82670. iOff = pReadr->iEof;
  82671. }
  82672. if( rc!=SQLITE_OK ){
  82673. vdbeMergeEngineFree(pNew);
  82674. *ppOut = 0;
  82675. }
  82676. *piOffset = iOff;
  82677. return rc;
  82678. }
  82679. /*
  82680. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  82681. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  82682. **
  82683. ** i.e.
  82684. **
  82685. ** nPMA<=16 -> TreeDepth() == 0
  82686. ** nPMA<=256 -> TreeDepth() == 1
  82687. ** nPMA<=65536 -> TreeDepth() == 2
  82688. */
  82689. static int vdbeSorterTreeDepth(int nPMA){
  82690. int nDepth = 0;
  82691. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  82692. while( nDiv < (i64)nPMA ){
  82693. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  82694. nDepth++;
  82695. }
  82696. return nDepth;
  82697. }
  82698. /*
  82699. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  82700. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  82701. ** tree, counting from zero. This function adds pLeaf to the tree.
  82702. **
  82703. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  82704. ** code is returned and pLeaf is freed.
  82705. */
  82706. static int vdbeSorterAddToTree(
  82707. SortSubtask *pTask, /* Task context */
  82708. int nDepth, /* Depth of tree according to TreeDepth() */
  82709. int iSeq, /* Sequence number of leaf within tree */
  82710. MergeEngine *pRoot, /* Root of tree */
  82711. MergeEngine *pLeaf /* Leaf to add to tree */
  82712. ){
  82713. int rc = SQLITE_OK;
  82714. int nDiv = 1;
  82715. int i;
  82716. MergeEngine *p = pRoot;
  82717. IncrMerger *pIncr;
  82718. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  82719. for(i=1; i<nDepth; i++){
  82720. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  82721. }
  82722. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  82723. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  82724. PmaReader *pReadr = &p->aReadr[iIter];
  82725. if( pReadr->pIncr==0 ){
  82726. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  82727. if( pNew==0 ){
  82728. rc = SQLITE_NOMEM_BKPT;
  82729. }else{
  82730. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  82731. }
  82732. }
  82733. if( rc==SQLITE_OK ){
  82734. p = pReadr->pIncr->pMerger;
  82735. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  82736. }
  82737. }
  82738. if( rc==SQLITE_OK ){
  82739. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  82740. }else{
  82741. vdbeIncrFree(pIncr);
  82742. }
  82743. return rc;
  82744. }
  82745. /*
  82746. ** This function is called as part of a SorterRewind() operation on a sorter
  82747. ** that has already written two or more level-0 PMAs to one or more temp
  82748. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  82749. ** can be used to incrementally merge all PMAs on disk.
  82750. **
  82751. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  82752. ** MergeEngine object at the root of the tree before returning. Or, if an
  82753. ** error occurs, an SQLite error code is returned and the final value
  82754. ** of *ppOut is undefined.
  82755. */
  82756. static int vdbeSorterMergeTreeBuild(
  82757. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  82758. MergeEngine **ppOut /* Write the MergeEngine here */
  82759. ){
  82760. MergeEngine *pMain = 0;
  82761. int rc = SQLITE_OK;
  82762. int iTask;
  82763. #if SQLITE_MAX_WORKER_THREADS>0
  82764. /* If the sorter uses more than one task, then create the top-level
  82765. ** MergeEngine here. This MergeEngine will read data from exactly
  82766. ** one PmaReader per sub-task. */
  82767. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  82768. if( pSorter->nTask>1 ){
  82769. pMain = vdbeMergeEngineNew(pSorter->nTask);
  82770. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  82771. }
  82772. #endif
  82773. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  82774. SortSubtask *pTask = &pSorter->aTask[iTask];
  82775. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  82776. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  82777. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  82778. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  82779. i64 iReadOff = 0;
  82780. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  82781. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  82782. }else{
  82783. int i;
  82784. int iSeq = 0;
  82785. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  82786. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  82787. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  82788. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  82789. int nReader; /* Number of level-0 PMAs to merge */
  82790. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  82791. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  82792. if( rc==SQLITE_OK ){
  82793. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  82794. }
  82795. }
  82796. }
  82797. if( rc==SQLITE_OK ){
  82798. #if SQLITE_MAX_WORKER_THREADS>0
  82799. if( pMain!=0 ){
  82800. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  82801. }else
  82802. #endif
  82803. {
  82804. assert( pMain==0 );
  82805. pMain = pRoot;
  82806. }
  82807. }else{
  82808. vdbeMergeEngineFree(pRoot);
  82809. }
  82810. }
  82811. }
  82812. if( rc!=SQLITE_OK ){
  82813. vdbeMergeEngineFree(pMain);
  82814. pMain = 0;
  82815. }
  82816. *ppOut = pMain;
  82817. return rc;
  82818. }
  82819. /*
  82820. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  82821. ** on a sorter that has written two or more PMAs to temporary files. It sets
  82822. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  82823. ** (for multi-threaded sorters) so that it can be used to iterate through
  82824. ** all records stored in the sorter.
  82825. **
  82826. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  82827. */
  82828. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  82829. int rc; /* Return code */
  82830. SortSubtask *pTask0 = &pSorter->aTask[0];
  82831. MergeEngine *pMain = 0;
  82832. #if SQLITE_MAX_WORKER_THREADS
  82833. sqlite3 *db = pTask0->pSorter->db;
  82834. int i;
  82835. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  82836. for(i=0; i<pSorter->nTask; i++){
  82837. pSorter->aTask[i].xCompare = xCompare;
  82838. }
  82839. #endif
  82840. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  82841. if( rc==SQLITE_OK ){
  82842. #if SQLITE_MAX_WORKER_THREADS
  82843. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  82844. if( pSorter->bUseThreads ){
  82845. int iTask;
  82846. PmaReader *pReadr = 0;
  82847. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  82848. rc = vdbeSortAllocUnpacked(pLast);
  82849. if( rc==SQLITE_OK ){
  82850. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  82851. pSorter->pReader = pReadr;
  82852. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  82853. }
  82854. if( rc==SQLITE_OK ){
  82855. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  82856. if( rc==SQLITE_OK ){
  82857. vdbeIncrMergerSetThreads(pReadr->pIncr);
  82858. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  82859. IncrMerger *pIncr;
  82860. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  82861. vdbeIncrMergerSetThreads(pIncr);
  82862. assert( pIncr->pTask!=pLast );
  82863. }
  82864. }
  82865. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  82866. /* Check that:
  82867. **
  82868. ** a) The incremental merge object is configured to use the
  82869. ** right task, and
  82870. ** b) If it is using task (nTask-1), it is configured to run
  82871. ** in single-threaded mode. This is important, as the
  82872. ** root merge (INCRINIT_ROOT) will be using the same task
  82873. ** object.
  82874. */
  82875. PmaReader *p = &pMain->aReadr[iTask];
  82876. assert( p->pIncr==0 || (
  82877. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  82878. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  82879. ));
  82880. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  82881. }
  82882. }
  82883. pMain = 0;
  82884. }
  82885. if( rc==SQLITE_OK ){
  82886. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  82887. }
  82888. }else
  82889. #endif
  82890. {
  82891. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  82892. pSorter->pMerger = pMain;
  82893. pMain = 0;
  82894. }
  82895. }
  82896. if( rc!=SQLITE_OK ){
  82897. vdbeMergeEngineFree(pMain);
  82898. }
  82899. return rc;
  82900. }
  82901. /*
  82902. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  82903. ** this function is called to prepare for iterating through the records
  82904. ** in sorted order.
  82905. */
  82906. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  82907. VdbeSorter *pSorter;
  82908. int rc = SQLITE_OK; /* Return code */
  82909. assert( pCsr->eCurType==CURTYPE_SORTER );
  82910. pSorter = pCsr->uc.pSorter;
  82911. assert( pSorter );
  82912. /* If no data has been written to disk, then do not do so now. Instead,
  82913. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  82914. ** from the in-memory list. */
  82915. if( pSorter->bUsePMA==0 ){
  82916. if( pSorter->list.pList ){
  82917. *pbEof = 0;
  82918. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  82919. }else{
  82920. *pbEof = 1;
  82921. }
  82922. return rc;
  82923. }
  82924. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  82925. ** function flushes the contents of memory to disk, it immediately always
  82926. ** creates a new list consisting of a single key immediately afterwards.
  82927. ** So the list is never empty at this point. */
  82928. assert( pSorter->list.pList );
  82929. rc = vdbeSorterFlushPMA(pSorter);
  82930. /* Join all threads */
  82931. rc = vdbeSorterJoinAll(pSorter, rc);
  82932. vdbeSorterRewindDebug("rewind");
  82933. /* Assuming no errors have occurred, set up a merger structure to
  82934. ** incrementally read and merge all remaining PMAs. */
  82935. assert( pSorter->pReader==0 );
  82936. if( rc==SQLITE_OK ){
  82937. rc = vdbeSorterSetupMerge(pSorter);
  82938. *pbEof = 0;
  82939. }
  82940. vdbeSorterRewindDebug("rewinddone");
  82941. return rc;
  82942. }
  82943. /*
  82944. ** Advance to the next element in the sorter.
  82945. */
  82946. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  82947. VdbeSorter *pSorter;
  82948. int rc; /* Return code */
  82949. assert( pCsr->eCurType==CURTYPE_SORTER );
  82950. pSorter = pCsr->uc.pSorter;
  82951. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  82952. if( pSorter->bUsePMA ){
  82953. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  82954. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  82955. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  82956. #if SQLITE_MAX_WORKER_THREADS>0
  82957. if( pSorter->bUseThreads ){
  82958. rc = vdbePmaReaderNext(pSorter->pReader);
  82959. *pbEof = (pSorter->pReader->pFd==0);
  82960. }else
  82961. #endif
  82962. /*if( !pSorter->bUseThreads )*/ {
  82963. assert( pSorter->pMerger!=0 );
  82964. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  82965. rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
  82966. }
  82967. }else{
  82968. SorterRecord *pFree = pSorter->list.pList;
  82969. pSorter->list.pList = pFree->u.pNext;
  82970. pFree->u.pNext = 0;
  82971. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  82972. *pbEof = !pSorter->list.pList;
  82973. rc = SQLITE_OK;
  82974. }
  82975. return rc;
  82976. }
  82977. /*
  82978. ** Return a pointer to a buffer owned by the sorter that contains the
  82979. ** current key.
  82980. */
  82981. static void *vdbeSorterRowkey(
  82982. const VdbeSorter *pSorter, /* Sorter object */
  82983. int *pnKey /* OUT: Size of current key in bytes */
  82984. ){
  82985. void *pKey;
  82986. if( pSorter->bUsePMA ){
  82987. PmaReader *pReader;
  82988. #if SQLITE_MAX_WORKER_THREADS>0
  82989. if( pSorter->bUseThreads ){
  82990. pReader = pSorter->pReader;
  82991. }else
  82992. #endif
  82993. /*if( !pSorter->bUseThreads )*/{
  82994. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  82995. }
  82996. *pnKey = pReader->nKey;
  82997. pKey = pReader->aKey;
  82998. }else{
  82999. *pnKey = pSorter->list.pList->nVal;
  83000. pKey = SRVAL(pSorter->list.pList);
  83001. }
  83002. return pKey;
  83003. }
  83004. /*
  83005. ** Copy the current sorter key into the memory cell pOut.
  83006. */
  83007. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  83008. VdbeSorter *pSorter;
  83009. void *pKey; int nKey; /* Sorter key to copy into pOut */
  83010. assert( pCsr->eCurType==CURTYPE_SORTER );
  83011. pSorter = pCsr->uc.pSorter;
  83012. pKey = vdbeSorterRowkey(pSorter, &nKey);
  83013. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  83014. return SQLITE_NOMEM_BKPT;
  83015. }
  83016. pOut->n = nKey;
  83017. MemSetTypeFlag(pOut, MEM_Blob);
  83018. memcpy(pOut->z, pKey, nKey);
  83019. return SQLITE_OK;
  83020. }
  83021. /*
  83022. ** Compare the key in memory cell pVal with the key that the sorter cursor
  83023. ** passed as the first argument currently points to. For the purposes of
  83024. ** the comparison, ignore the rowid field at the end of each record.
  83025. **
  83026. ** If the sorter cursor key contains any NULL values, consider it to be
  83027. ** less than pVal. Even if pVal also contains NULL values.
  83028. **
  83029. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  83030. ** Otherwise, set *pRes to a negative, zero or positive value if the
  83031. ** key in pVal is smaller than, equal to or larger than the current sorter
  83032. ** key.
  83033. **
  83034. ** This routine forms the core of the OP_SorterCompare opcode, which in
  83035. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  83036. */
  83037. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  83038. const VdbeCursor *pCsr, /* Sorter cursor */
  83039. Mem *pVal, /* Value to compare to current sorter key */
  83040. int nKeyCol, /* Compare this many columns */
  83041. int *pRes /* OUT: Result of comparison */
  83042. ){
  83043. VdbeSorter *pSorter;
  83044. UnpackedRecord *r2;
  83045. KeyInfo *pKeyInfo;
  83046. int i;
  83047. void *pKey; int nKey; /* Sorter key to compare pVal with */
  83048. assert( pCsr->eCurType==CURTYPE_SORTER );
  83049. pSorter = pCsr->uc.pSorter;
  83050. r2 = pSorter->pUnpacked;
  83051. pKeyInfo = pCsr->pKeyInfo;
  83052. if( r2==0 ){
  83053. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  83054. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  83055. r2->nField = nKeyCol;
  83056. }
  83057. assert( r2->nField==nKeyCol );
  83058. pKey = vdbeSorterRowkey(pSorter, &nKey);
  83059. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  83060. for(i=0; i<nKeyCol; i++){
  83061. if( r2->aMem[i].flags & MEM_Null ){
  83062. *pRes = -1;
  83063. return SQLITE_OK;
  83064. }
  83065. }
  83066. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  83067. return SQLITE_OK;
  83068. }
  83069. /************** End of vdbesort.c ********************************************/
  83070. /************** Begin file memjournal.c **************************************/
  83071. /*
  83072. ** 2008 October 7
  83073. **
  83074. ** The author disclaims copyright to this source code. In place of
  83075. ** a legal notice, here is a blessing:
  83076. **
  83077. ** May you do good and not evil.
  83078. ** May you find forgiveness for yourself and forgive others.
  83079. ** May you share freely, never taking more than you give.
  83080. **
  83081. *************************************************************************
  83082. **
  83083. ** This file contains code use to implement an in-memory rollback journal.
  83084. ** The in-memory rollback journal is used to journal transactions for
  83085. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  83086. **
  83087. ** Update: The in-memory journal is also used to temporarily cache
  83088. ** smaller journals that are not critical for power-loss recovery.
  83089. ** For example, statement journals that are not too big will be held
  83090. ** entirely in memory, thus reducing the number of file I/O calls, and
  83091. ** more importantly, reducing temporary file creation events. If these
  83092. ** journals become too large for memory, they are spilled to disk. But
  83093. ** in the common case, they are usually small and no file I/O needs to
  83094. ** occur.
  83095. */
  83096. /* #include "sqliteInt.h" */
  83097. /* Forward references to internal structures */
  83098. typedef struct MemJournal MemJournal;
  83099. typedef struct FilePoint FilePoint;
  83100. typedef struct FileChunk FileChunk;
  83101. /*
  83102. ** The rollback journal is composed of a linked list of these structures.
  83103. **
  83104. ** The zChunk array is always at least 8 bytes in size - usually much more.
  83105. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  83106. */
  83107. struct FileChunk {
  83108. FileChunk *pNext; /* Next chunk in the journal */
  83109. u8 zChunk[8]; /* Content of this chunk */
  83110. };
  83111. /*
  83112. ** By default, allocate this many bytes of memory for each FileChunk object.
  83113. */
  83114. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  83115. /*
  83116. ** For chunk size nChunkSize, return the number of bytes that should
  83117. ** be allocated for each FileChunk structure.
  83118. */
  83119. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  83120. /*
  83121. ** An instance of this object serves as a cursor into the rollback journal.
  83122. ** The cursor can be either for reading or writing.
  83123. */
  83124. struct FilePoint {
  83125. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  83126. FileChunk *pChunk; /* Specific chunk into which cursor points */
  83127. };
  83128. /*
  83129. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  83130. ** is an instance of this class.
  83131. */
  83132. struct MemJournal {
  83133. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  83134. int nChunkSize; /* In-memory chunk-size */
  83135. int nSpill; /* Bytes of data before flushing */
  83136. int nSize; /* Bytes of data currently in memory */
  83137. FileChunk *pFirst; /* Head of in-memory chunk-list */
  83138. FilePoint endpoint; /* Pointer to the end of the file */
  83139. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  83140. int flags; /* xOpen flags */
  83141. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  83142. const char *zJournal; /* Name of the journal file */
  83143. };
  83144. /*
  83145. ** Read data from the in-memory journal file. This is the implementation
  83146. ** of the sqlite3_vfs.xRead method.
  83147. */
  83148. static int memjrnlRead(
  83149. sqlite3_file *pJfd, /* The journal file from which to read */
  83150. void *zBuf, /* Put the results here */
  83151. int iAmt, /* Number of bytes to read */
  83152. sqlite_int64 iOfst /* Begin reading at this offset */
  83153. ){
  83154. MemJournal *p = (MemJournal *)pJfd;
  83155. u8 *zOut = zBuf;
  83156. int nRead = iAmt;
  83157. int iChunkOffset;
  83158. FileChunk *pChunk;
  83159. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  83160. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  83161. return SQLITE_IOERR_SHORT_READ;
  83162. }
  83163. #endif
  83164. assert( (iAmt+iOfst)<=p->endpoint.iOffset );
  83165. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  83166. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  83167. sqlite3_int64 iOff = 0;
  83168. for(pChunk=p->pFirst;
  83169. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  83170. pChunk=pChunk->pNext
  83171. ){
  83172. iOff += p->nChunkSize;
  83173. }
  83174. }else{
  83175. pChunk = p->readpoint.pChunk;
  83176. assert( pChunk!=0 );
  83177. }
  83178. iChunkOffset = (int)(iOfst%p->nChunkSize);
  83179. do {
  83180. int iSpace = p->nChunkSize - iChunkOffset;
  83181. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  83182. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  83183. zOut += nCopy;
  83184. nRead -= iSpace;
  83185. iChunkOffset = 0;
  83186. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  83187. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  83188. p->readpoint.pChunk = pChunk;
  83189. return SQLITE_OK;
  83190. }
  83191. /*
  83192. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  83193. */
  83194. static void memjrnlFreeChunks(MemJournal *p){
  83195. FileChunk *pIter;
  83196. FileChunk *pNext;
  83197. for(pIter=p->pFirst; pIter; pIter=pNext){
  83198. pNext = pIter->pNext;
  83199. sqlite3_free(pIter);
  83200. }
  83201. p->pFirst = 0;
  83202. }
  83203. /*
  83204. ** Flush the contents of memory to a real file on disk.
  83205. */
  83206. static int memjrnlCreateFile(MemJournal *p){
  83207. int rc;
  83208. sqlite3_file *pReal = (sqlite3_file*)p;
  83209. MemJournal copy = *p;
  83210. memset(p, 0, sizeof(MemJournal));
  83211. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  83212. if( rc==SQLITE_OK ){
  83213. int nChunk = copy.nChunkSize;
  83214. i64 iOff = 0;
  83215. FileChunk *pIter;
  83216. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  83217. if( iOff + nChunk > copy.endpoint.iOffset ){
  83218. nChunk = copy.endpoint.iOffset - iOff;
  83219. }
  83220. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  83221. if( rc ) break;
  83222. iOff += nChunk;
  83223. }
  83224. if( rc==SQLITE_OK ){
  83225. /* No error has occurred. Free the in-memory buffers. */
  83226. memjrnlFreeChunks(&copy);
  83227. }
  83228. }
  83229. if( rc!=SQLITE_OK ){
  83230. /* If an error occurred while creating or writing to the file, restore
  83231. ** the original before returning. This way, SQLite uses the in-memory
  83232. ** journal data to roll back changes made to the internal page-cache
  83233. ** before this function was called. */
  83234. sqlite3OsClose(pReal);
  83235. *p = copy;
  83236. }
  83237. return rc;
  83238. }
  83239. /*
  83240. ** Write data to the file.
  83241. */
  83242. static int memjrnlWrite(
  83243. sqlite3_file *pJfd, /* The journal file into which to write */
  83244. const void *zBuf, /* Take data to be written from here */
  83245. int iAmt, /* Number of bytes to write */
  83246. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  83247. ){
  83248. MemJournal *p = (MemJournal *)pJfd;
  83249. int nWrite = iAmt;
  83250. u8 *zWrite = (u8 *)zBuf;
  83251. /* If the file should be created now, create it and write the new data
  83252. ** into the file on disk. */
  83253. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  83254. int rc = memjrnlCreateFile(p);
  83255. if( rc==SQLITE_OK ){
  83256. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  83257. }
  83258. return rc;
  83259. }
  83260. /* If the contents of this write should be stored in memory */
  83261. else{
  83262. /* An in-memory journal file should only ever be appended to. Random
  83263. ** access writes are not required. The only exception to this is when
  83264. ** the in-memory journal is being used by a connection using the
  83265. ** atomic-write optimization. In this case the first 28 bytes of the
  83266. ** journal file may be written as part of committing the transaction. */
  83267. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  83268. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  83269. if( iOfst==0 && p->pFirst ){
  83270. assert( p->nChunkSize>iAmt );
  83271. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  83272. }else
  83273. #else
  83274. assert( iOfst>0 || p->pFirst==0 );
  83275. #endif
  83276. {
  83277. while( nWrite>0 ){
  83278. FileChunk *pChunk = p->endpoint.pChunk;
  83279. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  83280. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  83281. if( iChunkOffset==0 ){
  83282. /* New chunk is required to extend the file. */
  83283. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  83284. if( !pNew ){
  83285. return SQLITE_IOERR_NOMEM_BKPT;
  83286. }
  83287. pNew->pNext = 0;
  83288. if( pChunk ){
  83289. assert( p->pFirst );
  83290. pChunk->pNext = pNew;
  83291. }else{
  83292. assert( !p->pFirst );
  83293. p->pFirst = pNew;
  83294. }
  83295. p->endpoint.pChunk = pNew;
  83296. }
  83297. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  83298. zWrite += iSpace;
  83299. nWrite -= iSpace;
  83300. p->endpoint.iOffset += iSpace;
  83301. }
  83302. p->nSize = iAmt + iOfst;
  83303. }
  83304. }
  83305. return SQLITE_OK;
  83306. }
  83307. /*
  83308. ** Truncate the file.
  83309. **
  83310. ** If the journal file is already on disk, truncate it there. Or, if it
  83311. ** is still in main memory but is being truncated to zero bytes in size,
  83312. ** ignore
  83313. */
  83314. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  83315. MemJournal *p = (MemJournal *)pJfd;
  83316. if( ALWAYS(size==0) ){
  83317. memjrnlFreeChunks(p);
  83318. p->nSize = 0;
  83319. p->endpoint.pChunk = 0;
  83320. p->endpoint.iOffset = 0;
  83321. p->readpoint.pChunk = 0;
  83322. p->readpoint.iOffset = 0;
  83323. }
  83324. return SQLITE_OK;
  83325. }
  83326. /*
  83327. ** Close the file.
  83328. */
  83329. static int memjrnlClose(sqlite3_file *pJfd){
  83330. MemJournal *p = (MemJournal *)pJfd;
  83331. memjrnlFreeChunks(p);
  83332. return SQLITE_OK;
  83333. }
  83334. /*
  83335. ** Sync the file.
  83336. **
  83337. ** If the real file has been created, call its xSync method. Otherwise,
  83338. ** syncing an in-memory journal is a no-op.
  83339. */
  83340. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  83341. UNUSED_PARAMETER2(pJfd, flags);
  83342. return SQLITE_OK;
  83343. }
  83344. /*
  83345. ** Query the size of the file in bytes.
  83346. */
  83347. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  83348. MemJournal *p = (MemJournal *)pJfd;
  83349. *pSize = (sqlite_int64) p->endpoint.iOffset;
  83350. return SQLITE_OK;
  83351. }
  83352. /*
  83353. ** Table of methods for MemJournal sqlite3_file object.
  83354. */
  83355. static const struct sqlite3_io_methods MemJournalMethods = {
  83356. 1, /* iVersion */
  83357. memjrnlClose, /* xClose */
  83358. memjrnlRead, /* xRead */
  83359. memjrnlWrite, /* xWrite */
  83360. memjrnlTruncate, /* xTruncate */
  83361. memjrnlSync, /* xSync */
  83362. memjrnlFileSize, /* xFileSize */
  83363. 0, /* xLock */
  83364. 0, /* xUnlock */
  83365. 0, /* xCheckReservedLock */
  83366. 0, /* xFileControl */
  83367. 0, /* xSectorSize */
  83368. 0, /* xDeviceCharacteristics */
  83369. 0, /* xShmMap */
  83370. 0, /* xShmLock */
  83371. 0, /* xShmBarrier */
  83372. 0, /* xShmUnmap */
  83373. 0, /* xFetch */
  83374. 0 /* xUnfetch */
  83375. };
  83376. /*
  83377. ** Open a journal file.
  83378. **
  83379. ** The behaviour of the journal file depends on the value of parameter
  83380. ** nSpill. If nSpill is 0, then the journal file is always create and
  83381. ** accessed using the underlying VFS. If nSpill is less than zero, then
  83382. ** all content is always stored in main-memory. Finally, if nSpill is a
  83383. ** positive value, then the journal file is initially created in-memory
  83384. ** but may be flushed to disk later on. In this case the journal file is
  83385. ** flushed to disk either when it grows larger than nSpill bytes in size,
  83386. ** or when sqlite3JournalCreate() is called.
  83387. */
  83388. SQLITE_PRIVATE int sqlite3JournalOpen(
  83389. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  83390. const char *zName, /* Name of the journal file */
  83391. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  83392. int flags, /* Opening flags */
  83393. int nSpill /* Bytes buffered before opening the file */
  83394. ){
  83395. MemJournal *p = (MemJournal*)pJfd;
  83396. /* Zero the file-handle object. If nSpill was passed zero, initialize
  83397. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  83398. ** case none of the code in this module is executed as a result of calls
  83399. ** made on the journal file-handle. */
  83400. memset(p, 0, sizeof(MemJournal));
  83401. if( nSpill==0 ){
  83402. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  83403. }
  83404. if( nSpill>0 ){
  83405. p->nChunkSize = nSpill;
  83406. }else{
  83407. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  83408. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  83409. }
  83410. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  83411. p->nSpill = nSpill;
  83412. p->flags = flags;
  83413. p->zJournal = zName;
  83414. p->pVfs = pVfs;
  83415. return SQLITE_OK;
  83416. }
  83417. /*
  83418. ** Open an in-memory journal file.
  83419. */
  83420. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  83421. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  83422. }
  83423. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  83424. /*
  83425. ** If the argument p points to a MemJournal structure that is not an
  83426. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  83427. ** nSpill parameter), and the underlying file has not yet been created,
  83428. ** create it now.
  83429. */
  83430. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  83431. int rc = SQLITE_OK;
  83432. if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
  83433. rc = memjrnlCreateFile((MemJournal*)p);
  83434. }
  83435. return rc;
  83436. }
  83437. #endif
  83438. /*
  83439. ** The file-handle passed as the only argument is open on a journal file.
  83440. ** Return true if this "journal file" is currently stored in heap memory,
  83441. ** or false otherwise.
  83442. */
  83443. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  83444. return p->pMethods==&MemJournalMethods;
  83445. }
  83446. /*
  83447. ** Return the number of bytes required to store a JournalFile that uses vfs
  83448. ** pVfs to create the underlying on-disk files.
  83449. */
  83450. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  83451. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  83452. }
  83453. /************** End of memjournal.c ******************************************/
  83454. /************** Begin file walker.c ******************************************/
  83455. /*
  83456. ** 2008 August 16
  83457. **
  83458. ** The author disclaims copyright to this source code. In place of
  83459. ** a legal notice, here is a blessing:
  83460. **
  83461. ** May you do good and not evil.
  83462. ** May you find forgiveness for yourself and forgive others.
  83463. ** May you share freely, never taking more than you give.
  83464. **
  83465. *************************************************************************
  83466. ** This file contains routines used for walking the parser tree for
  83467. ** an SQL statement.
  83468. */
  83469. /* #include "sqliteInt.h" */
  83470. /* #include <stdlib.h> */
  83471. /* #include <string.h> */
  83472. /*
  83473. ** Walk an expression tree. Invoke the callback once for each node
  83474. ** of the expression, while descending. (In other words, the callback
  83475. ** is invoked before visiting children.)
  83476. **
  83477. ** The return value from the callback should be one of the WRC_*
  83478. ** constants to specify how to proceed with the walk.
  83479. **
  83480. ** WRC_Continue Continue descending down the tree.
  83481. **
  83482. ** WRC_Prune Do not descend into child nodes, but allow
  83483. ** the walk to continue with sibling nodes.
  83484. **
  83485. ** WRC_Abort Do no more callbacks. Unwind the stack and
  83486. ** return from the top-level walk call.
  83487. **
  83488. ** The return value from this routine is WRC_Abort to abandon the tree walk
  83489. ** and WRC_Continue to continue.
  83490. */
  83491. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  83492. int rc;
  83493. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  83494. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  83495. rc = pWalker->xExprCallback(pWalker, pExpr);
  83496. if( rc || ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
  83497. return rc & WRC_Abort;
  83498. }
  83499. if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  83500. if( pExpr->pRight && walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  83501. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  83502. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  83503. }else if( pExpr->x.pList ){
  83504. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  83505. }
  83506. return WRC_Continue;
  83507. }
  83508. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  83509. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  83510. }
  83511. /*
  83512. ** Call sqlite3WalkExpr() for every expression in list p or until
  83513. ** an abort request is seen.
  83514. */
  83515. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  83516. int i;
  83517. struct ExprList_item *pItem;
  83518. if( p ){
  83519. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  83520. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  83521. }
  83522. }
  83523. return WRC_Continue;
  83524. }
  83525. /*
  83526. ** Walk all expressions associated with SELECT statement p. Do
  83527. ** not invoke the SELECT callback on p, but do (of course) invoke
  83528. ** any expr callbacks and SELECT callbacks that come from subqueries.
  83529. ** Return WRC_Abort or WRC_Continue.
  83530. */
  83531. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  83532. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  83533. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  83534. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  83535. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  83536. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  83537. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  83538. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  83539. return WRC_Continue;
  83540. }
  83541. /*
  83542. ** Walk the parse trees associated with all subqueries in the
  83543. ** FROM clause of SELECT statement p. Do not invoke the select
  83544. ** callback on p, but do invoke it on each FROM clause subquery
  83545. ** and on any subqueries further down in the tree. Return
  83546. ** WRC_Abort or WRC_Continue;
  83547. */
  83548. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  83549. SrcList *pSrc;
  83550. int i;
  83551. struct SrcList_item *pItem;
  83552. pSrc = p->pSrc;
  83553. if( ALWAYS(pSrc) ){
  83554. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  83555. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  83556. return WRC_Abort;
  83557. }
  83558. if( pItem->fg.isTabFunc
  83559. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  83560. ){
  83561. return WRC_Abort;
  83562. }
  83563. }
  83564. }
  83565. return WRC_Continue;
  83566. }
  83567. /*
  83568. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  83569. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  83570. ** on the compound select chain, p->pPrior.
  83571. **
  83572. ** If it is not NULL, the xSelectCallback() callback is invoked before
  83573. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  83574. ** method, if it is not NULL, is invoked following the walk of the
  83575. ** expressions and FROM clause.
  83576. **
  83577. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  83578. ** there is an abort request.
  83579. **
  83580. ** If the Walker does not have an xSelectCallback() then this routine
  83581. ** is a no-op returning WRC_Continue.
  83582. */
  83583. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  83584. int rc;
  83585. if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
  83586. return WRC_Continue;
  83587. }
  83588. rc = WRC_Continue;
  83589. pWalker->walkerDepth++;
  83590. while( p ){
  83591. if( pWalker->xSelectCallback ){
  83592. rc = pWalker->xSelectCallback(pWalker, p);
  83593. if( rc ) break;
  83594. }
  83595. if( sqlite3WalkSelectExpr(pWalker, p)
  83596. || sqlite3WalkSelectFrom(pWalker, p)
  83597. ){
  83598. pWalker->walkerDepth--;
  83599. return WRC_Abort;
  83600. }
  83601. if( pWalker->xSelectCallback2 ){
  83602. pWalker->xSelectCallback2(pWalker, p);
  83603. }
  83604. p = p->pPrior;
  83605. }
  83606. pWalker->walkerDepth--;
  83607. return rc & WRC_Abort;
  83608. }
  83609. /************** End of walker.c **********************************************/
  83610. /************** Begin file resolve.c *****************************************/
  83611. /*
  83612. ** 2008 August 18
  83613. **
  83614. ** The author disclaims copyright to this source code. In place of
  83615. ** a legal notice, here is a blessing:
  83616. **
  83617. ** May you do good and not evil.
  83618. ** May you find forgiveness for yourself and forgive others.
  83619. ** May you share freely, never taking more than you give.
  83620. **
  83621. *************************************************************************
  83622. **
  83623. ** This file contains routines used for walking the parser tree and
  83624. ** resolve all identifiers by associating them with a particular
  83625. ** table and column.
  83626. */
  83627. /* #include "sqliteInt.h" */
  83628. /*
  83629. ** Walk the expression tree pExpr and increase the aggregate function
  83630. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  83631. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  83632. ** outer query into an inner subquery.
  83633. **
  83634. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  83635. ** is a helper function - a callback for the tree walker.
  83636. */
  83637. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  83638. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  83639. return WRC_Continue;
  83640. }
  83641. static void incrAggFunctionDepth(Expr *pExpr, int N){
  83642. if( N>0 ){
  83643. Walker w;
  83644. memset(&w, 0, sizeof(w));
  83645. w.xExprCallback = incrAggDepth;
  83646. w.u.n = N;
  83647. sqlite3WalkExpr(&w, pExpr);
  83648. }
  83649. }
  83650. /*
  83651. ** Turn the pExpr expression into an alias for the iCol-th column of the
  83652. ** result set in pEList.
  83653. **
  83654. ** If the reference is followed by a COLLATE operator, then make sure
  83655. ** the COLLATE operator is preserved. For example:
  83656. **
  83657. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  83658. **
  83659. ** Should be transformed into:
  83660. **
  83661. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  83662. **
  83663. ** The nSubquery parameter specifies how many levels of subquery the
  83664. ** alias is removed from the original expression. The usual value is
  83665. ** zero but it might be more if the alias is contained within a subquery
  83666. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  83667. ** structures must be increased by the nSubquery amount.
  83668. */
  83669. static void resolveAlias(
  83670. Parse *pParse, /* Parsing context */
  83671. ExprList *pEList, /* A result set */
  83672. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  83673. Expr *pExpr, /* Transform this into an alias to the result set */
  83674. const char *zType, /* "GROUP" or "ORDER" or "" */
  83675. int nSubquery /* Number of subqueries that the label is moving */
  83676. ){
  83677. Expr *pOrig; /* The iCol-th column of the result set */
  83678. Expr *pDup; /* Copy of pOrig */
  83679. sqlite3 *db; /* The database connection */
  83680. assert( iCol>=0 && iCol<pEList->nExpr );
  83681. pOrig = pEList->a[iCol].pExpr;
  83682. assert( pOrig!=0 );
  83683. db = pParse->db;
  83684. pDup = sqlite3ExprDup(db, pOrig, 0);
  83685. if( pDup==0 ) return;
  83686. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  83687. if( pExpr->op==TK_COLLATE ){
  83688. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  83689. }
  83690. ExprSetProperty(pDup, EP_Alias);
  83691. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  83692. ** prevents ExprDelete() from deleting the Expr structure itself,
  83693. ** allowing it to be repopulated by the memcpy() on the following line.
  83694. ** The pExpr->u.zToken might point into memory that will be freed by the
  83695. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  83696. ** make a copy of the token before doing the sqlite3DbFree().
  83697. */
  83698. ExprSetProperty(pExpr, EP_Static);
  83699. sqlite3ExprDelete(db, pExpr);
  83700. memcpy(pExpr, pDup, sizeof(*pExpr));
  83701. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  83702. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  83703. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  83704. pExpr->flags |= EP_MemToken;
  83705. }
  83706. sqlite3DbFree(db, pDup);
  83707. }
  83708. /*
  83709. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  83710. **
  83711. ** Return FALSE if the USING clause is NULL or if it does not contain
  83712. ** zCol.
  83713. */
  83714. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  83715. if( pUsing ){
  83716. int k;
  83717. for(k=0; k<pUsing->nId; k++){
  83718. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  83719. }
  83720. }
  83721. return 0;
  83722. }
  83723. /*
  83724. ** Subqueries stores the original database, table and column names for their
  83725. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  83726. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  83727. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  83728. ** match anything.
  83729. */
  83730. SQLITE_PRIVATE int sqlite3MatchSpanName(
  83731. const char *zSpan,
  83732. const char *zCol,
  83733. const char *zTab,
  83734. const char *zDb
  83735. ){
  83736. int n;
  83737. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  83738. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  83739. return 0;
  83740. }
  83741. zSpan += n+1;
  83742. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  83743. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  83744. return 0;
  83745. }
  83746. zSpan += n+1;
  83747. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  83748. return 0;
  83749. }
  83750. return 1;
  83751. }
  83752. /*
  83753. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  83754. ** that name in the set of source tables in pSrcList and make the pExpr
  83755. ** expression node refer back to that source column. The following changes
  83756. ** are made to pExpr:
  83757. **
  83758. ** pExpr->iDb Set the index in db->aDb[] of the database X
  83759. ** (even if X is implied).
  83760. ** pExpr->iTable Set to the cursor number for the table obtained
  83761. ** from pSrcList.
  83762. ** pExpr->pTab Points to the Table structure of X.Y (even if
  83763. ** X and/or Y are implied.)
  83764. ** pExpr->iColumn Set to the column number within the table.
  83765. ** pExpr->op Set to TK_COLUMN.
  83766. ** pExpr->pLeft Any expression this points to is deleted
  83767. ** pExpr->pRight Any expression this points to is deleted.
  83768. **
  83769. ** The zDb variable is the name of the database (the "X"). This value may be
  83770. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  83771. ** can be used. The zTable variable is the name of the table (the "Y"). This
  83772. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  83773. ** means that the form of the name is Z and that columns from any table
  83774. ** can be used.
  83775. **
  83776. ** If the name cannot be resolved unambiguously, leave an error message
  83777. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  83778. */
  83779. static int lookupName(
  83780. Parse *pParse, /* The parsing context */
  83781. const char *zDb, /* Name of the database containing table, or NULL */
  83782. const char *zTab, /* Name of table containing column, or NULL */
  83783. const char *zCol, /* Name of the column. */
  83784. NameContext *pNC, /* The name context used to resolve the name */
  83785. Expr *pExpr /* Make this EXPR node point to the selected column */
  83786. ){
  83787. int i, j; /* Loop counters */
  83788. int cnt = 0; /* Number of matching column names */
  83789. int cntTab = 0; /* Number of matching table names */
  83790. int nSubquery = 0; /* How many levels of subquery */
  83791. sqlite3 *db = pParse->db; /* The database connection */
  83792. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  83793. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  83794. NameContext *pTopNC = pNC; /* First namecontext in the list */
  83795. Schema *pSchema = 0; /* Schema of the expression */
  83796. int isTrigger = 0; /* True if resolved to a trigger column */
  83797. Table *pTab = 0; /* Table hold the row */
  83798. Column *pCol; /* A column of pTab */
  83799. assert( pNC ); /* the name context cannot be NULL. */
  83800. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  83801. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  83802. /* Initialize the node to no-match */
  83803. pExpr->iTable = -1;
  83804. pExpr->pTab = 0;
  83805. ExprSetVVAProperty(pExpr, EP_NoReduce);
  83806. /* Translate the schema name in zDb into a pointer to the corresponding
  83807. ** schema. If not found, pSchema will remain NULL and nothing will match
  83808. ** resulting in an appropriate error message toward the end of this routine
  83809. */
  83810. if( zDb ){
  83811. testcase( pNC->ncFlags & NC_PartIdx );
  83812. testcase( pNC->ncFlags & NC_IsCheck );
  83813. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  83814. /* Silently ignore database qualifiers inside CHECK constraints and
  83815. ** partial indices. Do not raise errors because that might break
  83816. ** legacy and because it does not hurt anything to just ignore the
  83817. ** database name. */
  83818. zDb = 0;
  83819. }else{
  83820. for(i=0; i<db->nDb; i++){
  83821. assert( db->aDb[i].zDbSName );
  83822. if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
  83823. pSchema = db->aDb[i].pSchema;
  83824. break;
  83825. }
  83826. }
  83827. }
  83828. }
  83829. /* Start at the inner-most context and move outward until a match is found */
  83830. assert( pNC && cnt==0 );
  83831. do{
  83832. ExprList *pEList;
  83833. SrcList *pSrcList = pNC->pSrcList;
  83834. if( pSrcList ){
  83835. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  83836. pTab = pItem->pTab;
  83837. assert( pTab!=0 && pTab->zName!=0 );
  83838. assert( pTab->nCol>0 );
  83839. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  83840. int hit = 0;
  83841. pEList = pItem->pSelect->pEList;
  83842. for(j=0; j<pEList->nExpr; j++){
  83843. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  83844. cnt++;
  83845. cntTab = 2;
  83846. pMatch = pItem;
  83847. pExpr->iColumn = j;
  83848. hit = 1;
  83849. }
  83850. }
  83851. if( hit || zTab==0 ) continue;
  83852. }
  83853. if( zDb && pTab->pSchema!=pSchema ){
  83854. continue;
  83855. }
  83856. if( zTab ){
  83857. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  83858. assert( zTabName!=0 );
  83859. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  83860. continue;
  83861. }
  83862. }
  83863. if( 0==(cntTab++) ){
  83864. pMatch = pItem;
  83865. }
  83866. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  83867. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  83868. /* If there has been exactly one prior match and this match
  83869. ** is for the right-hand table of a NATURAL JOIN or is in a
  83870. ** USING clause, then skip this match.
  83871. */
  83872. if( cnt==1 ){
  83873. if( pItem->fg.jointype & JT_NATURAL ) continue;
  83874. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  83875. }
  83876. cnt++;
  83877. pMatch = pItem;
  83878. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  83879. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  83880. break;
  83881. }
  83882. }
  83883. }
  83884. if( pMatch ){
  83885. pExpr->iTable = pMatch->iCursor;
  83886. pExpr->pTab = pMatch->pTab;
  83887. /* RIGHT JOIN not (yet) supported */
  83888. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  83889. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  83890. ExprSetProperty(pExpr, EP_CanBeNull);
  83891. }
  83892. pSchema = pExpr->pTab->pSchema;
  83893. }
  83894. } /* if( pSrcList ) */
  83895. #ifndef SQLITE_OMIT_TRIGGER
  83896. /* If we have not already resolved the name, then maybe
  83897. ** it is a new.* or old.* trigger argument reference
  83898. */
  83899. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  83900. int op = pParse->eTriggerOp;
  83901. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  83902. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  83903. pExpr->iTable = 1;
  83904. pTab = pParse->pTriggerTab;
  83905. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  83906. pExpr->iTable = 0;
  83907. pTab = pParse->pTriggerTab;
  83908. }else{
  83909. pTab = 0;
  83910. }
  83911. if( pTab ){
  83912. int iCol;
  83913. pSchema = pTab->pSchema;
  83914. cntTab++;
  83915. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  83916. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  83917. if( iCol==pTab->iPKey ){
  83918. iCol = -1;
  83919. }
  83920. break;
  83921. }
  83922. }
  83923. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  83924. /* IMP: R-51414-32910 */
  83925. iCol = -1;
  83926. }
  83927. if( iCol<pTab->nCol ){
  83928. cnt++;
  83929. if( iCol<0 ){
  83930. pExpr->affinity = SQLITE_AFF_INTEGER;
  83931. }else if( pExpr->iTable==0 ){
  83932. testcase( iCol==31 );
  83933. testcase( iCol==32 );
  83934. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  83935. }else{
  83936. testcase( iCol==31 );
  83937. testcase( iCol==32 );
  83938. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  83939. }
  83940. pExpr->iColumn = (i16)iCol;
  83941. pExpr->pTab = pTab;
  83942. isTrigger = 1;
  83943. }
  83944. }
  83945. }
  83946. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  83947. /*
  83948. ** Perhaps the name is a reference to the ROWID
  83949. */
  83950. if( cnt==0
  83951. && cntTab==1
  83952. && pMatch
  83953. && (pNC->ncFlags & NC_IdxExpr)==0
  83954. && sqlite3IsRowid(zCol)
  83955. && VisibleRowid(pMatch->pTab)
  83956. ){
  83957. cnt = 1;
  83958. pExpr->iColumn = -1;
  83959. pExpr->affinity = SQLITE_AFF_INTEGER;
  83960. }
  83961. /*
  83962. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  83963. ** might refer to an result-set alias. This happens, for example, when
  83964. ** we are resolving names in the WHERE clause of the following command:
  83965. **
  83966. ** SELECT a+b AS x FROM table WHERE x<10;
  83967. **
  83968. ** In cases like this, replace pExpr with a copy of the expression that
  83969. ** forms the result set entry ("a+b" in the example) and return immediately.
  83970. ** Note that the expression in the result set should have already been
  83971. ** resolved by the time the WHERE clause is resolved.
  83972. **
  83973. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  83974. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  83975. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  83976. ** is supported for backwards compatibility only. Hence, we issue a warning
  83977. ** on sqlite3_log() whenever the capability is used.
  83978. */
  83979. if( (pEList = pNC->pEList)!=0
  83980. && zTab==0
  83981. && cnt==0
  83982. ){
  83983. for(j=0; j<pEList->nExpr; j++){
  83984. char *zAs = pEList->a[j].zName;
  83985. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  83986. Expr *pOrig;
  83987. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  83988. assert( pExpr->x.pList==0 );
  83989. assert( pExpr->x.pSelect==0 );
  83990. pOrig = pEList->a[j].pExpr;
  83991. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  83992. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  83993. return WRC_Abort;
  83994. }
  83995. if( sqlite3ExprVectorSize(pOrig)!=1 ){
  83996. sqlite3ErrorMsg(pParse, "row value misused");
  83997. return WRC_Abort;
  83998. }
  83999. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  84000. cnt = 1;
  84001. pMatch = 0;
  84002. assert( zTab==0 && zDb==0 );
  84003. goto lookupname_end;
  84004. }
  84005. }
  84006. }
  84007. /* Advance to the next name context. The loop will exit when either
  84008. ** we have a match (cnt>0) or when we run out of name contexts.
  84009. */
  84010. if( cnt ) break;
  84011. pNC = pNC->pNext;
  84012. nSubquery++;
  84013. }while( pNC );
  84014. /*
  84015. ** If X and Y are NULL (in other words if only the column name Z is
  84016. ** supplied) and the value of Z is enclosed in double-quotes, then
  84017. ** Z is a string literal if it doesn't match any column names. In that
  84018. ** case, we need to return right away and not make any changes to
  84019. ** pExpr.
  84020. **
  84021. ** Because no reference was made to outer contexts, the pNC->nRef
  84022. ** fields are not changed in any context.
  84023. */
  84024. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  84025. pExpr->op = TK_STRING;
  84026. pExpr->pTab = 0;
  84027. return WRC_Prune;
  84028. }
  84029. /*
  84030. ** cnt==0 means there was not match. cnt>1 means there were two or
  84031. ** more matches. Either way, we have an error.
  84032. */
  84033. if( cnt!=1 ){
  84034. const char *zErr;
  84035. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  84036. if( zDb ){
  84037. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  84038. }else if( zTab ){
  84039. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  84040. }else{
  84041. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  84042. }
  84043. pParse->checkSchema = 1;
  84044. pTopNC->nErr++;
  84045. }
  84046. /* If a column from a table in pSrcList is referenced, then record
  84047. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  84048. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  84049. ** column number is greater than the number of bits in the bitmask
  84050. ** then set the high-order bit of the bitmask.
  84051. */
  84052. if( pExpr->iColumn>=0 && pMatch!=0 ){
  84053. int n = pExpr->iColumn;
  84054. testcase( n==BMS-1 );
  84055. if( n>=BMS ){
  84056. n = BMS-1;
  84057. }
  84058. assert( pMatch->iCursor==pExpr->iTable );
  84059. pMatch->colUsed |= ((Bitmask)1)<<n;
  84060. }
  84061. /* Clean up and return
  84062. */
  84063. sqlite3ExprDelete(db, pExpr->pLeft);
  84064. pExpr->pLeft = 0;
  84065. sqlite3ExprDelete(db, pExpr->pRight);
  84066. pExpr->pRight = 0;
  84067. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  84068. lookupname_end:
  84069. if( cnt==1 ){
  84070. assert( pNC!=0 );
  84071. if( !ExprHasProperty(pExpr, EP_Alias) ){
  84072. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  84073. }
  84074. /* Increment the nRef value on all name contexts from TopNC up to
  84075. ** the point where the name matched. */
  84076. for(;;){
  84077. assert( pTopNC!=0 );
  84078. pTopNC->nRef++;
  84079. if( pTopNC==pNC ) break;
  84080. pTopNC = pTopNC->pNext;
  84081. }
  84082. return WRC_Prune;
  84083. } else {
  84084. return WRC_Abort;
  84085. }
  84086. }
  84087. /*
  84088. ** Allocate and return a pointer to an expression to load the column iCol
  84089. ** from datasource iSrc in SrcList pSrc.
  84090. */
  84091. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  84092. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  84093. if( p ){
  84094. struct SrcList_item *pItem = &pSrc->a[iSrc];
  84095. p->pTab = pItem->pTab;
  84096. p->iTable = pItem->iCursor;
  84097. if( p->pTab->iPKey==iCol ){
  84098. p->iColumn = -1;
  84099. }else{
  84100. p->iColumn = (ynVar)iCol;
  84101. testcase( iCol==BMS );
  84102. testcase( iCol==BMS-1 );
  84103. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  84104. }
  84105. ExprSetProperty(p, EP_Resolved);
  84106. }
  84107. return p;
  84108. }
  84109. /*
  84110. ** Report an error that an expression is not valid for some set of
  84111. ** pNC->ncFlags values determined by validMask.
  84112. */
  84113. static void notValid(
  84114. Parse *pParse, /* Leave error message here */
  84115. NameContext *pNC, /* The name context */
  84116. const char *zMsg, /* Type of error */
  84117. int validMask /* Set of contexts for which prohibited */
  84118. ){
  84119. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  84120. if( (pNC->ncFlags & validMask)!=0 ){
  84121. const char *zIn = "partial index WHERE clauses";
  84122. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  84123. #ifndef SQLITE_OMIT_CHECK
  84124. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  84125. #endif
  84126. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  84127. }
  84128. }
  84129. /*
  84130. ** Expression p should encode a floating point value between 1.0 and 0.0.
  84131. ** Return 1024 times this value. Or return -1 if p is not a floating point
  84132. ** value between 1.0 and 0.0.
  84133. */
  84134. static int exprProbability(Expr *p){
  84135. double r = -1.0;
  84136. if( p->op!=TK_FLOAT ) return -1;
  84137. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  84138. assert( r>=0.0 );
  84139. if( r>1.0 ) return -1;
  84140. return (int)(r*134217728.0);
  84141. }
  84142. /*
  84143. ** This routine is callback for sqlite3WalkExpr().
  84144. **
  84145. ** Resolve symbolic names into TK_COLUMN operators for the current
  84146. ** node in the expression tree. Return 0 to continue the search down
  84147. ** the tree or 2 to abort the tree walk.
  84148. **
  84149. ** This routine also does error checking and name resolution for
  84150. ** function names. The operator for aggregate functions is changed
  84151. ** to TK_AGG_FUNCTION.
  84152. */
  84153. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  84154. NameContext *pNC;
  84155. Parse *pParse;
  84156. pNC = pWalker->u.pNC;
  84157. assert( pNC!=0 );
  84158. pParse = pNC->pParse;
  84159. assert( pParse==pWalker->pParse );
  84160. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  84161. ExprSetProperty(pExpr, EP_Resolved);
  84162. #ifndef NDEBUG
  84163. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  84164. SrcList *pSrcList = pNC->pSrcList;
  84165. int i;
  84166. for(i=0; i<pNC->pSrcList->nSrc; i++){
  84167. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  84168. }
  84169. }
  84170. #endif
  84171. switch( pExpr->op ){
  84172. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  84173. /* The special operator TK_ROW means use the rowid for the first
  84174. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  84175. ** clause processing on UPDATE and DELETE statements.
  84176. */
  84177. case TK_ROW: {
  84178. SrcList *pSrcList = pNC->pSrcList;
  84179. struct SrcList_item *pItem;
  84180. assert( pSrcList && pSrcList->nSrc==1 );
  84181. pItem = pSrcList->a;
  84182. pExpr->op = TK_COLUMN;
  84183. pExpr->pTab = pItem->pTab;
  84184. pExpr->iTable = pItem->iCursor;
  84185. pExpr->iColumn = -1;
  84186. pExpr->affinity = SQLITE_AFF_INTEGER;
  84187. break;
  84188. }
  84189. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  84190. && !defined(SQLITE_OMIT_SUBQUERY) */
  84191. /* A column name: ID
  84192. ** Or table name and column name: ID.ID
  84193. ** Or a database, table and column: ID.ID.ID
  84194. **
  84195. ** The TK_ID and TK_OUT cases are combined so that there will only
  84196. ** be one call to lookupName(). Then the compiler will in-line
  84197. ** lookupName() for a size reduction and performance increase.
  84198. */
  84199. case TK_ID:
  84200. case TK_DOT: {
  84201. const char *zColumn;
  84202. const char *zTable;
  84203. const char *zDb;
  84204. Expr *pRight;
  84205. if( pExpr->op==TK_ID ){
  84206. zDb = 0;
  84207. zTable = 0;
  84208. zColumn = pExpr->u.zToken;
  84209. }else{
  84210. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  84211. pRight = pExpr->pRight;
  84212. if( pRight->op==TK_ID ){
  84213. zDb = 0;
  84214. zTable = pExpr->pLeft->u.zToken;
  84215. zColumn = pRight->u.zToken;
  84216. }else{
  84217. assert( pRight->op==TK_DOT );
  84218. zDb = pExpr->pLeft->u.zToken;
  84219. zTable = pRight->pLeft->u.zToken;
  84220. zColumn = pRight->pRight->u.zToken;
  84221. }
  84222. }
  84223. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  84224. }
  84225. /* Resolve function names
  84226. */
  84227. case TK_FUNCTION: {
  84228. ExprList *pList = pExpr->x.pList; /* The argument list */
  84229. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  84230. int no_such_func = 0; /* True if no such function exists */
  84231. int wrong_num_args = 0; /* True if wrong number of arguments */
  84232. int is_agg = 0; /* True if is an aggregate function */
  84233. int nId; /* Number of characters in function name */
  84234. const char *zId; /* The function name. */
  84235. FuncDef *pDef; /* Information about the function */
  84236. u8 enc = ENC(pParse->db); /* The database encoding */
  84237. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  84238. zId = pExpr->u.zToken;
  84239. nId = sqlite3Strlen30(zId);
  84240. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  84241. if( pDef==0 ){
  84242. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  84243. if( pDef==0 ){
  84244. no_such_func = 1;
  84245. }else{
  84246. wrong_num_args = 1;
  84247. }
  84248. }else{
  84249. is_agg = pDef->xFinalize!=0;
  84250. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  84251. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  84252. if( n==2 ){
  84253. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  84254. if( pExpr->iTable<0 ){
  84255. sqlite3ErrorMsg(pParse,
  84256. "second argument to likelihood() must be a "
  84257. "constant between 0.0 and 1.0");
  84258. pNC->nErr++;
  84259. }
  84260. }else{
  84261. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  84262. ** equivalent to likelihood(X, 0.0625).
  84263. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  84264. ** short-hand for likelihood(X,0.0625).
  84265. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  84266. ** for likelihood(X,0.9375).
  84267. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  84268. ** to likelihood(X,0.9375). */
  84269. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  84270. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  84271. }
  84272. }
  84273. #ifndef SQLITE_OMIT_AUTHORIZATION
  84274. {
  84275. int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
  84276. if( auth!=SQLITE_OK ){
  84277. if( auth==SQLITE_DENY ){
  84278. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  84279. pDef->zName);
  84280. pNC->nErr++;
  84281. }
  84282. pExpr->op = TK_NULL;
  84283. return WRC_Prune;
  84284. }
  84285. }
  84286. #endif
  84287. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  84288. /* For the purposes of the EP_ConstFunc flag, date and time
  84289. ** functions and other functions that change slowly are considered
  84290. ** constant because they are constant for the duration of one query */
  84291. ExprSetProperty(pExpr,EP_ConstFunc);
  84292. }
  84293. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  84294. /* Date/time functions that use 'now', and other functions like
  84295. ** sqlite_version() that might change over time cannot be used
  84296. ** in an index. */
  84297. notValid(pParse, pNC, "non-deterministic functions",
  84298. NC_IdxExpr|NC_PartIdx);
  84299. }
  84300. }
  84301. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  84302. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  84303. pNC->nErr++;
  84304. is_agg = 0;
  84305. }else if( no_such_func && pParse->db->init.busy==0
  84306. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  84307. && pParse->explain==0
  84308. #endif
  84309. ){
  84310. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  84311. pNC->nErr++;
  84312. }else if( wrong_num_args ){
  84313. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  84314. nId, zId);
  84315. pNC->nErr++;
  84316. }
  84317. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  84318. sqlite3WalkExprList(pWalker, pList);
  84319. if( is_agg ){
  84320. NameContext *pNC2 = pNC;
  84321. pExpr->op = TK_AGG_FUNCTION;
  84322. pExpr->op2 = 0;
  84323. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  84324. pExpr->op2++;
  84325. pNC2 = pNC2->pNext;
  84326. }
  84327. assert( pDef!=0 );
  84328. if( pNC2 ){
  84329. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  84330. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  84331. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  84332. }
  84333. pNC->ncFlags |= NC_AllowAgg;
  84334. }
  84335. /* FIX ME: Compute pExpr->affinity based on the expected return
  84336. ** type of the function
  84337. */
  84338. return WRC_Prune;
  84339. }
  84340. #ifndef SQLITE_OMIT_SUBQUERY
  84341. case TK_SELECT:
  84342. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  84343. #endif
  84344. case TK_IN: {
  84345. testcase( pExpr->op==TK_IN );
  84346. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  84347. int nRef = pNC->nRef;
  84348. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  84349. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  84350. assert( pNC->nRef>=nRef );
  84351. if( nRef!=pNC->nRef ){
  84352. ExprSetProperty(pExpr, EP_VarSelect);
  84353. pNC->ncFlags |= NC_VarSelect;
  84354. }
  84355. }
  84356. break;
  84357. }
  84358. case TK_VARIABLE: {
  84359. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  84360. break;
  84361. }
  84362. case TK_BETWEEN:
  84363. case TK_EQ:
  84364. case TK_NE:
  84365. case TK_LT:
  84366. case TK_LE:
  84367. case TK_GT:
  84368. case TK_GE:
  84369. case TK_IS:
  84370. case TK_ISNOT: {
  84371. int nLeft, nRight;
  84372. if( pParse->db->mallocFailed ) break;
  84373. assert( pExpr->pLeft!=0 );
  84374. nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
  84375. if( pExpr->op==TK_BETWEEN ){
  84376. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
  84377. if( nRight==nLeft ){
  84378. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
  84379. }
  84380. }else{
  84381. assert( pExpr->pRight!=0 );
  84382. nRight = sqlite3ExprVectorSize(pExpr->pRight);
  84383. }
  84384. if( nLeft!=nRight ){
  84385. testcase( pExpr->op==TK_EQ );
  84386. testcase( pExpr->op==TK_NE );
  84387. testcase( pExpr->op==TK_LT );
  84388. testcase( pExpr->op==TK_LE );
  84389. testcase( pExpr->op==TK_GT );
  84390. testcase( pExpr->op==TK_GE );
  84391. testcase( pExpr->op==TK_IS );
  84392. testcase( pExpr->op==TK_ISNOT );
  84393. testcase( pExpr->op==TK_BETWEEN );
  84394. sqlite3ErrorMsg(pParse, "row value misused");
  84395. }
  84396. break;
  84397. }
  84398. }
  84399. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  84400. }
  84401. /*
  84402. ** pEList is a list of expressions which are really the result set of the
  84403. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  84404. ** This routine checks to see if pE is a simple identifier which corresponds
  84405. ** to the AS-name of one of the terms of the expression list. If it is,
  84406. ** this routine return an integer between 1 and N where N is the number of
  84407. ** elements in pEList, corresponding to the matching entry. If there is
  84408. ** no match, or if pE is not a simple identifier, then this routine
  84409. ** return 0.
  84410. **
  84411. ** pEList has been resolved. pE has not.
  84412. */
  84413. static int resolveAsName(
  84414. Parse *pParse, /* Parsing context for error messages */
  84415. ExprList *pEList, /* List of expressions to scan */
  84416. Expr *pE /* Expression we are trying to match */
  84417. ){
  84418. int i; /* Loop counter */
  84419. UNUSED_PARAMETER(pParse);
  84420. if( pE->op==TK_ID ){
  84421. char *zCol = pE->u.zToken;
  84422. for(i=0; i<pEList->nExpr; i++){
  84423. char *zAs = pEList->a[i].zName;
  84424. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  84425. return i+1;
  84426. }
  84427. }
  84428. }
  84429. return 0;
  84430. }
  84431. /*
  84432. ** pE is a pointer to an expression which is a single term in the
  84433. ** ORDER BY of a compound SELECT. The expression has not been
  84434. ** name resolved.
  84435. **
  84436. ** At the point this routine is called, we already know that the
  84437. ** ORDER BY term is not an integer index into the result set. That
  84438. ** case is handled by the calling routine.
  84439. **
  84440. ** Attempt to match pE against result set columns in the left-most
  84441. ** SELECT statement. Return the index i of the matching column,
  84442. ** as an indication to the caller that it should sort by the i-th column.
  84443. ** The left-most column is 1. In other words, the value returned is the
  84444. ** same integer value that would be used in the SQL statement to indicate
  84445. ** the column.
  84446. **
  84447. ** If there is no match, return 0. Return -1 if an error occurs.
  84448. */
  84449. static int resolveOrderByTermToExprList(
  84450. Parse *pParse, /* Parsing context for error messages */
  84451. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  84452. Expr *pE /* The specific ORDER BY term */
  84453. ){
  84454. int i; /* Loop counter */
  84455. ExprList *pEList; /* The columns of the result set */
  84456. NameContext nc; /* Name context for resolving pE */
  84457. sqlite3 *db; /* Database connection */
  84458. int rc; /* Return code from subprocedures */
  84459. u8 savedSuppErr; /* Saved value of db->suppressErr */
  84460. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  84461. pEList = pSelect->pEList;
  84462. /* Resolve all names in the ORDER BY term expression
  84463. */
  84464. memset(&nc, 0, sizeof(nc));
  84465. nc.pParse = pParse;
  84466. nc.pSrcList = pSelect->pSrc;
  84467. nc.pEList = pEList;
  84468. nc.ncFlags = NC_AllowAgg;
  84469. nc.nErr = 0;
  84470. db = pParse->db;
  84471. savedSuppErr = db->suppressErr;
  84472. db->suppressErr = 1;
  84473. rc = sqlite3ResolveExprNames(&nc, pE);
  84474. db->suppressErr = savedSuppErr;
  84475. if( rc ) return 0;
  84476. /* Try to match the ORDER BY expression against an expression
  84477. ** in the result set. Return an 1-based index of the matching
  84478. ** result-set entry.
  84479. */
  84480. for(i=0; i<pEList->nExpr; i++){
  84481. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  84482. return i+1;
  84483. }
  84484. }
  84485. /* If no match, return 0. */
  84486. return 0;
  84487. }
  84488. /*
  84489. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  84490. */
  84491. static void resolveOutOfRangeError(
  84492. Parse *pParse, /* The error context into which to write the error */
  84493. const char *zType, /* "ORDER" or "GROUP" */
  84494. int i, /* The index (1-based) of the term out of range */
  84495. int mx /* Largest permissible value of i */
  84496. ){
  84497. sqlite3ErrorMsg(pParse,
  84498. "%r %s BY term out of range - should be "
  84499. "between 1 and %d", i, zType, mx);
  84500. }
  84501. /*
  84502. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  84503. ** each term of the ORDER BY clause is a constant integer between 1
  84504. ** and N where N is the number of columns in the compound SELECT.
  84505. **
  84506. ** ORDER BY terms that are already an integer between 1 and N are
  84507. ** unmodified. ORDER BY terms that are integers outside the range of
  84508. ** 1 through N generate an error. ORDER BY terms that are expressions
  84509. ** are matched against result set expressions of compound SELECT
  84510. ** beginning with the left-most SELECT and working toward the right.
  84511. ** At the first match, the ORDER BY expression is transformed into
  84512. ** the integer column number.
  84513. **
  84514. ** Return the number of errors seen.
  84515. */
  84516. static int resolveCompoundOrderBy(
  84517. Parse *pParse, /* Parsing context. Leave error messages here */
  84518. Select *pSelect /* The SELECT statement containing the ORDER BY */
  84519. ){
  84520. int i;
  84521. ExprList *pOrderBy;
  84522. ExprList *pEList;
  84523. sqlite3 *db;
  84524. int moreToDo = 1;
  84525. pOrderBy = pSelect->pOrderBy;
  84526. if( pOrderBy==0 ) return 0;
  84527. db = pParse->db;
  84528. #if SQLITE_MAX_COLUMN
  84529. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  84530. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  84531. return 1;
  84532. }
  84533. #endif
  84534. for(i=0; i<pOrderBy->nExpr; i++){
  84535. pOrderBy->a[i].done = 0;
  84536. }
  84537. pSelect->pNext = 0;
  84538. while( pSelect->pPrior ){
  84539. pSelect->pPrior->pNext = pSelect;
  84540. pSelect = pSelect->pPrior;
  84541. }
  84542. while( pSelect && moreToDo ){
  84543. struct ExprList_item *pItem;
  84544. moreToDo = 0;
  84545. pEList = pSelect->pEList;
  84546. assert( pEList!=0 );
  84547. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  84548. int iCol = -1;
  84549. Expr *pE, *pDup;
  84550. if( pItem->done ) continue;
  84551. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  84552. if( sqlite3ExprIsInteger(pE, &iCol) ){
  84553. if( iCol<=0 || iCol>pEList->nExpr ){
  84554. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  84555. return 1;
  84556. }
  84557. }else{
  84558. iCol = resolveAsName(pParse, pEList, pE);
  84559. if( iCol==0 ){
  84560. pDup = sqlite3ExprDup(db, pE, 0);
  84561. if( !db->mallocFailed ){
  84562. assert(pDup);
  84563. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  84564. }
  84565. sqlite3ExprDelete(db, pDup);
  84566. }
  84567. }
  84568. if( iCol>0 ){
  84569. /* Convert the ORDER BY term into an integer column number iCol,
  84570. ** taking care to preserve the COLLATE clause if it exists */
  84571. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  84572. if( pNew==0 ) return 1;
  84573. pNew->flags |= EP_IntValue;
  84574. pNew->u.iValue = iCol;
  84575. if( pItem->pExpr==pE ){
  84576. pItem->pExpr = pNew;
  84577. }else{
  84578. Expr *pParent = pItem->pExpr;
  84579. assert( pParent->op==TK_COLLATE );
  84580. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  84581. assert( pParent->pLeft==pE );
  84582. pParent->pLeft = pNew;
  84583. }
  84584. sqlite3ExprDelete(db, pE);
  84585. pItem->u.x.iOrderByCol = (u16)iCol;
  84586. pItem->done = 1;
  84587. }else{
  84588. moreToDo = 1;
  84589. }
  84590. }
  84591. pSelect = pSelect->pNext;
  84592. }
  84593. for(i=0; i<pOrderBy->nExpr; i++){
  84594. if( pOrderBy->a[i].done==0 ){
  84595. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  84596. "column in the result set", i+1);
  84597. return 1;
  84598. }
  84599. }
  84600. return 0;
  84601. }
  84602. /*
  84603. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  84604. ** the SELECT statement pSelect. If any term is reference to a
  84605. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  84606. ** field) then convert that term into a copy of the corresponding result set
  84607. ** column.
  84608. **
  84609. ** If any errors are detected, add an error message to pParse and
  84610. ** return non-zero. Return zero if no errors are seen.
  84611. */
  84612. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  84613. Parse *pParse, /* Parsing context. Leave error messages here */
  84614. Select *pSelect, /* The SELECT statement containing the clause */
  84615. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  84616. const char *zType /* "ORDER" or "GROUP" */
  84617. ){
  84618. int i;
  84619. sqlite3 *db = pParse->db;
  84620. ExprList *pEList;
  84621. struct ExprList_item *pItem;
  84622. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  84623. #if SQLITE_MAX_COLUMN
  84624. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  84625. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  84626. return 1;
  84627. }
  84628. #endif
  84629. pEList = pSelect->pEList;
  84630. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  84631. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  84632. if( pItem->u.x.iOrderByCol ){
  84633. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  84634. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  84635. return 1;
  84636. }
  84637. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  84638. zType,0);
  84639. }
  84640. }
  84641. return 0;
  84642. }
  84643. /*
  84644. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  84645. ** The Name context of the SELECT statement is pNC. zType is either
  84646. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  84647. **
  84648. ** This routine resolves each term of the clause into an expression.
  84649. ** If the order-by term is an integer I between 1 and N (where N is the
  84650. ** number of columns in the result set of the SELECT) then the expression
  84651. ** in the resolution is a copy of the I-th result-set expression. If
  84652. ** the order-by term is an identifier that corresponds to the AS-name of
  84653. ** a result-set expression, then the term resolves to a copy of the
  84654. ** result-set expression. Otherwise, the expression is resolved in
  84655. ** the usual way - using sqlite3ResolveExprNames().
  84656. **
  84657. ** This routine returns the number of errors. If errors occur, then
  84658. ** an appropriate error message might be left in pParse. (OOM errors
  84659. ** excepted.)
  84660. */
  84661. static int resolveOrderGroupBy(
  84662. NameContext *pNC, /* The name context of the SELECT statement */
  84663. Select *pSelect, /* The SELECT statement holding pOrderBy */
  84664. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  84665. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  84666. ){
  84667. int i, j; /* Loop counters */
  84668. int iCol; /* Column number */
  84669. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  84670. Parse *pParse; /* Parsing context */
  84671. int nResult; /* Number of terms in the result set */
  84672. if( pOrderBy==0 ) return 0;
  84673. nResult = pSelect->pEList->nExpr;
  84674. pParse = pNC->pParse;
  84675. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  84676. Expr *pE = pItem->pExpr;
  84677. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  84678. if( zType[0]!='G' ){
  84679. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  84680. if( iCol>0 ){
  84681. /* If an AS-name match is found, mark this ORDER BY column as being
  84682. ** a copy of the iCol-th result-set column. The subsequent call to
  84683. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  84684. ** copy of the iCol-th result-set expression. */
  84685. pItem->u.x.iOrderByCol = (u16)iCol;
  84686. continue;
  84687. }
  84688. }
  84689. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  84690. /* The ORDER BY term is an integer constant. Again, set the column
  84691. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  84692. ** order-by term to a copy of the result-set expression */
  84693. if( iCol<1 || iCol>0xffff ){
  84694. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  84695. return 1;
  84696. }
  84697. pItem->u.x.iOrderByCol = (u16)iCol;
  84698. continue;
  84699. }
  84700. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  84701. pItem->u.x.iOrderByCol = 0;
  84702. if( sqlite3ResolveExprNames(pNC, pE) ){
  84703. return 1;
  84704. }
  84705. for(j=0; j<pSelect->pEList->nExpr; j++){
  84706. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  84707. pItem->u.x.iOrderByCol = j+1;
  84708. }
  84709. }
  84710. }
  84711. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  84712. }
  84713. /*
  84714. ** Resolve names in the SELECT statement p and all of its descendants.
  84715. */
  84716. static int resolveSelectStep(Walker *pWalker, Select *p){
  84717. NameContext *pOuterNC; /* Context that contains this SELECT */
  84718. NameContext sNC; /* Name context of this SELECT */
  84719. int isCompound; /* True if p is a compound select */
  84720. int nCompound; /* Number of compound terms processed so far */
  84721. Parse *pParse; /* Parsing context */
  84722. int i; /* Loop counter */
  84723. ExprList *pGroupBy; /* The GROUP BY clause */
  84724. Select *pLeftmost; /* Left-most of SELECT of a compound */
  84725. sqlite3 *db; /* Database connection */
  84726. assert( p!=0 );
  84727. if( p->selFlags & SF_Resolved ){
  84728. return WRC_Prune;
  84729. }
  84730. pOuterNC = pWalker->u.pNC;
  84731. pParse = pWalker->pParse;
  84732. db = pParse->db;
  84733. /* Normally sqlite3SelectExpand() will be called first and will have
  84734. ** already expanded this SELECT. However, if this is a subquery within
  84735. ** an expression, sqlite3ResolveExprNames() will be called without a
  84736. ** prior call to sqlite3SelectExpand(). When that happens, let
  84737. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  84738. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  84739. ** this routine in the correct order.
  84740. */
  84741. if( (p->selFlags & SF_Expanded)==0 ){
  84742. sqlite3SelectPrep(pParse, p, pOuterNC);
  84743. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  84744. }
  84745. isCompound = p->pPrior!=0;
  84746. nCompound = 0;
  84747. pLeftmost = p;
  84748. while( p ){
  84749. assert( (p->selFlags & SF_Expanded)!=0 );
  84750. assert( (p->selFlags & SF_Resolved)==0 );
  84751. p->selFlags |= SF_Resolved;
  84752. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  84753. ** are not allowed to refer to any names, so pass an empty NameContext.
  84754. */
  84755. memset(&sNC, 0, sizeof(sNC));
  84756. sNC.pParse = pParse;
  84757. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  84758. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  84759. return WRC_Abort;
  84760. }
  84761. /* If the SF_Converted flags is set, then this Select object was
  84762. ** was created by the convertCompoundSelectToSubquery() function.
  84763. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  84764. ** as if it were part of the sub-query, not the parent. This block
  84765. ** moves the pOrderBy down to the sub-query. It will be moved back
  84766. ** after the names have been resolved. */
  84767. if( p->selFlags & SF_Converted ){
  84768. Select *pSub = p->pSrc->a[0].pSelect;
  84769. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  84770. assert( pSub->pPrior && pSub->pOrderBy==0 );
  84771. pSub->pOrderBy = p->pOrderBy;
  84772. p->pOrderBy = 0;
  84773. }
  84774. /* Recursively resolve names in all subqueries
  84775. */
  84776. for(i=0; i<p->pSrc->nSrc; i++){
  84777. struct SrcList_item *pItem = &p->pSrc->a[i];
  84778. if( pItem->pSelect ){
  84779. NameContext *pNC; /* Used to iterate name contexts */
  84780. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  84781. const char *zSavedContext = pParse->zAuthContext;
  84782. /* Count the total number of references to pOuterNC and all of its
  84783. ** parent contexts. After resolving references to expressions in
  84784. ** pItem->pSelect, check if this value has changed. If so, then
  84785. ** SELECT statement pItem->pSelect must be correlated. Set the
  84786. ** pItem->fg.isCorrelated flag if this is the case. */
  84787. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  84788. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  84789. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  84790. pParse->zAuthContext = zSavedContext;
  84791. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  84792. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  84793. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  84794. pItem->fg.isCorrelated = (nRef!=0);
  84795. }
  84796. }
  84797. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  84798. ** resolve the result-set expression list.
  84799. */
  84800. sNC.ncFlags = NC_AllowAgg;
  84801. sNC.pSrcList = p->pSrc;
  84802. sNC.pNext = pOuterNC;
  84803. /* Resolve names in the result set. */
  84804. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  84805. /* If there are no aggregate functions in the result-set, and no GROUP BY
  84806. ** expression, do not allow aggregates in any of the other expressions.
  84807. */
  84808. assert( (p->selFlags & SF_Aggregate)==0 );
  84809. pGroupBy = p->pGroupBy;
  84810. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  84811. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  84812. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  84813. }else{
  84814. sNC.ncFlags &= ~NC_AllowAgg;
  84815. }
  84816. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  84817. */
  84818. if( p->pHaving && !pGroupBy ){
  84819. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  84820. return WRC_Abort;
  84821. }
  84822. /* Add the output column list to the name-context before parsing the
  84823. ** other expressions in the SELECT statement. This is so that
  84824. ** expressions in the WHERE clause (etc.) can refer to expressions by
  84825. ** aliases in the result set.
  84826. **
  84827. ** Minor point: If this is the case, then the expression will be
  84828. ** re-evaluated for each reference to it.
  84829. */
  84830. sNC.pEList = p->pEList;
  84831. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  84832. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  84833. /* Resolve names in table-valued-function arguments */
  84834. for(i=0; i<p->pSrc->nSrc; i++){
  84835. struct SrcList_item *pItem = &p->pSrc->a[i];
  84836. if( pItem->fg.isTabFunc
  84837. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  84838. ){
  84839. return WRC_Abort;
  84840. }
  84841. }
  84842. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  84843. ** outer queries
  84844. */
  84845. sNC.pNext = 0;
  84846. sNC.ncFlags |= NC_AllowAgg;
  84847. /* If this is a converted compound query, move the ORDER BY clause from
  84848. ** the sub-query back to the parent query. At this point each term
  84849. ** within the ORDER BY clause has been transformed to an integer value.
  84850. ** These integers will be replaced by copies of the corresponding result
  84851. ** set expressions by the call to resolveOrderGroupBy() below. */
  84852. if( p->selFlags & SF_Converted ){
  84853. Select *pSub = p->pSrc->a[0].pSelect;
  84854. p->pOrderBy = pSub->pOrderBy;
  84855. pSub->pOrderBy = 0;
  84856. }
  84857. /* Process the ORDER BY clause for singleton SELECT statements.
  84858. ** The ORDER BY clause for compounds SELECT statements is handled
  84859. ** below, after all of the result-sets for all of the elements of
  84860. ** the compound have been resolved.
  84861. **
  84862. ** If there is an ORDER BY clause on a term of a compound-select other
  84863. ** than the right-most term, then that is a syntax error. But the error
  84864. ** is not detected until much later, and so we need to go ahead and
  84865. ** resolve those symbols on the incorrect ORDER BY for consistency.
  84866. */
  84867. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  84868. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  84869. ){
  84870. return WRC_Abort;
  84871. }
  84872. if( db->mallocFailed ){
  84873. return WRC_Abort;
  84874. }
  84875. /* Resolve the GROUP BY clause. At the same time, make sure
  84876. ** the GROUP BY clause does not contain aggregate functions.
  84877. */
  84878. if( pGroupBy ){
  84879. struct ExprList_item *pItem;
  84880. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  84881. return WRC_Abort;
  84882. }
  84883. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  84884. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  84885. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  84886. "the GROUP BY clause");
  84887. return WRC_Abort;
  84888. }
  84889. }
  84890. }
  84891. /* If this is part of a compound SELECT, check that it has the right
  84892. ** number of expressions in the select list. */
  84893. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  84894. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  84895. return WRC_Abort;
  84896. }
  84897. /* Advance to the next term of the compound
  84898. */
  84899. p = p->pPrior;
  84900. nCompound++;
  84901. }
  84902. /* Resolve the ORDER BY on a compound SELECT after all terms of
  84903. ** the compound have been resolved.
  84904. */
  84905. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  84906. return WRC_Abort;
  84907. }
  84908. return WRC_Prune;
  84909. }
  84910. /*
  84911. ** This routine walks an expression tree and resolves references to
  84912. ** table columns and result-set columns. At the same time, do error
  84913. ** checking on function usage and set a flag if any aggregate functions
  84914. ** are seen.
  84915. **
  84916. ** To resolve table columns references we look for nodes (or subtrees) of the
  84917. ** form X.Y.Z or Y.Z or just Z where
  84918. **
  84919. ** X: The name of a database. Ex: "main" or "temp" or
  84920. ** the symbolic name assigned to an ATTACH-ed database.
  84921. **
  84922. ** Y: The name of a table in a FROM clause. Or in a trigger
  84923. ** one of the special names "old" or "new".
  84924. **
  84925. ** Z: The name of a column in table Y.
  84926. **
  84927. ** The node at the root of the subtree is modified as follows:
  84928. **
  84929. ** Expr.op Changed to TK_COLUMN
  84930. ** Expr.pTab Points to the Table object for X.Y
  84931. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  84932. ** Expr.iTable The VDBE cursor number for X.Y
  84933. **
  84934. **
  84935. ** To resolve result-set references, look for expression nodes of the
  84936. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  84937. ** size of an AS clause in the result-set of a SELECT. The Z expression
  84938. ** is replaced by a copy of the left-hand side of the result-set expression.
  84939. ** Table-name and function resolution occurs on the substituted expression
  84940. ** tree. For example, in:
  84941. **
  84942. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  84943. **
  84944. ** The "x" term of the order by is replaced by "a+b" to render:
  84945. **
  84946. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  84947. **
  84948. ** Function calls are checked to make sure that the function is
  84949. ** defined and that the correct number of arguments are specified.
  84950. ** If the function is an aggregate function, then the NC_HasAgg flag is
  84951. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  84952. ** If an expression contains aggregate functions then the EP_Agg
  84953. ** property on the expression is set.
  84954. **
  84955. ** An error message is left in pParse if anything is amiss. The number
  84956. ** if errors is returned.
  84957. */
  84958. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  84959. NameContext *pNC, /* Namespace to resolve expressions in. */
  84960. Expr *pExpr /* The expression to be analyzed. */
  84961. ){
  84962. u16 savedHasAgg;
  84963. Walker w;
  84964. if( pExpr==0 ) return 0;
  84965. #if SQLITE_MAX_EXPR_DEPTH>0
  84966. {
  84967. Parse *pParse = pNC->pParse;
  84968. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  84969. return 1;
  84970. }
  84971. pParse->nHeight += pExpr->nHeight;
  84972. }
  84973. #endif
  84974. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  84975. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  84976. w.pParse = pNC->pParse;
  84977. w.xExprCallback = resolveExprStep;
  84978. w.xSelectCallback = resolveSelectStep;
  84979. w.xSelectCallback2 = 0;
  84980. w.walkerDepth = 0;
  84981. w.eCode = 0;
  84982. w.u.pNC = pNC;
  84983. sqlite3WalkExpr(&w, pExpr);
  84984. #if SQLITE_MAX_EXPR_DEPTH>0
  84985. pNC->pParse->nHeight -= pExpr->nHeight;
  84986. #endif
  84987. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  84988. ExprSetProperty(pExpr, EP_Error);
  84989. }
  84990. if( pNC->ncFlags & NC_HasAgg ){
  84991. ExprSetProperty(pExpr, EP_Agg);
  84992. }
  84993. pNC->ncFlags |= savedHasAgg;
  84994. return ExprHasProperty(pExpr, EP_Error);
  84995. }
  84996. /*
  84997. ** Resolve all names for all expression in an expression list. This is
  84998. ** just like sqlite3ResolveExprNames() except that it works for an expression
  84999. ** list rather than a single expression.
  85000. */
  85001. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  85002. NameContext *pNC, /* Namespace to resolve expressions in. */
  85003. ExprList *pList /* The expression list to be analyzed. */
  85004. ){
  85005. int i;
  85006. if( pList ){
  85007. for(i=0; i<pList->nExpr; i++){
  85008. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  85009. }
  85010. }
  85011. return WRC_Continue;
  85012. }
  85013. /*
  85014. ** Resolve all names in all expressions of a SELECT and in all
  85015. ** decendents of the SELECT, including compounds off of p->pPrior,
  85016. ** subqueries in expressions, and subqueries used as FROM clause
  85017. ** terms.
  85018. **
  85019. ** See sqlite3ResolveExprNames() for a description of the kinds of
  85020. ** transformations that occur.
  85021. **
  85022. ** All SELECT statements should have been expanded using
  85023. ** sqlite3SelectExpand() prior to invoking this routine.
  85024. */
  85025. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  85026. Parse *pParse, /* The parser context */
  85027. Select *p, /* The SELECT statement being coded. */
  85028. NameContext *pOuterNC /* Name context for parent SELECT statement */
  85029. ){
  85030. Walker w;
  85031. assert( p!=0 );
  85032. memset(&w, 0, sizeof(w));
  85033. w.xExprCallback = resolveExprStep;
  85034. w.xSelectCallback = resolveSelectStep;
  85035. w.pParse = pParse;
  85036. w.u.pNC = pOuterNC;
  85037. sqlite3WalkSelect(&w, p);
  85038. }
  85039. /*
  85040. ** Resolve names in expressions that can only reference a single table:
  85041. **
  85042. ** * CHECK constraints
  85043. ** * WHERE clauses on partial indices
  85044. **
  85045. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  85046. ** is set to -1 and the Expr.iColumn value is set to the column number.
  85047. **
  85048. ** Any errors cause an error message to be set in pParse.
  85049. */
  85050. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  85051. Parse *pParse, /* Parsing context */
  85052. Table *pTab, /* The table being referenced */
  85053. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
  85054. Expr *pExpr, /* Expression to resolve. May be NULL. */
  85055. ExprList *pList /* Expression list to resolve. May be NUL. */
  85056. ){
  85057. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  85058. NameContext sNC; /* Name context for pParse->pNewTable */
  85059. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
  85060. memset(&sNC, 0, sizeof(sNC));
  85061. memset(&sSrc, 0, sizeof(sSrc));
  85062. sSrc.nSrc = 1;
  85063. sSrc.a[0].zName = pTab->zName;
  85064. sSrc.a[0].pTab = pTab;
  85065. sSrc.a[0].iCursor = -1;
  85066. sNC.pParse = pParse;
  85067. sNC.pSrcList = &sSrc;
  85068. sNC.ncFlags = type;
  85069. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  85070. if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
  85071. }
  85072. /************** End of resolve.c *********************************************/
  85073. /************** Begin file expr.c ********************************************/
  85074. /*
  85075. ** 2001 September 15
  85076. **
  85077. ** The author disclaims copyright to this source code. In place of
  85078. ** a legal notice, here is a blessing:
  85079. **
  85080. ** May you do good and not evil.
  85081. ** May you find forgiveness for yourself and forgive others.
  85082. ** May you share freely, never taking more than you give.
  85083. **
  85084. *************************************************************************
  85085. ** This file contains routines used for analyzing expressions and
  85086. ** for generating VDBE code that evaluates expressions in SQLite.
  85087. */
  85088. /* #include "sqliteInt.h" */
  85089. /* Forward declarations */
  85090. static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
  85091. static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
  85092. /*
  85093. ** Return the affinity character for a single column of a table.
  85094. */
  85095. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
  85096. assert( iCol<pTab->nCol );
  85097. return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  85098. }
  85099. /*
  85100. ** Return the 'affinity' of the expression pExpr if any.
  85101. **
  85102. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  85103. ** or a sub-select with a column as the return value, then the
  85104. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  85105. ** indicating no affinity for the expression.
  85106. **
  85107. ** i.e. the WHERE clause expressions in the following statements all
  85108. ** have an affinity:
  85109. **
  85110. ** CREATE TABLE t1(a);
  85111. ** SELECT * FROM t1 WHERE a;
  85112. ** SELECT a AS b FROM t1 WHERE b;
  85113. ** SELECT * FROM t1 WHERE (select a from t1);
  85114. */
  85115. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  85116. int op;
  85117. pExpr = sqlite3ExprSkipCollate(pExpr);
  85118. if( pExpr->flags & EP_Generic ) return 0;
  85119. op = pExpr->op;
  85120. if( op==TK_SELECT ){
  85121. assert( pExpr->flags&EP_xIsSelect );
  85122. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  85123. }
  85124. if( op==TK_REGISTER ) op = pExpr->op2;
  85125. #ifndef SQLITE_OMIT_CAST
  85126. if( op==TK_CAST ){
  85127. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  85128. return sqlite3AffinityType(pExpr->u.zToken, 0);
  85129. }
  85130. #endif
  85131. if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
  85132. return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
  85133. }
  85134. if( op==TK_SELECT_COLUMN ){
  85135. assert( pExpr->pLeft->flags&EP_xIsSelect );
  85136. return sqlite3ExprAffinity(
  85137. pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
  85138. );
  85139. }
  85140. return pExpr->affinity;
  85141. }
  85142. /*
  85143. ** Set the collating sequence for expression pExpr to be the collating
  85144. ** sequence named by pToken. Return a pointer to a new Expr node that
  85145. ** implements the COLLATE operator.
  85146. **
  85147. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  85148. ** and the pExpr parameter is returned unchanged.
  85149. */
  85150. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  85151. Parse *pParse, /* Parsing context */
  85152. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  85153. const Token *pCollName, /* Name of collating sequence */
  85154. int dequote /* True to dequote pCollName */
  85155. ){
  85156. if( pCollName->n>0 ){
  85157. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  85158. if( pNew ){
  85159. pNew->pLeft = pExpr;
  85160. pNew->flags |= EP_Collate|EP_Skip;
  85161. pExpr = pNew;
  85162. }
  85163. }
  85164. return pExpr;
  85165. }
  85166. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  85167. Token s;
  85168. assert( zC!=0 );
  85169. sqlite3TokenInit(&s, (char*)zC);
  85170. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  85171. }
  85172. /*
  85173. ** Skip over any TK_COLLATE operators and any unlikely()
  85174. ** or likelihood() function at the root of an expression.
  85175. */
  85176. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  85177. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  85178. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  85179. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  85180. assert( pExpr->x.pList->nExpr>0 );
  85181. assert( pExpr->op==TK_FUNCTION );
  85182. pExpr = pExpr->x.pList->a[0].pExpr;
  85183. }else{
  85184. assert( pExpr->op==TK_COLLATE );
  85185. pExpr = pExpr->pLeft;
  85186. }
  85187. }
  85188. return pExpr;
  85189. }
  85190. /*
  85191. ** Return the collation sequence for the expression pExpr. If
  85192. ** there is no defined collating sequence, return NULL.
  85193. **
  85194. ** The collating sequence might be determined by a COLLATE operator
  85195. ** or by the presence of a column with a defined collating sequence.
  85196. ** COLLATE operators take first precedence. Left operands take
  85197. ** precedence over right operands.
  85198. */
  85199. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  85200. sqlite3 *db = pParse->db;
  85201. CollSeq *pColl = 0;
  85202. Expr *p = pExpr;
  85203. while( p ){
  85204. int op = p->op;
  85205. if( p->flags & EP_Generic ) break;
  85206. if( op==TK_CAST || op==TK_UPLUS ){
  85207. p = p->pLeft;
  85208. continue;
  85209. }
  85210. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  85211. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  85212. break;
  85213. }
  85214. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  85215. || op==TK_REGISTER || op==TK_TRIGGER)
  85216. && p->pTab!=0
  85217. ){
  85218. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  85219. ** a TK_COLUMN but was previously evaluated and cached in a register */
  85220. int j = p->iColumn;
  85221. if( j>=0 ){
  85222. const char *zColl = p->pTab->aCol[j].zColl;
  85223. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  85224. }
  85225. break;
  85226. }
  85227. if( p->flags & EP_Collate ){
  85228. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  85229. p = p->pLeft;
  85230. }else{
  85231. Expr *pNext = p->pRight;
  85232. /* The Expr.x union is never used at the same time as Expr.pRight */
  85233. assert( p->x.pList==0 || p->pRight==0 );
  85234. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  85235. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  85236. ** least one EP_Collate. Thus the following two ALWAYS. */
  85237. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  85238. int i;
  85239. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  85240. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  85241. pNext = p->x.pList->a[i].pExpr;
  85242. break;
  85243. }
  85244. }
  85245. }
  85246. p = pNext;
  85247. }
  85248. }else{
  85249. break;
  85250. }
  85251. }
  85252. if( sqlite3CheckCollSeq(pParse, pColl) ){
  85253. pColl = 0;
  85254. }
  85255. return pColl;
  85256. }
  85257. /*
  85258. ** pExpr is an operand of a comparison operator. aff2 is the
  85259. ** type affinity of the other operand. This routine returns the
  85260. ** type affinity that should be used for the comparison operator.
  85261. */
  85262. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  85263. char aff1 = sqlite3ExprAffinity(pExpr);
  85264. if( aff1 && aff2 ){
  85265. /* Both sides of the comparison are columns. If one has numeric
  85266. ** affinity, use that. Otherwise use no affinity.
  85267. */
  85268. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  85269. return SQLITE_AFF_NUMERIC;
  85270. }else{
  85271. return SQLITE_AFF_BLOB;
  85272. }
  85273. }else if( !aff1 && !aff2 ){
  85274. /* Neither side of the comparison is a column. Compare the
  85275. ** results directly.
  85276. */
  85277. return SQLITE_AFF_BLOB;
  85278. }else{
  85279. /* One side is a column, the other is not. Use the columns affinity. */
  85280. assert( aff1==0 || aff2==0 );
  85281. return (aff1 + aff2);
  85282. }
  85283. }
  85284. /*
  85285. ** pExpr is a comparison operator. Return the type affinity that should
  85286. ** be applied to both operands prior to doing the comparison.
  85287. */
  85288. static char comparisonAffinity(Expr *pExpr){
  85289. char aff;
  85290. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  85291. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  85292. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  85293. assert( pExpr->pLeft );
  85294. aff = sqlite3ExprAffinity(pExpr->pLeft);
  85295. if( pExpr->pRight ){
  85296. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  85297. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  85298. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  85299. }else if( aff==0 ){
  85300. aff = SQLITE_AFF_BLOB;
  85301. }
  85302. return aff;
  85303. }
  85304. /*
  85305. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  85306. ** idx_affinity is the affinity of an indexed column. Return true
  85307. ** if the index with affinity idx_affinity may be used to implement
  85308. ** the comparison in pExpr.
  85309. */
  85310. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  85311. char aff = comparisonAffinity(pExpr);
  85312. switch( aff ){
  85313. case SQLITE_AFF_BLOB:
  85314. return 1;
  85315. case SQLITE_AFF_TEXT:
  85316. return idx_affinity==SQLITE_AFF_TEXT;
  85317. default:
  85318. return sqlite3IsNumericAffinity(idx_affinity);
  85319. }
  85320. }
  85321. /*
  85322. ** Return the P5 value that should be used for a binary comparison
  85323. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  85324. */
  85325. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  85326. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  85327. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  85328. return aff;
  85329. }
  85330. /*
  85331. ** Return a pointer to the collation sequence that should be used by
  85332. ** a binary comparison operator comparing pLeft and pRight.
  85333. **
  85334. ** If the left hand expression has a collating sequence type, then it is
  85335. ** used. Otherwise the collation sequence for the right hand expression
  85336. ** is used, or the default (BINARY) if neither expression has a collating
  85337. ** type.
  85338. **
  85339. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  85340. ** it is not considered.
  85341. */
  85342. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  85343. Parse *pParse,
  85344. Expr *pLeft,
  85345. Expr *pRight
  85346. ){
  85347. CollSeq *pColl;
  85348. assert( pLeft );
  85349. if( pLeft->flags & EP_Collate ){
  85350. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  85351. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  85352. pColl = sqlite3ExprCollSeq(pParse, pRight);
  85353. }else{
  85354. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  85355. if( !pColl ){
  85356. pColl = sqlite3ExprCollSeq(pParse, pRight);
  85357. }
  85358. }
  85359. return pColl;
  85360. }
  85361. /*
  85362. ** Generate code for a comparison operator.
  85363. */
  85364. static int codeCompare(
  85365. Parse *pParse, /* The parsing (and code generating) context */
  85366. Expr *pLeft, /* The left operand */
  85367. Expr *pRight, /* The right operand */
  85368. int opcode, /* The comparison opcode */
  85369. int in1, int in2, /* Register holding operands */
  85370. int dest, /* Jump here if true. */
  85371. int jumpIfNull /* If true, jump if either operand is NULL */
  85372. ){
  85373. int p5;
  85374. int addr;
  85375. CollSeq *p4;
  85376. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  85377. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  85378. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  85379. (void*)p4, P4_COLLSEQ);
  85380. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  85381. return addr;
  85382. }
  85383. /*
  85384. ** Return true if expression pExpr is a vector, or false otherwise.
  85385. **
  85386. ** A vector is defined as any expression that results in two or more
  85387. ** columns of result. Every TK_VECTOR node is an vector because the
  85388. ** parser will not generate a TK_VECTOR with fewer than two entries.
  85389. ** But a TK_SELECT might be either a vector or a scalar. It is only
  85390. ** considered a vector if it has two or more result columns.
  85391. */
  85392. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
  85393. return sqlite3ExprVectorSize(pExpr)>1;
  85394. }
  85395. /*
  85396. ** If the expression passed as the only argument is of type TK_VECTOR
  85397. ** return the number of expressions in the vector. Or, if the expression
  85398. ** is a sub-select, return the number of columns in the sub-select. For
  85399. ** any other type of expression, return 1.
  85400. */
  85401. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
  85402. u8 op = pExpr->op;
  85403. if( op==TK_REGISTER ) op = pExpr->op2;
  85404. if( op==TK_VECTOR ){
  85405. return pExpr->x.pList->nExpr;
  85406. }else if( op==TK_SELECT ){
  85407. return pExpr->x.pSelect->pEList->nExpr;
  85408. }else{
  85409. return 1;
  85410. }
  85411. }
  85412. /*
  85413. ** Return a pointer to a subexpression of pVector that is the i-th
  85414. ** column of the vector (numbered starting with 0). The caller must
  85415. ** ensure that i is within range.
  85416. **
  85417. ** If pVector is really a scalar (and "scalar" here includes subqueries
  85418. ** that return a single column!) then return pVector unmodified.
  85419. **
  85420. ** pVector retains ownership of the returned subexpression.
  85421. **
  85422. ** If the vector is a (SELECT ...) then the expression returned is
  85423. ** just the expression for the i-th term of the result set, and may
  85424. ** not be ready for evaluation because the table cursor has not yet
  85425. ** been positioned.
  85426. */
  85427. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
  85428. assert( i<sqlite3ExprVectorSize(pVector) );
  85429. if( sqlite3ExprIsVector(pVector) ){
  85430. assert( pVector->op2==0 || pVector->op==TK_REGISTER );
  85431. if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
  85432. return pVector->x.pSelect->pEList->a[i].pExpr;
  85433. }else{
  85434. return pVector->x.pList->a[i].pExpr;
  85435. }
  85436. }
  85437. return pVector;
  85438. }
  85439. /*
  85440. ** Compute and return a new Expr object which when passed to
  85441. ** sqlite3ExprCode() will generate all necessary code to compute
  85442. ** the iField-th column of the vector expression pVector.
  85443. **
  85444. ** It is ok for pVector to be a scalar (as long as iField==0).
  85445. ** In that case, this routine works like sqlite3ExprDup().
  85446. **
  85447. ** The caller owns the returned Expr object and is responsible for
  85448. ** ensuring that the returned value eventually gets freed.
  85449. **
  85450. ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
  85451. ** then the returned object will reference pVector and so pVector must remain
  85452. ** valid for the life of the returned object. If pVector is a TK_VECTOR
  85453. ** or a scalar expression, then it can be deleted as soon as this routine
  85454. ** returns.
  85455. **
  85456. ** A trick to cause a TK_SELECT pVector to be deleted together with
  85457. ** the returned Expr object is to attach the pVector to the pRight field
  85458. ** of the returned TK_SELECT_COLUMN Expr object.
  85459. */
  85460. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
  85461. Parse *pParse, /* Parsing context */
  85462. Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
  85463. int iField /* Which column of the vector to return */
  85464. ){
  85465. Expr *pRet;
  85466. if( pVector->op==TK_SELECT ){
  85467. assert( pVector->flags & EP_xIsSelect );
  85468. /* The TK_SELECT_COLUMN Expr node:
  85469. **
  85470. ** pLeft: pVector containing TK_SELECT. Not deleted.
  85471. ** pRight: not used. But recursively deleted.
  85472. ** iColumn: Index of a column in pVector
  85473. ** iTable: 0 or the number of columns on the LHS of an assignment
  85474. ** pLeft->iTable: First in an array of register holding result, or 0
  85475. ** if the result is not yet computed.
  85476. **
  85477. ** sqlite3ExprDelete() specifically skips the recursive delete of
  85478. ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
  85479. ** can be attached to pRight to cause this node to take ownership of
  85480. ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
  85481. ** with the same pLeft pointer to the pVector, but only one of them
  85482. ** will own the pVector.
  85483. */
  85484. pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
  85485. if( pRet ){
  85486. pRet->iColumn = iField;
  85487. pRet->pLeft = pVector;
  85488. }
  85489. assert( pRet==0 || pRet->iTable==0 );
  85490. }else{
  85491. if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
  85492. pRet = sqlite3ExprDup(pParse->db, pVector, 0);
  85493. }
  85494. return pRet;
  85495. }
  85496. /*
  85497. ** If expression pExpr is of type TK_SELECT, generate code to evaluate
  85498. ** it. Return the register in which the result is stored (or, if the
  85499. ** sub-select returns more than one column, the first in an array
  85500. ** of registers in which the result is stored).
  85501. **
  85502. ** If pExpr is not a TK_SELECT expression, return 0.
  85503. */
  85504. static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
  85505. int reg = 0;
  85506. #ifndef SQLITE_OMIT_SUBQUERY
  85507. if( pExpr->op==TK_SELECT ){
  85508. reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  85509. }
  85510. #endif
  85511. return reg;
  85512. }
  85513. /*
  85514. ** Argument pVector points to a vector expression - either a TK_VECTOR
  85515. ** or TK_SELECT that returns more than one column. This function returns
  85516. ** the register number of a register that contains the value of
  85517. ** element iField of the vector.
  85518. **
  85519. ** If pVector is a TK_SELECT expression, then code for it must have
  85520. ** already been generated using the exprCodeSubselect() routine. In this
  85521. ** case parameter regSelect should be the first in an array of registers
  85522. ** containing the results of the sub-select.
  85523. **
  85524. ** If pVector is of type TK_VECTOR, then code for the requested field
  85525. ** is generated. In this case (*pRegFree) may be set to the number of
  85526. ** a temporary register to be freed by the caller before returning.
  85527. **
  85528. ** Before returning, output parameter (*ppExpr) is set to point to the
  85529. ** Expr object corresponding to element iElem of the vector.
  85530. */
  85531. static int exprVectorRegister(
  85532. Parse *pParse, /* Parse context */
  85533. Expr *pVector, /* Vector to extract element from */
  85534. int iField, /* Field to extract from pVector */
  85535. int regSelect, /* First in array of registers */
  85536. Expr **ppExpr, /* OUT: Expression element */
  85537. int *pRegFree /* OUT: Temp register to free */
  85538. ){
  85539. u8 op = pVector->op;
  85540. assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
  85541. if( op==TK_REGISTER ){
  85542. *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
  85543. return pVector->iTable+iField;
  85544. }
  85545. if( op==TK_SELECT ){
  85546. *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
  85547. return regSelect+iField;
  85548. }
  85549. *ppExpr = pVector->x.pList->a[iField].pExpr;
  85550. return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
  85551. }
  85552. /*
  85553. ** Expression pExpr is a comparison between two vector values. Compute
  85554. ** the result of the comparison (1, 0, or NULL) and write that
  85555. ** result into register dest.
  85556. **
  85557. ** The caller must satisfy the following preconditions:
  85558. **
  85559. ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
  85560. ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
  85561. ** otherwise: op==pExpr->op and p5==0
  85562. */
  85563. static void codeVectorCompare(
  85564. Parse *pParse, /* Code generator context */
  85565. Expr *pExpr, /* The comparison operation */
  85566. int dest, /* Write results into this register */
  85567. u8 op, /* Comparison operator */
  85568. u8 p5 /* SQLITE_NULLEQ or zero */
  85569. ){
  85570. Vdbe *v = pParse->pVdbe;
  85571. Expr *pLeft = pExpr->pLeft;
  85572. Expr *pRight = pExpr->pRight;
  85573. int nLeft = sqlite3ExprVectorSize(pLeft);
  85574. int i;
  85575. int regLeft = 0;
  85576. int regRight = 0;
  85577. u8 opx = op;
  85578. int addrDone = sqlite3VdbeMakeLabel(v);
  85579. if( nLeft!=sqlite3ExprVectorSize(pRight) ){
  85580. sqlite3ErrorMsg(pParse, "row value misused");
  85581. return;
  85582. }
  85583. assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
  85584. || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
  85585. || pExpr->op==TK_LT || pExpr->op==TK_GT
  85586. || pExpr->op==TK_LE || pExpr->op==TK_GE
  85587. );
  85588. assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
  85589. || (pExpr->op==TK_ISNOT && op==TK_NE) );
  85590. assert( p5==0 || pExpr->op!=op );
  85591. assert( p5==SQLITE_NULLEQ || pExpr->op==op );
  85592. p5 |= SQLITE_STOREP2;
  85593. if( opx==TK_LE ) opx = TK_LT;
  85594. if( opx==TK_GE ) opx = TK_GT;
  85595. regLeft = exprCodeSubselect(pParse, pLeft);
  85596. regRight = exprCodeSubselect(pParse, pRight);
  85597. for(i=0; 1 /*Loop exits by "break"*/; i++){
  85598. int regFree1 = 0, regFree2 = 0;
  85599. Expr *pL, *pR;
  85600. int r1, r2;
  85601. assert( i>=0 && i<nLeft );
  85602. if( i>0 ) sqlite3ExprCachePush(pParse);
  85603. r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
  85604. r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
  85605. codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
  85606. testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  85607. testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  85608. testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  85609. testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  85610. testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  85611. testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  85612. sqlite3ReleaseTempReg(pParse, regFree1);
  85613. sqlite3ReleaseTempReg(pParse, regFree2);
  85614. if( i>0 ) sqlite3ExprCachePop(pParse);
  85615. if( i==nLeft-1 ){
  85616. break;
  85617. }
  85618. if( opx==TK_EQ ){
  85619. sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
  85620. p5 |= SQLITE_KEEPNULL;
  85621. }else if( opx==TK_NE ){
  85622. sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
  85623. p5 |= SQLITE_KEEPNULL;
  85624. }else{
  85625. assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
  85626. sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
  85627. VdbeCoverageIf(v, op==TK_LT);
  85628. VdbeCoverageIf(v, op==TK_GT);
  85629. VdbeCoverageIf(v, op==TK_LE);
  85630. VdbeCoverageIf(v, op==TK_GE);
  85631. if( i==nLeft-2 ) opx = op;
  85632. }
  85633. }
  85634. sqlite3VdbeResolveLabel(v, addrDone);
  85635. }
  85636. #if SQLITE_MAX_EXPR_DEPTH>0
  85637. /*
  85638. ** Check that argument nHeight is less than or equal to the maximum
  85639. ** expression depth allowed. If it is not, leave an error message in
  85640. ** pParse.
  85641. */
  85642. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  85643. int rc = SQLITE_OK;
  85644. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  85645. if( nHeight>mxHeight ){
  85646. sqlite3ErrorMsg(pParse,
  85647. "Expression tree is too large (maximum depth %d)", mxHeight
  85648. );
  85649. rc = SQLITE_ERROR;
  85650. }
  85651. return rc;
  85652. }
  85653. /* The following three functions, heightOfExpr(), heightOfExprList()
  85654. ** and heightOfSelect(), are used to determine the maximum height
  85655. ** of any expression tree referenced by the structure passed as the
  85656. ** first argument.
  85657. **
  85658. ** If this maximum height is greater than the current value pointed
  85659. ** to by pnHeight, the second parameter, then set *pnHeight to that
  85660. ** value.
  85661. */
  85662. static void heightOfExpr(Expr *p, int *pnHeight){
  85663. if( p ){
  85664. if( p->nHeight>*pnHeight ){
  85665. *pnHeight = p->nHeight;
  85666. }
  85667. }
  85668. }
  85669. static void heightOfExprList(ExprList *p, int *pnHeight){
  85670. if( p ){
  85671. int i;
  85672. for(i=0; i<p->nExpr; i++){
  85673. heightOfExpr(p->a[i].pExpr, pnHeight);
  85674. }
  85675. }
  85676. }
  85677. static void heightOfSelect(Select *p, int *pnHeight){
  85678. if( p ){
  85679. heightOfExpr(p->pWhere, pnHeight);
  85680. heightOfExpr(p->pHaving, pnHeight);
  85681. heightOfExpr(p->pLimit, pnHeight);
  85682. heightOfExpr(p->pOffset, pnHeight);
  85683. heightOfExprList(p->pEList, pnHeight);
  85684. heightOfExprList(p->pGroupBy, pnHeight);
  85685. heightOfExprList(p->pOrderBy, pnHeight);
  85686. heightOfSelect(p->pPrior, pnHeight);
  85687. }
  85688. }
  85689. /*
  85690. ** Set the Expr.nHeight variable in the structure passed as an
  85691. ** argument. An expression with no children, Expr.pList or
  85692. ** Expr.pSelect member has a height of 1. Any other expression
  85693. ** has a height equal to the maximum height of any other
  85694. ** referenced Expr plus one.
  85695. **
  85696. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  85697. ** if appropriate.
  85698. */
  85699. static void exprSetHeight(Expr *p){
  85700. int nHeight = 0;
  85701. heightOfExpr(p->pLeft, &nHeight);
  85702. heightOfExpr(p->pRight, &nHeight);
  85703. if( ExprHasProperty(p, EP_xIsSelect) ){
  85704. heightOfSelect(p->x.pSelect, &nHeight);
  85705. }else if( p->x.pList ){
  85706. heightOfExprList(p->x.pList, &nHeight);
  85707. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  85708. }
  85709. p->nHeight = nHeight + 1;
  85710. }
  85711. /*
  85712. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  85713. ** the height is greater than the maximum allowed expression depth,
  85714. ** leave an error in pParse.
  85715. **
  85716. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  85717. ** Expr.flags.
  85718. */
  85719. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  85720. if( pParse->nErr ) return;
  85721. exprSetHeight(p);
  85722. sqlite3ExprCheckHeight(pParse, p->nHeight);
  85723. }
  85724. /*
  85725. ** Return the maximum height of any expression tree referenced
  85726. ** by the select statement passed as an argument.
  85727. */
  85728. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  85729. int nHeight = 0;
  85730. heightOfSelect(p, &nHeight);
  85731. return nHeight;
  85732. }
  85733. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  85734. /*
  85735. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  85736. ** Expr.flags.
  85737. */
  85738. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  85739. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  85740. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  85741. }
  85742. }
  85743. #define exprSetHeight(y)
  85744. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  85745. /*
  85746. ** This routine is the core allocator for Expr nodes.
  85747. **
  85748. ** Construct a new expression node and return a pointer to it. Memory
  85749. ** for this node and for the pToken argument is a single allocation
  85750. ** obtained from sqlite3DbMalloc(). The calling function
  85751. ** is responsible for making sure the node eventually gets freed.
  85752. **
  85753. ** If dequote is true, then the token (if it exists) is dequoted.
  85754. ** If dequote is false, no dequoting is performed. The deQuote
  85755. ** parameter is ignored if pToken is NULL or if the token does not
  85756. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  85757. ** then the EP_DblQuoted flag is set on the expression node.
  85758. **
  85759. ** Special case: If op==TK_INTEGER and pToken points to a string that
  85760. ** can be translated into a 32-bit integer, then the token is not
  85761. ** stored in u.zToken. Instead, the integer values is written
  85762. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  85763. ** is allocated to hold the integer text and the dequote flag is ignored.
  85764. */
  85765. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  85766. sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
  85767. int op, /* Expression opcode */
  85768. const Token *pToken, /* Token argument. Might be NULL */
  85769. int dequote /* True to dequote */
  85770. ){
  85771. Expr *pNew;
  85772. int nExtra = 0;
  85773. int iValue = 0;
  85774. assert( db!=0 );
  85775. if( pToken ){
  85776. if( op!=TK_INTEGER || pToken->z==0
  85777. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  85778. nExtra = pToken->n+1;
  85779. assert( iValue>=0 );
  85780. }
  85781. }
  85782. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  85783. if( pNew ){
  85784. memset(pNew, 0, sizeof(Expr));
  85785. pNew->op = (u8)op;
  85786. pNew->iAgg = -1;
  85787. if( pToken ){
  85788. if( nExtra==0 ){
  85789. pNew->flags |= EP_IntValue;
  85790. pNew->u.iValue = iValue;
  85791. }else{
  85792. pNew->u.zToken = (char*)&pNew[1];
  85793. assert( pToken->z!=0 || pToken->n==0 );
  85794. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  85795. pNew->u.zToken[pToken->n] = 0;
  85796. if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
  85797. if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
  85798. sqlite3Dequote(pNew->u.zToken);
  85799. }
  85800. }
  85801. }
  85802. #if SQLITE_MAX_EXPR_DEPTH>0
  85803. pNew->nHeight = 1;
  85804. #endif
  85805. }
  85806. return pNew;
  85807. }
  85808. /*
  85809. ** Allocate a new expression node from a zero-terminated token that has
  85810. ** already been dequoted.
  85811. */
  85812. SQLITE_PRIVATE Expr *sqlite3Expr(
  85813. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  85814. int op, /* Expression opcode */
  85815. const char *zToken /* Token argument. Might be NULL */
  85816. ){
  85817. Token x;
  85818. x.z = zToken;
  85819. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  85820. return sqlite3ExprAlloc(db, op, &x, 0);
  85821. }
  85822. /*
  85823. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  85824. **
  85825. ** If pRoot==NULL that means that a memory allocation error has occurred.
  85826. ** In that case, delete the subtrees pLeft and pRight.
  85827. */
  85828. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  85829. sqlite3 *db,
  85830. Expr *pRoot,
  85831. Expr *pLeft,
  85832. Expr *pRight
  85833. ){
  85834. if( pRoot==0 ){
  85835. assert( db->mallocFailed );
  85836. sqlite3ExprDelete(db, pLeft);
  85837. sqlite3ExprDelete(db, pRight);
  85838. }else{
  85839. if( pRight ){
  85840. pRoot->pRight = pRight;
  85841. pRoot->flags |= EP_Propagate & pRight->flags;
  85842. }
  85843. if( pLeft ){
  85844. pRoot->pLeft = pLeft;
  85845. pRoot->flags |= EP_Propagate & pLeft->flags;
  85846. }
  85847. exprSetHeight(pRoot);
  85848. }
  85849. }
  85850. /*
  85851. ** Allocate an Expr node which joins as many as two subtrees.
  85852. **
  85853. ** One or both of the subtrees can be NULL. Return a pointer to the new
  85854. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  85855. ** free the subtrees and return NULL.
  85856. */
  85857. SQLITE_PRIVATE Expr *sqlite3PExpr(
  85858. Parse *pParse, /* Parsing context */
  85859. int op, /* Expression opcode */
  85860. Expr *pLeft, /* Left operand */
  85861. Expr *pRight /* Right operand */
  85862. ){
  85863. Expr *p;
  85864. if( op==TK_AND && pParse->nErr==0 ){
  85865. /* Take advantage of short-circuit false optimization for AND */
  85866. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  85867. }else{
  85868. p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
  85869. if( p ){
  85870. memset(p, 0, sizeof(Expr));
  85871. p->op = op & TKFLG_MASK;
  85872. p->iAgg = -1;
  85873. }
  85874. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  85875. }
  85876. if( p ) {
  85877. sqlite3ExprCheckHeight(pParse, p->nHeight);
  85878. }
  85879. return p;
  85880. }
  85881. /*
  85882. ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
  85883. ** do a memory allocation failure) then delete the pSelect object.
  85884. */
  85885. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
  85886. if( pExpr ){
  85887. pExpr->x.pSelect = pSelect;
  85888. ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
  85889. sqlite3ExprSetHeightAndFlags(pParse, pExpr);
  85890. }else{
  85891. assert( pParse->db->mallocFailed );
  85892. sqlite3SelectDelete(pParse->db, pSelect);
  85893. }
  85894. }
  85895. /*
  85896. ** If the expression is always either TRUE or FALSE (respectively),
  85897. ** then return 1. If one cannot determine the truth value of the
  85898. ** expression at compile-time return 0.
  85899. **
  85900. ** This is an optimization. If is OK to return 0 here even if
  85901. ** the expression really is always false or false (a false negative).
  85902. ** But it is a bug to return 1 if the expression might have different
  85903. ** boolean values in different circumstances (a false positive.)
  85904. **
  85905. ** Note that if the expression is part of conditional for a
  85906. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  85907. ** is it true or false, so always return 0.
  85908. */
  85909. static int exprAlwaysTrue(Expr *p){
  85910. int v = 0;
  85911. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  85912. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  85913. return v!=0;
  85914. }
  85915. static int exprAlwaysFalse(Expr *p){
  85916. int v = 0;
  85917. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  85918. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  85919. return v==0;
  85920. }
  85921. /*
  85922. ** Join two expressions using an AND operator. If either expression is
  85923. ** NULL, then just return the other expression.
  85924. **
  85925. ** If one side or the other of the AND is known to be false, then instead
  85926. ** of returning an AND expression, just return a constant expression with
  85927. ** a value of false.
  85928. */
  85929. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  85930. if( pLeft==0 ){
  85931. return pRight;
  85932. }else if( pRight==0 ){
  85933. return pLeft;
  85934. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  85935. sqlite3ExprDelete(db, pLeft);
  85936. sqlite3ExprDelete(db, pRight);
  85937. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  85938. }else{
  85939. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  85940. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  85941. return pNew;
  85942. }
  85943. }
  85944. /*
  85945. ** Construct a new expression node for a function with multiple
  85946. ** arguments.
  85947. */
  85948. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  85949. Expr *pNew;
  85950. sqlite3 *db = pParse->db;
  85951. assert( pToken );
  85952. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  85953. if( pNew==0 ){
  85954. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  85955. return 0;
  85956. }
  85957. pNew->x.pList = pList;
  85958. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  85959. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  85960. return pNew;
  85961. }
  85962. /*
  85963. ** Assign a variable number to an expression that encodes a wildcard
  85964. ** in the original SQL statement.
  85965. **
  85966. ** Wildcards consisting of a single "?" are assigned the next sequential
  85967. ** variable number.
  85968. **
  85969. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  85970. ** sure "nnn" is not too big to avoid a denial of service attack when
  85971. ** the SQL statement comes from an external source.
  85972. **
  85973. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  85974. ** as the previous instance of the same wildcard. Or if this is the first
  85975. ** instance of the wildcard, the next sequential variable number is
  85976. ** assigned.
  85977. */
  85978. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
  85979. sqlite3 *db = pParse->db;
  85980. const char *z;
  85981. ynVar x;
  85982. if( pExpr==0 ) return;
  85983. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  85984. z = pExpr->u.zToken;
  85985. assert( z!=0 );
  85986. assert( z[0]!=0 );
  85987. assert( n==(u32)sqlite3Strlen30(z) );
  85988. if( z[1]==0 ){
  85989. /* Wildcard of the form "?". Assign the next variable number */
  85990. assert( z[0]=='?' );
  85991. x = (ynVar)(++pParse->nVar);
  85992. }else{
  85993. int doAdd = 0;
  85994. if( z[0]=='?' ){
  85995. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  85996. ** use it as the variable number */
  85997. i64 i;
  85998. int bOk;
  85999. if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
  86000. i = z[1]-'0'; /* The common case of ?N for a single digit N */
  86001. bOk = 1;
  86002. }else{
  86003. bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  86004. }
  86005. testcase( i==0 );
  86006. testcase( i==1 );
  86007. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  86008. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  86009. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  86010. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  86011. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  86012. return;
  86013. }
  86014. x = (ynVar)i;
  86015. if( x>pParse->nVar ){
  86016. pParse->nVar = (int)x;
  86017. doAdd = 1;
  86018. }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
  86019. doAdd = 1;
  86020. }
  86021. }else{
  86022. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  86023. ** number as the prior appearance of the same name, or if the name
  86024. ** has never appeared before, reuse the same variable number
  86025. */
  86026. x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
  86027. if( x==0 ){
  86028. x = (ynVar)(++pParse->nVar);
  86029. doAdd = 1;
  86030. }
  86031. }
  86032. if( doAdd ){
  86033. pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
  86034. }
  86035. }
  86036. pExpr->iColumn = x;
  86037. if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  86038. sqlite3ErrorMsg(pParse, "too many SQL variables");
  86039. }
  86040. }
  86041. /*
  86042. ** Recursively delete an expression tree.
  86043. */
  86044. static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  86045. assert( p!=0 );
  86046. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  86047. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  86048. #ifdef SQLITE_DEBUG
  86049. if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
  86050. assert( p->pLeft==0 );
  86051. assert( p->pRight==0 );
  86052. assert( p->x.pSelect==0 );
  86053. }
  86054. #endif
  86055. if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
  86056. /* The Expr.x union is never used at the same time as Expr.pRight */
  86057. assert( p->x.pList==0 || p->pRight==0 );
  86058. if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
  86059. sqlite3ExprDelete(db, p->pRight);
  86060. if( ExprHasProperty(p, EP_xIsSelect) ){
  86061. sqlite3SelectDelete(db, p->x.pSelect);
  86062. }else{
  86063. sqlite3ExprListDelete(db, p->x.pList);
  86064. }
  86065. }
  86066. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  86067. if( !ExprHasProperty(p, EP_Static) ){
  86068. sqlite3DbFreeNN(db, p);
  86069. }
  86070. }
  86071. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  86072. if( p ) sqlite3ExprDeleteNN(db, p);
  86073. }
  86074. /*
  86075. ** Return the number of bytes allocated for the expression structure
  86076. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  86077. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  86078. */
  86079. static int exprStructSize(Expr *p){
  86080. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  86081. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  86082. return EXPR_FULLSIZE;
  86083. }
  86084. /*
  86085. ** The dupedExpr*Size() routines each return the number of bytes required
  86086. ** to store a copy of an expression or expression tree. They differ in
  86087. ** how much of the tree is measured.
  86088. **
  86089. ** dupedExprStructSize() Size of only the Expr structure
  86090. ** dupedExprNodeSize() Size of Expr + space for token
  86091. ** dupedExprSize() Expr + token + subtree components
  86092. **
  86093. ***************************************************************************
  86094. **
  86095. ** The dupedExprStructSize() function returns two values OR-ed together:
  86096. ** (1) the space required for a copy of the Expr structure only and
  86097. ** (2) the EP_xxx flags that indicate what the structure size should be.
  86098. ** The return values is always one of:
  86099. **
  86100. ** EXPR_FULLSIZE
  86101. ** EXPR_REDUCEDSIZE | EP_Reduced
  86102. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  86103. **
  86104. ** The size of the structure can be found by masking the return value
  86105. ** of this routine with 0xfff. The flags can be found by masking the
  86106. ** return value with EP_Reduced|EP_TokenOnly.
  86107. **
  86108. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  86109. ** (unreduced) Expr objects as they or originally constructed by the parser.
  86110. ** During expression analysis, extra information is computed and moved into
  86111. ** later parts of teh Expr object and that extra information might get chopped
  86112. ** off if the expression is reduced. Note also that it does not work to
  86113. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  86114. ** to reduce a pristine expression tree from the parser. The implementation
  86115. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  86116. ** to enforce this constraint.
  86117. */
  86118. static int dupedExprStructSize(Expr *p, int flags){
  86119. int nSize;
  86120. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  86121. assert( EXPR_FULLSIZE<=0xfff );
  86122. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  86123. if( 0==flags || p->op==TK_SELECT_COLUMN ){
  86124. nSize = EXPR_FULLSIZE;
  86125. }else{
  86126. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  86127. assert( !ExprHasProperty(p, EP_FromJoin) );
  86128. assert( !ExprHasProperty(p, EP_MemToken) );
  86129. assert( !ExprHasProperty(p, EP_NoReduce) );
  86130. if( p->pLeft || p->x.pList ){
  86131. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  86132. }else{
  86133. assert( p->pRight==0 );
  86134. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  86135. }
  86136. }
  86137. return nSize;
  86138. }
  86139. /*
  86140. ** This function returns the space in bytes required to store the copy
  86141. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  86142. ** string is defined.)
  86143. */
  86144. static int dupedExprNodeSize(Expr *p, int flags){
  86145. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  86146. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  86147. nByte += sqlite3Strlen30(p->u.zToken)+1;
  86148. }
  86149. return ROUND8(nByte);
  86150. }
  86151. /*
  86152. ** Return the number of bytes required to create a duplicate of the
  86153. ** expression passed as the first argument. The second argument is a
  86154. ** mask containing EXPRDUP_XXX flags.
  86155. **
  86156. ** The value returned includes space to create a copy of the Expr struct
  86157. ** itself and the buffer referred to by Expr.u.zToken, if any.
  86158. **
  86159. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  86160. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  86161. ** and Expr.pRight variables (but not for any structures pointed to or
  86162. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  86163. */
  86164. static int dupedExprSize(Expr *p, int flags){
  86165. int nByte = 0;
  86166. if( p ){
  86167. nByte = dupedExprNodeSize(p, flags);
  86168. if( flags&EXPRDUP_REDUCE ){
  86169. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  86170. }
  86171. }
  86172. return nByte;
  86173. }
  86174. /*
  86175. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  86176. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  86177. ** to store the copy of expression p, the copies of p->u.zToken
  86178. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  86179. ** if any. Before returning, *pzBuffer is set to the first byte past the
  86180. ** portion of the buffer copied into by this function.
  86181. */
  86182. static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
  86183. Expr *pNew; /* Value to return */
  86184. u8 *zAlloc; /* Memory space from which to build Expr object */
  86185. u32 staticFlag; /* EP_Static if space not obtained from malloc */
  86186. assert( db!=0 );
  86187. assert( p );
  86188. assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
  86189. assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
  86190. /* Figure out where to write the new Expr structure. */
  86191. if( pzBuffer ){
  86192. zAlloc = *pzBuffer;
  86193. staticFlag = EP_Static;
  86194. }else{
  86195. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
  86196. staticFlag = 0;
  86197. }
  86198. pNew = (Expr *)zAlloc;
  86199. if( pNew ){
  86200. /* Set nNewSize to the size allocated for the structure pointed to
  86201. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  86202. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  86203. ** by the copy of the p->u.zToken string (if any).
  86204. */
  86205. const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
  86206. const int nNewSize = nStructSize & 0xfff;
  86207. int nToken;
  86208. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  86209. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  86210. }else{
  86211. nToken = 0;
  86212. }
  86213. if( dupFlags ){
  86214. assert( ExprHasProperty(p, EP_Reduced)==0 );
  86215. memcpy(zAlloc, p, nNewSize);
  86216. }else{
  86217. u32 nSize = (u32)exprStructSize(p);
  86218. memcpy(zAlloc, p, nSize);
  86219. if( nSize<EXPR_FULLSIZE ){
  86220. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  86221. }
  86222. }
  86223. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  86224. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  86225. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  86226. pNew->flags |= staticFlag;
  86227. /* Copy the p->u.zToken string, if any. */
  86228. if( nToken ){
  86229. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  86230. memcpy(zToken, p->u.zToken, nToken);
  86231. }
  86232. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
  86233. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  86234. if( ExprHasProperty(p, EP_xIsSelect) ){
  86235. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
  86236. }else{
  86237. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
  86238. }
  86239. }
  86240. /* Fill in pNew->pLeft and pNew->pRight. */
  86241. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  86242. zAlloc += dupedExprNodeSize(p, dupFlags);
  86243. if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
  86244. pNew->pLeft = p->pLeft ?
  86245. exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
  86246. pNew->pRight = p->pRight ?
  86247. exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
  86248. }
  86249. if( pzBuffer ){
  86250. *pzBuffer = zAlloc;
  86251. }
  86252. }else{
  86253. if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  86254. if( pNew->op==TK_SELECT_COLUMN ){
  86255. pNew->pLeft = p->pLeft;
  86256. assert( p->iColumn==0 || p->pRight==0 );
  86257. assert( p->pRight==0 || p->pRight==p->pLeft );
  86258. }else{
  86259. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  86260. }
  86261. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  86262. }
  86263. }
  86264. }
  86265. return pNew;
  86266. }
  86267. /*
  86268. ** Create and return a deep copy of the object passed as the second
  86269. ** argument. If an OOM condition is encountered, NULL is returned
  86270. ** and the db->mallocFailed flag set.
  86271. */
  86272. #ifndef SQLITE_OMIT_CTE
  86273. static With *withDup(sqlite3 *db, With *p){
  86274. With *pRet = 0;
  86275. if( p ){
  86276. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  86277. pRet = sqlite3DbMallocZero(db, nByte);
  86278. if( pRet ){
  86279. int i;
  86280. pRet->nCte = p->nCte;
  86281. for(i=0; i<p->nCte; i++){
  86282. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  86283. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  86284. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  86285. }
  86286. }
  86287. }
  86288. return pRet;
  86289. }
  86290. #else
  86291. # define withDup(x,y) 0
  86292. #endif
  86293. /*
  86294. ** The following group of routines make deep copies of expressions,
  86295. ** expression lists, ID lists, and select statements. The copies can
  86296. ** be deleted (by being passed to their respective ...Delete() routines)
  86297. ** without effecting the originals.
  86298. **
  86299. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  86300. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  86301. ** by subsequent calls to sqlite*ListAppend() routines.
  86302. **
  86303. ** Any tables that the SrcList might point to are not duplicated.
  86304. **
  86305. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  86306. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  86307. ** truncated version of the usual Expr structure that will be stored as
  86308. ** part of the in-memory representation of the database schema.
  86309. */
  86310. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  86311. assert( flags==0 || flags==EXPRDUP_REDUCE );
  86312. return p ? exprDup(db, p, flags, 0) : 0;
  86313. }
  86314. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  86315. ExprList *pNew;
  86316. struct ExprList_item *pItem, *pOldItem;
  86317. int i;
  86318. Expr *pPriorSelectCol = 0;
  86319. assert( db!=0 );
  86320. if( p==0 ) return 0;
  86321. pNew = sqlite3DbMallocRawNN(db,
  86322. sizeof(*pNew)+sizeof(pNew->a[0])*(p->nExpr-1) );
  86323. if( pNew==0 ) return 0;
  86324. pNew->nAlloc = pNew->nExpr = p->nExpr;
  86325. pItem = pNew->a;
  86326. pOldItem = p->a;
  86327. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  86328. Expr *pOldExpr = pOldItem->pExpr;
  86329. Expr *pNewExpr;
  86330. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  86331. if( pOldExpr
  86332. && pOldExpr->op==TK_SELECT_COLUMN
  86333. && (pNewExpr = pItem->pExpr)!=0
  86334. ){
  86335. assert( pNewExpr->iColumn==0 || i>0 );
  86336. if( pNewExpr->iColumn==0 ){
  86337. assert( pOldExpr->pLeft==pOldExpr->pRight );
  86338. pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
  86339. }else{
  86340. assert( i>0 );
  86341. assert( pItem[-1].pExpr!=0 );
  86342. assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
  86343. assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
  86344. pNewExpr->pLeft = pPriorSelectCol;
  86345. }
  86346. }
  86347. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  86348. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  86349. pItem->sortOrder = pOldItem->sortOrder;
  86350. pItem->done = 0;
  86351. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  86352. pItem->u = pOldItem->u;
  86353. }
  86354. return pNew;
  86355. }
  86356. /*
  86357. ** If cursors, triggers, views and subqueries are all omitted from
  86358. ** the build, then none of the following routines, except for
  86359. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  86360. ** called with a NULL argument.
  86361. */
  86362. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  86363. || !defined(SQLITE_OMIT_SUBQUERY)
  86364. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  86365. SrcList *pNew;
  86366. int i;
  86367. int nByte;
  86368. assert( db!=0 );
  86369. if( p==0 ) return 0;
  86370. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  86371. pNew = sqlite3DbMallocRawNN(db, nByte );
  86372. if( pNew==0 ) return 0;
  86373. pNew->nSrc = pNew->nAlloc = p->nSrc;
  86374. for(i=0; i<p->nSrc; i++){
  86375. struct SrcList_item *pNewItem = &pNew->a[i];
  86376. struct SrcList_item *pOldItem = &p->a[i];
  86377. Table *pTab;
  86378. pNewItem->pSchema = pOldItem->pSchema;
  86379. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  86380. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  86381. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  86382. pNewItem->fg = pOldItem->fg;
  86383. pNewItem->iCursor = pOldItem->iCursor;
  86384. pNewItem->addrFillSub = pOldItem->addrFillSub;
  86385. pNewItem->regReturn = pOldItem->regReturn;
  86386. if( pNewItem->fg.isIndexedBy ){
  86387. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  86388. }
  86389. pNewItem->pIBIndex = pOldItem->pIBIndex;
  86390. if( pNewItem->fg.isTabFunc ){
  86391. pNewItem->u1.pFuncArg =
  86392. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  86393. }
  86394. pTab = pNewItem->pTab = pOldItem->pTab;
  86395. if( pTab ){
  86396. pTab->nTabRef++;
  86397. }
  86398. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  86399. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  86400. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  86401. pNewItem->colUsed = pOldItem->colUsed;
  86402. }
  86403. return pNew;
  86404. }
  86405. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  86406. IdList *pNew;
  86407. int i;
  86408. assert( db!=0 );
  86409. if( p==0 ) return 0;
  86410. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  86411. if( pNew==0 ) return 0;
  86412. pNew->nId = p->nId;
  86413. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  86414. if( pNew->a==0 ){
  86415. sqlite3DbFreeNN(db, pNew);
  86416. return 0;
  86417. }
  86418. /* Note that because the size of the allocation for p->a[] is not
  86419. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  86420. ** on the duplicate created by this function. */
  86421. for(i=0; i<p->nId; i++){
  86422. struct IdList_item *pNewItem = &pNew->a[i];
  86423. struct IdList_item *pOldItem = &p->a[i];
  86424. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  86425. pNewItem->idx = pOldItem->idx;
  86426. }
  86427. return pNew;
  86428. }
  86429. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
  86430. Select *pRet = 0;
  86431. Select *pNext = 0;
  86432. Select **pp = &pRet;
  86433. Select *p;
  86434. assert( db!=0 );
  86435. for(p=pDup; p; p=p->pPrior){
  86436. Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  86437. if( pNew==0 ) break;
  86438. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  86439. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  86440. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  86441. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  86442. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  86443. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  86444. pNew->op = p->op;
  86445. pNew->pNext = pNext;
  86446. pNew->pPrior = 0;
  86447. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  86448. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  86449. pNew->iLimit = 0;
  86450. pNew->iOffset = 0;
  86451. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  86452. pNew->addrOpenEphm[0] = -1;
  86453. pNew->addrOpenEphm[1] = -1;
  86454. pNew->nSelectRow = p->nSelectRow;
  86455. pNew->pWith = withDup(db, p->pWith);
  86456. sqlite3SelectSetName(pNew, p->zSelName);
  86457. *pp = pNew;
  86458. pp = &pNew->pPrior;
  86459. pNext = pNew;
  86460. }
  86461. return pRet;
  86462. }
  86463. #else
  86464. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  86465. assert( p==0 );
  86466. return 0;
  86467. }
  86468. #endif
  86469. /*
  86470. ** Add a new element to the end of an expression list. If pList is
  86471. ** initially NULL, then create a new expression list.
  86472. **
  86473. ** If a memory allocation error occurs, the entire list is freed and
  86474. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  86475. ** that the new entry was successfully appended.
  86476. */
  86477. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  86478. Parse *pParse, /* Parsing context */
  86479. ExprList *pList, /* List to which to append. Might be NULL */
  86480. Expr *pExpr /* Expression to be appended. Might be NULL */
  86481. ){
  86482. struct ExprList_item *pItem;
  86483. sqlite3 *db = pParse->db;
  86484. assert( db!=0 );
  86485. if( pList==0 ){
  86486. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  86487. if( pList==0 ){
  86488. goto no_mem;
  86489. }
  86490. pList->nExpr = 0;
  86491. pList->nAlloc = 1;
  86492. }else if( pList->nExpr==pList->nAlloc ){
  86493. ExprList *pNew;
  86494. pNew = sqlite3DbRealloc(db, pList,
  86495. sizeof(*pList)+(2*pList->nAlloc - 1)*sizeof(pList->a[0]));
  86496. if( pNew==0 ){
  86497. goto no_mem;
  86498. }
  86499. pList = pNew;
  86500. pList->nAlloc *= 2;
  86501. }
  86502. pItem = &pList->a[pList->nExpr++];
  86503. memset(pItem, 0, sizeof(*pItem));
  86504. pItem->pExpr = pExpr;
  86505. return pList;
  86506. no_mem:
  86507. /* Avoid leaking memory if malloc has failed. */
  86508. sqlite3ExprDelete(db, pExpr);
  86509. sqlite3ExprListDelete(db, pList);
  86510. return 0;
  86511. }
  86512. /*
  86513. ** pColumns and pExpr form a vector assignment which is part of the SET
  86514. ** clause of an UPDATE statement. Like this:
  86515. **
  86516. ** (a,b,c) = (expr1,expr2,expr3)
  86517. ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
  86518. **
  86519. ** For each term of the vector assignment, append new entries to the
  86520. ** expression list pList. In the case of a subquery on the RHS, append
  86521. ** TK_SELECT_COLUMN expressions.
  86522. */
  86523. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
  86524. Parse *pParse, /* Parsing context */
  86525. ExprList *pList, /* List to which to append. Might be NULL */
  86526. IdList *pColumns, /* List of names of LHS of the assignment */
  86527. Expr *pExpr /* Vector expression to be appended. Might be NULL */
  86528. ){
  86529. sqlite3 *db = pParse->db;
  86530. int n;
  86531. int i;
  86532. int iFirst = pList ? pList->nExpr : 0;
  86533. /* pColumns can only be NULL due to an OOM but an OOM will cause an
  86534. ** exit prior to this routine being invoked */
  86535. if( NEVER(pColumns==0) ) goto vector_append_error;
  86536. if( pExpr==0 ) goto vector_append_error;
  86537. /* If the RHS is a vector, then we can immediately check to see that
  86538. ** the size of the RHS and LHS match. But if the RHS is a SELECT,
  86539. ** wildcards ("*") in the result set of the SELECT must be expanded before
  86540. ** we can do the size check, so defer the size check until code generation.
  86541. */
  86542. if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
  86543. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  86544. pColumns->nId, n);
  86545. goto vector_append_error;
  86546. }
  86547. for(i=0; i<pColumns->nId; i++){
  86548. Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
  86549. pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
  86550. if( pList ){
  86551. assert( pList->nExpr==iFirst+i+1 );
  86552. pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
  86553. pColumns->a[i].zName = 0;
  86554. }
  86555. }
  86556. if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
  86557. Expr *pFirst = pList->a[iFirst].pExpr;
  86558. assert( pFirst!=0 );
  86559. assert( pFirst->op==TK_SELECT_COLUMN );
  86560. /* Store the SELECT statement in pRight so it will be deleted when
  86561. ** sqlite3ExprListDelete() is called */
  86562. pFirst->pRight = pExpr;
  86563. pExpr = 0;
  86564. /* Remember the size of the LHS in iTable so that we can check that
  86565. ** the RHS and LHS sizes match during code generation. */
  86566. pFirst->iTable = pColumns->nId;
  86567. }
  86568. vector_append_error:
  86569. sqlite3ExprDelete(db, pExpr);
  86570. sqlite3IdListDelete(db, pColumns);
  86571. return pList;
  86572. }
  86573. /*
  86574. ** Set the sort order for the last element on the given ExprList.
  86575. */
  86576. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  86577. if( p==0 ) return;
  86578. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  86579. assert( p->nExpr>0 );
  86580. if( iSortOrder<0 ){
  86581. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  86582. return;
  86583. }
  86584. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  86585. }
  86586. /*
  86587. ** Set the ExprList.a[].zName element of the most recently added item
  86588. ** on the expression list.
  86589. **
  86590. ** pList might be NULL following an OOM error. But pName should never be
  86591. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  86592. ** is set.
  86593. */
  86594. SQLITE_PRIVATE void sqlite3ExprListSetName(
  86595. Parse *pParse, /* Parsing context */
  86596. ExprList *pList, /* List to which to add the span. */
  86597. Token *pName, /* Name to be added */
  86598. int dequote /* True to cause the name to be dequoted */
  86599. ){
  86600. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  86601. if( pList ){
  86602. struct ExprList_item *pItem;
  86603. assert( pList->nExpr>0 );
  86604. pItem = &pList->a[pList->nExpr-1];
  86605. assert( pItem->zName==0 );
  86606. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  86607. if( dequote ) sqlite3Dequote(pItem->zName);
  86608. }
  86609. }
  86610. /*
  86611. ** Set the ExprList.a[].zSpan element of the most recently added item
  86612. ** on the expression list.
  86613. **
  86614. ** pList might be NULL following an OOM error. But pSpan should never be
  86615. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  86616. ** is set.
  86617. */
  86618. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  86619. Parse *pParse, /* Parsing context */
  86620. ExprList *pList, /* List to which to add the span. */
  86621. ExprSpan *pSpan /* The span to be added */
  86622. ){
  86623. sqlite3 *db = pParse->db;
  86624. assert( pList!=0 || db->mallocFailed!=0 );
  86625. if( pList ){
  86626. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  86627. assert( pList->nExpr>0 );
  86628. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  86629. sqlite3DbFree(db, pItem->zSpan);
  86630. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  86631. (int)(pSpan->zEnd - pSpan->zStart));
  86632. }
  86633. }
  86634. /*
  86635. ** If the expression list pEList contains more than iLimit elements,
  86636. ** leave an error message in pParse.
  86637. */
  86638. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  86639. Parse *pParse,
  86640. ExprList *pEList,
  86641. const char *zObject
  86642. ){
  86643. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  86644. testcase( pEList && pEList->nExpr==mx );
  86645. testcase( pEList && pEList->nExpr==mx+1 );
  86646. if( pEList && pEList->nExpr>mx ){
  86647. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  86648. }
  86649. }
  86650. /*
  86651. ** Delete an entire expression list.
  86652. */
  86653. static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
  86654. int i = pList->nExpr;
  86655. struct ExprList_item *pItem = pList->a;
  86656. assert( pList->nExpr>0 );
  86657. do{
  86658. sqlite3ExprDelete(db, pItem->pExpr);
  86659. sqlite3DbFree(db, pItem->zName);
  86660. sqlite3DbFree(db, pItem->zSpan);
  86661. pItem++;
  86662. }while( --i>0 );
  86663. sqlite3DbFreeNN(db, pList);
  86664. }
  86665. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  86666. if( pList ) exprListDeleteNN(db, pList);
  86667. }
  86668. /*
  86669. ** Return the bitwise-OR of all Expr.flags fields in the given
  86670. ** ExprList.
  86671. */
  86672. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  86673. int i;
  86674. u32 m = 0;
  86675. if( pList ){
  86676. for(i=0; i<pList->nExpr; i++){
  86677. Expr *pExpr = pList->a[i].pExpr;
  86678. assert( pExpr!=0 );
  86679. m |= pExpr->flags;
  86680. }
  86681. }
  86682. return m;
  86683. }
  86684. /*
  86685. ** These routines are Walker callbacks used to check expressions to
  86686. ** see if they are "constant" for some definition of constant. The
  86687. ** Walker.eCode value determines the type of "constant" we are looking
  86688. ** for.
  86689. **
  86690. ** These callback routines are used to implement the following:
  86691. **
  86692. ** sqlite3ExprIsConstant() pWalker->eCode==1
  86693. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  86694. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  86695. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  86696. **
  86697. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  86698. ** is found to not be a constant.
  86699. **
  86700. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  86701. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  86702. ** an existing schema and 4 when processing a new statement. A bound
  86703. ** parameter raises an error for new statements, but is silently converted
  86704. ** to NULL for existing schemas. This allows sqlite_master tables that
  86705. ** contain a bound parameter because they were generated by older versions
  86706. ** of SQLite to be parsed by newer versions of SQLite without raising a
  86707. ** malformed schema error.
  86708. */
  86709. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  86710. /* If pWalker->eCode is 2 then any term of the expression that comes from
  86711. ** the ON or USING clauses of a left join disqualifies the expression
  86712. ** from being considered constant. */
  86713. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  86714. pWalker->eCode = 0;
  86715. return WRC_Abort;
  86716. }
  86717. switch( pExpr->op ){
  86718. /* Consider functions to be constant if all their arguments are constant
  86719. ** and either pWalker->eCode==4 or 5 or the function has the
  86720. ** SQLITE_FUNC_CONST flag. */
  86721. case TK_FUNCTION:
  86722. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  86723. return WRC_Continue;
  86724. }else{
  86725. pWalker->eCode = 0;
  86726. return WRC_Abort;
  86727. }
  86728. case TK_ID:
  86729. case TK_COLUMN:
  86730. case TK_AGG_FUNCTION:
  86731. case TK_AGG_COLUMN:
  86732. testcase( pExpr->op==TK_ID );
  86733. testcase( pExpr->op==TK_COLUMN );
  86734. testcase( pExpr->op==TK_AGG_FUNCTION );
  86735. testcase( pExpr->op==TK_AGG_COLUMN );
  86736. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  86737. return WRC_Continue;
  86738. }
  86739. /* Fall through */
  86740. case TK_IF_NULL_ROW:
  86741. testcase( pExpr->op==TK_IF_NULL_ROW );
  86742. pWalker->eCode = 0;
  86743. return WRC_Abort;
  86744. case TK_VARIABLE:
  86745. if( pWalker->eCode==5 ){
  86746. /* Silently convert bound parameters that appear inside of CREATE
  86747. ** statements into a NULL when parsing the CREATE statement text out
  86748. ** of the sqlite_master table */
  86749. pExpr->op = TK_NULL;
  86750. }else if( pWalker->eCode==4 ){
  86751. /* A bound parameter in a CREATE statement that originates from
  86752. ** sqlite3_prepare() causes an error */
  86753. pWalker->eCode = 0;
  86754. return WRC_Abort;
  86755. }
  86756. /* Fall through */
  86757. default:
  86758. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  86759. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  86760. return WRC_Continue;
  86761. }
  86762. }
  86763. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  86764. UNUSED_PARAMETER(NotUsed);
  86765. pWalker->eCode = 0;
  86766. return WRC_Abort;
  86767. }
  86768. static int exprIsConst(Expr *p, int initFlag, int iCur){
  86769. Walker w;
  86770. memset(&w, 0, sizeof(w));
  86771. w.eCode = initFlag;
  86772. w.xExprCallback = exprNodeIsConstant;
  86773. w.xSelectCallback = selectNodeIsConstant;
  86774. w.u.iCur = iCur;
  86775. sqlite3WalkExpr(&w, p);
  86776. return w.eCode;
  86777. }
  86778. /*
  86779. ** Walk an expression tree. Return non-zero if the expression is constant
  86780. ** and 0 if it involves variables or function calls.
  86781. **
  86782. ** For the purposes of this function, a double-quoted string (ex: "abc")
  86783. ** is considered a variable but a single-quoted string (ex: 'abc') is
  86784. ** a constant.
  86785. */
  86786. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  86787. return exprIsConst(p, 1, 0);
  86788. }
  86789. /*
  86790. ** Walk an expression tree. Return non-zero if the expression is constant
  86791. ** that does no originate from the ON or USING clauses of a join.
  86792. ** Return 0 if it involves variables or function calls or terms from
  86793. ** an ON or USING clause.
  86794. */
  86795. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  86796. return exprIsConst(p, 2, 0);
  86797. }
  86798. /*
  86799. ** Walk an expression tree. Return non-zero if the expression is constant
  86800. ** for any single row of the table with cursor iCur. In other words, the
  86801. ** expression must not refer to any non-deterministic function nor any
  86802. ** table other than iCur.
  86803. */
  86804. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  86805. return exprIsConst(p, 3, iCur);
  86806. }
  86807. /*
  86808. ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
  86809. */
  86810. static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
  86811. ExprList *pGroupBy = pWalker->u.pGroupBy;
  86812. int i;
  86813. /* Check if pExpr is identical to any GROUP BY term. If so, consider
  86814. ** it constant. */
  86815. for(i=0; i<pGroupBy->nExpr; i++){
  86816. Expr *p = pGroupBy->a[i].pExpr;
  86817. if( sqlite3ExprCompare(pExpr, p, -1)<2 ){
  86818. CollSeq *pColl = sqlite3ExprCollSeq(pWalker->pParse, p);
  86819. if( pColl==0 || sqlite3_stricmp("BINARY", pColl->zName)==0 ){
  86820. return WRC_Prune;
  86821. }
  86822. }
  86823. }
  86824. /* Check if pExpr is a sub-select. If so, consider it variable. */
  86825. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  86826. pWalker->eCode = 0;
  86827. return WRC_Abort;
  86828. }
  86829. return exprNodeIsConstant(pWalker, pExpr);
  86830. }
  86831. /*
  86832. ** Walk the expression tree passed as the first argument. Return non-zero
  86833. ** if the expression consists entirely of constants or copies of terms
  86834. ** in pGroupBy that sort with the BINARY collation sequence.
  86835. **
  86836. ** This routine is used to determine if a term of the HAVING clause can
  86837. ** be promoted into the WHERE clause. In order for such a promotion to work,
  86838. ** the value of the HAVING clause term must be the same for all members of
  86839. ** a "group". The requirement that the GROUP BY term must be BINARY
  86840. ** assumes that no other collating sequence will have a finer-grained
  86841. ** grouping than binary. In other words (A=B COLLATE binary) implies
  86842. ** A=B in every other collating sequence. The requirement that the
  86843. ** GROUP BY be BINARY is stricter than necessary. It would also work
  86844. ** to promote HAVING clauses that use the same alternative collating
  86845. ** sequence as the GROUP BY term, but that is much harder to check,
  86846. ** alternative collating sequences are uncommon, and this is only an
  86847. ** optimization, so we take the easy way out and simply require the
  86848. ** GROUP BY to use the BINARY collating sequence.
  86849. */
  86850. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
  86851. Walker w;
  86852. memset(&w, 0, sizeof(w));
  86853. w.eCode = 1;
  86854. w.xExprCallback = exprNodeIsConstantOrGroupBy;
  86855. w.u.pGroupBy = pGroupBy;
  86856. w.pParse = pParse;
  86857. sqlite3WalkExpr(&w, p);
  86858. return w.eCode;
  86859. }
  86860. /*
  86861. ** Walk an expression tree. Return non-zero if the expression is constant
  86862. ** or a function call with constant arguments. Return and 0 if there
  86863. ** are any variables.
  86864. **
  86865. ** For the purposes of this function, a double-quoted string (ex: "abc")
  86866. ** is considered a variable but a single-quoted string (ex: 'abc') is
  86867. ** a constant.
  86868. */
  86869. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  86870. assert( isInit==0 || isInit==1 );
  86871. return exprIsConst(p, 4+isInit, 0);
  86872. }
  86873. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  86874. /*
  86875. ** Walk an expression tree. Return 1 if the expression contains a
  86876. ** subquery of some kind. Return 0 if there are no subqueries.
  86877. */
  86878. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  86879. Walker w;
  86880. memset(&w, 0, sizeof(w));
  86881. w.eCode = 1;
  86882. w.xExprCallback = sqlite3ExprWalkNoop;
  86883. w.xSelectCallback = selectNodeIsConstant;
  86884. sqlite3WalkExpr(&w, p);
  86885. return w.eCode==0;
  86886. }
  86887. #endif
  86888. /*
  86889. ** If the expression p codes a constant integer that is small enough
  86890. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  86891. ** in *pValue. If the expression is not an integer or if it is too big
  86892. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  86893. */
  86894. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  86895. int rc = 0;
  86896. if( p==0 ) return 0; /* Can only happen following on OOM */
  86897. /* If an expression is an integer literal that fits in a signed 32-bit
  86898. ** integer, then the EP_IntValue flag will have already been set */
  86899. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  86900. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  86901. if( p->flags & EP_IntValue ){
  86902. *pValue = p->u.iValue;
  86903. return 1;
  86904. }
  86905. switch( p->op ){
  86906. case TK_UPLUS: {
  86907. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  86908. break;
  86909. }
  86910. case TK_UMINUS: {
  86911. int v;
  86912. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  86913. assert( v!=(-2147483647-1) );
  86914. *pValue = -v;
  86915. rc = 1;
  86916. }
  86917. break;
  86918. }
  86919. default: break;
  86920. }
  86921. return rc;
  86922. }
  86923. /*
  86924. ** Return FALSE if there is no chance that the expression can be NULL.
  86925. **
  86926. ** If the expression might be NULL or if the expression is too complex
  86927. ** to tell return TRUE.
  86928. **
  86929. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  86930. ** when we know that a value cannot be NULL. Hence, a false positive
  86931. ** (returning TRUE when in fact the expression can never be NULL) might
  86932. ** be a small performance hit but is otherwise harmless. On the other
  86933. ** hand, a false negative (returning FALSE when the result could be NULL)
  86934. ** will likely result in an incorrect answer. So when in doubt, return
  86935. ** TRUE.
  86936. */
  86937. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  86938. u8 op;
  86939. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  86940. op = p->op;
  86941. if( op==TK_REGISTER ) op = p->op2;
  86942. switch( op ){
  86943. case TK_INTEGER:
  86944. case TK_STRING:
  86945. case TK_FLOAT:
  86946. case TK_BLOB:
  86947. return 0;
  86948. case TK_COLUMN:
  86949. assert( p->pTab!=0 );
  86950. return ExprHasProperty(p, EP_CanBeNull) ||
  86951. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  86952. default:
  86953. return 1;
  86954. }
  86955. }
  86956. /*
  86957. ** Return TRUE if the given expression is a constant which would be
  86958. ** unchanged by OP_Affinity with the affinity given in the second
  86959. ** argument.
  86960. **
  86961. ** This routine is used to determine if the OP_Affinity operation
  86962. ** can be omitted. When in doubt return FALSE. A false negative
  86963. ** is harmless. A false positive, however, can result in the wrong
  86964. ** answer.
  86965. */
  86966. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  86967. u8 op;
  86968. if( aff==SQLITE_AFF_BLOB ) return 1;
  86969. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  86970. op = p->op;
  86971. if( op==TK_REGISTER ) op = p->op2;
  86972. switch( op ){
  86973. case TK_INTEGER: {
  86974. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  86975. }
  86976. case TK_FLOAT: {
  86977. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  86978. }
  86979. case TK_STRING: {
  86980. return aff==SQLITE_AFF_TEXT;
  86981. }
  86982. case TK_BLOB: {
  86983. return 1;
  86984. }
  86985. case TK_COLUMN: {
  86986. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  86987. return p->iColumn<0
  86988. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  86989. }
  86990. default: {
  86991. return 0;
  86992. }
  86993. }
  86994. }
  86995. /*
  86996. ** Return TRUE if the given string is a row-id column name.
  86997. */
  86998. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  86999. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  87000. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  87001. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  87002. return 0;
  87003. }
  87004. /*
  87005. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  87006. ** that can be simplified to a direct table access, then return
  87007. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  87008. ** or if the SELECT statement needs to be manifested into a transient
  87009. ** table, then return NULL.
  87010. */
  87011. #ifndef SQLITE_OMIT_SUBQUERY
  87012. static Select *isCandidateForInOpt(Expr *pX){
  87013. Select *p;
  87014. SrcList *pSrc;
  87015. ExprList *pEList;
  87016. Table *pTab;
  87017. int i;
  87018. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  87019. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  87020. p = pX->x.pSelect;
  87021. if( p->pPrior ) return 0; /* Not a compound SELECT */
  87022. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  87023. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  87024. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  87025. return 0; /* No DISTINCT keyword and no aggregate functions */
  87026. }
  87027. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  87028. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  87029. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  87030. if( p->pWhere ) return 0; /* Has no WHERE clause */
  87031. pSrc = p->pSrc;
  87032. assert( pSrc!=0 );
  87033. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  87034. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  87035. pTab = pSrc->a[0].pTab;
  87036. assert( pTab!=0 );
  87037. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  87038. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  87039. pEList = p->pEList;
  87040. assert( pEList!=0 );
  87041. /* All SELECT results must be columns. */
  87042. for(i=0; i<pEList->nExpr; i++){
  87043. Expr *pRes = pEList->a[i].pExpr;
  87044. if( pRes->op!=TK_COLUMN ) return 0;
  87045. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  87046. }
  87047. return p;
  87048. }
  87049. #endif /* SQLITE_OMIT_SUBQUERY */
  87050. #ifndef SQLITE_OMIT_SUBQUERY
  87051. /*
  87052. ** Generate code that checks the left-most column of index table iCur to see if
  87053. ** it contains any NULL entries. Cause the register at regHasNull to be set
  87054. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  87055. ** to be set to NULL if iCur contains one or more NULL values.
  87056. */
  87057. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  87058. int addr1;
  87059. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  87060. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  87061. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  87062. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  87063. VdbeComment((v, "first_entry_in(%d)", iCur));
  87064. sqlite3VdbeJumpHere(v, addr1);
  87065. }
  87066. #endif
  87067. #ifndef SQLITE_OMIT_SUBQUERY
  87068. /*
  87069. ** The argument is an IN operator with a list (not a subquery) on the
  87070. ** right-hand side. Return TRUE if that list is constant.
  87071. */
  87072. static int sqlite3InRhsIsConstant(Expr *pIn){
  87073. Expr *pLHS;
  87074. int res;
  87075. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  87076. pLHS = pIn->pLeft;
  87077. pIn->pLeft = 0;
  87078. res = sqlite3ExprIsConstant(pIn);
  87079. pIn->pLeft = pLHS;
  87080. return res;
  87081. }
  87082. #endif
  87083. /*
  87084. ** This function is used by the implementation of the IN (...) operator.
  87085. ** The pX parameter is the expression on the RHS of the IN operator, which
  87086. ** might be either a list of expressions or a subquery.
  87087. **
  87088. ** The job of this routine is to find or create a b-tree object that can
  87089. ** be used either to test for membership in the RHS set or to iterate through
  87090. ** all members of the RHS set, skipping duplicates.
  87091. **
  87092. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  87093. ** and pX->iTable is set to the index of that cursor.
  87094. **
  87095. ** The returned value of this function indicates the b-tree type, as follows:
  87096. **
  87097. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  87098. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  87099. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  87100. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  87101. ** populated epheremal table.
  87102. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  87103. ** implemented as a sequence of comparisons.
  87104. **
  87105. ** An existing b-tree might be used if the RHS expression pX is a simple
  87106. ** subquery such as:
  87107. **
  87108. ** SELECT <column1>, <column2>... FROM <table>
  87109. **
  87110. ** If the RHS of the IN operator is a list or a more complex subquery, then
  87111. ** an ephemeral table might need to be generated from the RHS and then
  87112. ** pX->iTable made to point to the ephemeral table instead of an
  87113. ** existing table.
  87114. **
  87115. ** The inFlags parameter must contain exactly one of the bits
  87116. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  87117. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  87118. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  87119. ** IN index will be used to loop over all values of the RHS of the
  87120. ** IN operator.
  87121. **
  87122. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  87123. ** through the set members) then the b-tree must not contain duplicates.
  87124. ** An epheremal table must be used unless the selected columns are guaranteed
  87125. ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
  87126. ** a UNIQUE constraint or index.
  87127. **
  87128. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  87129. ** for fast set membership tests) then an epheremal table must
  87130. ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
  87131. ** index can be found with the specified <columns> as its left-most.
  87132. **
  87133. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  87134. ** if the RHS of the IN operator is a list (not a subquery) then this
  87135. ** routine might decide that creating an ephemeral b-tree for membership
  87136. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  87137. ** calling routine should implement the IN operator using a sequence
  87138. ** of Eq or Ne comparison operations.
  87139. **
  87140. ** When the b-tree is being used for membership tests, the calling function
  87141. ** might need to know whether or not the RHS side of the IN operator
  87142. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  87143. ** if there is any chance that the (...) might contain a NULL value at
  87144. ** runtime, then a register is allocated and the register number written
  87145. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  87146. ** NULL value, then *prRhsHasNull is left unchanged.
  87147. **
  87148. ** If a register is allocated and its location stored in *prRhsHasNull, then
  87149. ** the value in that register will be NULL if the b-tree contains one or more
  87150. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  87151. ** NULL values.
  87152. **
  87153. ** If the aiMap parameter is not NULL, it must point to an array containing
  87154. ** one element for each column returned by the SELECT statement on the RHS
  87155. ** of the IN(...) operator. The i'th entry of the array is populated with the
  87156. ** offset of the index column that matches the i'th column returned by the
  87157. ** SELECT. For example, if the expression and selected index are:
  87158. **
  87159. ** (?,?,?) IN (SELECT a, b, c FROM t1)
  87160. ** CREATE INDEX i1 ON t1(b, c, a);
  87161. **
  87162. ** then aiMap[] is populated with {2, 0, 1}.
  87163. */
  87164. #ifndef SQLITE_OMIT_SUBQUERY
  87165. SQLITE_PRIVATE int sqlite3FindInIndex(
  87166. Parse *pParse, /* Parsing context */
  87167. Expr *pX, /* The right-hand side (RHS) of the IN operator */
  87168. u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
  87169. int *prRhsHasNull, /* Register holding NULL status. See notes */
  87170. int *aiMap /* Mapping from Index fields to RHS fields */
  87171. ){
  87172. Select *p; /* SELECT to the right of IN operator */
  87173. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  87174. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  87175. int mustBeUnique; /* True if RHS must be unique */
  87176. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  87177. assert( pX->op==TK_IN );
  87178. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  87179. /* If the RHS of this IN(...) operator is a SELECT, and if it matters
  87180. ** whether or not the SELECT result contains NULL values, check whether
  87181. ** or not NULL is actually possible (it may not be, for example, due
  87182. ** to NOT NULL constraints in the schema). If no NULL values are possible,
  87183. ** set prRhsHasNull to 0 before continuing. */
  87184. if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
  87185. int i;
  87186. ExprList *pEList = pX->x.pSelect->pEList;
  87187. for(i=0; i<pEList->nExpr; i++){
  87188. if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
  87189. }
  87190. if( i==pEList->nExpr ){
  87191. prRhsHasNull = 0;
  87192. }
  87193. }
  87194. /* Check to see if an existing table or index can be used to
  87195. ** satisfy the query. This is preferable to generating a new
  87196. ** ephemeral table. */
  87197. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  87198. sqlite3 *db = pParse->db; /* Database connection */
  87199. Table *pTab; /* Table <table>. */
  87200. i16 iDb; /* Database idx for pTab */
  87201. ExprList *pEList = p->pEList;
  87202. int nExpr = pEList->nExpr;
  87203. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  87204. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  87205. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  87206. pTab = p->pSrc->a[0].pTab;
  87207. /* Code an OP_Transaction and OP_TableLock for <table>. */
  87208. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  87209. sqlite3CodeVerifySchema(pParse, iDb);
  87210. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  87211. assert(v); /* sqlite3GetVdbe() has always been previously called */
  87212. if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
  87213. /* The "x IN (SELECT rowid FROM table)" case */
  87214. int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
  87215. VdbeCoverage(v);
  87216. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  87217. eType = IN_INDEX_ROWID;
  87218. sqlite3VdbeJumpHere(v, iAddr);
  87219. }else{
  87220. Index *pIdx; /* Iterator variable */
  87221. int affinity_ok = 1;
  87222. int i;
  87223. /* Check that the affinity that will be used to perform each
  87224. ** comparison is the same as the affinity of each column in table
  87225. ** on the RHS of the IN operator. If it not, it is not possible to
  87226. ** use any index of the RHS table. */
  87227. for(i=0; i<nExpr && affinity_ok; i++){
  87228. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  87229. int iCol = pEList->a[i].pExpr->iColumn;
  87230. char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
  87231. char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
  87232. testcase( cmpaff==SQLITE_AFF_BLOB );
  87233. testcase( cmpaff==SQLITE_AFF_TEXT );
  87234. switch( cmpaff ){
  87235. case SQLITE_AFF_BLOB:
  87236. break;
  87237. case SQLITE_AFF_TEXT:
  87238. /* sqlite3CompareAffinity() only returns TEXT if one side or the
  87239. ** other has no affinity and the other side is TEXT. Hence,
  87240. ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
  87241. ** and for the term on the LHS of the IN to have no affinity. */
  87242. assert( idxaff==SQLITE_AFF_TEXT );
  87243. break;
  87244. default:
  87245. affinity_ok = sqlite3IsNumericAffinity(idxaff);
  87246. }
  87247. }
  87248. if( affinity_ok ){
  87249. /* Search for an existing index that will work for this IN operator */
  87250. for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
  87251. Bitmask colUsed; /* Columns of the index used */
  87252. Bitmask mCol; /* Mask for the current column */
  87253. if( pIdx->nColumn<nExpr ) continue;
  87254. /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
  87255. ** BITMASK(nExpr) without overflowing */
  87256. testcase( pIdx->nColumn==BMS-2 );
  87257. testcase( pIdx->nColumn==BMS-1 );
  87258. if( pIdx->nColumn>=BMS-1 ) continue;
  87259. if( mustBeUnique ){
  87260. if( pIdx->nKeyCol>nExpr
  87261. ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
  87262. ){
  87263. continue; /* This index is not unique over the IN RHS columns */
  87264. }
  87265. }
  87266. colUsed = 0; /* Columns of index used so far */
  87267. for(i=0; i<nExpr; i++){
  87268. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  87269. Expr *pRhs = pEList->a[i].pExpr;
  87270. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  87271. int j;
  87272. assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
  87273. for(j=0; j<nExpr; j++){
  87274. if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
  87275. assert( pIdx->azColl[j] );
  87276. if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
  87277. continue;
  87278. }
  87279. break;
  87280. }
  87281. if( j==nExpr ) break;
  87282. mCol = MASKBIT(j);
  87283. if( mCol & colUsed ) break; /* Each column used only once */
  87284. colUsed |= mCol;
  87285. if( aiMap ) aiMap[i] = j;
  87286. }
  87287. assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
  87288. if( colUsed==(MASKBIT(nExpr)-1) ){
  87289. /* If we reach this point, that means the index pIdx is usable */
  87290. int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  87291. #ifndef SQLITE_OMIT_EXPLAIN
  87292. sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
  87293. sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
  87294. P4_DYNAMIC);
  87295. #endif
  87296. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  87297. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  87298. VdbeComment((v, "%s", pIdx->zName));
  87299. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  87300. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  87301. if( prRhsHasNull ){
  87302. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  87303. i64 mask = (1<<nExpr)-1;
  87304. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
  87305. iTab, 0, 0, (u8*)&mask, P4_INT64);
  87306. #endif
  87307. *prRhsHasNull = ++pParse->nMem;
  87308. if( nExpr==1 ){
  87309. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  87310. }
  87311. }
  87312. sqlite3VdbeJumpHere(v, iAddr);
  87313. }
  87314. } /* End loop over indexes */
  87315. } /* End if( affinity_ok ) */
  87316. } /* End if not an rowid index */
  87317. } /* End attempt to optimize using an index */
  87318. /* If no preexisting index is available for the IN clause
  87319. ** and IN_INDEX_NOOP is an allowed reply
  87320. ** and the RHS of the IN operator is a list, not a subquery
  87321. ** and the RHS is not constant or has two or fewer terms,
  87322. ** then it is not worth creating an ephemeral table to evaluate
  87323. ** the IN operator so return IN_INDEX_NOOP.
  87324. */
  87325. if( eType==0
  87326. && (inFlags & IN_INDEX_NOOP_OK)
  87327. && !ExprHasProperty(pX, EP_xIsSelect)
  87328. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  87329. ){
  87330. eType = IN_INDEX_NOOP;
  87331. }
  87332. if( eType==0 ){
  87333. /* Could not find an existing table or index to use as the RHS b-tree.
  87334. ** We will have to generate an ephemeral table to do the job.
  87335. */
  87336. u32 savedNQueryLoop = pParse->nQueryLoop;
  87337. int rMayHaveNull = 0;
  87338. eType = IN_INDEX_EPH;
  87339. if( inFlags & IN_INDEX_LOOP ){
  87340. pParse->nQueryLoop = 0;
  87341. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  87342. eType = IN_INDEX_ROWID;
  87343. }
  87344. }else if( prRhsHasNull ){
  87345. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  87346. }
  87347. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  87348. pParse->nQueryLoop = savedNQueryLoop;
  87349. }else{
  87350. pX->iTable = iTab;
  87351. }
  87352. if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
  87353. int i, n;
  87354. n = sqlite3ExprVectorSize(pX->pLeft);
  87355. for(i=0; i<n; i++) aiMap[i] = i;
  87356. }
  87357. return eType;
  87358. }
  87359. #endif
  87360. #ifndef SQLITE_OMIT_SUBQUERY
  87361. /*
  87362. ** Argument pExpr is an (?, ?...) IN(...) expression. This
  87363. ** function allocates and returns a nul-terminated string containing
  87364. ** the affinities to be used for each column of the comparison.
  87365. **
  87366. ** It is the responsibility of the caller to ensure that the returned
  87367. ** string is eventually freed using sqlite3DbFree().
  87368. */
  87369. static char *exprINAffinity(Parse *pParse, Expr *pExpr){
  87370. Expr *pLeft = pExpr->pLeft;
  87371. int nVal = sqlite3ExprVectorSize(pLeft);
  87372. Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
  87373. char *zRet;
  87374. assert( pExpr->op==TK_IN );
  87375. zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
  87376. if( zRet ){
  87377. int i;
  87378. for(i=0; i<nVal; i++){
  87379. Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
  87380. char a = sqlite3ExprAffinity(pA);
  87381. if( pSelect ){
  87382. zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
  87383. }else{
  87384. zRet[i] = a;
  87385. }
  87386. }
  87387. zRet[nVal] = '\0';
  87388. }
  87389. return zRet;
  87390. }
  87391. #endif
  87392. #ifndef SQLITE_OMIT_SUBQUERY
  87393. /*
  87394. ** Load the Parse object passed as the first argument with an error
  87395. ** message of the form:
  87396. **
  87397. ** "sub-select returns N columns - expected M"
  87398. */
  87399. SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
  87400. const char *zFmt = "sub-select returns %d columns - expected %d";
  87401. sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
  87402. }
  87403. #endif
  87404. /*
  87405. ** Expression pExpr is a vector that has been used in a context where
  87406. ** it is not permitted. If pExpr is a sub-select vector, this routine
  87407. ** loads the Parse object with a message of the form:
  87408. **
  87409. ** "sub-select returns N columns - expected 1"
  87410. **
  87411. ** Or, if it is a regular scalar vector:
  87412. **
  87413. ** "row value misused"
  87414. */
  87415. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
  87416. #ifndef SQLITE_OMIT_SUBQUERY
  87417. if( pExpr->flags & EP_xIsSelect ){
  87418. sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
  87419. }else
  87420. #endif
  87421. {
  87422. sqlite3ErrorMsg(pParse, "row value misused");
  87423. }
  87424. }
  87425. /*
  87426. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  87427. ** or IN operators. Examples:
  87428. **
  87429. ** (SELECT a FROM b) -- subquery
  87430. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  87431. ** x IN (4,5,11) -- IN operator with list on right-hand side
  87432. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  87433. **
  87434. ** The pExpr parameter describes the expression that contains the IN
  87435. ** operator or subquery.
  87436. **
  87437. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  87438. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  87439. ** to some integer key column of a table B-Tree. In this case, use an
  87440. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  87441. ** (slower) variable length keys B-Tree.
  87442. **
  87443. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  87444. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  87445. ** All this routine does is initialize the register given by rMayHaveNull
  87446. ** to NULL. Calling routines will take care of changing this register
  87447. ** value to non-NULL if the RHS is NULL-free.
  87448. **
  87449. ** For a SELECT or EXISTS operator, return the register that holds the
  87450. ** result. For a multi-column SELECT, the result is stored in a contiguous
  87451. ** array of registers and the return value is the register of the left-most
  87452. ** result column. Return 0 for IN operators or if an error occurs.
  87453. */
  87454. #ifndef SQLITE_OMIT_SUBQUERY
  87455. SQLITE_PRIVATE int sqlite3CodeSubselect(
  87456. Parse *pParse, /* Parsing context */
  87457. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  87458. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  87459. int isRowid /* If true, LHS of IN operator is a rowid */
  87460. ){
  87461. int jmpIfDynamic = -1; /* One-time test address */
  87462. int rReg = 0; /* Register storing resulting */
  87463. Vdbe *v = sqlite3GetVdbe(pParse);
  87464. if( NEVER(v==0) ) return 0;
  87465. sqlite3ExprCachePush(pParse);
  87466. /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
  87467. ** is encountered if any of the following is true:
  87468. **
  87469. ** * The right-hand side is a correlated subquery
  87470. ** * The right-hand side is an expression list containing variables
  87471. ** * We are inside a trigger
  87472. **
  87473. ** If all of the above are false, then we can run this code just once
  87474. ** save the results, and reuse the same result on subsequent invocations.
  87475. */
  87476. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  87477. jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  87478. }
  87479. #ifndef SQLITE_OMIT_EXPLAIN
  87480. if( pParse->explain==2 ){
  87481. char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
  87482. jmpIfDynamic>=0?"":"CORRELATED ",
  87483. pExpr->op==TK_IN?"LIST":"SCALAR",
  87484. pParse->iNextSelectId
  87485. );
  87486. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  87487. }
  87488. #endif
  87489. switch( pExpr->op ){
  87490. case TK_IN: {
  87491. int addr; /* Address of OP_OpenEphemeral instruction */
  87492. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  87493. KeyInfo *pKeyInfo = 0; /* Key information */
  87494. int nVal; /* Size of vector pLeft */
  87495. nVal = sqlite3ExprVectorSize(pLeft);
  87496. assert( !isRowid || nVal==1 );
  87497. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  87498. ** expression it is handled the same way. An ephemeral table is
  87499. ** filled with index keys representing the results from the
  87500. ** SELECT or the <exprlist>.
  87501. **
  87502. ** If the 'x' expression is a column value, or the SELECT...
  87503. ** statement returns a column value, then the affinity of that
  87504. ** column is used to build the index keys. If both 'x' and the
  87505. ** SELECT... statement are columns, then numeric affinity is used
  87506. ** if either column has NUMERIC or INTEGER affinity. If neither
  87507. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  87508. ** is used.
  87509. */
  87510. pExpr->iTable = pParse->nTab++;
  87511. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
  87512. pExpr->iTable, (isRowid?0:nVal));
  87513. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
  87514. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  87515. /* Case 1: expr IN (SELECT ...)
  87516. **
  87517. ** Generate code to write the results of the select into the temporary
  87518. ** table allocated and opened above.
  87519. */
  87520. Select *pSelect = pExpr->x.pSelect;
  87521. ExprList *pEList = pSelect->pEList;
  87522. assert( !isRowid );
  87523. /* If the LHS and RHS of the IN operator do not match, that
  87524. ** error will have been caught long before we reach this point. */
  87525. if( ALWAYS(pEList->nExpr==nVal) ){
  87526. SelectDest dest;
  87527. int i;
  87528. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  87529. dest.zAffSdst = exprINAffinity(pParse, pExpr);
  87530. pSelect->iLimit = 0;
  87531. testcase( pSelect->selFlags & SF_Distinct );
  87532. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  87533. if( sqlite3Select(pParse, pSelect, &dest) ){
  87534. sqlite3DbFree(pParse->db, dest.zAffSdst);
  87535. sqlite3KeyInfoUnref(pKeyInfo);
  87536. return 0;
  87537. }
  87538. sqlite3DbFree(pParse->db, dest.zAffSdst);
  87539. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  87540. assert( pEList!=0 );
  87541. assert( pEList->nExpr>0 );
  87542. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  87543. for(i=0; i<nVal; i++){
  87544. Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
  87545. pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
  87546. pParse, p, pEList->a[i].pExpr
  87547. );
  87548. }
  87549. }
  87550. }else if( ALWAYS(pExpr->x.pList!=0) ){
  87551. /* Case 2: expr IN (exprlist)
  87552. **
  87553. ** For each expression, build an index key from the evaluation and
  87554. ** store it in the temporary table. If <expr> is a column, then use
  87555. ** that columns affinity when building index keys. If <expr> is not
  87556. ** a column, use numeric affinity.
  87557. */
  87558. char affinity; /* Affinity of the LHS of the IN */
  87559. int i;
  87560. ExprList *pList = pExpr->x.pList;
  87561. struct ExprList_item *pItem;
  87562. int r1, r2, r3;
  87563. affinity = sqlite3ExprAffinity(pLeft);
  87564. if( !affinity ){
  87565. affinity = SQLITE_AFF_BLOB;
  87566. }
  87567. if( pKeyInfo ){
  87568. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  87569. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  87570. }
  87571. /* Loop through each expression in <exprlist>. */
  87572. r1 = sqlite3GetTempReg(pParse);
  87573. r2 = sqlite3GetTempReg(pParse);
  87574. if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  87575. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  87576. Expr *pE2 = pItem->pExpr;
  87577. int iValToIns;
  87578. /* If the expression is not constant then we will need to
  87579. ** disable the test that was generated above that makes sure
  87580. ** this code only executes once. Because for a non-constant
  87581. ** expression we need to rerun this code each time.
  87582. */
  87583. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  87584. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  87585. jmpIfDynamic = -1;
  87586. }
  87587. /* Evaluate the expression and insert it into the temp table */
  87588. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  87589. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  87590. }else{
  87591. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  87592. if( isRowid ){
  87593. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  87594. sqlite3VdbeCurrentAddr(v)+2);
  87595. VdbeCoverage(v);
  87596. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  87597. }else{
  87598. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  87599. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  87600. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
  87601. }
  87602. }
  87603. }
  87604. sqlite3ReleaseTempReg(pParse, r1);
  87605. sqlite3ReleaseTempReg(pParse, r2);
  87606. }
  87607. if( pKeyInfo ){
  87608. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  87609. }
  87610. break;
  87611. }
  87612. case TK_EXISTS:
  87613. case TK_SELECT:
  87614. default: {
  87615. /* Case 3: (SELECT ... FROM ...)
  87616. ** or: EXISTS(SELECT ... FROM ...)
  87617. **
  87618. ** For a SELECT, generate code to put the values for all columns of
  87619. ** the first row into an array of registers and return the index of
  87620. ** the first register.
  87621. **
  87622. ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
  87623. ** into a register and return that register number.
  87624. **
  87625. ** In both cases, the query is augmented with "LIMIT 1". Any
  87626. ** preexisting limit is discarded in place of the new LIMIT 1.
  87627. */
  87628. Select *pSel; /* SELECT statement to encode */
  87629. SelectDest dest; /* How to deal with SELECT result */
  87630. int nReg; /* Registers to allocate */
  87631. testcase( pExpr->op==TK_EXISTS );
  87632. testcase( pExpr->op==TK_SELECT );
  87633. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  87634. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  87635. pSel = pExpr->x.pSelect;
  87636. nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
  87637. sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
  87638. pParse->nMem += nReg;
  87639. if( pExpr->op==TK_SELECT ){
  87640. dest.eDest = SRT_Mem;
  87641. dest.iSdst = dest.iSDParm;
  87642. dest.nSdst = nReg;
  87643. sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
  87644. VdbeComment((v, "Init subquery result"));
  87645. }else{
  87646. dest.eDest = SRT_Exists;
  87647. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  87648. VdbeComment((v, "Init EXISTS result"));
  87649. }
  87650. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  87651. pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
  87652. &sqlite3IntTokens[1], 0);
  87653. pSel->iLimit = 0;
  87654. pSel->selFlags &= ~SF_MultiValue;
  87655. if( sqlite3Select(pParse, pSel, &dest) ){
  87656. return 0;
  87657. }
  87658. rReg = dest.iSDParm;
  87659. ExprSetVVAProperty(pExpr, EP_NoReduce);
  87660. break;
  87661. }
  87662. }
  87663. if( rHasNullFlag ){
  87664. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  87665. }
  87666. if( jmpIfDynamic>=0 ){
  87667. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  87668. }
  87669. sqlite3ExprCachePop(pParse);
  87670. return rReg;
  87671. }
  87672. #endif /* SQLITE_OMIT_SUBQUERY */
  87673. #ifndef SQLITE_OMIT_SUBQUERY
  87674. /*
  87675. ** Expr pIn is an IN(...) expression. This function checks that the
  87676. ** sub-select on the RHS of the IN() operator has the same number of
  87677. ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
  87678. ** a sub-query, that the LHS is a vector of size 1.
  87679. */
  87680. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
  87681. int nVector = sqlite3ExprVectorSize(pIn->pLeft);
  87682. if( (pIn->flags & EP_xIsSelect) ){
  87683. if( nVector!=pIn->x.pSelect->pEList->nExpr ){
  87684. sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
  87685. return 1;
  87686. }
  87687. }else if( nVector!=1 ){
  87688. sqlite3VectorErrorMsg(pParse, pIn->pLeft);
  87689. return 1;
  87690. }
  87691. return 0;
  87692. }
  87693. #endif
  87694. #ifndef SQLITE_OMIT_SUBQUERY
  87695. /*
  87696. ** Generate code for an IN expression.
  87697. **
  87698. ** x IN (SELECT ...)
  87699. ** x IN (value, value, ...)
  87700. **
  87701. ** The left-hand side (LHS) is a scalar or vector expression. The
  87702. ** right-hand side (RHS) is an array of zero or more scalar values, or a
  87703. ** subquery. If the RHS is a subquery, the number of result columns must
  87704. ** match the number of columns in the vector on the LHS. If the RHS is
  87705. ** a list of values, the LHS must be a scalar.
  87706. **
  87707. ** The IN operator is true if the LHS value is contained within the RHS.
  87708. ** The result is false if the LHS is definitely not in the RHS. The
  87709. ** result is NULL if the presence of the LHS in the RHS cannot be
  87710. ** determined due to NULLs.
  87711. **
  87712. ** This routine generates code that jumps to destIfFalse if the LHS is not
  87713. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  87714. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  87715. ** within the RHS then fall through.
  87716. **
  87717. ** See the separate in-operator.md documentation file in the canonical
  87718. ** SQLite source tree for additional information.
  87719. */
  87720. static void sqlite3ExprCodeIN(
  87721. Parse *pParse, /* Parsing and code generating context */
  87722. Expr *pExpr, /* The IN expression */
  87723. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  87724. int destIfNull /* Jump here if the results are unknown due to NULLs */
  87725. ){
  87726. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  87727. int eType; /* Type of the RHS */
  87728. int rLhs; /* Register(s) holding the LHS values */
  87729. int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
  87730. Vdbe *v; /* Statement under construction */
  87731. int *aiMap = 0; /* Map from vector field to index column */
  87732. char *zAff = 0; /* Affinity string for comparisons */
  87733. int nVector; /* Size of vectors for this IN operator */
  87734. int iDummy; /* Dummy parameter to exprCodeVector() */
  87735. Expr *pLeft; /* The LHS of the IN operator */
  87736. int i; /* loop counter */
  87737. int destStep2; /* Where to jump when NULLs seen in step 2 */
  87738. int destStep6 = 0; /* Start of code for Step 6 */
  87739. int addrTruthOp; /* Address of opcode that determines the IN is true */
  87740. int destNotNull; /* Jump here if a comparison is not true in step 6 */
  87741. int addrTop; /* Top of the step-6 loop */
  87742. pLeft = pExpr->pLeft;
  87743. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  87744. zAff = exprINAffinity(pParse, pExpr);
  87745. nVector = sqlite3ExprVectorSize(pExpr->pLeft);
  87746. aiMap = (int*)sqlite3DbMallocZero(
  87747. pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
  87748. );
  87749. if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
  87750. /* Attempt to compute the RHS. After this step, if anything other than
  87751. ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
  87752. ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
  87753. ** the RHS has not yet been coded. */
  87754. v = pParse->pVdbe;
  87755. assert( v!=0 ); /* OOM detected prior to this routine */
  87756. VdbeNoopComment((v, "begin IN expr"));
  87757. eType = sqlite3FindInIndex(pParse, pExpr,
  87758. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  87759. destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
  87760. assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
  87761. || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
  87762. );
  87763. #ifdef SQLITE_DEBUG
  87764. /* Confirm that aiMap[] contains nVector integer values between 0 and
  87765. ** nVector-1. */
  87766. for(i=0; i<nVector; i++){
  87767. int j, cnt;
  87768. for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
  87769. assert( cnt==1 );
  87770. }
  87771. #endif
  87772. /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
  87773. ** vector, then it is stored in an array of nVector registers starting
  87774. ** at r1.
  87775. **
  87776. ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
  87777. ** so that the fields are in the same order as an existing index. The
  87778. ** aiMap[] array contains a mapping from the original LHS field order to
  87779. ** the field order that matches the RHS index.
  87780. */
  87781. sqlite3ExprCachePush(pParse);
  87782. rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
  87783. for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
  87784. if( i==nVector ){
  87785. /* LHS fields are not reordered */
  87786. rLhs = rLhsOrig;
  87787. }else{
  87788. /* Need to reorder the LHS fields according to aiMap */
  87789. rLhs = sqlite3GetTempRange(pParse, nVector);
  87790. for(i=0; i<nVector; i++){
  87791. sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
  87792. }
  87793. }
  87794. /* If sqlite3FindInIndex() did not find or create an index that is
  87795. ** suitable for evaluating the IN operator, then evaluate using a
  87796. ** sequence of comparisons.
  87797. **
  87798. ** This is step (1) in the in-operator.md optimized algorithm.
  87799. */
  87800. if( eType==IN_INDEX_NOOP ){
  87801. ExprList *pList = pExpr->x.pList;
  87802. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  87803. int labelOk = sqlite3VdbeMakeLabel(v);
  87804. int r2, regToFree;
  87805. int regCkNull = 0;
  87806. int ii;
  87807. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  87808. if( destIfNull!=destIfFalse ){
  87809. regCkNull = sqlite3GetTempReg(pParse);
  87810. sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
  87811. }
  87812. for(ii=0; ii<pList->nExpr; ii++){
  87813. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  87814. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  87815. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  87816. }
  87817. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  87818. sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
  87819. (void*)pColl, P4_COLLSEQ);
  87820. VdbeCoverageIf(v, ii<pList->nExpr-1);
  87821. VdbeCoverageIf(v, ii==pList->nExpr-1);
  87822. sqlite3VdbeChangeP5(v, zAff[0]);
  87823. }else{
  87824. assert( destIfNull==destIfFalse );
  87825. sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
  87826. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  87827. sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
  87828. }
  87829. sqlite3ReleaseTempReg(pParse, regToFree);
  87830. }
  87831. if( regCkNull ){
  87832. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  87833. sqlite3VdbeGoto(v, destIfFalse);
  87834. }
  87835. sqlite3VdbeResolveLabel(v, labelOk);
  87836. sqlite3ReleaseTempReg(pParse, regCkNull);
  87837. goto sqlite3ExprCodeIN_finished;
  87838. }
  87839. /* Step 2: Check to see if the LHS contains any NULL columns. If the
  87840. ** LHS does contain NULLs then the result must be either FALSE or NULL.
  87841. ** We will then skip the binary search of the RHS.
  87842. */
  87843. if( destIfNull==destIfFalse ){
  87844. destStep2 = destIfFalse;
  87845. }else{
  87846. destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
  87847. }
  87848. for(i=0; i<nVector; i++){
  87849. Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
  87850. if( sqlite3ExprCanBeNull(p) ){
  87851. sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
  87852. VdbeCoverage(v);
  87853. }
  87854. }
  87855. /* Step 3. The LHS is now known to be non-NULL. Do the binary search
  87856. ** of the RHS using the LHS as a probe. If found, the result is
  87857. ** true.
  87858. */
  87859. if( eType==IN_INDEX_ROWID ){
  87860. /* In this case, the RHS is the ROWID of table b-tree and so we also
  87861. ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
  87862. ** into a single opcode. */
  87863. sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
  87864. VdbeCoverage(v);
  87865. addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
  87866. }else{
  87867. sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
  87868. if( destIfFalse==destIfNull ){
  87869. /* Combine Step 3 and Step 5 into a single opcode */
  87870. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
  87871. rLhs, nVector); VdbeCoverage(v);
  87872. goto sqlite3ExprCodeIN_finished;
  87873. }
  87874. /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
  87875. addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
  87876. rLhs, nVector); VdbeCoverage(v);
  87877. }
  87878. /* Step 4. If the RHS is known to be non-NULL and we did not find
  87879. ** an match on the search above, then the result must be FALSE.
  87880. */
  87881. if( rRhsHasNull && nVector==1 ){
  87882. sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
  87883. VdbeCoverage(v);
  87884. }
  87885. /* Step 5. If we do not care about the difference between NULL and
  87886. ** FALSE, then just return false.
  87887. */
  87888. if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
  87889. /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
  87890. ** If any comparison is NULL, then the result is NULL. If all
  87891. ** comparisons are FALSE then the final result is FALSE.
  87892. **
  87893. ** For a scalar LHS, it is sufficient to check just the first row
  87894. ** of the RHS.
  87895. */
  87896. if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
  87897. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  87898. VdbeCoverage(v);
  87899. if( nVector>1 ){
  87900. destNotNull = sqlite3VdbeMakeLabel(v);
  87901. }else{
  87902. /* For nVector==1, combine steps 6 and 7 by immediately returning
  87903. ** FALSE if the first comparison is not NULL */
  87904. destNotNull = destIfFalse;
  87905. }
  87906. for(i=0; i<nVector; i++){
  87907. Expr *p;
  87908. CollSeq *pColl;
  87909. int r3 = sqlite3GetTempReg(pParse);
  87910. p = sqlite3VectorFieldSubexpr(pLeft, i);
  87911. pColl = sqlite3ExprCollSeq(pParse, p);
  87912. sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
  87913. sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
  87914. (void*)pColl, P4_COLLSEQ);
  87915. VdbeCoverage(v);
  87916. sqlite3ReleaseTempReg(pParse, r3);
  87917. }
  87918. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  87919. if( nVector>1 ){
  87920. sqlite3VdbeResolveLabel(v, destNotNull);
  87921. sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
  87922. VdbeCoverage(v);
  87923. /* Step 7: If we reach this point, we know that the result must
  87924. ** be false. */
  87925. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  87926. }
  87927. /* Jumps here in order to return true. */
  87928. sqlite3VdbeJumpHere(v, addrTruthOp);
  87929. sqlite3ExprCodeIN_finished:
  87930. if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
  87931. sqlite3ExprCachePop(pParse);
  87932. VdbeComment((v, "end IN expr"));
  87933. sqlite3ExprCodeIN_oom_error:
  87934. sqlite3DbFree(pParse->db, aiMap);
  87935. sqlite3DbFree(pParse->db, zAff);
  87936. }
  87937. #endif /* SQLITE_OMIT_SUBQUERY */
  87938. #ifndef SQLITE_OMIT_FLOATING_POINT
  87939. /*
  87940. ** Generate an instruction that will put the floating point
  87941. ** value described by z[0..n-1] into register iMem.
  87942. **
  87943. ** The z[] string will probably not be zero-terminated. But the
  87944. ** z[n] character is guaranteed to be something that does not look
  87945. ** like the continuation of the number.
  87946. */
  87947. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  87948. if( ALWAYS(z!=0) ){
  87949. double value;
  87950. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  87951. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  87952. if( negateFlag ) value = -value;
  87953. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  87954. }
  87955. }
  87956. #endif
  87957. /*
  87958. ** Generate an instruction that will put the integer describe by
  87959. ** text z[0..n-1] into register iMem.
  87960. **
  87961. ** Expr.u.zToken is always UTF8 and zero-terminated.
  87962. */
  87963. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  87964. Vdbe *v = pParse->pVdbe;
  87965. if( pExpr->flags & EP_IntValue ){
  87966. int i = pExpr->u.iValue;
  87967. assert( i>=0 );
  87968. if( negFlag ) i = -i;
  87969. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  87970. }else{
  87971. int c;
  87972. i64 value;
  87973. const char *z = pExpr->u.zToken;
  87974. assert( z!=0 );
  87975. c = sqlite3DecOrHexToI64(z, &value);
  87976. if( c==1 || (c==2 && !negFlag) || (negFlag && value==SMALLEST_INT64)){
  87977. #ifdef SQLITE_OMIT_FLOATING_POINT
  87978. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  87979. #else
  87980. #ifndef SQLITE_OMIT_HEX_INTEGER
  87981. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  87982. sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
  87983. }else
  87984. #endif
  87985. {
  87986. codeReal(v, z, negFlag, iMem);
  87987. }
  87988. #endif
  87989. }else{
  87990. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  87991. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  87992. }
  87993. }
  87994. }
  87995. /*
  87996. ** Erase column-cache entry number i
  87997. */
  87998. static void cacheEntryClear(Parse *pParse, int i){
  87999. if( pParse->aColCache[i].tempReg ){
  88000. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  88001. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  88002. }
  88003. }
  88004. pParse->nColCache--;
  88005. if( i<pParse->nColCache ){
  88006. pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
  88007. }
  88008. }
  88009. /*
  88010. ** Record in the column cache that a particular column from a
  88011. ** particular table is stored in a particular register.
  88012. */
  88013. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  88014. int i;
  88015. int minLru;
  88016. int idxLru;
  88017. struct yColCache *p;
  88018. /* Unless an error has occurred, register numbers are always positive. */
  88019. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  88020. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  88021. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  88022. ** for testing only - to verify that SQLite always gets the same answer
  88023. ** with and without the column cache.
  88024. */
  88025. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  88026. /* First replace any existing entry.
  88027. **
  88028. ** Actually, the way the column cache is currently used, we are guaranteed
  88029. ** that the object will never already be in cache. Verify this guarantee.
  88030. */
  88031. #ifndef NDEBUG
  88032. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  88033. assert( p->iTable!=iTab || p->iColumn!=iCol );
  88034. }
  88035. #endif
  88036. /* If the cache is already full, delete the least recently used entry */
  88037. if( pParse->nColCache>=SQLITE_N_COLCACHE ){
  88038. minLru = 0x7fffffff;
  88039. idxLru = -1;
  88040. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  88041. if( p->lru<minLru ){
  88042. idxLru = i;
  88043. minLru = p->lru;
  88044. }
  88045. }
  88046. p = &pParse->aColCache[idxLru];
  88047. }else{
  88048. p = &pParse->aColCache[pParse->nColCache++];
  88049. }
  88050. /* Add the new entry to the end of the cache */
  88051. p->iLevel = pParse->iCacheLevel;
  88052. p->iTable = iTab;
  88053. p->iColumn = iCol;
  88054. p->iReg = iReg;
  88055. p->tempReg = 0;
  88056. p->lru = pParse->iCacheCnt++;
  88057. }
  88058. /*
  88059. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  88060. ** Purge the range of registers from the column cache.
  88061. */
  88062. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  88063. int i = 0;
  88064. while( i<pParse->nColCache ){
  88065. struct yColCache *p = &pParse->aColCache[i];
  88066. if( p->iReg >= iReg && p->iReg < iReg+nReg ){
  88067. cacheEntryClear(pParse, i);
  88068. }else{
  88069. i++;
  88070. }
  88071. }
  88072. }
  88073. /*
  88074. ** Remember the current column cache context. Any new entries added
  88075. ** added to the column cache after this call are removed when the
  88076. ** corresponding pop occurs.
  88077. */
  88078. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  88079. pParse->iCacheLevel++;
  88080. #ifdef SQLITE_DEBUG
  88081. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  88082. printf("PUSH to %d\n", pParse->iCacheLevel);
  88083. }
  88084. #endif
  88085. }
  88086. /*
  88087. ** Remove from the column cache any entries that were added since the
  88088. ** the previous sqlite3ExprCachePush operation. In other words, restore
  88089. ** the cache to the state it was in prior the most recent Push.
  88090. */
  88091. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  88092. int i = 0;
  88093. assert( pParse->iCacheLevel>=1 );
  88094. pParse->iCacheLevel--;
  88095. #ifdef SQLITE_DEBUG
  88096. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  88097. printf("POP to %d\n", pParse->iCacheLevel);
  88098. }
  88099. #endif
  88100. while( i<pParse->nColCache ){
  88101. if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
  88102. cacheEntryClear(pParse, i);
  88103. }else{
  88104. i++;
  88105. }
  88106. }
  88107. }
  88108. /*
  88109. ** When a cached column is reused, make sure that its register is
  88110. ** no longer available as a temp register. ticket #3879: that same
  88111. ** register might be in the cache in multiple places, so be sure to
  88112. ** get them all.
  88113. */
  88114. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  88115. int i;
  88116. struct yColCache *p;
  88117. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  88118. if( p->iReg==iReg ){
  88119. p->tempReg = 0;
  88120. }
  88121. }
  88122. }
  88123. /* Generate code that will load into register regOut a value that is
  88124. ** appropriate for the iIdxCol-th column of index pIdx.
  88125. */
  88126. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  88127. Parse *pParse, /* The parsing context */
  88128. Index *pIdx, /* The index whose column is to be loaded */
  88129. int iTabCur, /* Cursor pointing to a table row */
  88130. int iIdxCol, /* The column of the index to be loaded */
  88131. int regOut /* Store the index column value in this register */
  88132. ){
  88133. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  88134. if( iTabCol==XN_EXPR ){
  88135. assert( pIdx->aColExpr );
  88136. assert( pIdx->aColExpr->nExpr>iIdxCol );
  88137. pParse->iSelfTab = iTabCur;
  88138. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  88139. }else{
  88140. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  88141. iTabCol, regOut);
  88142. }
  88143. }
  88144. /*
  88145. ** Generate code to extract the value of the iCol-th column of a table.
  88146. */
  88147. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  88148. Vdbe *v, /* The VDBE under construction */
  88149. Table *pTab, /* The table containing the value */
  88150. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  88151. int iCol, /* Index of the column to extract */
  88152. int regOut /* Extract the value into this register */
  88153. ){
  88154. if( pTab==0 ){
  88155. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
  88156. return;
  88157. }
  88158. if( iCol<0 || iCol==pTab->iPKey ){
  88159. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  88160. }else{
  88161. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  88162. int x = iCol;
  88163. if( !HasRowid(pTab) && !IsVirtual(pTab) ){
  88164. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  88165. }
  88166. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  88167. }
  88168. if( iCol>=0 ){
  88169. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  88170. }
  88171. }
  88172. /*
  88173. ** Generate code that will extract the iColumn-th column from
  88174. ** table pTab and store the column value in a register.
  88175. **
  88176. ** An effort is made to store the column value in register iReg. This
  88177. ** is not garanteeed for GetColumn() - the result can be stored in
  88178. ** any register. But the result is guaranteed to land in register iReg
  88179. ** for GetColumnToReg().
  88180. **
  88181. ** There must be an open cursor to pTab in iTable when this routine
  88182. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  88183. */
  88184. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  88185. Parse *pParse, /* Parsing and code generating context */
  88186. Table *pTab, /* Description of the table we are reading from */
  88187. int iColumn, /* Index of the table column */
  88188. int iTable, /* The cursor pointing to the table */
  88189. int iReg, /* Store results here */
  88190. u8 p5 /* P5 value for OP_Column + FLAGS */
  88191. ){
  88192. Vdbe *v = pParse->pVdbe;
  88193. int i;
  88194. struct yColCache *p;
  88195. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  88196. if( p->iTable==iTable && p->iColumn==iColumn ){
  88197. p->lru = pParse->iCacheCnt++;
  88198. sqlite3ExprCachePinRegister(pParse, p->iReg);
  88199. return p->iReg;
  88200. }
  88201. }
  88202. assert( v!=0 );
  88203. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  88204. if( p5 ){
  88205. sqlite3VdbeChangeP5(v, p5);
  88206. }else{
  88207. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  88208. }
  88209. return iReg;
  88210. }
  88211. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
  88212. Parse *pParse, /* Parsing and code generating context */
  88213. Table *pTab, /* Description of the table we are reading from */
  88214. int iColumn, /* Index of the table column */
  88215. int iTable, /* The cursor pointing to the table */
  88216. int iReg /* Store results here */
  88217. ){
  88218. int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
  88219. if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
  88220. }
  88221. /*
  88222. ** Clear all column cache entries.
  88223. */
  88224. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  88225. int i;
  88226. #ifdef SQLITE_DEBUG
  88227. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  88228. printf("CLEAR\n");
  88229. }
  88230. #endif
  88231. for(i=0; i<pParse->nColCache; i++){
  88232. if( pParse->aColCache[i].tempReg
  88233. && pParse->nTempReg<ArraySize(pParse->aTempReg)
  88234. ){
  88235. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  88236. }
  88237. }
  88238. pParse->nColCache = 0;
  88239. }
  88240. /*
  88241. ** Record the fact that an affinity change has occurred on iCount
  88242. ** registers starting with iStart.
  88243. */
  88244. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  88245. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  88246. }
  88247. /*
  88248. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  88249. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  88250. */
  88251. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  88252. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  88253. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  88254. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  88255. }
  88256. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  88257. /*
  88258. ** Return true if any register in the range iFrom..iTo (inclusive)
  88259. ** is used as part of the column cache.
  88260. **
  88261. ** This routine is used within assert() and testcase() macros only
  88262. ** and does not appear in a normal build.
  88263. */
  88264. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  88265. int i;
  88266. struct yColCache *p;
  88267. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  88268. int r = p->iReg;
  88269. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  88270. }
  88271. return 0;
  88272. }
  88273. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  88274. /*
  88275. ** Convert a scalar expression node to a TK_REGISTER referencing
  88276. ** register iReg. The caller must ensure that iReg already contains
  88277. ** the correct value for the expression.
  88278. */
  88279. static void exprToRegister(Expr *p, int iReg){
  88280. p->op2 = p->op;
  88281. p->op = TK_REGISTER;
  88282. p->iTable = iReg;
  88283. ExprClearProperty(p, EP_Skip);
  88284. }
  88285. /*
  88286. ** Evaluate an expression (either a vector or a scalar expression) and store
  88287. ** the result in continguous temporary registers. Return the index of
  88288. ** the first register used to store the result.
  88289. **
  88290. ** If the returned result register is a temporary scalar, then also write
  88291. ** that register number into *piFreeable. If the returned result register
  88292. ** is not a temporary or if the expression is a vector set *piFreeable
  88293. ** to 0.
  88294. */
  88295. static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
  88296. int iResult;
  88297. int nResult = sqlite3ExprVectorSize(p);
  88298. if( nResult==1 ){
  88299. iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
  88300. }else{
  88301. *piFreeable = 0;
  88302. if( p->op==TK_SELECT ){
  88303. #if SQLITE_OMIT_SUBQUERY
  88304. iResult = 0;
  88305. #else
  88306. iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
  88307. #endif
  88308. }else{
  88309. int i;
  88310. iResult = pParse->nMem+1;
  88311. pParse->nMem += nResult;
  88312. for(i=0; i<nResult; i++){
  88313. sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
  88314. }
  88315. }
  88316. }
  88317. return iResult;
  88318. }
  88319. /*
  88320. ** Generate code into the current Vdbe to evaluate the given
  88321. ** expression. Attempt to store the results in register "target".
  88322. ** Return the register where results are stored.
  88323. **
  88324. ** With this routine, there is no guarantee that results will
  88325. ** be stored in target. The result might be stored in some other
  88326. ** register if it is convenient to do so. The calling function
  88327. ** must check the return code and move the results to the desired
  88328. ** register.
  88329. */
  88330. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  88331. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  88332. int op; /* The opcode being coded */
  88333. int inReg = target; /* Results stored in register inReg */
  88334. int regFree1 = 0; /* If non-zero free this temporary register */
  88335. int regFree2 = 0; /* If non-zero free this temporary register */
  88336. int r1, r2; /* Various register numbers */
  88337. Expr tempX; /* Temporary expression node */
  88338. int p5 = 0;
  88339. assert( target>0 && target<=pParse->nMem );
  88340. if( v==0 ){
  88341. assert( pParse->db->mallocFailed );
  88342. return 0;
  88343. }
  88344. if( pExpr==0 ){
  88345. op = TK_NULL;
  88346. }else{
  88347. op = pExpr->op;
  88348. }
  88349. switch( op ){
  88350. case TK_AGG_COLUMN: {
  88351. AggInfo *pAggInfo = pExpr->pAggInfo;
  88352. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  88353. if( !pAggInfo->directMode ){
  88354. assert( pCol->iMem>0 );
  88355. return pCol->iMem;
  88356. }else if( pAggInfo->useSortingIdx ){
  88357. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  88358. pCol->iSorterColumn, target);
  88359. return target;
  88360. }
  88361. /* Otherwise, fall thru into the TK_COLUMN case */
  88362. }
  88363. case TK_COLUMN: {
  88364. int iTab = pExpr->iTable;
  88365. if( iTab<0 ){
  88366. if( pParse->ckBase>0 ){
  88367. /* Generating CHECK constraints or inserting into partial index */
  88368. return pExpr->iColumn + pParse->ckBase;
  88369. }else{
  88370. /* Coding an expression that is part of an index where column names
  88371. ** in the index refer to the table to which the index belongs */
  88372. iTab = pParse->iSelfTab;
  88373. }
  88374. }
  88375. return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  88376. pExpr->iColumn, iTab, target,
  88377. pExpr->op2);
  88378. }
  88379. case TK_INTEGER: {
  88380. codeInteger(pParse, pExpr, 0, target);
  88381. return target;
  88382. }
  88383. #ifndef SQLITE_OMIT_FLOATING_POINT
  88384. case TK_FLOAT: {
  88385. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88386. codeReal(v, pExpr->u.zToken, 0, target);
  88387. return target;
  88388. }
  88389. #endif
  88390. case TK_STRING: {
  88391. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88392. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  88393. return target;
  88394. }
  88395. case TK_NULL: {
  88396. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  88397. return target;
  88398. }
  88399. #ifndef SQLITE_OMIT_BLOB_LITERAL
  88400. case TK_BLOB: {
  88401. int n;
  88402. const char *z;
  88403. char *zBlob;
  88404. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88405. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  88406. assert( pExpr->u.zToken[1]=='\'' );
  88407. z = &pExpr->u.zToken[2];
  88408. n = sqlite3Strlen30(z) - 1;
  88409. assert( z[n]=='\'' );
  88410. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  88411. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  88412. return target;
  88413. }
  88414. #endif
  88415. case TK_VARIABLE: {
  88416. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88417. assert( pExpr->u.zToken!=0 );
  88418. assert( pExpr->u.zToken[0]!=0 );
  88419. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  88420. if( pExpr->u.zToken[1]!=0 ){
  88421. const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
  88422. assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
  88423. pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
  88424. sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
  88425. }
  88426. return target;
  88427. }
  88428. case TK_REGISTER: {
  88429. return pExpr->iTable;
  88430. }
  88431. #ifndef SQLITE_OMIT_CAST
  88432. case TK_CAST: {
  88433. /* Expressions of the form: CAST(pLeft AS token) */
  88434. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  88435. if( inReg!=target ){
  88436. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  88437. inReg = target;
  88438. }
  88439. sqlite3VdbeAddOp2(v, OP_Cast, target,
  88440. sqlite3AffinityType(pExpr->u.zToken, 0));
  88441. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  88442. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  88443. return inReg;
  88444. }
  88445. #endif /* SQLITE_OMIT_CAST */
  88446. case TK_IS:
  88447. case TK_ISNOT:
  88448. op = (op==TK_IS) ? TK_EQ : TK_NE;
  88449. p5 = SQLITE_NULLEQ;
  88450. /* fall-through */
  88451. case TK_LT:
  88452. case TK_LE:
  88453. case TK_GT:
  88454. case TK_GE:
  88455. case TK_NE:
  88456. case TK_EQ: {
  88457. Expr *pLeft = pExpr->pLeft;
  88458. if( sqlite3ExprIsVector(pLeft) ){
  88459. codeVectorCompare(pParse, pExpr, target, op, p5);
  88460. }else{
  88461. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  88462. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  88463. codeCompare(pParse, pLeft, pExpr->pRight, op,
  88464. r1, r2, inReg, SQLITE_STOREP2 | p5);
  88465. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  88466. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  88467. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  88468. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  88469. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  88470. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  88471. testcase( regFree1==0 );
  88472. testcase( regFree2==0 );
  88473. }
  88474. break;
  88475. }
  88476. case TK_AND:
  88477. case TK_OR:
  88478. case TK_PLUS:
  88479. case TK_STAR:
  88480. case TK_MINUS:
  88481. case TK_REM:
  88482. case TK_BITAND:
  88483. case TK_BITOR:
  88484. case TK_SLASH:
  88485. case TK_LSHIFT:
  88486. case TK_RSHIFT:
  88487. case TK_CONCAT: {
  88488. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  88489. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  88490. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  88491. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  88492. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  88493. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  88494. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  88495. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  88496. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  88497. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  88498. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  88499. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  88500. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  88501. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  88502. testcase( regFree1==0 );
  88503. testcase( regFree2==0 );
  88504. break;
  88505. }
  88506. case TK_UMINUS: {
  88507. Expr *pLeft = pExpr->pLeft;
  88508. assert( pLeft );
  88509. if( pLeft->op==TK_INTEGER ){
  88510. codeInteger(pParse, pLeft, 1, target);
  88511. return target;
  88512. #ifndef SQLITE_OMIT_FLOATING_POINT
  88513. }else if( pLeft->op==TK_FLOAT ){
  88514. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88515. codeReal(v, pLeft->u.zToken, 1, target);
  88516. return target;
  88517. #endif
  88518. }else{
  88519. tempX.op = TK_INTEGER;
  88520. tempX.flags = EP_IntValue|EP_TokenOnly;
  88521. tempX.u.iValue = 0;
  88522. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  88523. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  88524. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  88525. testcase( regFree2==0 );
  88526. }
  88527. break;
  88528. }
  88529. case TK_BITNOT:
  88530. case TK_NOT: {
  88531. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  88532. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  88533. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  88534. testcase( regFree1==0 );
  88535. sqlite3VdbeAddOp2(v, op, r1, inReg);
  88536. break;
  88537. }
  88538. case TK_ISNULL:
  88539. case TK_NOTNULL: {
  88540. int addr;
  88541. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  88542. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  88543. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  88544. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  88545. testcase( regFree1==0 );
  88546. addr = sqlite3VdbeAddOp1(v, op, r1);
  88547. VdbeCoverageIf(v, op==TK_ISNULL);
  88548. VdbeCoverageIf(v, op==TK_NOTNULL);
  88549. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  88550. sqlite3VdbeJumpHere(v, addr);
  88551. break;
  88552. }
  88553. case TK_AGG_FUNCTION: {
  88554. AggInfo *pInfo = pExpr->pAggInfo;
  88555. if( pInfo==0 ){
  88556. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88557. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  88558. }else{
  88559. return pInfo->aFunc[pExpr->iAgg].iMem;
  88560. }
  88561. break;
  88562. }
  88563. case TK_FUNCTION: {
  88564. ExprList *pFarg; /* List of function arguments */
  88565. int nFarg; /* Number of function arguments */
  88566. FuncDef *pDef; /* The function definition object */
  88567. const char *zId; /* The function name */
  88568. u32 constMask = 0; /* Mask of function arguments that are constant */
  88569. int i; /* Loop counter */
  88570. sqlite3 *db = pParse->db; /* The database connection */
  88571. u8 enc = ENC(db); /* The text encoding used by this database */
  88572. CollSeq *pColl = 0; /* A collating sequence */
  88573. if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
  88574. /* SQL functions can be expensive. So try to move constant functions
  88575. ** out of the inner loop, even if that means an extra OP_Copy. */
  88576. return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  88577. }
  88578. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  88579. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  88580. pFarg = 0;
  88581. }else{
  88582. pFarg = pExpr->x.pList;
  88583. }
  88584. nFarg = pFarg ? pFarg->nExpr : 0;
  88585. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88586. zId = pExpr->u.zToken;
  88587. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  88588. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  88589. if( pDef==0 && pParse->explain ){
  88590. pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
  88591. }
  88592. #endif
  88593. if( pDef==0 || pDef->xFinalize!=0 ){
  88594. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  88595. break;
  88596. }
  88597. /* Attempt a direct implementation of the built-in COALESCE() and
  88598. ** IFNULL() functions. This avoids unnecessary evaluation of
  88599. ** arguments past the first non-NULL argument.
  88600. */
  88601. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  88602. int endCoalesce = sqlite3VdbeMakeLabel(v);
  88603. assert( nFarg>=2 );
  88604. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  88605. for(i=1; i<nFarg; i++){
  88606. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  88607. VdbeCoverage(v);
  88608. sqlite3ExprCacheRemove(pParse, target, 1);
  88609. sqlite3ExprCachePush(pParse);
  88610. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  88611. sqlite3ExprCachePop(pParse);
  88612. }
  88613. sqlite3VdbeResolveLabel(v, endCoalesce);
  88614. break;
  88615. }
  88616. /* The UNLIKELY() function is a no-op. The result is the value
  88617. ** of the first argument.
  88618. */
  88619. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  88620. assert( nFarg>=1 );
  88621. return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  88622. }
  88623. #ifdef SQLITE_DEBUG
  88624. /* The AFFINITY() function evaluates to a string that describes
  88625. ** the type affinity of the argument. This is used for testing of
  88626. ** the SQLite type logic.
  88627. */
  88628. if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
  88629. const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
  88630. char aff;
  88631. assert( nFarg==1 );
  88632. aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
  88633. sqlite3VdbeLoadString(v, target,
  88634. aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
  88635. return target;
  88636. }
  88637. #endif
  88638. for(i=0; i<nFarg; i++){
  88639. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  88640. testcase( i==31 );
  88641. constMask |= MASKBIT32(i);
  88642. }
  88643. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  88644. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  88645. }
  88646. }
  88647. if( pFarg ){
  88648. if( constMask ){
  88649. r1 = pParse->nMem+1;
  88650. pParse->nMem += nFarg;
  88651. }else{
  88652. r1 = sqlite3GetTempRange(pParse, nFarg);
  88653. }
  88654. /* For length() and typeof() functions with a column argument,
  88655. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  88656. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  88657. ** loading.
  88658. */
  88659. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  88660. u8 exprOp;
  88661. assert( nFarg==1 );
  88662. assert( pFarg->a[0].pExpr!=0 );
  88663. exprOp = pFarg->a[0].pExpr->op;
  88664. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  88665. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  88666. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  88667. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  88668. pFarg->a[0].pExpr->op2 =
  88669. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  88670. }
  88671. }
  88672. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  88673. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  88674. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  88675. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  88676. }else{
  88677. r1 = 0;
  88678. }
  88679. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88680. /* Possibly overload the function if the first argument is
  88681. ** a virtual table column.
  88682. **
  88683. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  88684. ** second argument, not the first, as the argument to test to
  88685. ** see if it is a column in a virtual table. This is done because
  88686. ** the left operand of infix functions (the operand we want to
  88687. ** control overloading) ends up as the second argument to the
  88688. ** function. The expression "A glob B" is equivalent to
  88689. ** "glob(B,A). We want to use the A in "A glob B" to test
  88690. ** for function overloading. But we use the B term in "glob(B,A)".
  88691. */
  88692. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  88693. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  88694. }else if( nFarg>0 ){
  88695. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  88696. }
  88697. #endif
  88698. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  88699. if( !pColl ) pColl = db->pDfltColl;
  88700. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  88701. }
  88702. sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
  88703. (char*)pDef, P4_FUNCDEF);
  88704. sqlite3VdbeChangeP5(v, (u8)nFarg);
  88705. if( nFarg && constMask==0 ){
  88706. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  88707. }
  88708. return target;
  88709. }
  88710. #ifndef SQLITE_OMIT_SUBQUERY
  88711. case TK_EXISTS:
  88712. case TK_SELECT: {
  88713. int nCol;
  88714. testcase( op==TK_EXISTS );
  88715. testcase( op==TK_SELECT );
  88716. if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
  88717. sqlite3SubselectError(pParse, nCol, 1);
  88718. }else{
  88719. return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  88720. }
  88721. break;
  88722. }
  88723. case TK_SELECT_COLUMN: {
  88724. int n;
  88725. if( pExpr->pLeft->iTable==0 ){
  88726. pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
  88727. }
  88728. assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
  88729. if( pExpr->iTable
  88730. && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
  88731. ){
  88732. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  88733. pExpr->iTable, n);
  88734. }
  88735. return pExpr->pLeft->iTable + pExpr->iColumn;
  88736. }
  88737. case TK_IN: {
  88738. int destIfFalse = sqlite3VdbeMakeLabel(v);
  88739. int destIfNull = sqlite3VdbeMakeLabel(v);
  88740. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  88741. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  88742. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  88743. sqlite3VdbeResolveLabel(v, destIfFalse);
  88744. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  88745. sqlite3VdbeResolveLabel(v, destIfNull);
  88746. return target;
  88747. }
  88748. #endif /* SQLITE_OMIT_SUBQUERY */
  88749. /*
  88750. ** x BETWEEN y AND z
  88751. **
  88752. ** This is equivalent to
  88753. **
  88754. ** x>=y AND x<=z
  88755. **
  88756. ** X is stored in pExpr->pLeft.
  88757. ** Y is stored in pExpr->pList->a[0].pExpr.
  88758. ** Z is stored in pExpr->pList->a[1].pExpr.
  88759. */
  88760. case TK_BETWEEN: {
  88761. exprCodeBetween(pParse, pExpr, target, 0, 0);
  88762. return target;
  88763. }
  88764. case TK_SPAN:
  88765. case TK_COLLATE:
  88766. case TK_UPLUS: {
  88767. return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  88768. }
  88769. case TK_TRIGGER: {
  88770. /* If the opcode is TK_TRIGGER, then the expression is a reference
  88771. ** to a column in the new.* or old.* pseudo-tables available to
  88772. ** trigger programs. In this case Expr.iTable is set to 1 for the
  88773. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  88774. ** is set to the column of the pseudo-table to read, or to -1 to
  88775. ** read the rowid field.
  88776. **
  88777. ** The expression is implemented using an OP_Param opcode. The p1
  88778. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  88779. ** to reference another column of the old.* pseudo-table, where
  88780. ** i is the index of the column. For a new.rowid reference, p1 is
  88781. ** set to (n+1), where n is the number of columns in each pseudo-table.
  88782. ** For a reference to any other column in the new.* pseudo-table, p1
  88783. ** is set to (n+2+i), where n and i are as defined previously. For
  88784. ** example, if the table on which triggers are being fired is
  88785. ** declared as:
  88786. **
  88787. ** CREATE TABLE t1(a, b);
  88788. **
  88789. ** Then p1 is interpreted as follows:
  88790. **
  88791. ** p1==0 -> old.rowid p1==3 -> new.rowid
  88792. ** p1==1 -> old.a p1==4 -> new.a
  88793. ** p1==2 -> old.b p1==5 -> new.b
  88794. */
  88795. Table *pTab = pExpr->pTab;
  88796. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  88797. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  88798. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  88799. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  88800. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  88801. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  88802. VdbeComment((v, "%s.%s -> $%d",
  88803. (pExpr->iTable ? "new" : "old"),
  88804. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  88805. target
  88806. ));
  88807. #ifndef SQLITE_OMIT_FLOATING_POINT
  88808. /* If the column has REAL affinity, it may currently be stored as an
  88809. ** integer. Use OP_RealAffinity to make sure it is really real.
  88810. **
  88811. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  88812. ** floating point when extracting it from the record. */
  88813. if( pExpr->iColumn>=0
  88814. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  88815. ){
  88816. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  88817. }
  88818. #endif
  88819. break;
  88820. }
  88821. case TK_VECTOR: {
  88822. sqlite3ErrorMsg(pParse, "row value misused");
  88823. break;
  88824. }
  88825. case TK_IF_NULL_ROW: {
  88826. int addrINR;
  88827. addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
  88828. sqlite3ExprCachePush(pParse);
  88829. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  88830. sqlite3ExprCachePop(pParse);
  88831. sqlite3VdbeJumpHere(v, addrINR);
  88832. sqlite3VdbeChangeP3(v, addrINR, inReg);
  88833. break;
  88834. }
  88835. /*
  88836. ** Form A:
  88837. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  88838. **
  88839. ** Form B:
  88840. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  88841. **
  88842. ** Form A is can be transformed into the equivalent form B as follows:
  88843. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  88844. ** WHEN x=eN THEN rN ELSE y END
  88845. **
  88846. ** X (if it exists) is in pExpr->pLeft.
  88847. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  88848. ** odd. The Y is also optional. If the number of elements in x.pList
  88849. ** is even, then Y is omitted and the "otherwise" result is NULL.
  88850. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  88851. **
  88852. ** The result of the expression is the Ri for the first matching Ei,
  88853. ** or if there is no matching Ei, the ELSE term Y, or if there is
  88854. ** no ELSE term, NULL.
  88855. */
  88856. default: assert( op==TK_CASE ); {
  88857. int endLabel; /* GOTO label for end of CASE stmt */
  88858. int nextCase; /* GOTO label for next WHEN clause */
  88859. int nExpr; /* 2x number of WHEN terms */
  88860. int i; /* Loop counter */
  88861. ExprList *pEList; /* List of WHEN terms */
  88862. struct ExprList_item *aListelem; /* Array of WHEN terms */
  88863. Expr opCompare; /* The X==Ei expression */
  88864. Expr *pX; /* The X expression */
  88865. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  88866. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  88867. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  88868. assert(pExpr->x.pList->nExpr > 0);
  88869. pEList = pExpr->x.pList;
  88870. aListelem = pEList->a;
  88871. nExpr = pEList->nExpr;
  88872. endLabel = sqlite3VdbeMakeLabel(v);
  88873. if( (pX = pExpr->pLeft)!=0 ){
  88874. tempX = *pX;
  88875. testcase( pX->op==TK_COLUMN );
  88876. exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
  88877. testcase( regFree1==0 );
  88878. memset(&opCompare, 0, sizeof(opCompare));
  88879. opCompare.op = TK_EQ;
  88880. opCompare.pLeft = &tempX;
  88881. pTest = &opCompare;
  88882. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  88883. ** The value in regFree1 might get SCopy-ed into the file result.
  88884. ** So make sure that the regFree1 register is not reused for other
  88885. ** purposes and possibly overwritten. */
  88886. regFree1 = 0;
  88887. }
  88888. for(i=0; i<nExpr-1; i=i+2){
  88889. sqlite3ExprCachePush(pParse);
  88890. if( pX ){
  88891. assert( pTest!=0 );
  88892. opCompare.pRight = aListelem[i].pExpr;
  88893. }else{
  88894. pTest = aListelem[i].pExpr;
  88895. }
  88896. nextCase = sqlite3VdbeMakeLabel(v);
  88897. testcase( pTest->op==TK_COLUMN );
  88898. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  88899. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  88900. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  88901. sqlite3VdbeGoto(v, endLabel);
  88902. sqlite3ExprCachePop(pParse);
  88903. sqlite3VdbeResolveLabel(v, nextCase);
  88904. }
  88905. if( (nExpr&1)!=0 ){
  88906. sqlite3ExprCachePush(pParse);
  88907. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  88908. sqlite3ExprCachePop(pParse);
  88909. }else{
  88910. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  88911. }
  88912. assert( pParse->db->mallocFailed || pParse->nErr>0
  88913. || pParse->iCacheLevel==iCacheLevel );
  88914. sqlite3VdbeResolveLabel(v, endLabel);
  88915. break;
  88916. }
  88917. #ifndef SQLITE_OMIT_TRIGGER
  88918. case TK_RAISE: {
  88919. assert( pExpr->affinity==OE_Rollback
  88920. || pExpr->affinity==OE_Abort
  88921. || pExpr->affinity==OE_Fail
  88922. || pExpr->affinity==OE_Ignore
  88923. );
  88924. if( !pParse->pTriggerTab ){
  88925. sqlite3ErrorMsg(pParse,
  88926. "RAISE() may only be used within a trigger-program");
  88927. return 0;
  88928. }
  88929. if( pExpr->affinity==OE_Abort ){
  88930. sqlite3MayAbort(pParse);
  88931. }
  88932. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88933. if( pExpr->affinity==OE_Ignore ){
  88934. sqlite3VdbeAddOp4(
  88935. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  88936. VdbeCoverage(v);
  88937. }else{
  88938. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  88939. pExpr->affinity, pExpr->u.zToken, 0, 0);
  88940. }
  88941. break;
  88942. }
  88943. #endif
  88944. }
  88945. sqlite3ReleaseTempReg(pParse, regFree1);
  88946. sqlite3ReleaseTempReg(pParse, regFree2);
  88947. return inReg;
  88948. }
  88949. /*
  88950. ** Factor out the code of the given expression to initialization time.
  88951. **
  88952. ** If regDest>=0 then the result is always stored in that register and the
  88953. ** result is not reusable. If regDest<0 then this routine is free to
  88954. ** store the value whereever it wants. The register where the expression
  88955. ** is stored is returned. When regDest<0, two identical expressions will
  88956. ** code to the same register.
  88957. */
  88958. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
  88959. Parse *pParse, /* Parsing context */
  88960. Expr *pExpr, /* The expression to code when the VDBE initializes */
  88961. int regDest /* Store the value in this register */
  88962. ){
  88963. ExprList *p;
  88964. assert( ConstFactorOk(pParse) );
  88965. p = pParse->pConstExpr;
  88966. if( regDest<0 && p ){
  88967. struct ExprList_item *pItem;
  88968. int i;
  88969. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  88970. if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
  88971. return pItem->u.iConstExprReg;
  88972. }
  88973. }
  88974. }
  88975. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  88976. p = sqlite3ExprListAppend(pParse, p, pExpr);
  88977. if( p ){
  88978. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  88979. pItem->reusable = regDest<0;
  88980. if( regDest<0 ) regDest = ++pParse->nMem;
  88981. pItem->u.iConstExprReg = regDest;
  88982. }
  88983. pParse->pConstExpr = p;
  88984. return regDest;
  88985. }
  88986. /*
  88987. ** Generate code to evaluate an expression and store the results
  88988. ** into a register. Return the register number where the results
  88989. ** are stored.
  88990. **
  88991. ** If the register is a temporary register that can be deallocated,
  88992. ** then write its number into *pReg. If the result register is not
  88993. ** a temporary, then set *pReg to zero.
  88994. **
  88995. ** If pExpr is a constant, then this routine might generate this
  88996. ** code to fill the register in the initialization section of the
  88997. ** VDBE program, in order to factor it out of the evaluation loop.
  88998. */
  88999. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  89000. int r2;
  89001. pExpr = sqlite3ExprSkipCollate(pExpr);
  89002. if( ConstFactorOk(pParse)
  89003. && pExpr->op!=TK_REGISTER
  89004. && sqlite3ExprIsConstantNotJoin(pExpr)
  89005. ){
  89006. *pReg = 0;
  89007. r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  89008. }else{
  89009. int r1 = sqlite3GetTempReg(pParse);
  89010. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  89011. if( r2==r1 ){
  89012. *pReg = r1;
  89013. }else{
  89014. sqlite3ReleaseTempReg(pParse, r1);
  89015. *pReg = 0;
  89016. }
  89017. }
  89018. return r2;
  89019. }
  89020. /*
  89021. ** Generate code that will evaluate expression pExpr and store the
  89022. ** results in register target. The results are guaranteed to appear
  89023. ** in register target.
  89024. */
  89025. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  89026. int inReg;
  89027. assert( target>0 && target<=pParse->nMem );
  89028. if( pExpr && pExpr->op==TK_REGISTER ){
  89029. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  89030. }else{
  89031. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  89032. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  89033. if( inReg!=target && pParse->pVdbe ){
  89034. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  89035. }
  89036. }
  89037. }
  89038. /*
  89039. ** Make a transient copy of expression pExpr and then code it using
  89040. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  89041. ** except that the input expression is guaranteed to be unchanged.
  89042. */
  89043. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  89044. sqlite3 *db = pParse->db;
  89045. pExpr = sqlite3ExprDup(db, pExpr, 0);
  89046. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  89047. sqlite3ExprDelete(db, pExpr);
  89048. }
  89049. /*
  89050. ** Generate code that will evaluate expression pExpr and store the
  89051. ** results in register target. The results are guaranteed to appear
  89052. ** in register target. If the expression is constant, then this routine
  89053. ** might choose to code the expression at initialization time.
  89054. */
  89055. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  89056. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  89057. sqlite3ExprCodeAtInit(pParse, pExpr, target);
  89058. }else{
  89059. sqlite3ExprCode(pParse, pExpr, target);
  89060. }
  89061. }
  89062. /*
  89063. ** Generate code that evaluates the given expression and puts the result
  89064. ** in register target.
  89065. **
  89066. ** Also make a copy of the expression results into another "cache" register
  89067. ** and modify the expression so that the next time it is evaluated,
  89068. ** the result is a copy of the cache register.
  89069. **
  89070. ** This routine is used for expressions that are used multiple
  89071. ** times. They are evaluated once and the results of the expression
  89072. ** are reused.
  89073. */
  89074. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  89075. Vdbe *v = pParse->pVdbe;
  89076. int iMem;
  89077. assert( target>0 );
  89078. assert( pExpr->op!=TK_REGISTER );
  89079. sqlite3ExprCode(pParse, pExpr, target);
  89080. iMem = ++pParse->nMem;
  89081. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  89082. exprToRegister(pExpr, iMem);
  89083. }
  89084. /*
  89085. ** Generate code that pushes the value of every element of the given
  89086. ** expression list into a sequence of registers beginning at target.
  89087. **
  89088. ** Return the number of elements evaluated.
  89089. **
  89090. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  89091. ** filled using OP_SCopy. OP_Copy must be used instead.
  89092. **
  89093. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  89094. ** factored out into initialization code.
  89095. **
  89096. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  89097. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  89098. ** in registers at srcReg, and so the value can be copied from there.
  89099. */
  89100. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  89101. Parse *pParse, /* Parsing context */
  89102. ExprList *pList, /* The expression list to be coded */
  89103. int target, /* Where to write results */
  89104. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  89105. u8 flags /* SQLITE_ECEL_* flags */
  89106. ){
  89107. struct ExprList_item *pItem;
  89108. int i, j, n;
  89109. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  89110. Vdbe *v = pParse->pVdbe;
  89111. assert( pList!=0 );
  89112. assert( target>0 );
  89113. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  89114. n = pList->nExpr;
  89115. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  89116. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  89117. Expr *pExpr = pItem->pExpr;
  89118. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
  89119. if( flags & SQLITE_ECEL_OMITREF ){
  89120. i--;
  89121. n--;
  89122. }else{
  89123. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  89124. }
  89125. }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  89126. sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
  89127. }else{
  89128. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  89129. if( inReg!=target+i ){
  89130. VdbeOp *pOp;
  89131. if( copyOp==OP_Copy
  89132. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  89133. && pOp->p1+pOp->p3+1==inReg
  89134. && pOp->p2+pOp->p3+1==target+i
  89135. ){
  89136. pOp->p3++;
  89137. }else{
  89138. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  89139. }
  89140. }
  89141. }
  89142. }
  89143. return n;
  89144. }
  89145. /*
  89146. ** Generate code for a BETWEEN operator.
  89147. **
  89148. ** x BETWEEN y AND z
  89149. **
  89150. ** The above is equivalent to
  89151. **
  89152. ** x>=y AND x<=z
  89153. **
  89154. ** Code it as such, taking care to do the common subexpression
  89155. ** elimination of x.
  89156. **
  89157. ** The xJumpIf parameter determines details:
  89158. **
  89159. ** NULL: Store the boolean result in reg[dest]
  89160. ** sqlite3ExprIfTrue: Jump to dest if true
  89161. ** sqlite3ExprIfFalse: Jump to dest if false
  89162. **
  89163. ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
  89164. */
  89165. static void exprCodeBetween(
  89166. Parse *pParse, /* Parsing and code generating context */
  89167. Expr *pExpr, /* The BETWEEN expression */
  89168. int dest, /* Jump destination or storage location */
  89169. void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
  89170. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  89171. ){
  89172. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  89173. Expr compLeft; /* The x>=y term */
  89174. Expr compRight; /* The x<=z term */
  89175. Expr exprX; /* The x subexpression */
  89176. int regFree1 = 0; /* Temporary use register */
  89177. memset(&compLeft, 0, sizeof(Expr));
  89178. memset(&compRight, 0, sizeof(Expr));
  89179. memset(&exprAnd, 0, sizeof(Expr));
  89180. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  89181. exprX = *pExpr->pLeft;
  89182. exprAnd.op = TK_AND;
  89183. exprAnd.pLeft = &compLeft;
  89184. exprAnd.pRight = &compRight;
  89185. compLeft.op = TK_GE;
  89186. compLeft.pLeft = &exprX;
  89187. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  89188. compRight.op = TK_LE;
  89189. compRight.pLeft = &exprX;
  89190. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  89191. exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
  89192. if( xJump ){
  89193. xJump(pParse, &exprAnd, dest, jumpIfNull);
  89194. }else{
  89195. /* Mark the expression is being from the ON or USING clause of a join
  89196. ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
  89197. ** it into the Parse.pConstExpr list. We should use a new bit for this,
  89198. ** for clarity, but we are out of bits in the Expr.flags field so we
  89199. ** have to reuse the EP_FromJoin bit. Bummer. */
  89200. exprX.flags |= EP_FromJoin;
  89201. sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
  89202. }
  89203. sqlite3ReleaseTempReg(pParse, regFree1);
  89204. /* Ensure adequate test coverage */
  89205. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
  89206. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
  89207. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
  89208. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
  89209. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
  89210. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
  89211. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
  89212. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
  89213. testcase( xJump==0 );
  89214. }
  89215. /*
  89216. ** Generate code for a boolean expression such that a jump is made
  89217. ** to the label "dest" if the expression is true but execution
  89218. ** continues straight thru if the expression is false.
  89219. **
  89220. ** If the expression evaluates to NULL (neither true nor false), then
  89221. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  89222. **
  89223. ** This code depends on the fact that certain token values (ex: TK_EQ)
  89224. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  89225. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  89226. ** the make process cause these values to align. Assert()s in the code
  89227. ** below verify that the numbers are aligned correctly.
  89228. */
  89229. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  89230. Vdbe *v = pParse->pVdbe;
  89231. int op = 0;
  89232. int regFree1 = 0;
  89233. int regFree2 = 0;
  89234. int r1, r2;
  89235. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  89236. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  89237. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  89238. op = pExpr->op;
  89239. switch( op ){
  89240. case TK_AND: {
  89241. int d2 = sqlite3VdbeMakeLabel(v);
  89242. testcase( jumpIfNull==0 );
  89243. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  89244. sqlite3ExprCachePush(pParse);
  89245. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  89246. sqlite3VdbeResolveLabel(v, d2);
  89247. sqlite3ExprCachePop(pParse);
  89248. break;
  89249. }
  89250. case TK_OR: {
  89251. testcase( jumpIfNull==0 );
  89252. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  89253. sqlite3ExprCachePush(pParse);
  89254. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  89255. sqlite3ExprCachePop(pParse);
  89256. break;
  89257. }
  89258. case TK_NOT: {
  89259. testcase( jumpIfNull==0 );
  89260. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  89261. break;
  89262. }
  89263. case TK_IS:
  89264. case TK_ISNOT:
  89265. testcase( op==TK_IS );
  89266. testcase( op==TK_ISNOT );
  89267. op = (op==TK_IS) ? TK_EQ : TK_NE;
  89268. jumpIfNull = SQLITE_NULLEQ;
  89269. /* Fall thru */
  89270. case TK_LT:
  89271. case TK_LE:
  89272. case TK_GT:
  89273. case TK_GE:
  89274. case TK_NE:
  89275. case TK_EQ: {
  89276. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  89277. testcase( jumpIfNull==0 );
  89278. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89279. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  89280. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  89281. r1, r2, dest, jumpIfNull);
  89282. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  89283. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  89284. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  89285. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  89286. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  89287. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  89288. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  89289. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  89290. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  89291. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  89292. testcase( regFree1==0 );
  89293. testcase( regFree2==0 );
  89294. break;
  89295. }
  89296. case TK_ISNULL:
  89297. case TK_NOTNULL: {
  89298. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  89299. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  89300. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89301. sqlite3VdbeAddOp2(v, op, r1, dest);
  89302. VdbeCoverageIf(v, op==TK_ISNULL);
  89303. VdbeCoverageIf(v, op==TK_NOTNULL);
  89304. testcase( regFree1==0 );
  89305. break;
  89306. }
  89307. case TK_BETWEEN: {
  89308. testcase( jumpIfNull==0 );
  89309. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
  89310. break;
  89311. }
  89312. #ifndef SQLITE_OMIT_SUBQUERY
  89313. case TK_IN: {
  89314. int destIfFalse = sqlite3VdbeMakeLabel(v);
  89315. int destIfNull = jumpIfNull ? dest : destIfFalse;
  89316. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  89317. sqlite3VdbeGoto(v, dest);
  89318. sqlite3VdbeResolveLabel(v, destIfFalse);
  89319. break;
  89320. }
  89321. #endif
  89322. default: {
  89323. default_expr:
  89324. if( exprAlwaysTrue(pExpr) ){
  89325. sqlite3VdbeGoto(v, dest);
  89326. }else if( exprAlwaysFalse(pExpr) ){
  89327. /* No-op */
  89328. }else{
  89329. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  89330. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  89331. VdbeCoverage(v);
  89332. testcase( regFree1==0 );
  89333. testcase( jumpIfNull==0 );
  89334. }
  89335. break;
  89336. }
  89337. }
  89338. sqlite3ReleaseTempReg(pParse, regFree1);
  89339. sqlite3ReleaseTempReg(pParse, regFree2);
  89340. }
  89341. /*
  89342. ** Generate code for a boolean expression such that a jump is made
  89343. ** to the label "dest" if the expression is false but execution
  89344. ** continues straight thru if the expression is true.
  89345. **
  89346. ** If the expression evaluates to NULL (neither true nor false) then
  89347. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  89348. ** is 0.
  89349. */
  89350. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  89351. Vdbe *v = pParse->pVdbe;
  89352. int op = 0;
  89353. int regFree1 = 0;
  89354. int regFree2 = 0;
  89355. int r1, r2;
  89356. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  89357. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  89358. if( pExpr==0 ) return;
  89359. /* The value of pExpr->op and op are related as follows:
  89360. **
  89361. ** pExpr->op op
  89362. ** --------- ----------
  89363. ** TK_ISNULL OP_NotNull
  89364. ** TK_NOTNULL OP_IsNull
  89365. ** TK_NE OP_Eq
  89366. ** TK_EQ OP_Ne
  89367. ** TK_GT OP_Le
  89368. ** TK_LE OP_Gt
  89369. ** TK_GE OP_Lt
  89370. ** TK_LT OP_Ge
  89371. **
  89372. ** For other values of pExpr->op, op is undefined and unused.
  89373. ** The value of TK_ and OP_ constants are arranged such that we
  89374. ** can compute the mapping above using the following expression.
  89375. ** Assert()s verify that the computation is correct.
  89376. */
  89377. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  89378. /* Verify correct alignment of TK_ and OP_ constants
  89379. */
  89380. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  89381. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  89382. assert( pExpr->op!=TK_NE || op==OP_Eq );
  89383. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  89384. assert( pExpr->op!=TK_LT || op==OP_Ge );
  89385. assert( pExpr->op!=TK_LE || op==OP_Gt );
  89386. assert( pExpr->op!=TK_GT || op==OP_Le );
  89387. assert( pExpr->op!=TK_GE || op==OP_Lt );
  89388. switch( pExpr->op ){
  89389. case TK_AND: {
  89390. testcase( jumpIfNull==0 );
  89391. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  89392. sqlite3ExprCachePush(pParse);
  89393. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  89394. sqlite3ExprCachePop(pParse);
  89395. break;
  89396. }
  89397. case TK_OR: {
  89398. int d2 = sqlite3VdbeMakeLabel(v);
  89399. testcase( jumpIfNull==0 );
  89400. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  89401. sqlite3ExprCachePush(pParse);
  89402. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  89403. sqlite3VdbeResolveLabel(v, d2);
  89404. sqlite3ExprCachePop(pParse);
  89405. break;
  89406. }
  89407. case TK_NOT: {
  89408. testcase( jumpIfNull==0 );
  89409. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  89410. break;
  89411. }
  89412. case TK_IS:
  89413. case TK_ISNOT:
  89414. testcase( pExpr->op==TK_IS );
  89415. testcase( pExpr->op==TK_ISNOT );
  89416. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  89417. jumpIfNull = SQLITE_NULLEQ;
  89418. /* Fall thru */
  89419. case TK_LT:
  89420. case TK_LE:
  89421. case TK_GT:
  89422. case TK_GE:
  89423. case TK_NE:
  89424. case TK_EQ: {
  89425. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  89426. testcase( jumpIfNull==0 );
  89427. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89428. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  89429. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  89430. r1, r2, dest, jumpIfNull);
  89431. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  89432. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  89433. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  89434. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  89435. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  89436. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  89437. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  89438. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  89439. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  89440. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  89441. testcase( regFree1==0 );
  89442. testcase( regFree2==0 );
  89443. break;
  89444. }
  89445. case TK_ISNULL:
  89446. case TK_NOTNULL: {
  89447. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89448. sqlite3VdbeAddOp2(v, op, r1, dest);
  89449. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  89450. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  89451. testcase( regFree1==0 );
  89452. break;
  89453. }
  89454. case TK_BETWEEN: {
  89455. testcase( jumpIfNull==0 );
  89456. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
  89457. break;
  89458. }
  89459. #ifndef SQLITE_OMIT_SUBQUERY
  89460. case TK_IN: {
  89461. if( jumpIfNull ){
  89462. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  89463. }else{
  89464. int destIfNull = sqlite3VdbeMakeLabel(v);
  89465. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  89466. sqlite3VdbeResolveLabel(v, destIfNull);
  89467. }
  89468. break;
  89469. }
  89470. #endif
  89471. default: {
  89472. default_expr:
  89473. if( exprAlwaysFalse(pExpr) ){
  89474. sqlite3VdbeGoto(v, dest);
  89475. }else if( exprAlwaysTrue(pExpr) ){
  89476. /* no-op */
  89477. }else{
  89478. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  89479. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  89480. VdbeCoverage(v);
  89481. testcase( regFree1==0 );
  89482. testcase( jumpIfNull==0 );
  89483. }
  89484. break;
  89485. }
  89486. }
  89487. sqlite3ReleaseTempReg(pParse, regFree1);
  89488. sqlite3ReleaseTempReg(pParse, regFree2);
  89489. }
  89490. /*
  89491. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  89492. ** code generation, and that copy is deleted after code generation. This
  89493. ** ensures that the original pExpr is unchanged.
  89494. */
  89495. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  89496. sqlite3 *db = pParse->db;
  89497. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  89498. if( db->mallocFailed==0 ){
  89499. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  89500. }
  89501. sqlite3ExprDelete(db, pCopy);
  89502. }
  89503. /*
  89504. ** Do a deep comparison of two expression trees. Return 0 if the two
  89505. ** expressions are completely identical. Return 1 if they differ only
  89506. ** by a COLLATE operator at the top level. Return 2 if there are differences
  89507. ** other than the top-level COLLATE operator.
  89508. **
  89509. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  89510. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  89511. **
  89512. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  89513. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  89514. **
  89515. ** Sometimes this routine will return 2 even if the two expressions
  89516. ** really are equivalent. If we cannot prove that the expressions are
  89517. ** identical, we return 2 just to be safe. So if this routine
  89518. ** returns 2, then you do not really know for certain if the two
  89519. ** expressions are the same. But if you get a 0 or 1 return, then you
  89520. ** can be sure the expressions are the same. In the places where
  89521. ** this routine is used, it does not hurt to get an extra 2 - that
  89522. ** just might result in some slightly slower code. But returning
  89523. ** an incorrect 0 or 1 could lead to a malfunction.
  89524. */
  89525. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  89526. u32 combinedFlags;
  89527. if( pA==0 || pB==0 ){
  89528. return pB==pA ? 0 : 2;
  89529. }
  89530. combinedFlags = pA->flags | pB->flags;
  89531. if( combinedFlags & EP_IntValue ){
  89532. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  89533. return 0;
  89534. }
  89535. return 2;
  89536. }
  89537. if( pA->op!=pB->op ){
  89538. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  89539. return 1;
  89540. }
  89541. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  89542. return 1;
  89543. }
  89544. return 2;
  89545. }
  89546. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  89547. if( pA->op==TK_FUNCTION ){
  89548. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  89549. }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  89550. return pA->op==TK_COLLATE ? 1 : 2;
  89551. }
  89552. }
  89553. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  89554. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  89555. if( combinedFlags & EP_xIsSelect ) return 2;
  89556. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  89557. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  89558. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  89559. if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
  89560. if( pA->iColumn!=pB->iColumn ) return 2;
  89561. if( pA->iTable!=pB->iTable
  89562. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  89563. }
  89564. }
  89565. return 0;
  89566. }
  89567. /*
  89568. ** Compare two ExprList objects. Return 0 if they are identical and
  89569. ** non-zero if they differ in any way.
  89570. **
  89571. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  89572. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  89573. **
  89574. ** This routine might return non-zero for equivalent ExprLists. The
  89575. ** only consequence will be disabled optimizations. But this routine
  89576. ** must never return 0 if the two ExprList objects are different, or
  89577. ** a malfunction will result.
  89578. **
  89579. ** Two NULL pointers are considered to be the same. But a NULL pointer
  89580. ** always differs from a non-NULL pointer.
  89581. */
  89582. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  89583. int i;
  89584. if( pA==0 && pB==0 ) return 0;
  89585. if( pA==0 || pB==0 ) return 1;
  89586. if( pA->nExpr!=pB->nExpr ) return 1;
  89587. for(i=0; i<pA->nExpr; i++){
  89588. Expr *pExprA = pA->a[i].pExpr;
  89589. Expr *pExprB = pB->a[i].pExpr;
  89590. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  89591. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  89592. }
  89593. return 0;
  89594. }
  89595. /*
  89596. ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
  89597. ** are ignored.
  89598. */
  89599. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
  89600. return sqlite3ExprCompare(
  89601. sqlite3ExprSkipCollate(pA),
  89602. sqlite3ExprSkipCollate(pB),
  89603. iTab);
  89604. }
  89605. /*
  89606. ** Return true if we can prove the pE2 will always be true if pE1 is
  89607. ** true. Return false if we cannot complete the proof or if pE2 might
  89608. ** be false. Examples:
  89609. **
  89610. ** pE1: x==5 pE2: x==5 Result: true
  89611. ** pE1: x>0 pE2: x==5 Result: false
  89612. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  89613. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  89614. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  89615. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  89616. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  89617. **
  89618. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  89619. ** Expr.iTable<0 then assume a table number given by iTab.
  89620. **
  89621. ** When in doubt, return false. Returning true might give a performance
  89622. ** improvement. Returning false might cause a performance reduction, but
  89623. ** it will always give the correct answer and is hence always safe.
  89624. */
  89625. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  89626. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  89627. return 1;
  89628. }
  89629. if( pE2->op==TK_OR
  89630. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  89631. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  89632. ){
  89633. return 1;
  89634. }
  89635. if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
  89636. Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
  89637. testcase( pX!=pE1->pLeft );
  89638. if( sqlite3ExprCompare(pX, pE2->pLeft, iTab)==0 ) return 1;
  89639. }
  89640. return 0;
  89641. }
  89642. /*
  89643. ** An instance of the following structure is used by the tree walker
  89644. ** to determine if an expression can be evaluated by reference to the
  89645. ** index only, without having to do a search for the corresponding
  89646. ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
  89647. ** is the cursor for the table.
  89648. */
  89649. struct IdxCover {
  89650. Index *pIdx; /* The index to be tested for coverage */
  89651. int iCur; /* Cursor number for the table corresponding to the index */
  89652. };
  89653. /*
  89654. ** Check to see if there are references to columns in table
  89655. ** pWalker->u.pIdxCover->iCur can be satisfied using the index
  89656. ** pWalker->u.pIdxCover->pIdx.
  89657. */
  89658. static int exprIdxCover(Walker *pWalker, Expr *pExpr){
  89659. if( pExpr->op==TK_COLUMN
  89660. && pExpr->iTable==pWalker->u.pIdxCover->iCur
  89661. && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
  89662. ){
  89663. pWalker->eCode = 1;
  89664. return WRC_Abort;
  89665. }
  89666. return WRC_Continue;
  89667. }
  89668. /*
  89669. ** Determine if an index pIdx on table with cursor iCur contains will
  89670. ** the expression pExpr. Return true if the index does cover the
  89671. ** expression and false if the pExpr expression references table columns
  89672. ** that are not found in the index pIdx.
  89673. **
  89674. ** An index covering an expression means that the expression can be
  89675. ** evaluated using only the index and without having to lookup the
  89676. ** corresponding table entry.
  89677. */
  89678. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
  89679. Expr *pExpr, /* The index to be tested */
  89680. int iCur, /* The cursor number for the corresponding table */
  89681. Index *pIdx /* The index that might be used for coverage */
  89682. ){
  89683. Walker w;
  89684. struct IdxCover xcov;
  89685. memset(&w, 0, sizeof(w));
  89686. xcov.iCur = iCur;
  89687. xcov.pIdx = pIdx;
  89688. w.xExprCallback = exprIdxCover;
  89689. w.u.pIdxCover = &xcov;
  89690. sqlite3WalkExpr(&w, pExpr);
  89691. return !w.eCode;
  89692. }
  89693. /*
  89694. ** An instance of the following structure is used by the tree walker
  89695. ** to count references to table columns in the arguments of an
  89696. ** aggregate function, in order to implement the
  89697. ** sqlite3FunctionThisSrc() routine.
  89698. */
  89699. struct SrcCount {
  89700. SrcList *pSrc; /* One particular FROM clause in a nested query */
  89701. int nThis; /* Number of references to columns in pSrcList */
  89702. int nOther; /* Number of references to columns in other FROM clauses */
  89703. };
  89704. /*
  89705. ** Count the number of references to columns.
  89706. */
  89707. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  89708. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  89709. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  89710. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  89711. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  89712. ** NEVER() will need to be removed. */
  89713. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  89714. int i;
  89715. struct SrcCount *p = pWalker->u.pSrcCount;
  89716. SrcList *pSrc = p->pSrc;
  89717. int nSrc = pSrc ? pSrc->nSrc : 0;
  89718. for(i=0; i<nSrc; i++){
  89719. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  89720. }
  89721. if( i<nSrc ){
  89722. p->nThis++;
  89723. }else{
  89724. p->nOther++;
  89725. }
  89726. }
  89727. return WRC_Continue;
  89728. }
  89729. /*
  89730. ** Determine if any of the arguments to the pExpr Function reference
  89731. ** pSrcList. Return true if they do. Also return true if the function
  89732. ** has no arguments or has only constant arguments. Return false if pExpr
  89733. ** references columns but not columns of tables found in pSrcList.
  89734. */
  89735. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  89736. Walker w;
  89737. struct SrcCount cnt;
  89738. assert( pExpr->op==TK_AGG_FUNCTION );
  89739. memset(&w, 0, sizeof(w));
  89740. w.xExprCallback = exprSrcCount;
  89741. w.u.pSrcCount = &cnt;
  89742. cnt.pSrc = pSrcList;
  89743. cnt.nThis = 0;
  89744. cnt.nOther = 0;
  89745. sqlite3WalkExprList(&w, pExpr->x.pList);
  89746. return cnt.nThis>0 || cnt.nOther==0;
  89747. }
  89748. /*
  89749. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  89750. ** the new element. Return a negative number if malloc fails.
  89751. */
  89752. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  89753. int i;
  89754. pInfo->aCol = sqlite3ArrayAllocate(
  89755. db,
  89756. pInfo->aCol,
  89757. sizeof(pInfo->aCol[0]),
  89758. &pInfo->nColumn,
  89759. &i
  89760. );
  89761. return i;
  89762. }
  89763. /*
  89764. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  89765. ** the new element. Return a negative number if malloc fails.
  89766. */
  89767. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  89768. int i;
  89769. pInfo->aFunc = sqlite3ArrayAllocate(
  89770. db,
  89771. pInfo->aFunc,
  89772. sizeof(pInfo->aFunc[0]),
  89773. &pInfo->nFunc,
  89774. &i
  89775. );
  89776. return i;
  89777. }
  89778. /*
  89779. ** This is the xExprCallback for a tree walker. It is used to
  89780. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  89781. ** for additional information.
  89782. */
  89783. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  89784. int i;
  89785. NameContext *pNC = pWalker->u.pNC;
  89786. Parse *pParse = pNC->pParse;
  89787. SrcList *pSrcList = pNC->pSrcList;
  89788. AggInfo *pAggInfo = pNC->pAggInfo;
  89789. switch( pExpr->op ){
  89790. case TK_AGG_COLUMN:
  89791. case TK_COLUMN: {
  89792. testcase( pExpr->op==TK_AGG_COLUMN );
  89793. testcase( pExpr->op==TK_COLUMN );
  89794. /* Check to see if the column is in one of the tables in the FROM
  89795. ** clause of the aggregate query */
  89796. if( ALWAYS(pSrcList!=0) ){
  89797. struct SrcList_item *pItem = pSrcList->a;
  89798. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  89799. struct AggInfo_col *pCol;
  89800. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  89801. if( pExpr->iTable==pItem->iCursor ){
  89802. /* If we reach this point, it means that pExpr refers to a table
  89803. ** that is in the FROM clause of the aggregate query.
  89804. **
  89805. ** Make an entry for the column in pAggInfo->aCol[] if there
  89806. ** is not an entry there already.
  89807. */
  89808. int k;
  89809. pCol = pAggInfo->aCol;
  89810. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  89811. if( pCol->iTable==pExpr->iTable &&
  89812. pCol->iColumn==pExpr->iColumn ){
  89813. break;
  89814. }
  89815. }
  89816. if( (k>=pAggInfo->nColumn)
  89817. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  89818. ){
  89819. pCol = &pAggInfo->aCol[k];
  89820. pCol->pTab = pExpr->pTab;
  89821. pCol->iTable = pExpr->iTable;
  89822. pCol->iColumn = pExpr->iColumn;
  89823. pCol->iMem = ++pParse->nMem;
  89824. pCol->iSorterColumn = -1;
  89825. pCol->pExpr = pExpr;
  89826. if( pAggInfo->pGroupBy ){
  89827. int j, n;
  89828. ExprList *pGB = pAggInfo->pGroupBy;
  89829. struct ExprList_item *pTerm = pGB->a;
  89830. n = pGB->nExpr;
  89831. for(j=0; j<n; j++, pTerm++){
  89832. Expr *pE = pTerm->pExpr;
  89833. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  89834. pE->iColumn==pExpr->iColumn ){
  89835. pCol->iSorterColumn = j;
  89836. break;
  89837. }
  89838. }
  89839. }
  89840. if( pCol->iSorterColumn<0 ){
  89841. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  89842. }
  89843. }
  89844. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  89845. ** because it was there before or because we just created it).
  89846. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  89847. ** pAggInfo->aCol[] entry.
  89848. */
  89849. ExprSetVVAProperty(pExpr, EP_NoReduce);
  89850. pExpr->pAggInfo = pAggInfo;
  89851. pExpr->op = TK_AGG_COLUMN;
  89852. pExpr->iAgg = (i16)k;
  89853. break;
  89854. } /* endif pExpr->iTable==pItem->iCursor */
  89855. } /* end loop over pSrcList */
  89856. }
  89857. return WRC_Prune;
  89858. }
  89859. case TK_AGG_FUNCTION: {
  89860. if( (pNC->ncFlags & NC_InAggFunc)==0
  89861. && pWalker->walkerDepth==pExpr->op2
  89862. ){
  89863. /* Check to see if pExpr is a duplicate of another aggregate
  89864. ** function that is already in the pAggInfo structure
  89865. */
  89866. struct AggInfo_func *pItem = pAggInfo->aFunc;
  89867. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  89868. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  89869. break;
  89870. }
  89871. }
  89872. if( i>=pAggInfo->nFunc ){
  89873. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  89874. */
  89875. u8 enc = ENC(pParse->db);
  89876. i = addAggInfoFunc(pParse->db, pAggInfo);
  89877. if( i>=0 ){
  89878. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  89879. pItem = &pAggInfo->aFunc[i];
  89880. pItem->pExpr = pExpr;
  89881. pItem->iMem = ++pParse->nMem;
  89882. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89883. pItem->pFunc = sqlite3FindFunction(pParse->db,
  89884. pExpr->u.zToken,
  89885. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  89886. if( pExpr->flags & EP_Distinct ){
  89887. pItem->iDistinct = pParse->nTab++;
  89888. }else{
  89889. pItem->iDistinct = -1;
  89890. }
  89891. }
  89892. }
  89893. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  89894. */
  89895. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  89896. ExprSetVVAProperty(pExpr, EP_NoReduce);
  89897. pExpr->iAgg = (i16)i;
  89898. pExpr->pAggInfo = pAggInfo;
  89899. return WRC_Prune;
  89900. }else{
  89901. return WRC_Continue;
  89902. }
  89903. }
  89904. }
  89905. return WRC_Continue;
  89906. }
  89907. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  89908. UNUSED_PARAMETER(pWalker);
  89909. UNUSED_PARAMETER(pSelect);
  89910. return WRC_Continue;
  89911. }
  89912. /*
  89913. ** Analyze the pExpr expression looking for aggregate functions and
  89914. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  89915. ** points to. Additional entries are made on the AggInfo object as
  89916. ** necessary.
  89917. **
  89918. ** This routine should only be called after the expression has been
  89919. ** analyzed by sqlite3ResolveExprNames().
  89920. */
  89921. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  89922. Walker w;
  89923. memset(&w, 0, sizeof(w));
  89924. w.xExprCallback = analyzeAggregate;
  89925. w.xSelectCallback = analyzeAggregatesInSelect;
  89926. w.u.pNC = pNC;
  89927. assert( pNC->pSrcList!=0 );
  89928. sqlite3WalkExpr(&w, pExpr);
  89929. }
  89930. /*
  89931. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  89932. ** expression list. Return the number of errors.
  89933. **
  89934. ** If an error is found, the analysis is cut short.
  89935. */
  89936. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  89937. struct ExprList_item *pItem;
  89938. int i;
  89939. if( pList ){
  89940. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  89941. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  89942. }
  89943. }
  89944. }
  89945. /*
  89946. ** Allocate a single new register for use to hold some intermediate result.
  89947. */
  89948. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  89949. if( pParse->nTempReg==0 ){
  89950. return ++pParse->nMem;
  89951. }
  89952. return pParse->aTempReg[--pParse->nTempReg];
  89953. }
  89954. /*
  89955. ** Deallocate a register, making available for reuse for some other
  89956. ** purpose.
  89957. **
  89958. ** If a register is currently being used by the column cache, then
  89959. ** the deallocation is deferred until the column cache line that uses
  89960. ** the register becomes stale.
  89961. */
  89962. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  89963. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  89964. int i;
  89965. struct yColCache *p;
  89966. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  89967. if( p->iReg==iReg ){
  89968. p->tempReg = 1;
  89969. return;
  89970. }
  89971. }
  89972. pParse->aTempReg[pParse->nTempReg++] = iReg;
  89973. }
  89974. }
  89975. /*
  89976. ** Allocate or deallocate a block of nReg consecutive registers.
  89977. */
  89978. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  89979. int i, n;
  89980. if( nReg==1 ) return sqlite3GetTempReg(pParse);
  89981. i = pParse->iRangeReg;
  89982. n = pParse->nRangeReg;
  89983. if( nReg<=n ){
  89984. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  89985. pParse->iRangeReg += nReg;
  89986. pParse->nRangeReg -= nReg;
  89987. }else{
  89988. i = pParse->nMem+1;
  89989. pParse->nMem += nReg;
  89990. }
  89991. return i;
  89992. }
  89993. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  89994. if( nReg==1 ){
  89995. sqlite3ReleaseTempReg(pParse, iReg);
  89996. return;
  89997. }
  89998. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  89999. if( nReg>pParse->nRangeReg ){
  90000. pParse->nRangeReg = nReg;
  90001. pParse->iRangeReg = iReg;
  90002. }
  90003. }
  90004. /*
  90005. ** Mark all temporary registers as being unavailable for reuse.
  90006. */
  90007. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  90008. pParse->nTempReg = 0;
  90009. pParse->nRangeReg = 0;
  90010. }
  90011. /*
  90012. ** Validate that no temporary register falls within the range of
  90013. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  90014. ** statements.
  90015. */
  90016. #ifdef SQLITE_DEBUG
  90017. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  90018. int i;
  90019. if( pParse->nRangeReg>0
  90020. && pParse->iRangeReg+pParse->nRangeReg<iLast
  90021. && pParse->iRangeReg>=iFirst
  90022. ){
  90023. return 0;
  90024. }
  90025. for(i=0; i<pParse->nTempReg; i++){
  90026. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  90027. return 0;
  90028. }
  90029. }
  90030. return 1;
  90031. }
  90032. #endif /* SQLITE_DEBUG */
  90033. /************** End of expr.c ************************************************/
  90034. /************** Begin file alter.c *******************************************/
  90035. /*
  90036. ** 2005 February 15
  90037. **
  90038. ** The author disclaims copyright to this source code. In place of
  90039. ** a legal notice, here is a blessing:
  90040. **
  90041. ** May you do good and not evil.
  90042. ** May you find forgiveness for yourself and forgive others.
  90043. ** May you share freely, never taking more than you give.
  90044. **
  90045. *************************************************************************
  90046. ** This file contains C code routines that used to generate VDBE code
  90047. ** that implements the ALTER TABLE command.
  90048. */
  90049. /* #include "sqliteInt.h" */
  90050. /*
  90051. ** The code in this file only exists if we are not omitting the
  90052. ** ALTER TABLE logic from the build.
  90053. */
  90054. #ifndef SQLITE_OMIT_ALTERTABLE
  90055. /*
  90056. ** This function is used by SQL generated to implement the
  90057. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  90058. ** CREATE INDEX command. The second is a table name. The table name in
  90059. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  90060. ** argument and the result returned. Examples:
  90061. **
  90062. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  90063. ** -> 'CREATE TABLE def(a, b, c)'
  90064. **
  90065. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  90066. ** -> 'CREATE INDEX i ON def(a, b, c)'
  90067. */
  90068. static void renameTableFunc(
  90069. sqlite3_context *context,
  90070. int NotUsed,
  90071. sqlite3_value **argv
  90072. ){
  90073. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  90074. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  90075. int token;
  90076. Token tname;
  90077. unsigned char const *zCsr = zSql;
  90078. int len = 0;
  90079. char *zRet;
  90080. sqlite3 *db = sqlite3_context_db_handle(context);
  90081. UNUSED_PARAMETER(NotUsed);
  90082. /* The principle used to locate the table name in the CREATE TABLE
  90083. ** statement is that the table name is the first non-space token that
  90084. ** is immediately followed by a TK_LP or TK_USING token.
  90085. */
  90086. if( zSql ){
  90087. do {
  90088. if( !*zCsr ){
  90089. /* Ran out of input before finding an opening bracket. Return NULL. */
  90090. return;
  90091. }
  90092. /* Store the token that zCsr points to in tname. */
  90093. tname.z = (char*)zCsr;
  90094. tname.n = len;
  90095. /* Advance zCsr to the next token. Store that token type in 'token',
  90096. ** and its length in 'len' (to be used next iteration of this loop).
  90097. */
  90098. do {
  90099. zCsr += len;
  90100. len = sqlite3GetToken(zCsr, &token);
  90101. } while( token==TK_SPACE );
  90102. assert( len>0 );
  90103. } while( token!=TK_LP && token!=TK_USING );
  90104. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  90105. zSql, zTableName, tname.z+tname.n);
  90106. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  90107. }
  90108. }
  90109. /*
  90110. ** This C function implements an SQL user function that is used by SQL code
  90111. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  90112. ** of any foreign key constraints that use the table being renamed as the
  90113. ** parent table. It is passed three arguments:
  90114. **
  90115. ** 1) The complete text of the CREATE TABLE statement being modified,
  90116. ** 2) The old name of the table being renamed, and
  90117. ** 3) The new name of the table being renamed.
  90118. **
  90119. ** It returns the new CREATE TABLE statement. For example:
  90120. **
  90121. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  90122. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  90123. */
  90124. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90125. static void renameParentFunc(
  90126. sqlite3_context *context,
  90127. int NotUsed,
  90128. sqlite3_value **argv
  90129. ){
  90130. sqlite3 *db = sqlite3_context_db_handle(context);
  90131. char *zOutput = 0;
  90132. char *zResult;
  90133. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  90134. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  90135. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  90136. unsigned const char *z; /* Pointer to token */
  90137. int n; /* Length of token z */
  90138. int token; /* Type of token */
  90139. UNUSED_PARAMETER(NotUsed);
  90140. if( zInput==0 || zOld==0 ) return;
  90141. for(z=zInput; *z; z=z+n){
  90142. n = sqlite3GetToken(z, &token);
  90143. if( token==TK_REFERENCES ){
  90144. char *zParent;
  90145. do {
  90146. z += n;
  90147. n = sqlite3GetToken(z, &token);
  90148. }while( token==TK_SPACE );
  90149. if( token==TK_ILLEGAL ) break;
  90150. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  90151. if( zParent==0 ) break;
  90152. sqlite3Dequote(zParent);
  90153. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  90154. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  90155. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  90156. );
  90157. sqlite3DbFree(db, zOutput);
  90158. zOutput = zOut;
  90159. zInput = &z[n];
  90160. }
  90161. sqlite3DbFree(db, zParent);
  90162. }
  90163. }
  90164. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  90165. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  90166. sqlite3DbFree(db, zOutput);
  90167. }
  90168. #endif
  90169. #ifndef SQLITE_OMIT_TRIGGER
  90170. /* This function is used by SQL generated to implement the
  90171. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  90172. ** statement. The second is a table name. The table name in the CREATE
  90173. ** TRIGGER statement is replaced with the third argument and the result
  90174. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  90175. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  90176. */
  90177. static void renameTriggerFunc(
  90178. sqlite3_context *context,
  90179. int NotUsed,
  90180. sqlite3_value **argv
  90181. ){
  90182. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  90183. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  90184. int token;
  90185. Token tname;
  90186. int dist = 3;
  90187. unsigned char const *zCsr = zSql;
  90188. int len = 0;
  90189. char *zRet;
  90190. sqlite3 *db = sqlite3_context_db_handle(context);
  90191. UNUSED_PARAMETER(NotUsed);
  90192. /* The principle used to locate the table name in the CREATE TRIGGER
  90193. ** statement is that the table name is the first token that is immediately
  90194. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  90195. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  90196. */
  90197. if( zSql ){
  90198. do {
  90199. if( !*zCsr ){
  90200. /* Ran out of input before finding the table name. Return NULL. */
  90201. return;
  90202. }
  90203. /* Store the token that zCsr points to in tname. */
  90204. tname.z = (char*)zCsr;
  90205. tname.n = len;
  90206. /* Advance zCsr to the next token. Store that token type in 'token',
  90207. ** and its length in 'len' (to be used next iteration of this loop).
  90208. */
  90209. do {
  90210. zCsr += len;
  90211. len = sqlite3GetToken(zCsr, &token);
  90212. }while( token==TK_SPACE );
  90213. assert( len>0 );
  90214. /* Variable 'dist' stores the number of tokens read since the most
  90215. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  90216. ** token is read and 'dist' equals 2, the condition stated above
  90217. ** to be met.
  90218. **
  90219. ** Note that ON cannot be a database, table or column name, so
  90220. ** there is no need to worry about syntax like
  90221. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  90222. */
  90223. dist++;
  90224. if( token==TK_DOT || token==TK_ON ){
  90225. dist = 0;
  90226. }
  90227. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  90228. /* Variable tname now contains the token that is the old table-name
  90229. ** in the CREATE TRIGGER statement.
  90230. */
  90231. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  90232. zSql, zTableName, tname.z+tname.n);
  90233. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  90234. }
  90235. }
  90236. #endif /* !SQLITE_OMIT_TRIGGER */
  90237. /*
  90238. ** Register built-in functions used to help implement ALTER TABLE
  90239. */
  90240. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  90241. static FuncDef aAlterTableFuncs[] = {
  90242. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  90243. #ifndef SQLITE_OMIT_TRIGGER
  90244. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  90245. #endif
  90246. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90247. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  90248. #endif
  90249. };
  90250. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  90251. }
  90252. /*
  90253. ** This function is used to create the text of expressions of the form:
  90254. **
  90255. ** name=<constant1> OR name=<constant2> OR ...
  90256. **
  90257. ** If argument zWhere is NULL, then a pointer string containing the text
  90258. ** "name=<constant>" is returned, where <constant> is the quoted version
  90259. ** of the string passed as argument zConstant. The returned buffer is
  90260. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  90261. ** caller to ensure that it is eventually freed.
  90262. **
  90263. ** If argument zWhere is not NULL, then the string returned is
  90264. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  90265. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  90266. **
  90267. */
  90268. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  90269. char *zNew;
  90270. if( !zWhere ){
  90271. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  90272. }else{
  90273. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  90274. sqlite3DbFree(db, zWhere);
  90275. }
  90276. return zNew;
  90277. }
  90278. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  90279. /*
  90280. ** Generate the text of a WHERE expression which can be used to select all
  90281. ** tables that have foreign key constraints that refer to table pTab (i.e.
  90282. ** constraints for which pTab is the parent table) from the sqlite_master
  90283. ** table.
  90284. */
  90285. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  90286. FKey *p;
  90287. char *zWhere = 0;
  90288. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  90289. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  90290. }
  90291. return zWhere;
  90292. }
  90293. #endif
  90294. /*
  90295. ** Generate the text of a WHERE expression which can be used to select all
  90296. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  90297. ** table pTab has no temporary triggers, or is itself stored in the
  90298. ** temporary database, NULL is returned.
  90299. */
  90300. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  90301. Trigger *pTrig;
  90302. char *zWhere = 0;
  90303. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  90304. /* If the table is not located in the temp-db (in which case NULL is
  90305. ** returned, loop through the tables list of triggers. For each trigger
  90306. ** that is not part of the temp-db schema, add a clause to the WHERE
  90307. ** expression being built up in zWhere.
  90308. */
  90309. if( pTab->pSchema!=pTempSchema ){
  90310. sqlite3 *db = pParse->db;
  90311. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  90312. if( pTrig->pSchema==pTempSchema ){
  90313. zWhere = whereOrName(db, zWhere, pTrig->zName);
  90314. }
  90315. }
  90316. }
  90317. if( zWhere ){
  90318. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  90319. sqlite3DbFree(pParse->db, zWhere);
  90320. zWhere = zNew;
  90321. }
  90322. return zWhere;
  90323. }
  90324. /*
  90325. ** Generate code to drop and reload the internal representation of table
  90326. ** pTab from the database, including triggers and temporary triggers.
  90327. ** Argument zName is the name of the table in the database schema at
  90328. ** the time the generated code is executed. This can be different from
  90329. ** pTab->zName if this function is being called to code part of an
  90330. ** "ALTER TABLE RENAME TO" statement.
  90331. */
  90332. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  90333. Vdbe *v;
  90334. char *zWhere;
  90335. int iDb; /* Index of database containing pTab */
  90336. #ifndef SQLITE_OMIT_TRIGGER
  90337. Trigger *pTrig;
  90338. #endif
  90339. v = sqlite3GetVdbe(pParse);
  90340. if( NEVER(v==0) ) return;
  90341. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  90342. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  90343. assert( iDb>=0 );
  90344. #ifndef SQLITE_OMIT_TRIGGER
  90345. /* Drop any table triggers from the internal schema. */
  90346. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  90347. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  90348. assert( iTrigDb==iDb || iTrigDb==1 );
  90349. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  90350. }
  90351. #endif
  90352. /* Drop the table and index from the internal schema. */
  90353. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  90354. /* Reload the table, index and permanent trigger schemas. */
  90355. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  90356. if( !zWhere ) return;
  90357. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  90358. #ifndef SQLITE_OMIT_TRIGGER
  90359. /* Now, if the table is not stored in the temp database, reload any temp
  90360. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  90361. */
  90362. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  90363. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  90364. }
  90365. #endif
  90366. }
  90367. /*
  90368. ** Parameter zName is the name of a table that is about to be altered
  90369. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  90370. ** If the table is a system table, this function leaves an error message
  90371. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  90372. **
  90373. ** Or, if zName is not a system table, zero is returned.
  90374. */
  90375. static int isSystemTable(Parse *pParse, const char *zName){
  90376. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  90377. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  90378. return 1;
  90379. }
  90380. return 0;
  90381. }
  90382. /*
  90383. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  90384. ** command.
  90385. */
  90386. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  90387. Parse *pParse, /* Parser context. */
  90388. SrcList *pSrc, /* The table to rename. */
  90389. Token *pName /* The new table name. */
  90390. ){
  90391. int iDb; /* Database that contains the table */
  90392. char *zDb; /* Name of database iDb */
  90393. Table *pTab; /* Table being renamed */
  90394. char *zName = 0; /* NULL-terminated version of pName */
  90395. sqlite3 *db = pParse->db; /* Database connection */
  90396. int nTabName; /* Number of UTF-8 characters in zTabName */
  90397. const char *zTabName; /* Original name of the table */
  90398. Vdbe *v;
  90399. #ifndef SQLITE_OMIT_TRIGGER
  90400. char *zWhere = 0; /* Where clause to locate temp triggers */
  90401. #endif
  90402. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  90403. int savedDbFlags; /* Saved value of db->flags */
  90404. savedDbFlags = db->flags;
  90405. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  90406. assert( pSrc->nSrc==1 );
  90407. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  90408. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  90409. if( !pTab ) goto exit_rename_table;
  90410. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  90411. zDb = db->aDb[iDb].zDbSName;
  90412. db->flags |= SQLITE_PreferBuiltin;
  90413. /* Get a NULL terminated version of the new table name. */
  90414. zName = sqlite3NameFromToken(db, pName);
  90415. if( !zName ) goto exit_rename_table;
  90416. /* Check that a table or index named 'zName' does not already exist
  90417. ** in database iDb. If so, this is an error.
  90418. */
  90419. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  90420. sqlite3ErrorMsg(pParse,
  90421. "there is already another table or index with this name: %s", zName);
  90422. goto exit_rename_table;
  90423. }
  90424. /* Make sure it is not a system table being altered, or a reserved name
  90425. ** that the table is being renamed to.
  90426. */
  90427. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  90428. goto exit_rename_table;
  90429. }
  90430. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  90431. exit_rename_table;
  90432. }
  90433. #ifndef SQLITE_OMIT_VIEW
  90434. if( pTab->pSelect ){
  90435. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  90436. goto exit_rename_table;
  90437. }
  90438. #endif
  90439. #ifndef SQLITE_OMIT_AUTHORIZATION
  90440. /* Invoke the authorization callback. */
  90441. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  90442. goto exit_rename_table;
  90443. }
  90444. #endif
  90445. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90446. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  90447. goto exit_rename_table;
  90448. }
  90449. if( IsVirtual(pTab) ){
  90450. pVTab = sqlite3GetVTable(db, pTab);
  90451. if( pVTab->pVtab->pModule->xRename==0 ){
  90452. pVTab = 0;
  90453. }
  90454. }
  90455. #endif
  90456. /* Begin a transaction for database iDb.
  90457. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  90458. ** schema). Open a statement transaction if the table is a virtual
  90459. ** table.
  90460. */
  90461. v = sqlite3GetVdbe(pParse);
  90462. if( v==0 ){
  90463. goto exit_rename_table;
  90464. }
  90465. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  90466. sqlite3ChangeCookie(pParse, iDb);
  90467. /* If this is a virtual table, invoke the xRename() function if
  90468. ** one is defined. The xRename() callback will modify the names
  90469. ** of any resources used by the v-table implementation (including other
  90470. ** SQLite tables) that are identified by the name of the virtual table.
  90471. */
  90472. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90473. if( pVTab ){
  90474. int i = ++pParse->nMem;
  90475. sqlite3VdbeLoadString(v, i, zName);
  90476. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  90477. sqlite3MayAbort(pParse);
  90478. }
  90479. #endif
  90480. /* figure out how many UTF-8 characters are in zName */
  90481. zTabName = pTab->zName;
  90482. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  90483. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  90484. if( db->flags&SQLITE_ForeignKeys ){
  90485. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  90486. ** statements corresponding to all child tables of foreign key constraints
  90487. ** for which the renamed table is the parent table. */
  90488. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  90489. sqlite3NestedParse(pParse,
  90490. "UPDATE \"%w\".%s SET "
  90491. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  90492. "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
  90493. sqlite3DbFree(db, zWhere);
  90494. }
  90495. }
  90496. #endif
  90497. /* Modify the sqlite_master table to use the new table name. */
  90498. sqlite3NestedParse(pParse,
  90499. "UPDATE %Q.%s SET "
  90500. #ifdef SQLITE_OMIT_TRIGGER
  90501. "sql = sqlite_rename_table(sql, %Q), "
  90502. #else
  90503. "sql = CASE "
  90504. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  90505. "ELSE sqlite_rename_table(sql, %Q) END, "
  90506. #endif
  90507. "tbl_name = %Q, "
  90508. "name = CASE "
  90509. "WHEN type='table' THEN %Q "
  90510. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  90511. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  90512. "ELSE name END "
  90513. "WHERE tbl_name=%Q COLLATE nocase AND "
  90514. "(type='table' OR type='index' OR type='trigger');",
  90515. zDb, MASTER_NAME, zName, zName, zName,
  90516. #ifndef SQLITE_OMIT_TRIGGER
  90517. zName,
  90518. #endif
  90519. zName, nTabName, zTabName
  90520. );
  90521. #ifndef SQLITE_OMIT_AUTOINCREMENT
  90522. /* If the sqlite_sequence table exists in this database, then update
  90523. ** it with the new table name.
  90524. */
  90525. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  90526. sqlite3NestedParse(pParse,
  90527. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  90528. zDb, zName, pTab->zName);
  90529. }
  90530. #endif
  90531. #ifndef SQLITE_OMIT_TRIGGER
  90532. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  90533. ** table. Don't do this if the table being ALTERed is itself located in
  90534. ** the temp database.
  90535. */
  90536. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  90537. sqlite3NestedParse(pParse,
  90538. "UPDATE sqlite_temp_master SET "
  90539. "sql = sqlite_rename_trigger(sql, %Q), "
  90540. "tbl_name = %Q "
  90541. "WHERE %s;", zName, zName, zWhere);
  90542. sqlite3DbFree(db, zWhere);
  90543. }
  90544. #endif
  90545. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  90546. if( db->flags&SQLITE_ForeignKeys ){
  90547. FKey *p;
  90548. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  90549. Table *pFrom = p->pFrom;
  90550. if( pFrom!=pTab ){
  90551. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  90552. }
  90553. }
  90554. }
  90555. #endif
  90556. /* Drop and reload the internal table schema. */
  90557. reloadTableSchema(pParse, pTab, zName);
  90558. exit_rename_table:
  90559. sqlite3SrcListDelete(db, pSrc);
  90560. sqlite3DbFree(db, zName);
  90561. db->flags = savedDbFlags;
  90562. }
  90563. /*
  90564. ** This function is called after an "ALTER TABLE ... ADD" statement
  90565. ** has been parsed. Argument pColDef contains the text of the new
  90566. ** column definition.
  90567. **
  90568. ** The Table structure pParse->pNewTable was extended to include
  90569. ** the new column during parsing.
  90570. */
  90571. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  90572. Table *pNew; /* Copy of pParse->pNewTable */
  90573. Table *pTab; /* Table being altered */
  90574. int iDb; /* Database number */
  90575. const char *zDb; /* Database name */
  90576. const char *zTab; /* Table name */
  90577. char *zCol; /* Null-terminated column definition */
  90578. Column *pCol; /* The new column */
  90579. Expr *pDflt; /* Default value for the new column */
  90580. sqlite3 *db; /* The database connection; */
  90581. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  90582. int r1; /* Temporary registers */
  90583. db = pParse->db;
  90584. if( pParse->nErr || db->mallocFailed ) return;
  90585. assert( v!=0 );
  90586. pNew = pParse->pNewTable;
  90587. assert( pNew );
  90588. assert( sqlite3BtreeHoldsAllMutexes(db) );
  90589. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  90590. zDb = db->aDb[iDb].zDbSName;
  90591. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  90592. pCol = &pNew->aCol[pNew->nCol-1];
  90593. pDflt = pCol->pDflt;
  90594. pTab = sqlite3FindTable(db, zTab, zDb);
  90595. assert( pTab );
  90596. #ifndef SQLITE_OMIT_AUTHORIZATION
  90597. /* Invoke the authorization callback. */
  90598. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  90599. return;
  90600. }
  90601. #endif
  90602. /* If the default value for the new column was specified with a
  90603. ** literal NULL, then set pDflt to 0. This simplifies checking
  90604. ** for an SQL NULL default below.
  90605. */
  90606. assert( pDflt==0 || pDflt->op==TK_SPAN );
  90607. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  90608. pDflt = 0;
  90609. }
  90610. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  90611. ** If there is a NOT NULL constraint, then the default value for the
  90612. ** column must not be NULL.
  90613. */
  90614. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  90615. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  90616. return;
  90617. }
  90618. if( pNew->pIndex ){
  90619. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  90620. return;
  90621. }
  90622. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  90623. sqlite3ErrorMsg(pParse,
  90624. "Cannot add a REFERENCES column with non-NULL default value");
  90625. return;
  90626. }
  90627. if( pCol->notNull && !pDflt ){
  90628. sqlite3ErrorMsg(pParse,
  90629. "Cannot add a NOT NULL column with default value NULL");
  90630. return;
  90631. }
  90632. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  90633. ** can handle (i.e. not CURRENT_TIME etc.)
  90634. */
  90635. if( pDflt ){
  90636. sqlite3_value *pVal = 0;
  90637. int rc;
  90638. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  90639. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  90640. if( rc!=SQLITE_OK ){
  90641. assert( db->mallocFailed == 1 );
  90642. return;
  90643. }
  90644. if( !pVal ){
  90645. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  90646. return;
  90647. }
  90648. sqlite3ValueFree(pVal);
  90649. }
  90650. /* Modify the CREATE TABLE statement. */
  90651. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  90652. if( zCol ){
  90653. char *zEnd = &zCol[pColDef->n-1];
  90654. int savedDbFlags = db->flags;
  90655. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  90656. *zEnd-- = '\0';
  90657. }
  90658. db->flags |= SQLITE_PreferBuiltin;
  90659. sqlite3NestedParse(pParse,
  90660. "UPDATE \"%w\".%s SET "
  90661. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  90662. "WHERE type = 'table' AND name = %Q",
  90663. zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
  90664. zTab
  90665. );
  90666. sqlite3DbFree(db, zCol);
  90667. db->flags = savedDbFlags;
  90668. }
  90669. /* Make sure the schema version is at least 3. But do not upgrade
  90670. ** from less than 3 to 4, as that will corrupt any preexisting DESC
  90671. ** index.
  90672. */
  90673. r1 = sqlite3GetTempReg(pParse);
  90674. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  90675. sqlite3VdbeUsesBtree(v, iDb);
  90676. sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
  90677. sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
  90678. VdbeCoverage(v);
  90679. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
  90680. sqlite3ReleaseTempReg(pParse, r1);
  90681. /* Reload the schema of the modified table. */
  90682. reloadTableSchema(pParse, pTab, pTab->zName);
  90683. }
  90684. /*
  90685. ** This function is called by the parser after the table-name in
  90686. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  90687. ** pSrc is the full-name of the table being altered.
  90688. **
  90689. ** This routine makes a (partial) copy of the Table structure
  90690. ** for the table being altered and sets Parse.pNewTable to point
  90691. ** to it. Routines called by the parser as the column definition
  90692. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  90693. ** the copy. The copy of the Table structure is deleted by tokenize.c
  90694. ** after parsing is finished.
  90695. **
  90696. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  90697. ** coding the "ALTER TABLE ... ADD" statement.
  90698. */
  90699. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  90700. Table *pNew;
  90701. Table *pTab;
  90702. Vdbe *v;
  90703. int iDb;
  90704. int i;
  90705. int nAlloc;
  90706. sqlite3 *db = pParse->db;
  90707. /* Look up the table being altered. */
  90708. assert( pParse->pNewTable==0 );
  90709. assert( sqlite3BtreeHoldsAllMutexes(db) );
  90710. if( db->mallocFailed ) goto exit_begin_add_column;
  90711. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  90712. if( !pTab ) goto exit_begin_add_column;
  90713. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90714. if( IsVirtual(pTab) ){
  90715. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  90716. goto exit_begin_add_column;
  90717. }
  90718. #endif
  90719. /* Make sure this is not an attempt to ALTER a view. */
  90720. if( pTab->pSelect ){
  90721. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  90722. goto exit_begin_add_column;
  90723. }
  90724. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  90725. goto exit_begin_add_column;
  90726. }
  90727. assert( pTab->addColOffset>0 );
  90728. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90729. /* Put a copy of the Table struct in Parse.pNewTable for the
  90730. ** sqlite3AddColumn() function and friends to modify. But modify
  90731. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  90732. ** prefix, we insure that the name will not collide with an existing
  90733. ** table because user table are not allowed to have the "sqlite_"
  90734. ** prefix on their name.
  90735. */
  90736. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  90737. if( !pNew ) goto exit_begin_add_column;
  90738. pParse->pNewTable = pNew;
  90739. pNew->nTabRef = 1;
  90740. pNew->nCol = pTab->nCol;
  90741. assert( pNew->nCol>0 );
  90742. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  90743. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  90744. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  90745. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  90746. if( !pNew->aCol || !pNew->zName ){
  90747. assert( db->mallocFailed );
  90748. goto exit_begin_add_column;
  90749. }
  90750. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  90751. for(i=0; i<pNew->nCol; i++){
  90752. Column *pCol = &pNew->aCol[i];
  90753. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  90754. pCol->zColl = 0;
  90755. pCol->pDflt = 0;
  90756. }
  90757. pNew->pSchema = db->aDb[iDb].pSchema;
  90758. pNew->addColOffset = pTab->addColOffset;
  90759. pNew->nTabRef = 1;
  90760. /* Begin a transaction and increment the schema cookie. */
  90761. sqlite3BeginWriteOperation(pParse, 0, iDb);
  90762. v = sqlite3GetVdbe(pParse);
  90763. if( !v ) goto exit_begin_add_column;
  90764. sqlite3ChangeCookie(pParse, iDb);
  90765. exit_begin_add_column:
  90766. sqlite3SrcListDelete(db, pSrc);
  90767. return;
  90768. }
  90769. #endif /* SQLITE_ALTER_TABLE */
  90770. /************** End of alter.c ***********************************************/
  90771. /************** Begin file analyze.c *****************************************/
  90772. /*
  90773. ** 2005-07-08
  90774. **
  90775. ** The author disclaims copyright to this source code. In place of
  90776. ** a legal notice, here is a blessing:
  90777. **
  90778. ** May you do good and not evil.
  90779. ** May you find forgiveness for yourself and forgive others.
  90780. ** May you share freely, never taking more than you give.
  90781. **
  90782. *************************************************************************
  90783. ** This file contains code associated with the ANALYZE command.
  90784. **
  90785. ** The ANALYZE command gather statistics about the content of tables
  90786. ** and indices. These statistics are made available to the query planner
  90787. ** to help it make better decisions about how to perform queries.
  90788. **
  90789. ** The following system tables are or have been supported:
  90790. **
  90791. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  90792. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  90793. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  90794. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  90795. **
  90796. ** Additional tables might be added in future releases of SQLite.
  90797. ** The sqlite_stat2 table is not created or used unless the SQLite version
  90798. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  90799. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  90800. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  90801. ** created and used by SQLite versions 3.7.9 and later and with
  90802. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  90803. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  90804. ** version of sqlite_stat3 and is only available when compiled with
  90805. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  90806. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  90807. ** are both enabled, then STAT4 takes precedence.
  90808. **
  90809. ** For most applications, sqlite_stat1 provides all the statistics required
  90810. ** for the query planner to make good choices.
  90811. **
  90812. ** Format of sqlite_stat1:
  90813. **
  90814. ** There is normally one row per index, with the index identified by the
  90815. ** name in the idx column. The tbl column is the name of the table to
  90816. ** which the index belongs. In each such row, the stat column will be
  90817. ** a string consisting of a list of integers. The first integer in this
  90818. ** list is the number of rows in the index. (This is the same as the
  90819. ** number of rows in the table, except for partial indices.) The second
  90820. ** integer is the average number of rows in the index that have the same
  90821. ** value in the first column of the index. The third integer is the average
  90822. ** number of rows in the index that have the same value for the first two
  90823. ** columns. The N-th integer (for N>1) is the average number of rows in
  90824. ** the index which have the same value for the first N-1 columns. For
  90825. ** a K-column index, there will be K+1 integers in the stat column. If
  90826. ** the index is unique, then the last integer will be 1.
  90827. **
  90828. ** The list of integers in the stat column can optionally be followed
  90829. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  90830. ** must be separated from the last integer by a single space. If the
  90831. ** "unordered" keyword is present, then the query planner assumes that
  90832. ** the index is unordered and will not use the index for a range query.
  90833. **
  90834. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  90835. ** column contains a single integer which is the (estimated) number of
  90836. ** rows in the table identified by sqlite_stat1.tbl.
  90837. **
  90838. ** Format of sqlite_stat2:
  90839. **
  90840. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  90841. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  90842. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  90843. ** about the distribution of keys within an index. The index is identified by
  90844. ** the "idx" column and the "tbl" column is the name of the table to which
  90845. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  90846. ** table for each index.
  90847. **
  90848. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  90849. ** inclusive are samples of the left-most key value in the index taken at
  90850. ** evenly spaced points along the index. Let the number of samples be S
  90851. ** (10 in the standard build) and let C be the number of rows in the index.
  90852. ** Then the sampled rows are given by:
  90853. **
  90854. ** rownumber = (i*C*2 + C)/(S*2)
  90855. **
  90856. ** For i between 0 and S-1. Conceptually, the index space is divided into
  90857. ** S uniform buckets and the samples are the middle row from each bucket.
  90858. **
  90859. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  90860. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  90861. ** writes the sqlite_stat2 table. This version of SQLite only supports
  90862. ** sqlite_stat3.
  90863. **
  90864. ** Format for sqlite_stat3:
  90865. **
  90866. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  90867. ** sqlite_stat4 format will be described first. Further information
  90868. ** about sqlite_stat3 follows the sqlite_stat4 description.
  90869. **
  90870. ** Format for sqlite_stat4:
  90871. **
  90872. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  90873. ** to aid the query planner in choosing good indices based on the values
  90874. ** that indexed columns are compared against in the WHERE clauses of
  90875. ** queries.
  90876. **
  90877. ** The sqlite_stat4 table contains multiple entries for each index.
  90878. ** The idx column names the index and the tbl column is the table of the
  90879. ** index. If the idx and tbl columns are the same, then the sample is
  90880. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  90881. ** binary encoding of a key from the index. The nEq column is a
  90882. ** list of integers. The first integer is the approximate number
  90883. ** of entries in the index whose left-most column exactly matches
  90884. ** the left-most column of the sample. The second integer in nEq
  90885. ** is the approximate number of entries in the index where the
  90886. ** first two columns match the first two columns of the sample.
  90887. ** And so forth. nLt is another list of integers that show the approximate
  90888. ** number of entries that are strictly less than the sample. The first
  90889. ** integer in nLt contains the number of entries in the index where the
  90890. ** left-most column is less than the left-most column of the sample.
  90891. ** The K-th integer in the nLt entry is the number of index entries
  90892. ** where the first K columns are less than the first K columns of the
  90893. ** sample. The nDLt column is like nLt except that it contains the
  90894. ** number of distinct entries in the index that are less than the
  90895. ** sample.
  90896. **
  90897. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  90898. ** The ANALYZE command will typically generate sqlite_stat4 tables
  90899. ** that contain between 10 and 40 samples which are distributed across
  90900. ** the key space, though not uniformly, and which include samples with
  90901. ** large nEq values.
  90902. **
  90903. ** Format for sqlite_stat3 redux:
  90904. **
  90905. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  90906. ** looks at the left-most column of the index. The sqlite_stat3.sample
  90907. ** column contains the actual value of the left-most column instead
  90908. ** of a blob encoding of the complete index key as is found in
  90909. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  90910. ** all contain just a single integer which is the same as the first
  90911. ** integer in the equivalent columns in sqlite_stat4.
  90912. */
  90913. #ifndef SQLITE_OMIT_ANALYZE
  90914. /* #include "sqliteInt.h" */
  90915. #if defined(SQLITE_ENABLE_STAT4)
  90916. # define IsStat4 1
  90917. # define IsStat3 0
  90918. #elif defined(SQLITE_ENABLE_STAT3)
  90919. # define IsStat4 0
  90920. # define IsStat3 1
  90921. #else
  90922. # define IsStat4 0
  90923. # define IsStat3 0
  90924. # undef SQLITE_STAT4_SAMPLES
  90925. # define SQLITE_STAT4_SAMPLES 1
  90926. #endif
  90927. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  90928. /*
  90929. ** This routine generates code that opens the sqlite_statN tables.
  90930. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  90931. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  90932. ** appropriate compile-time options are provided.
  90933. **
  90934. ** If the sqlite_statN tables do not previously exist, it is created.
  90935. **
  90936. ** Argument zWhere may be a pointer to a buffer containing a table name,
  90937. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  90938. ** the sqlite_statN tables associated with the named table are deleted.
  90939. ** If zWhere==0, then code is generated to delete all stat table entries.
  90940. */
  90941. static void openStatTable(
  90942. Parse *pParse, /* Parsing context */
  90943. int iDb, /* The database we are looking in */
  90944. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  90945. const char *zWhere, /* Delete entries for this table or index */
  90946. const char *zWhereType /* Either "tbl" or "idx" */
  90947. ){
  90948. static const struct {
  90949. const char *zName;
  90950. const char *zCols;
  90951. } aTable[] = {
  90952. { "sqlite_stat1", "tbl,idx,stat" },
  90953. #if defined(SQLITE_ENABLE_STAT4)
  90954. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  90955. { "sqlite_stat3", 0 },
  90956. #elif defined(SQLITE_ENABLE_STAT3)
  90957. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  90958. { "sqlite_stat4", 0 },
  90959. #else
  90960. { "sqlite_stat3", 0 },
  90961. { "sqlite_stat4", 0 },
  90962. #endif
  90963. };
  90964. int i;
  90965. sqlite3 *db = pParse->db;
  90966. Db *pDb;
  90967. Vdbe *v = sqlite3GetVdbe(pParse);
  90968. int aRoot[ArraySize(aTable)];
  90969. u8 aCreateTbl[ArraySize(aTable)];
  90970. if( v==0 ) return;
  90971. assert( sqlite3BtreeHoldsAllMutexes(db) );
  90972. assert( sqlite3VdbeDb(v)==db );
  90973. pDb = &db->aDb[iDb];
  90974. /* Create new statistic tables if they do not exist, or clear them
  90975. ** if they do already exist.
  90976. */
  90977. for(i=0; i<ArraySize(aTable); i++){
  90978. const char *zTab = aTable[i].zName;
  90979. Table *pStat;
  90980. if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
  90981. if( aTable[i].zCols ){
  90982. /* The sqlite_statN table does not exist. Create it. Note that a
  90983. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  90984. ** of the new table in register pParse->regRoot. This is important
  90985. ** because the OpenWrite opcode below will be needing it. */
  90986. sqlite3NestedParse(pParse,
  90987. "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
  90988. );
  90989. aRoot[i] = pParse->regRoot;
  90990. aCreateTbl[i] = OPFLAG_P2ISREG;
  90991. }
  90992. }else{
  90993. /* The table already exists. If zWhere is not NULL, delete all entries
  90994. ** associated with the table zWhere. If zWhere is NULL, delete the
  90995. ** entire contents of the table. */
  90996. aRoot[i] = pStat->tnum;
  90997. aCreateTbl[i] = 0;
  90998. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  90999. if( zWhere ){
  91000. sqlite3NestedParse(pParse,
  91001. "DELETE FROM %Q.%s WHERE %s=%Q",
  91002. pDb->zDbSName, zTab, zWhereType, zWhere
  91003. );
  91004. }else{
  91005. /* The sqlite_stat[134] table already exists. Delete all rows. */
  91006. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  91007. }
  91008. }
  91009. }
  91010. /* Open the sqlite_stat[134] tables for writing. */
  91011. for(i=0; aTable[i].zCols; i++){
  91012. assert( i<ArraySize(aTable) );
  91013. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  91014. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  91015. VdbeComment((v, aTable[i].zName));
  91016. }
  91017. }
  91018. /*
  91019. ** Recommended number of samples for sqlite_stat4
  91020. */
  91021. #ifndef SQLITE_STAT4_SAMPLES
  91022. # define SQLITE_STAT4_SAMPLES 24
  91023. #endif
  91024. /*
  91025. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  91026. ** share an instance of the following structure to hold their state
  91027. ** information.
  91028. */
  91029. typedef struct Stat4Accum Stat4Accum;
  91030. typedef struct Stat4Sample Stat4Sample;
  91031. struct Stat4Sample {
  91032. tRowcnt *anEq; /* sqlite_stat4.nEq */
  91033. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  91034. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91035. tRowcnt *anLt; /* sqlite_stat4.nLt */
  91036. union {
  91037. i64 iRowid; /* Rowid in main table of the key */
  91038. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  91039. } u;
  91040. u32 nRowid; /* Sizeof aRowid[] */
  91041. u8 isPSample; /* True if a periodic sample */
  91042. int iCol; /* If !isPSample, the reason for inclusion */
  91043. u32 iHash; /* Tiebreaker hash */
  91044. #endif
  91045. };
  91046. struct Stat4Accum {
  91047. tRowcnt nRow; /* Number of rows in the entire table */
  91048. tRowcnt nPSample; /* How often to do a periodic sample */
  91049. int nCol; /* Number of columns in index + pk/rowid */
  91050. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  91051. int mxSample; /* Maximum number of samples to accumulate */
  91052. Stat4Sample current; /* Current row as a Stat4Sample */
  91053. u32 iPrn; /* Pseudo-random number used for sampling */
  91054. Stat4Sample *aBest; /* Array of nCol best samples */
  91055. int iMin; /* Index in a[] of entry with minimum score */
  91056. int nSample; /* Current number of samples */
  91057. int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
  91058. int iGet; /* Index of current sample accessed by stat_get() */
  91059. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  91060. sqlite3 *db; /* Database connection, for malloc() */
  91061. };
  91062. /* Reclaim memory used by a Stat4Sample
  91063. */
  91064. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91065. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  91066. assert( db!=0 );
  91067. if( p->nRowid ){
  91068. sqlite3DbFree(db, p->u.aRowid);
  91069. p->nRowid = 0;
  91070. }
  91071. }
  91072. #endif
  91073. /* Initialize the BLOB value of a ROWID
  91074. */
  91075. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91076. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  91077. assert( db!=0 );
  91078. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  91079. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  91080. if( p->u.aRowid ){
  91081. p->nRowid = n;
  91082. memcpy(p->u.aRowid, pData, n);
  91083. }else{
  91084. p->nRowid = 0;
  91085. }
  91086. }
  91087. #endif
  91088. /* Initialize the INTEGER value of a ROWID.
  91089. */
  91090. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91091. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  91092. assert( db!=0 );
  91093. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  91094. p->nRowid = 0;
  91095. p->u.iRowid = iRowid;
  91096. }
  91097. #endif
  91098. /*
  91099. ** Copy the contents of object (*pFrom) into (*pTo).
  91100. */
  91101. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91102. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  91103. pTo->isPSample = pFrom->isPSample;
  91104. pTo->iCol = pFrom->iCol;
  91105. pTo->iHash = pFrom->iHash;
  91106. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  91107. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  91108. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  91109. if( pFrom->nRowid ){
  91110. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  91111. }else{
  91112. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  91113. }
  91114. }
  91115. #endif
  91116. /*
  91117. ** Reclaim all memory of a Stat4Accum structure.
  91118. */
  91119. static void stat4Destructor(void *pOld){
  91120. Stat4Accum *p = (Stat4Accum*)pOld;
  91121. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91122. int i;
  91123. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  91124. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  91125. sampleClear(p->db, &p->current);
  91126. #endif
  91127. sqlite3DbFree(p->db, p);
  91128. }
  91129. /*
  91130. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  91131. ** are:
  91132. ** N: The number of columns in the index including the rowid/pk (note 1)
  91133. ** K: The number of columns in the index excluding the rowid/pk.
  91134. ** C: The number of rows in the index (note 2)
  91135. **
  91136. ** Note 1: In the special case of the covering index that implements a
  91137. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  91138. ** total number of columns in the table.
  91139. **
  91140. ** Note 2: C is only used for STAT3 and STAT4.
  91141. **
  91142. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  91143. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  91144. ** PRIMARY KEY of the table. The covering index that implements the
  91145. ** original WITHOUT ROWID table as N==K as a special case.
  91146. **
  91147. ** This routine allocates the Stat4Accum object in heap memory. The return
  91148. ** value is a pointer to the Stat4Accum object. The datatype of the
  91149. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  91150. ** object.
  91151. */
  91152. static void statInit(
  91153. sqlite3_context *context,
  91154. int argc,
  91155. sqlite3_value **argv
  91156. ){
  91157. Stat4Accum *p;
  91158. int nCol; /* Number of columns in index being sampled */
  91159. int nKeyCol; /* Number of key columns */
  91160. int nColUp; /* nCol rounded up for alignment */
  91161. int n; /* Bytes of space to allocate */
  91162. sqlite3 *db; /* Database connection */
  91163. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91164. int mxSample = SQLITE_STAT4_SAMPLES;
  91165. #endif
  91166. /* Decode the three function arguments */
  91167. UNUSED_PARAMETER(argc);
  91168. nCol = sqlite3_value_int(argv[0]);
  91169. assert( nCol>0 );
  91170. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  91171. nKeyCol = sqlite3_value_int(argv[1]);
  91172. assert( nKeyCol<=nCol );
  91173. assert( nKeyCol>0 );
  91174. /* Allocate the space required for the Stat4Accum object */
  91175. n = sizeof(*p)
  91176. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  91177. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  91178. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91179. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  91180. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  91181. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  91182. #endif
  91183. ;
  91184. db = sqlite3_context_db_handle(context);
  91185. p = sqlite3DbMallocZero(db, n);
  91186. if( p==0 ){
  91187. sqlite3_result_error_nomem(context);
  91188. return;
  91189. }
  91190. p->db = db;
  91191. p->nRow = 0;
  91192. p->nCol = nCol;
  91193. p->nKeyCol = nKeyCol;
  91194. p->current.anDLt = (tRowcnt*)&p[1];
  91195. p->current.anEq = &p->current.anDLt[nColUp];
  91196. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91197. {
  91198. u8 *pSpace; /* Allocated space not yet assigned */
  91199. int i; /* Used to iterate through p->aSample[] */
  91200. p->iGet = -1;
  91201. p->mxSample = mxSample;
  91202. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  91203. p->current.anLt = &p->current.anEq[nColUp];
  91204. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  91205. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  91206. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  91207. p->aBest = &p->a[mxSample];
  91208. pSpace = (u8*)(&p->a[mxSample+nCol]);
  91209. for(i=0; i<(mxSample+nCol); i++){
  91210. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  91211. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  91212. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  91213. }
  91214. assert( (pSpace - (u8*)p)==n );
  91215. for(i=0; i<nCol; i++){
  91216. p->aBest[i].iCol = i;
  91217. }
  91218. }
  91219. #endif
  91220. /* Return a pointer to the allocated object to the caller. Note that
  91221. ** only the pointer (the 2nd parameter) matters. The size of the object
  91222. ** (given by the 3rd parameter) is never used and can be any positive
  91223. ** value. */
  91224. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  91225. }
  91226. static const FuncDef statInitFuncdef = {
  91227. 2+IsStat34, /* nArg */
  91228. SQLITE_UTF8, /* funcFlags */
  91229. 0, /* pUserData */
  91230. 0, /* pNext */
  91231. statInit, /* xSFunc */
  91232. 0, /* xFinalize */
  91233. "stat_init", /* zName */
  91234. {0}
  91235. };
  91236. #ifdef SQLITE_ENABLE_STAT4
  91237. /*
  91238. ** pNew and pOld are both candidate non-periodic samples selected for
  91239. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  91240. ** considering only any trailing columns and the sample hash value, this
  91241. ** function returns true if sample pNew is to be preferred over pOld.
  91242. ** In other words, if we assume that the cardinalities of the selected
  91243. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  91244. **
  91245. ** This function assumes that for each argument sample, the contents of
  91246. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  91247. */
  91248. static int sampleIsBetterPost(
  91249. Stat4Accum *pAccum,
  91250. Stat4Sample *pNew,
  91251. Stat4Sample *pOld
  91252. ){
  91253. int nCol = pAccum->nCol;
  91254. int i;
  91255. assert( pNew->iCol==pOld->iCol );
  91256. for(i=pNew->iCol+1; i<nCol; i++){
  91257. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  91258. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  91259. }
  91260. if( pNew->iHash>pOld->iHash ) return 1;
  91261. return 0;
  91262. }
  91263. #endif
  91264. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91265. /*
  91266. ** Return true if pNew is to be preferred over pOld.
  91267. **
  91268. ** This function assumes that for each argument sample, the contents of
  91269. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  91270. */
  91271. static int sampleIsBetter(
  91272. Stat4Accum *pAccum,
  91273. Stat4Sample *pNew,
  91274. Stat4Sample *pOld
  91275. ){
  91276. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  91277. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  91278. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  91279. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  91280. if( (nEqNew>nEqOld) ) return 1;
  91281. #ifdef SQLITE_ENABLE_STAT4
  91282. if( nEqNew==nEqOld ){
  91283. if( pNew->iCol<pOld->iCol ) return 1;
  91284. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  91285. }
  91286. return 0;
  91287. #else
  91288. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  91289. #endif
  91290. }
  91291. /*
  91292. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  91293. ** remove the least desirable sample from p->a[] to make room.
  91294. */
  91295. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  91296. Stat4Sample *pSample = 0;
  91297. int i;
  91298. assert( IsStat4 || nEqZero==0 );
  91299. #ifdef SQLITE_ENABLE_STAT4
  91300. /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
  91301. ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
  91302. ** other words, if nMaxEqZero is n, then it is guaranteed that there
  91303. ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
  91304. if( nEqZero>p->nMaxEqZero ){
  91305. p->nMaxEqZero = nEqZero;
  91306. }
  91307. if( pNew->isPSample==0 ){
  91308. Stat4Sample *pUpgrade = 0;
  91309. assert( pNew->anEq[pNew->iCol]>0 );
  91310. /* This sample is being added because the prefix that ends in column
  91311. ** iCol occurs many times in the table. However, if we have already
  91312. ** added a sample that shares this prefix, there is no need to add
  91313. ** this one. Instead, upgrade the priority of the highest priority
  91314. ** existing sample that shares this prefix. */
  91315. for(i=p->nSample-1; i>=0; i--){
  91316. Stat4Sample *pOld = &p->a[i];
  91317. if( pOld->anEq[pNew->iCol]==0 ){
  91318. if( pOld->isPSample ) return;
  91319. assert( pOld->iCol>pNew->iCol );
  91320. assert( sampleIsBetter(p, pNew, pOld) );
  91321. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  91322. pUpgrade = pOld;
  91323. }
  91324. }
  91325. }
  91326. if( pUpgrade ){
  91327. pUpgrade->iCol = pNew->iCol;
  91328. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  91329. goto find_new_min;
  91330. }
  91331. }
  91332. #endif
  91333. /* If necessary, remove sample iMin to make room for the new sample. */
  91334. if( p->nSample>=p->mxSample ){
  91335. Stat4Sample *pMin = &p->a[p->iMin];
  91336. tRowcnt *anEq = pMin->anEq;
  91337. tRowcnt *anLt = pMin->anLt;
  91338. tRowcnt *anDLt = pMin->anDLt;
  91339. sampleClear(p->db, pMin);
  91340. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  91341. pSample = &p->a[p->nSample-1];
  91342. pSample->nRowid = 0;
  91343. pSample->anEq = anEq;
  91344. pSample->anDLt = anDLt;
  91345. pSample->anLt = anLt;
  91346. p->nSample = p->mxSample-1;
  91347. }
  91348. /* The "rows less-than" for the rowid column must be greater than that
  91349. ** for the last sample in the p->a[] array. Otherwise, the samples would
  91350. ** be out of order. */
  91351. #ifdef SQLITE_ENABLE_STAT4
  91352. assert( p->nSample==0
  91353. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  91354. #endif
  91355. /* Insert the new sample */
  91356. pSample = &p->a[p->nSample];
  91357. sampleCopy(p, pSample, pNew);
  91358. p->nSample++;
  91359. /* Zero the first nEqZero entries in the anEq[] array. */
  91360. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  91361. #ifdef SQLITE_ENABLE_STAT4
  91362. find_new_min:
  91363. #endif
  91364. if( p->nSample>=p->mxSample ){
  91365. int iMin = -1;
  91366. for(i=0; i<p->mxSample; i++){
  91367. if( p->a[i].isPSample ) continue;
  91368. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  91369. iMin = i;
  91370. }
  91371. }
  91372. assert( iMin>=0 );
  91373. p->iMin = iMin;
  91374. }
  91375. }
  91376. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  91377. /*
  91378. ** Field iChng of the index being scanned has changed. So at this point
  91379. ** p->current contains a sample that reflects the previous row of the
  91380. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  91381. ** correct at this point.
  91382. */
  91383. static void samplePushPrevious(Stat4Accum *p, int iChng){
  91384. #ifdef SQLITE_ENABLE_STAT4
  91385. int i;
  91386. /* Check if any samples from the aBest[] array should be pushed
  91387. ** into IndexSample.a[] at this point. */
  91388. for(i=(p->nCol-2); i>=iChng; i--){
  91389. Stat4Sample *pBest = &p->aBest[i];
  91390. pBest->anEq[i] = p->current.anEq[i];
  91391. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  91392. sampleInsert(p, pBest, i);
  91393. }
  91394. }
  91395. /* Check that no sample contains an anEq[] entry with an index of
  91396. ** p->nMaxEqZero or greater set to zero. */
  91397. for(i=p->nSample-1; i>=0; i--){
  91398. int j;
  91399. for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
  91400. }
  91401. /* Update the anEq[] fields of any samples already collected. */
  91402. if( iChng<p->nMaxEqZero ){
  91403. for(i=p->nSample-1; i>=0; i--){
  91404. int j;
  91405. for(j=iChng; j<p->nCol; j++){
  91406. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  91407. }
  91408. }
  91409. p->nMaxEqZero = iChng;
  91410. }
  91411. #endif
  91412. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  91413. if( iChng==0 ){
  91414. tRowcnt nLt = p->current.anLt[0];
  91415. tRowcnt nEq = p->current.anEq[0];
  91416. /* Check if this is to be a periodic sample. If so, add it. */
  91417. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  91418. p->current.isPSample = 1;
  91419. sampleInsert(p, &p->current, 0);
  91420. p->current.isPSample = 0;
  91421. }else
  91422. /* Or if it is a non-periodic sample. Add it in this case too. */
  91423. if( p->nSample<p->mxSample
  91424. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  91425. ){
  91426. sampleInsert(p, &p->current, 0);
  91427. }
  91428. }
  91429. #endif
  91430. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  91431. UNUSED_PARAMETER( p );
  91432. UNUSED_PARAMETER( iChng );
  91433. #endif
  91434. }
  91435. /*
  91436. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  91437. ** Arguments:
  91438. **
  91439. ** P Pointer to the Stat4Accum object created by stat_init()
  91440. ** C Index of left-most column to differ from previous row
  91441. ** R Rowid for the current row. Might be a key record for
  91442. ** WITHOUT ROWID tables.
  91443. **
  91444. ** This SQL function always returns NULL. It's purpose it to accumulate
  91445. ** statistical data and/or samples in the Stat4Accum object about the
  91446. ** index being analyzed. The stat_get() SQL function will later be used to
  91447. ** extract relevant information for constructing the sqlite_statN tables.
  91448. **
  91449. ** The R parameter is only used for STAT3 and STAT4
  91450. */
  91451. static void statPush(
  91452. sqlite3_context *context,
  91453. int argc,
  91454. sqlite3_value **argv
  91455. ){
  91456. int i;
  91457. /* The three function arguments */
  91458. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  91459. int iChng = sqlite3_value_int(argv[1]);
  91460. UNUSED_PARAMETER( argc );
  91461. UNUSED_PARAMETER( context );
  91462. assert( p->nCol>0 );
  91463. assert( iChng<p->nCol );
  91464. if( p->nRow==0 ){
  91465. /* This is the first call to this function. Do initialization. */
  91466. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  91467. }else{
  91468. /* Second and subsequent calls get processed here */
  91469. samplePushPrevious(p, iChng);
  91470. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  91471. ** to the current row of the index. */
  91472. for(i=0; i<iChng; i++){
  91473. p->current.anEq[i]++;
  91474. }
  91475. for(i=iChng; i<p->nCol; i++){
  91476. p->current.anDLt[i]++;
  91477. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91478. p->current.anLt[i] += p->current.anEq[i];
  91479. #endif
  91480. p->current.anEq[i] = 1;
  91481. }
  91482. }
  91483. p->nRow++;
  91484. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91485. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  91486. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  91487. }else{
  91488. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  91489. sqlite3_value_blob(argv[2]));
  91490. }
  91491. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  91492. #endif
  91493. #ifdef SQLITE_ENABLE_STAT4
  91494. {
  91495. tRowcnt nLt = p->current.anLt[p->nCol-1];
  91496. /* Check if this is to be a periodic sample. If so, add it. */
  91497. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  91498. p->current.isPSample = 1;
  91499. p->current.iCol = 0;
  91500. sampleInsert(p, &p->current, p->nCol-1);
  91501. p->current.isPSample = 0;
  91502. }
  91503. /* Update the aBest[] array. */
  91504. for(i=0; i<(p->nCol-1); i++){
  91505. p->current.iCol = i;
  91506. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  91507. sampleCopy(p, &p->aBest[i], &p->current);
  91508. }
  91509. }
  91510. }
  91511. #endif
  91512. }
  91513. static const FuncDef statPushFuncdef = {
  91514. 2+IsStat34, /* nArg */
  91515. SQLITE_UTF8, /* funcFlags */
  91516. 0, /* pUserData */
  91517. 0, /* pNext */
  91518. statPush, /* xSFunc */
  91519. 0, /* xFinalize */
  91520. "stat_push", /* zName */
  91521. {0}
  91522. };
  91523. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  91524. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  91525. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  91526. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  91527. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  91528. /*
  91529. ** Implementation of the stat_get(P,J) SQL function. This routine is
  91530. ** used to query statistical information that has been gathered into
  91531. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  91532. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  91533. ** The content to returned is determined by the parameter J
  91534. ** which is one of the STAT_GET_xxxx values defined above.
  91535. **
  91536. ** The stat_get(P,J) function is not available to generic SQL. It is
  91537. ** inserted as part of a manually constructed bytecode program. (See
  91538. ** the callStatGet() routine below.) It is guaranteed that the P
  91539. ** parameter will always be a poiner to a Stat4Accum object, never a
  91540. ** NULL.
  91541. **
  91542. ** If neither STAT3 nor STAT4 are enabled, then J is always
  91543. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  91544. ** a one-parameter function, stat_get(P), that always returns the
  91545. ** stat1 table entry information.
  91546. */
  91547. static void statGet(
  91548. sqlite3_context *context,
  91549. int argc,
  91550. sqlite3_value **argv
  91551. ){
  91552. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  91553. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91554. /* STAT3 and STAT4 have a parameter on this routine. */
  91555. int eCall = sqlite3_value_int(argv[1]);
  91556. assert( argc==2 );
  91557. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  91558. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  91559. || eCall==STAT_GET_NDLT
  91560. );
  91561. if( eCall==STAT_GET_STAT1 )
  91562. #else
  91563. assert( argc==1 );
  91564. #endif
  91565. {
  91566. /* Return the value to store in the "stat" column of the sqlite_stat1
  91567. ** table for this index.
  91568. **
  91569. ** The value is a string composed of a list of integers describing
  91570. ** the index. The first integer in the list is the total number of
  91571. ** entries in the index. There is one additional integer in the list
  91572. ** for each indexed column. This additional integer is an estimate of
  91573. ** the number of rows matched by a stabbing query on the index using
  91574. ** a key with the corresponding number of fields. In other words,
  91575. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  91576. ** "100 10 2", then SQLite estimates that:
  91577. **
  91578. ** * the index contains 100 rows,
  91579. ** * "WHERE a=?" matches 10 rows, and
  91580. ** * "WHERE a=? AND b=?" matches 2 rows.
  91581. **
  91582. ** If D is the count of distinct values and K is the total number of
  91583. ** rows, then each estimate is computed as:
  91584. **
  91585. ** I = (K+D-1)/D
  91586. */
  91587. char *z;
  91588. int i;
  91589. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  91590. if( zRet==0 ){
  91591. sqlite3_result_error_nomem(context);
  91592. return;
  91593. }
  91594. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  91595. z = zRet + sqlite3Strlen30(zRet);
  91596. for(i=0; i<p->nKeyCol; i++){
  91597. u64 nDistinct = p->current.anDLt[i] + 1;
  91598. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  91599. sqlite3_snprintf(24, z, " %llu", iVal);
  91600. z += sqlite3Strlen30(z);
  91601. assert( p->current.anEq[i] );
  91602. }
  91603. assert( z[0]=='\0' && z>zRet );
  91604. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  91605. }
  91606. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91607. else if( eCall==STAT_GET_ROWID ){
  91608. if( p->iGet<0 ){
  91609. samplePushPrevious(p, 0);
  91610. p->iGet = 0;
  91611. }
  91612. if( p->iGet<p->nSample ){
  91613. Stat4Sample *pS = p->a + p->iGet;
  91614. if( pS->nRowid==0 ){
  91615. sqlite3_result_int64(context, pS->u.iRowid);
  91616. }else{
  91617. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  91618. SQLITE_TRANSIENT);
  91619. }
  91620. }
  91621. }else{
  91622. tRowcnt *aCnt = 0;
  91623. assert( p->iGet<p->nSample );
  91624. switch( eCall ){
  91625. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  91626. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  91627. default: {
  91628. aCnt = p->a[p->iGet].anDLt;
  91629. p->iGet++;
  91630. break;
  91631. }
  91632. }
  91633. if( IsStat3 ){
  91634. sqlite3_result_int64(context, (i64)aCnt[0]);
  91635. }else{
  91636. char *zRet = sqlite3MallocZero(p->nCol * 25);
  91637. if( zRet==0 ){
  91638. sqlite3_result_error_nomem(context);
  91639. }else{
  91640. int i;
  91641. char *z = zRet;
  91642. for(i=0; i<p->nCol; i++){
  91643. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  91644. z += sqlite3Strlen30(z);
  91645. }
  91646. assert( z[0]=='\0' && z>zRet );
  91647. z[-1] = '\0';
  91648. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  91649. }
  91650. }
  91651. }
  91652. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  91653. #ifndef SQLITE_DEBUG
  91654. UNUSED_PARAMETER( argc );
  91655. #endif
  91656. }
  91657. static const FuncDef statGetFuncdef = {
  91658. 1+IsStat34, /* nArg */
  91659. SQLITE_UTF8, /* funcFlags */
  91660. 0, /* pUserData */
  91661. 0, /* pNext */
  91662. statGet, /* xSFunc */
  91663. 0, /* xFinalize */
  91664. "stat_get", /* zName */
  91665. {0}
  91666. };
  91667. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  91668. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  91669. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91670. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  91671. #elif SQLITE_DEBUG
  91672. assert( iParam==STAT_GET_STAT1 );
  91673. #else
  91674. UNUSED_PARAMETER( iParam );
  91675. #endif
  91676. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
  91677. (char*)&statGetFuncdef, P4_FUNCDEF);
  91678. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  91679. }
  91680. /*
  91681. ** Generate code to do an analysis of all indices associated with
  91682. ** a single table.
  91683. */
  91684. static void analyzeOneTable(
  91685. Parse *pParse, /* Parser context */
  91686. Table *pTab, /* Table whose indices are to be analyzed */
  91687. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  91688. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  91689. int iMem, /* Available memory locations begin here */
  91690. int iTab /* Next available cursor */
  91691. ){
  91692. sqlite3 *db = pParse->db; /* Database handle */
  91693. Index *pIdx; /* An index to being analyzed */
  91694. int iIdxCur; /* Cursor open on index being analyzed */
  91695. int iTabCur; /* Table cursor */
  91696. Vdbe *v; /* The virtual machine being built up */
  91697. int i; /* Loop counter */
  91698. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  91699. int iDb; /* Index of database containing pTab */
  91700. u8 needTableCnt = 1; /* True to count the table */
  91701. int regNewRowid = iMem++; /* Rowid for the inserted record */
  91702. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  91703. int regChng = iMem++; /* Index of changed index field */
  91704. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91705. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  91706. #endif
  91707. int regTemp = iMem++; /* Temporary use register */
  91708. int regTabname = iMem++; /* Register containing table name */
  91709. int regIdxname = iMem++; /* Register containing index name */
  91710. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  91711. int regPrev = iMem; /* MUST BE LAST (see below) */
  91712. pParse->nMem = MAX(pParse->nMem, iMem);
  91713. v = sqlite3GetVdbe(pParse);
  91714. if( v==0 || NEVER(pTab==0) ){
  91715. return;
  91716. }
  91717. if( pTab->tnum==0 ){
  91718. /* Do not gather statistics on views or virtual tables */
  91719. return;
  91720. }
  91721. if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
  91722. /* Do not gather statistics on system tables */
  91723. return;
  91724. }
  91725. assert( sqlite3BtreeHoldsAllMutexes(db) );
  91726. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  91727. assert( iDb>=0 );
  91728. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  91729. #ifndef SQLITE_OMIT_AUTHORIZATION
  91730. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  91731. db->aDb[iDb].zDbSName ) ){
  91732. return;
  91733. }
  91734. #endif
  91735. /* Establish a read-lock on the table at the shared-cache level.
  91736. ** Open a read-only cursor on the table. Also allocate a cursor number
  91737. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  91738. ** this time though. */
  91739. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  91740. iTabCur = iTab++;
  91741. iIdxCur = iTab++;
  91742. pParse->nTab = MAX(pParse->nTab, iTab);
  91743. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  91744. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  91745. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  91746. int nCol; /* Number of columns in pIdx. "N" */
  91747. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  91748. int addrNextRow; /* Address of "next_row:" */
  91749. const char *zIdxName; /* Name of the index */
  91750. int nColTest; /* Number of columns to test for changes */
  91751. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  91752. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  91753. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  91754. nCol = pIdx->nKeyCol;
  91755. zIdxName = pTab->zName;
  91756. nColTest = nCol - 1;
  91757. }else{
  91758. nCol = pIdx->nColumn;
  91759. zIdxName = pIdx->zName;
  91760. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  91761. }
  91762. /* Populate the register containing the index name. */
  91763. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  91764. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  91765. /*
  91766. ** Pseudo-code for loop that calls stat_push():
  91767. **
  91768. ** Rewind csr
  91769. ** if eof(csr) goto end_of_scan;
  91770. ** regChng = 0
  91771. ** goto chng_addr_0;
  91772. **
  91773. ** next_row:
  91774. ** regChng = 0
  91775. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  91776. ** regChng = 1
  91777. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  91778. ** ...
  91779. ** regChng = N
  91780. ** goto chng_addr_N
  91781. **
  91782. ** chng_addr_0:
  91783. ** regPrev(0) = idx(0)
  91784. ** chng_addr_1:
  91785. ** regPrev(1) = idx(1)
  91786. ** ...
  91787. **
  91788. ** endDistinctTest:
  91789. ** regRowid = idx(rowid)
  91790. ** stat_push(P, regChng, regRowid)
  91791. ** Next csr
  91792. ** if !eof(csr) goto next_row;
  91793. **
  91794. ** end_of_scan:
  91795. */
  91796. /* Make sure there are enough memory cells allocated to accommodate
  91797. ** the regPrev array and a trailing rowid (the rowid slot is required
  91798. ** when building a record to insert into the sample column of
  91799. ** the sqlite_stat4 table. */
  91800. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  91801. /* Open a read-only cursor on the index being analyzed. */
  91802. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  91803. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  91804. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  91805. VdbeComment((v, "%s", pIdx->zName));
  91806. /* Invoke the stat_init() function. The arguments are:
  91807. **
  91808. ** (1) the number of columns in the index including the rowid
  91809. ** (or for a WITHOUT ROWID table, the number of PK columns),
  91810. ** (2) the number of columns in the key without the rowid/pk
  91811. ** (3) the number of rows in the index,
  91812. **
  91813. **
  91814. ** The third argument is only used for STAT3 and STAT4
  91815. */
  91816. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91817. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  91818. #endif
  91819. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  91820. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  91821. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
  91822. (char*)&statInitFuncdef, P4_FUNCDEF);
  91823. sqlite3VdbeChangeP5(v, 2+IsStat34);
  91824. /* Implementation of the following:
  91825. **
  91826. ** Rewind csr
  91827. ** if eof(csr) goto end_of_scan;
  91828. ** regChng = 0
  91829. ** goto next_push_0;
  91830. **
  91831. */
  91832. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  91833. VdbeCoverage(v);
  91834. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  91835. addrNextRow = sqlite3VdbeCurrentAddr(v);
  91836. if( nColTest>0 ){
  91837. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  91838. int *aGotoChng; /* Array of jump instruction addresses */
  91839. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  91840. if( aGotoChng==0 ) continue;
  91841. /*
  91842. ** next_row:
  91843. ** regChng = 0
  91844. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  91845. ** regChng = 1
  91846. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  91847. ** ...
  91848. ** regChng = N
  91849. ** goto endDistinctTest
  91850. */
  91851. sqlite3VdbeAddOp0(v, OP_Goto);
  91852. addrNextRow = sqlite3VdbeCurrentAddr(v);
  91853. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  91854. /* For a single-column UNIQUE index, once we have found a non-NULL
  91855. ** row, we know that all the rest will be distinct, so skip
  91856. ** subsequent distinctness tests. */
  91857. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  91858. VdbeCoverage(v);
  91859. }
  91860. for(i=0; i<nColTest; i++){
  91861. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  91862. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  91863. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  91864. aGotoChng[i] =
  91865. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  91866. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  91867. VdbeCoverage(v);
  91868. }
  91869. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  91870. sqlite3VdbeGoto(v, endDistinctTest);
  91871. /*
  91872. ** chng_addr_0:
  91873. ** regPrev(0) = idx(0)
  91874. ** chng_addr_1:
  91875. ** regPrev(1) = idx(1)
  91876. ** ...
  91877. */
  91878. sqlite3VdbeJumpHere(v, addrNextRow-1);
  91879. for(i=0; i<nColTest; i++){
  91880. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  91881. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  91882. }
  91883. sqlite3VdbeResolveLabel(v, endDistinctTest);
  91884. sqlite3DbFree(db, aGotoChng);
  91885. }
  91886. /*
  91887. ** chng_addr_N:
  91888. ** regRowid = idx(rowid) // STAT34 only
  91889. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  91890. ** Next csr
  91891. ** if !eof(csr) goto next_row;
  91892. */
  91893. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91894. assert( regRowid==(regStat4+2) );
  91895. if( HasRowid(pTab) ){
  91896. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  91897. }else{
  91898. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  91899. int j, k, regKey;
  91900. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  91901. for(j=0; j<pPk->nKeyCol; j++){
  91902. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  91903. assert( k>=0 && k<pIdx->nColumn );
  91904. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  91905. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  91906. }
  91907. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  91908. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  91909. }
  91910. #endif
  91911. assert( regChng==(regStat4+1) );
  91912. sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
  91913. (char*)&statPushFuncdef, P4_FUNCDEF);
  91914. sqlite3VdbeChangeP5(v, 2+IsStat34);
  91915. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  91916. /* Add the entry to the stat1 table. */
  91917. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  91918. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  91919. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  91920. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  91921. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  91922. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  91923. /* Add the entries to the stat3 or stat4 table. */
  91924. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91925. {
  91926. int regEq = regStat1;
  91927. int regLt = regStat1+1;
  91928. int regDLt = regStat1+2;
  91929. int regSample = regStat1+3;
  91930. int regCol = regStat1+4;
  91931. int regSampleRowid = regCol + nCol;
  91932. int addrNext;
  91933. int addrIsNull;
  91934. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  91935. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  91936. addrNext = sqlite3VdbeCurrentAddr(v);
  91937. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  91938. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  91939. VdbeCoverage(v);
  91940. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  91941. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  91942. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  91943. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  91944. /* We know that the regSampleRowid row exists because it was read by
  91945. ** the previous loop. Thus the not-found jump of seekOp will never
  91946. ** be taken */
  91947. VdbeCoverageNeverTaken(v);
  91948. #ifdef SQLITE_ENABLE_STAT3
  91949. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  91950. #else
  91951. for(i=0; i<nCol; i++){
  91952. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  91953. }
  91954. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  91955. #endif
  91956. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  91957. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  91958. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  91959. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  91960. sqlite3VdbeJumpHere(v, addrIsNull);
  91961. }
  91962. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  91963. /* End of analysis */
  91964. sqlite3VdbeJumpHere(v, addrRewind);
  91965. }
  91966. /* Create a single sqlite_stat1 entry containing NULL as the index
  91967. ** name and the row count as the content.
  91968. */
  91969. if( pOnlyIdx==0 && needTableCnt ){
  91970. VdbeComment((v, "%s", pTab->zName));
  91971. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  91972. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  91973. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  91974. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  91975. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  91976. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  91977. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  91978. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  91979. sqlite3VdbeJumpHere(v, jZeroRows);
  91980. }
  91981. }
  91982. /*
  91983. ** Generate code that will cause the most recent index analysis to
  91984. ** be loaded into internal hash tables where is can be used.
  91985. */
  91986. static void loadAnalysis(Parse *pParse, int iDb){
  91987. Vdbe *v = sqlite3GetVdbe(pParse);
  91988. if( v ){
  91989. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  91990. }
  91991. }
  91992. /*
  91993. ** Generate code that will do an analysis of an entire database
  91994. */
  91995. static void analyzeDatabase(Parse *pParse, int iDb){
  91996. sqlite3 *db = pParse->db;
  91997. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  91998. HashElem *k;
  91999. int iStatCur;
  92000. int iMem;
  92001. int iTab;
  92002. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92003. iStatCur = pParse->nTab;
  92004. pParse->nTab += 3;
  92005. openStatTable(pParse, iDb, iStatCur, 0, 0);
  92006. iMem = pParse->nMem+1;
  92007. iTab = pParse->nTab;
  92008. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92009. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  92010. Table *pTab = (Table*)sqliteHashData(k);
  92011. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  92012. }
  92013. loadAnalysis(pParse, iDb);
  92014. }
  92015. /*
  92016. ** Generate code that will do an analysis of a single table in
  92017. ** a database. If pOnlyIdx is not NULL then it is a single index
  92018. ** in pTab that should be analyzed.
  92019. */
  92020. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  92021. int iDb;
  92022. int iStatCur;
  92023. assert( pTab!=0 );
  92024. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  92025. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  92026. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92027. iStatCur = pParse->nTab;
  92028. pParse->nTab += 3;
  92029. if( pOnlyIdx ){
  92030. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  92031. }else{
  92032. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  92033. }
  92034. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  92035. loadAnalysis(pParse, iDb);
  92036. }
  92037. /*
  92038. ** Generate code for the ANALYZE command. The parser calls this routine
  92039. ** when it recognizes an ANALYZE command.
  92040. **
  92041. ** ANALYZE -- 1
  92042. ** ANALYZE <database> -- 2
  92043. ** ANALYZE ?<database>.?<tablename> -- 3
  92044. **
  92045. ** Form 1 causes all indices in all attached databases to be analyzed.
  92046. ** Form 2 analyzes all indices the single database named.
  92047. ** Form 3 analyzes all indices associated with the named table.
  92048. */
  92049. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  92050. sqlite3 *db = pParse->db;
  92051. int iDb;
  92052. int i;
  92053. char *z, *zDb;
  92054. Table *pTab;
  92055. Index *pIdx;
  92056. Token *pTableName;
  92057. Vdbe *v;
  92058. /* Read the database schema. If an error occurs, leave an error message
  92059. ** and code in pParse and return NULL. */
  92060. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  92061. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  92062. return;
  92063. }
  92064. assert( pName2!=0 || pName1==0 );
  92065. if( pName1==0 ){
  92066. /* Form 1: Analyze everything */
  92067. for(i=0; i<db->nDb; i++){
  92068. if( i==1 ) continue; /* Do not analyze the TEMP database */
  92069. analyzeDatabase(pParse, i);
  92070. }
  92071. }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
  92072. /* Analyze the schema named as the argument */
  92073. analyzeDatabase(pParse, iDb);
  92074. }else{
  92075. /* Form 3: Analyze the table or index named as an argument */
  92076. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  92077. if( iDb>=0 ){
  92078. zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
  92079. z = sqlite3NameFromToken(db, pTableName);
  92080. if( z ){
  92081. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  92082. analyzeTable(pParse, pIdx->pTable, pIdx);
  92083. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  92084. analyzeTable(pParse, pTab, 0);
  92085. }
  92086. sqlite3DbFree(db, z);
  92087. }
  92088. }
  92089. }
  92090. if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
  92091. sqlite3VdbeAddOp0(v, OP_Expire);
  92092. }
  92093. }
  92094. /*
  92095. ** Used to pass information from the analyzer reader through to the
  92096. ** callback routine.
  92097. */
  92098. typedef struct analysisInfo analysisInfo;
  92099. struct analysisInfo {
  92100. sqlite3 *db;
  92101. const char *zDatabase;
  92102. };
  92103. /*
  92104. ** The first argument points to a nul-terminated string containing a
  92105. ** list of space separated integers. Read the first nOut of these into
  92106. ** the array aOut[].
  92107. */
  92108. static void decodeIntArray(
  92109. char *zIntArray, /* String containing int array to decode */
  92110. int nOut, /* Number of slots in aOut[] */
  92111. tRowcnt *aOut, /* Store integers here */
  92112. LogEst *aLog, /* Or, if aOut==0, here */
  92113. Index *pIndex /* Handle extra flags for this index, if not NULL */
  92114. ){
  92115. char *z = zIntArray;
  92116. int c;
  92117. int i;
  92118. tRowcnt v;
  92119. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92120. if( z==0 ) z = "";
  92121. #else
  92122. assert( z!=0 );
  92123. #endif
  92124. for(i=0; *z && i<nOut; i++){
  92125. v = 0;
  92126. while( (c=z[0])>='0' && c<='9' ){
  92127. v = v*10 + c - '0';
  92128. z++;
  92129. }
  92130. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92131. if( aOut ) aOut[i] = v;
  92132. if( aLog ) aLog[i] = sqlite3LogEst(v);
  92133. #else
  92134. assert( aOut==0 );
  92135. UNUSED_PARAMETER(aOut);
  92136. assert( aLog!=0 );
  92137. aLog[i] = sqlite3LogEst(v);
  92138. #endif
  92139. if( *z==' ' ) z++;
  92140. }
  92141. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  92142. assert( pIndex!=0 ); {
  92143. #else
  92144. if( pIndex ){
  92145. #endif
  92146. pIndex->bUnordered = 0;
  92147. pIndex->noSkipScan = 0;
  92148. while( z[0] ){
  92149. if( sqlite3_strglob("unordered*", z)==0 ){
  92150. pIndex->bUnordered = 1;
  92151. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  92152. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  92153. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  92154. pIndex->noSkipScan = 1;
  92155. }
  92156. #ifdef SQLITE_ENABLE_COSTMULT
  92157. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  92158. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  92159. }
  92160. #endif
  92161. while( z[0]!=0 && z[0]!=' ' ) z++;
  92162. while( z[0]==' ' ) z++;
  92163. }
  92164. }
  92165. }
  92166. /*
  92167. ** This callback is invoked once for each index when reading the
  92168. ** sqlite_stat1 table.
  92169. **
  92170. ** argv[0] = name of the table
  92171. ** argv[1] = name of the index (might be NULL)
  92172. ** argv[2] = results of analysis - on integer for each column
  92173. **
  92174. ** Entries for which argv[1]==NULL simply record the number of rows in
  92175. ** the table.
  92176. */
  92177. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  92178. analysisInfo *pInfo = (analysisInfo*)pData;
  92179. Index *pIndex;
  92180. Table *pTable;
  92181. const char *z;
  92182. assert( argc==3 );
  92183. UNUSED_PARAMETER2(NotUsed, argc);
  92184. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  92185. return 0;
  92186. }
  92187. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  92188. if( pTable==0 ){
  92189. return 0;
  92190. }
  92191. if( argv[1]==0 ){
  92192. pIndex = 0;
  92193. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  92194. pIndex = sqlite3PrimaryKeyIndex(pTable);
  92195. }else{
  92196. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  92197. }
  92198. z = argv[2];
  92199. if( pIndex ){
  92200. tRowcnt *aiRowEst = 0;
  92201. int nCol = pIndex->nKeyCol+1;
  92202. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92203. /* Index.aiRowEst may already be set here if there are duplicate
  92204. ** sqlite_stat1 entries for this index. In that case just clobber
  92205. ** the old data with the new instead of allocating a new array. */
  92206. if( pIndex->aiRowEst==0 ){
  92207. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  92208. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  92209. }
  92210. aiRowEst = pIndex->aiRowEst;
  92211. #endif
  92212. pIndex->bUnordered = 0;
  92213. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  92214. pIndex->hasStat1 = 1;
  92215. if( pIndex->pPartIdxWhere==0 ){
  92216. pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  92217. pTable->tabFlags |= TF_HasStat1;
  92218. }
  92219. }else{
  92220. Index fakeIdx;
  92221. fakeIdx.szIdxRow = pTable->szTabRow;
  92222. #ifdef SQLITE_ENABLE_COSTMULT
  92223. fakeIdx.pTable = pTable;
  92224. #endif
  92225. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  92226. pTable->szTabRow = fakeIdx.szIdxRow;
  92227. pTable->tabFlags |= TF_HasStat1;
  92228. }
  92229. return 0;
  92230. }
  92231. /*
  92232. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  92233. ** and its contents.
  92234. */
  92235. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  92236. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92237. if( pIdx->aSample ){
  92238. int j;
  92239. for(j=0; j<pIdx->nSample; j++){
  92240. IndexSample *p = &pIdx->aSample[j];
  92241. sqlite3DbFree(db, p->p);
  92242. }
  92243. sqlite3DbFree(db, pIdx->aSample);
  92244. }
  92245. if( db && db->pnBytesFreed==0 ){
  92246. pIdx->nSample = 0;
  92247. pIdx->aSample = 0;
  92248. }
  92249. #else
  92250. UNUSED_PARAMETER(db);
  92251. UNUSED_PARAMETER(pIdx);
  92252. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92253. }
  92254. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92255. /*
  92256. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  92257. ** stored in pIdx->aSample[].
  92258. */
  92259. static void initAvgEq(Index *pIdx){
  92260. if( pIdx ){
  92261. IndexSample *aSample = pIdx->aSample;
  92262. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  92263. int iCol;
  92264. int nCol = 1;
  92265. if( pIdx->nSampleCol>1 ){
  92266. /* If this is stat4 data, then calculate aAvgEq[] values for all
  92267. ** sample columns except the last. The last is always set to 1, as
  92268. ** once the trailing PK fields are considered all index keys are
  92269. ** unique. */
  92270. nCol = pIdx->nSampleCol-1;
  92271. pIdx->aAvgEq[nCol] = 1;
  92272. }
  92273. for(iCol=0; iCol<nCol; iCol++){
  92274. int nSample = pIdx->nSample;
  92275. int i; /* Used to iterate through samples */
  92276. tRowcnt sumEq = 0; /* Sum of the nEq values */
  92277. tRowcnt avgEq = 0;
  92278. tRowcnt nRow; /* Number of rows in index */
  92279. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  92280. i64 nDist100; /* Number of distinct values in index */
  92281. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  92282. nRow = pFinal->anLt[iCol];
  92283. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  92284. nSample--;
  92285. }else{
  92286. nRow = pIdx->aiRowEst[0];
  92287. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  92288. }
  92289. pIdx->nRowEst0 = nRow;
  92290. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  92291. ** occur in the stat4 table for this index. Set sumEq to the sum of
  92292. ** the nEq values for column iCol for the same set (adding the value
  92293. ** only once where there exist duplicate prefixes). */
  92294. for(i=0; i<nSample; i++){
  92295. if( i==(pIdx->nSample-1)
  92296. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  92297. ){
  92298. sumEq += aSample[i].anEq[iCol];
  92299. nSum100 += 100;
  92300. }
  92301. }
  92302. if( nDist100>nSum100 && sumEq<nRow ){
  92303. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  92304. }
  92305. if( avgEq==0 ) avgEq = 1;
  92306. pIdx->aAvgEq[iCol] = avgEq;
  92307. }
  92308. }
  92309. }
  92310. /*
  92311. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  92312. ** is supplied instead, find the PRIMARY KEY index for that table.
  92313. */
  92314. static Index *findIndexOrPrimaryKey(
  92315. sqlite3 *db,
  92316. const char *zName,
  92317. const char *zDb
  92318. ){
  92319. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  92320. if( pIdx==0 ){
  92321. Table *pTab = sqlite3FindTable(db, zName, zDb);
  92322. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  92323. }
  92324. return pIdx;
  92325. }
  92326. /*
  92327. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  92328. ** into the relevant Index.aSample[] arrays.
  92329. **
  92330. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  92331. ** data equivalent to the following (statements are different for stat3,
  92332. ** see the caller of this function for details):
  92333. **
  92334. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  92335. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  92336. **
  92337. ** where %Q is replaced with the database name before the SQL is executed.
  92338. */
  92339. static int loadStatTbl(
  92340. sqlite3 *db, /* Database handle */
  92341. int bStat3, /* Assume single column records only */
  92342. const char *zSql1, /* SQL statement 1 (see above) */
  92343. const char *zSql2, /* SQL statement 2 (see above) */
  92344. const char *zDb /* Database name (e.g. "main") */
  92345. ){
  92346. int rc; /* Result codes from subroutines */
  92347. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  92348. char *zSql; /* Text of the SQL statement */
  92349. Index *pPrevIdx = 0; /* Previous index in the loop */
  92350. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  92351. assert( db->lookaside.bDisable );
  92352. zSql = sqlite3MPrintf(db, zSql1, zDb);
  92353. if( !zSql ){
  92354. return SQLITE_NOMEM_BKPT;
  92355. }
  92356. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  92357. sqlite3DbFree(db, zSql);
  92358. if( rc ) return rc;
  92359. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  92360. int nIdxCol = 1; /* Number of columns in stat4 records */
  92361. char *zIndex; /* Index name */
  92362. Index *pIdx; /* Pointer to the index object */
  92363. int nSample; /* Number of samples */
  92364. int nByte; /* Bytes of space required */
  92365. int i; /* Bytes of space required */
  92366. tRowcnt *pSpace;
  92367. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  92368. if( zIndex==0 ) continue;
  92369. nSample = sqlite3_column_int(pStmt, 1);
  92370. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  92371. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  92372. /* Index.nSample is non-zero at this point if data has already been
  92373. ** loaded from the stat4 table. In this case ignore stat3 data. */
  92374. if( pIdx==0 || pIdx->nSample ) continue;
  92375. if( bStat3==0 ){
  92376. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  92377. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  92378. nIdxCol = pIdx->nKeyCol;
  92379. }else{
  92380. nIdxCol = pIdx->nColumn;
  92381. }
  92382. }
  92383. pIdx->nSampleCol = nIdxCol;
  92384. nByte = sizeof(IndexSample) * nSample;
  92385. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  92386. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  92387. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  92388. if( pIdx->aSample==0 ){
  92389. sqlite3_finalize(pStmt);
  92390. return SQLITE_NOMEM_BKPT;
  92391. }
  92392. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  92393. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  92394. for(i=0; i<nSample; i++){
  92395. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  92396. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  92397. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  92398. }
  92399. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  92400. }
  92401. rc = sqlite3_finalize(pStmt);
  92402. if( rc ) return rc;
  92403. zSql = sqlite3MPrintf(db, zSql2, zDb);
  92404. if( !zSql ){
  92405. return SQLITE_NOMEM_BKPT;
  92406. }
  92407. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  92408. sqlite3DbFree(db, zSql);
  92409. if( rc ) return rc;
  92410. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  92411. char *zIndex; /* Index name */
  92412. Index *pIdx; /* Pointer to the index object */
  92413. int nCol = 1; /* Number of columns in index */
  92414. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  92415. if( zIndex==0 ) continue;
  92416. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  92417. if( pIdx==0 ) continue;
  92418. /* This next condition is true if data has already been loaded from
  92419. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  92420. nCol = pIdx->nSampleCol;
  92421. if( bStat3 && nCol>1 ) continue;
  92422. if( pIdx!=pPrevIdx ){
  92423. initAvgEq(pPrevIdx);
  92424. pPrevIdx = pIdx;
  92425. }
  92426. pSample = &pIdx->aSample[pIdx->nSample];
  92427. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  92428. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  92429. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  92430. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  92431. ** This is in case the sample record is corrupted. In that case, the
  92432. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  92433. ** end of the allocated buffer before it realizes it is dealing with
  92434. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  92435. ** a buffer overread. */
  92436. pSample->n = sqlite3_column_bytes(pStmt, 4);
  92437. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  92438. if( pSample->p==0 ){
  92439. sqlite3_finalize(pStmt);
  92440. return SQLITE_NOMEM_BKPT;
  92441. }
  92442. if( pSample->n ){
  92443. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  92444. }
  92445. pIdx->nSample++;
  92446. }
  92447. rc = sqlite3_finalize(pStmt);
  92448. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  92449. return rc;
  92450. }
  92451. /*
  92452. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  92453. ** the Index.aSample[] arrays of all indices.
  92454. */
  92455. static int loadStat4(sqlite3 *db, const char *zDb){
  92456. int rc = SQLITE_OK; /* Result codes from subroutines */
  92457. assert( db->lookaside.bDisable );
  92458. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  92459. rc = loadStatTbl(db, 0,
  92460. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  92461. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  92462. zDb
  92463. );
  92464. }
  92465. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  92466. rc = loadStatTbl(db, 1,
  92467. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  92468. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  92469. zDb
  92470. );
  92471. }
  92472. return rc;
  92473. }
  92474. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92475. /*
  92476. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  92477. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  92478. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  92479. ** Index.aSample[] arrays.
  92480. **
  92481. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  92482. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  92483. ** during compilation and the sqlite_stat3/4 table is present, no data is
  92484. ** read from it.
  92485. **
  92486. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  92487. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  92488. ** returned. However, in this case, data is read from the sqlite_stat1
  92489. ** table (if it is present) before returning.
  92490. **
  92491. ** If an OOM error occurs, this function always sets db->mallocFailed.
  92492. ** This means if the caller does not care about other errors, the return
  92493. ** code may be ignored.
  92494. */
  92495. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  92496. analysisInfo sInfo;
  92497. HashElem *i;
  92498. char *zSql;
  92499. int rc = SQLITE_OK;
  92500. Schema *pSchema = db->aDb[iDb].pSchema;
  92501. assert( iDb>=0 && iDb<db->nDb );
  92502. assert( db->aDb[iDb].pBt!=0 );
  92503. /* Clear any prior statistics */
  92504. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92505. for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
  92506. Table *pTab = sqliteHashData(i);
  92507. pTab->tabFlags &= ~TF_HasStat1;
  92508. }
  92509. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  92510. Index *pIdx = sqliteHashData(i);
  92511. pIdx->hasStat1 = 0;
  92512. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92513. sqlite3DeleteIndexSamples(db, pIdx);
  92514. pIdx->aSample = 0;
  92515. #endif
  92516. }
  92517. /* Load new statistics out of the sqlite_stat1 table */
  92518. sInfo.db = db;
  92519. sInfo.zDatabase = db->aDb[iDb].zDbSName;
  92520. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  92521. zSql = sqlite3MPrintf(db,
  92522. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  92523. if( zSql==0 ){
  92524. rc = SQLITE_NOMEM_BKPT;
  92525. }else{
  92526. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  92527. sqlite3DbFree(db, zSql);
  92528. }
  92529. }
  92530. /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
  92531. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92532. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  92533. Index *pIdx = sqliteHashData(i);
  92534. if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
  92535. }
  92536. /* Load the statistics from the sqlite_stat4 table. */
  92537. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92538. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  92539. db->lookaside.bDisable++;
  92540. rc = loadStat4(db, sInfo.zDatabase);
  92541. db->lookaside.bDisable--;
  92542. }
  92543. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  92544. Index *pIdx = sqliteHashData(i);
  92545. sqlite3_free(pIdx->aiRowEst);
  92546. pIdx->aiRowEst = 0;
  92547. }
  92548. #endif
  92549. if( rc==SQLITE_NOMEM ){
  92550. sqlite3OomFault(db);
  92551. }
  92552. return rc;
  92553. }
  92554. #endif /* SQLITE_OMIT_ANALYZE */
  92555. /************** End of analyze.c *********************************************/
  92556. /************** Begin file attach.c ******************************************/
  92557. /*
  92558. ** 2003 April 6
  92559. **
  92560. ** The author disclaims copyright to this source code. In place of
  92561. ** a legal notice, here is a blessing:
  92562. **
  92563. ** May you do good and not evil.
  92564. ** May you find forgiveness for yourself and forgive others.
  92565. ** May you share freely, never taking more than you give.
  92566. **
  92567. *************************************************************************
  92568. ** This file contains code used to implement the ATTACH and DETACH commands.
  92569. */
  92570. /* #include "sqliteInt.h" */
  92571. #ifndef SQLITE_OMIT_ATTACH
  92572. /*
  92573. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  92574. ** is slightly different from resolving a normal SQL expression, because simple
  92575. ** identifiers are treated as strings, not possible column names or aliases.
  92576. **
  92577. ** i.e. if the parser sees:
  92578. **
  92579. ** ATTACH DATABASE abc AS def
  92580. **
  92581. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  92582. ** looking for columns of the same name.
  92583. **
  92584. ** This only applies to the root node of pExpr, so the statement:
  92585. **
  92586. ** ATTACH DATABASE abc||def AS 'db2'
  92587. **
  92588. ** will fail because neither abc or def can be resolved.
  92589. */
  92590. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  92591. {
  92592. int rc = SQLITE_OK;
  92593. if( pExpr ){
  92594. if( pExpr->op!=TK_ID ){
  92595. rc = sqlite3ResolveExprNames(pName, pExpr);
  92596. }else{
  92597. pExpr->op = TK_STRING;
  92598. }
  92599. }
  92600. return rc;
  92601. }
  92602. /*
  92603. ** An SQL user-function registered to do the work of an ATTACH statement. The
  92604. ** three arguments to the function come directly from an attach statement:
  92605. **
  92606. ** ATTACH DATABASE x AS y KEY z
  92607. **
  92608. ** SELECT sqlite_attach(x, y, z)
  92609. **
  92610. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  92611. ** third argument.
  92612. */
  92613. static void attachFunc(
  92614. sqlite3_context *context,
  92615. int NotUsed,
  92616. sqlite3_value **argv
  92617. ){
  92618. int i;
  92619. int rc = 0;
  92620. sqlite3 *db = sqlite3_context_db_handle(context);
  92621. const char *zName;
  92622. const char *zFile;
  92623. char *zPath = 0;
  92624. char *zErr = 0;
  92625. unsigned int flags;
  92626. Db *aNew;
  92627. char *zErrDyn = 0;
  92628. sqlite3_vfs *pVfs;
  92629. UNUSED_PARAMETER(NotUsed);
  92630. zFile = (const char *)sqlite3_value_text(argv[0]);
  92631. zName = (const char *)sqlite3_value_text(argv[1]);
  92632. if( zFile==0 ) zFile = "";
  92633. if( zName==0 ) zName = "";
  92634. /* Check for the following errors:
  92635. **
  92636. ** * Too many attached databases,
  92637. ** * Transaction currently open
  92638. ** * Specified database name already being used.
  92639. */
  92640. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  92641. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  92642. db->aLimit[SQLITE_LIMIT_ATTACHED]
  92643. );
  92644. goto attach_error;
  92645. }
  92646. if( !db->autoCommit ){
  92647. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  92648. goto attach_error;
  92649. }
  92650. for(i=0; i<db->nDb; i++){
  92651. char *z = db->aDb[i].zDbSName;
  92652. assert( z && zName );
  92653. if( sqlite3StrICmp(z, zName)==0 ){
  92654. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  92655. goto attach_error;
  92656. }
  92657. }
  92658. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  92659. ** hash tables.
  92660. */
  92661. if( db->aDb==db->aDbStatic ){
  92662. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  92663. if( aNew==0 ) return;
  92664. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  92665. }else{
  92666. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  92667. if( aNew==0 ) return;
  92668. }
  92669. db->aDb = aNew;
  92670. aNew = &db->aDb[db->nDb];
  92671. memset(aNew, 0, sizeof(*aNew));
  92672. /* Open the database file. If the btree is successfully opened, use
  92673. ** it to obtain the database schema. At this point the schema may
  92674. ** or may not be initialized.
  92675. */
  92676. flags = db->openFlags;
  92677. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  92678. if( rc!=SQLITE_OK ){
  92679. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  92680. sqlite3_result_error(context, zErr, -1);
  92681. sqlite3_free(zErr);
  92682. return;
  92683. }
  92684. assert( pVfs );
  92685. flags |= SQLITE_OPEN_MAIN_DB;
  92686. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  92687. sqlite3_free( zPath );
  92688. db->nDb++;
  92689. db->skipBtreeMutex = 0;
  92690. if( rc==SQLITE_CONSTRAINT ){
  92691. rc = SQLITE_ERROR;
  92692. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  92693. }else if( rc==SQLITE_OK ){
  92694. Pager *pPager;
  92695. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  92696. if( !aNew->pSchema ){
  92697. rc = SQLITE_NOMEM_BKPT;
  92698. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  92699. zErrDyn = sqlite3MPrintf(db,
  92700. "attached databases must use the same text encoding as main database");
  92701. rc = SQLITE_ERROR;
  92702. }
  92703. sqlite3BtreeEnter(aNew->pBt);
  92704. pPager = sqlite3BtreePager(aNew->pBt);
  92705. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  92706. sqlite3BtreeSecureDelete(aNew->pBt,
  92707. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  92708. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92709. sqlite3BtreeSetPagerFlags(aNew->pBt,
  92710. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  92711. #endif
  92712. sqlite3BtreeLeave(aNew->pBt);
  92713. }
  92714. aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  92715. aNew->zDbSName = sqlite3DbStrDup(db, zName);
  92716. if( rc==SQLITE_OK && aNew->zDbSName==0 ){
  92717. rc = SQLITE_NOMEM_BKPT;
  92718. }
  92719. #ifdef SQLITE_HAS_CODEC
  92720. if( rc==SQLITE_OK ){
  92721. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  92722. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  92723. int nKey;
  92724. char *zKey;
  92725. int t = sqlite3_value_type(argv[2]);
  92726. switch( t ){
  92727. case SQLITE_INTEGER:
  92728. case SQLITE_FLOAT:
  92729. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  92730. rc = SQLITE_ERROR;
  92731. break;
  92732. case SQLITE_TEXT:
  92733. case SQLITE_BLOB:
  92734. nKey = sqlite3_value_bytes(argv[2]);
  92735. zKey = (char *)sqlite3_value_blob(argv[2]);
  92736. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  92737. break;
  92738. case SQLITE_NULL:
  92739. /* No key specified. Use the key from the main database */
  92740. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  92741. if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  92742. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  92743. }
  92744. break;
  92745. }
  92746. }
  92747. #endif
  92748. /* If the file was opened successfully, read the schema for the new database.
  92749. ** If this fails, or if opening the file failed, then close the file and
  92750. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  92751. ** we found it.
  92752. */
  92753. if( rc==SQLITE_OK ){
  92754. sqlite3BtreeEnterAll(db);
  92755. rc = sqlite3Init(db, &zErrDyn);
  92756. sqlite3BtreeLeaveAll(db);
  92757. }
  92758. #ifdef SQLITE_USER_AUTHENTICATION
  92759. if( rc==SQLITE_OK ){
  92760. u8 newAuth = 0;
  92761. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  92762. if( newAuth<db->auth.authLevel ){
  92763. rc = SQLITE_AUTH_USER;
  92764. }
  92765. }
  92766. #endif
  92767. if( rc ){
  92768. int iDb = db->nDb - 1;
  92769. assert( iDb>=2 );
  92770. if( db->aDb[iDb].pBt ){
  92771. sqlite3BtreeClose(db->aDb[iDb].pBt);
  92772. db->aDb[iDb].pBt = 0;
  92773. db->aDb[iDb].pSchema = 0;
  92774. }
  92775. sqlite3ResetAllSchemasOfConnection(db);
  92776. db->nDb = iDb;
  92777. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  92778. sqlite3OomFault(db);
  92779. sqlite3DbFree(db, zErrDyn);
  92780. zErrDyn = sqlite3MPrintf(db, "out of memory");
  92781. }else if( zErrDyn==0 ){
  92782. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  92783. }
  92784. goto attach_error;
  92785. }
  92786. return;
  92787. attach_error:
  92788. /* Return an error if we get here */
  92789. if( zErrDyn ){
  92790. sqlite3_result_error(context, zErrDyn, -1);
  92791. sqlite3DbFree(db, zErrDyn);
  92792. }
  92793. if( rc ) sqlite3_result_error_code(context, rc);
  92794. }
  92795. /*
  92796. ** An SQL user-function registered to do the work of an DETACH statement. The
  92797. ** three arguments to the function come directly from a detach statement:
  92798. **
  92799. ** DETACH DATABASE x
  92800. **
  92801. ** SELECT sqlite_detach(x)
  92802. */
  92803. static void detachFunc(
  92804. sqlite3_context *context,
  92805. int NotUsed,
  92806. sqlite3_value **argv
  92807. ){
  92808. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  92809. sqlite3 *db = sqlite3_context_db_handle(context);
  92810. int i;
  92811. Db *pDb = 0;
  92812. char zErr[128];
  92813. UNUSED_PARAMETER(NotUsed);
  92814. if( zName==0 ) zName = "";
  92815. for(i=0; i<db->nDb; i++){
  92816. pDb = &db->aDb[i];
  92817. if( pDb->pBt==0 ) continue;
  92818. if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
  92819. }
  92820. if( i>=db->nDb ){
  92821. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  92822. goto detach_error;
  92823. }
  92824. if( i<2 ){
  92825. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  92826. goto detach_error;
  92827. }
  92828. if( !db->autoCommit ){
  92829. sqlite3_snprintf(sizeof(zErr), zErr,
  92830. "cannot DETACH database within transaction");
  92831. goto detach_error;
  92832. }
  92833. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  92834. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  92835. goto detach_error;
  92836. }
  92837. sqlite3BtreeClose(pDb->pBt);
  92838. pDb->pBt = 0;
  92839. pDb->pSchema = 0;
  92840. sqlite3CollapseDatabaseArray(db);
  92841. return;
  92842. detach_error:
  92843. sqlite3_result_error(context, zErr, -1);
  92844. }
  92845. /*
  92846. ** This procedure generates VDBE code for a single invocation of either the
  92847. ** sqlite_detach() or sqlite_attach() SQL user functions.
  92848. */
  92849. static void codeAttach(
  92850. Parse *pParse, /* The parser context */
  92851. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  92852. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  92853. Expr *pAuthArg, /* Expression to pass to authorization callback */
  92854. Expr *pFilename, /* Name of database file */
  92855. Expr *pDbname, /* Name of the database to use internally */
  92856. Expr *pKey /* Database key for encryption extension */
  92857. ){
  92858. int rc;
  92859. NameContext sName;
  92860. Vdbe *v;
  92861. sqlite3* db = pParse->db;
  92862. int regArgs;
  92863. if( pParse->nErr ) goto attach_end;
  92864. memset(&sName, 0, sizeof(NameContext));
  92865. sName.pParse = pParse;
  92866. if(
  92867. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  92868. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  92869. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  92870. ){
  92871. goto attach_end;
  92872. }
  92873. #ifndef SQLITE_OMIT_AUTHORIZATION
  92874. if( pAuthArg ){
  92875. char *zAuthArg;
  92876. if( pAuthArg->op==TK_STRING ){
  92877. zAuthArg = pAuthArg->u.zToken;
  92878. }else{
  92879. zAuthArg = 0;
  92880. }
  92881. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  92882. if(rc!=SQLITE_OK ){
  92883. goto attach_end;
  92884. }
  92885. }
  92886. #endif /* SQLITE_OMIT_AUTHORIZATION */
  92887. v = sqlite3GetVdbe(pParse);
  92888. regArgs = sqlite3GetTempRange(pParse, 4);
  92889. sqlite3ExprCode(pParse, pFilename, regArgs);
  92890. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  92891. sqlite3ExprCode(pParse, pKey, regArgs+2);
  92892. assert( v || db->mallocFailed );
  92893. if( v ){
  92894. sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
  92895. (char *)pFunc, P4_FUNCDEF);
  92896. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  92897. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  92898. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  92899. ** statement only). For DETACH, set it to false (expire all existing
  92900. ** statements).
  92901. */
  92902. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  92903. }
  92904. attach_end:
  92905. sqlite3ExprDelete(db, pFilename);
  92906. sqlite3ExprDelete(db, pDbname);
  92907. sqlite3ExprDelete(db, pKey);
  92908. }
  92909. /*
  92910. ** Called by the parser to compile a DETACH statement.
  92911. **
  92912. ** DETACH pDbname
  92913. */
  92914. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  92915. static const FuncDef detach_func = {
  92916. 1, /* nArg */
  92917. SQLITE_UTF8, /* funcFlags */
  92918. 0, /* pUserData */
  92919. 0, /* pNext */
  92920. detachFunc, /* xSFunc */
  92921. 0, /* xFinalize */
  92922. "sqlite_detach", /* zName */
  92923. {0}
  92924. };
  92925. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  92926. }
  92927. /*
  92928. ** Called by the parser to compile an ATTACH statement.
  92929. **
  92930. ** ATTACH p AS pDbname KEY pKey
  92931. */
  92932. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  92933. static const FuncDef attach_func = {
  92934. 3, /* nArg */
  92935. SQLITE_UTF8, /* funcFlags */
  92936. 0, /* pUserData */
  92937. 0, /* pNext */
  92938. attachFunc, /* xSFunc */
  92939. 0, /* xFinalize */
  92940. "sqlite_attach", /* zName */
  92941. {0}
  92942. };
  92943. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  92944. }
  92945. #endif /* SQLITE_OMIT_ATTACH */
  92946. /*
  92947. ** Initialize a DbFixer structure. This routine must be called prior
  92948. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  92949. */
  92950. SQLITE_PRIVATE void sqlite3FixInit(
  92951. DbFixer *pFix, /* The fixer to be initialized */
  92952. Parse *pParse, /* Error messages will be written here */
  92953. int iDb, /* This is the database that must be used */
  92954. const char *zType, /* "view", "trigger", or "index" */
  92955. const Token *pName /* Name of the view, trigger, or index */
  92956. ){
  92957. sqlite3 *db;
  92958. db = pParse->db;
  92959. assert( db->nDb>iDb );
  92960. pFix->pParse = pParse;
  92961. pFix->zDb = db->aDb[iDb].zDbSName;
  92962. pFix->pSchema = db->aDb[iDb].pSchema;
  92963. pFix->zType = zType;
  92964. pFix->pName = pName;
  92965. pFix->bVarOnly = (iDb==1);
  92966. }
  92967. /*
  92968. ** The following set of routines walk through the parse tree and assign
  92969. ** a specific database to all table references where the database name
  92970. ** was left unspecified in the original SQL statement. The pFix structure
  92971. ** must have been initialized by a prior call to sqlite3FixInit().
  92972. **
  92973. ** These routines are used to make sure that an index, trigger, or
  92974. ** view in one database does not refer to objects in a different database.
  92975. ** (Exception: indices, triggers, and views in the TEMP database are
  92976. ** allowed to refer to anything.) If a reference is explicitly made
  92977. ** to an object in a different database, an error message is added to
  92978. ** pParse->zErrMsg and these routines return non-zero. If everything
  92979. ** checks out, these routines return 0.
  92980. */
  92981. SQLITE_PRIVATE int sqlite3FixSrcList(
  92982. DbFixer *pFix, /* Context of the fixation */
  92983. SrcList *pList /* The Source list to check and modify */
  92984. ){
  92985. int i;
  92986. const char *zDb;
  92987. struct SrcList_item *pItem;
  92988. if( NEVER(pList==0) ) return 0;
  92989. zDb = pFix->zDb;
  92990. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  92991. if( pFix->bVarOnly==0 ){
  92992. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  92993. sqlite3ErrorMsg(pFix->pParse,
  92994. "%s %T cannot reference objects in database %s",
  92995. pFix->zType, pFix->pName, pItem->zDatabase);
  92996. return 1;
  92997. }
  92998. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  92999. pItem->zDatabase = 0;
  93000. pItem->pSchema = pFix->pSchema;
  93001. }
  93002. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  93003. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  93004. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  93005. #endif
  93006. }
  93007. return 0;
  93008. }
  93009. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  93010. SQLITE_PRIVATE int sqlite3FixSelect(
  93011. DbFixer *pFix, /* Context of the fixation */
  93012. Select *pSelect /* The SELECT statement to be fixed to one database */
  93013. ){
  93014. while( pSelect ){
  93015. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  93016. return 1;
  93017. }
  93018. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  93019. return 1;
  93020. }
  93021. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  93022. return 1;
  93023. }
  93024. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  93025. return 1;
  93026. }
  93027. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  93028. return 1;
  93029. }
  93030. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  93031. return 1;
  93032. }
  93033. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  93034. return 1;
  93035. }
  93036. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  93037. return 1;
  93038. }
  93039. pSelect = pSelect->pPrior;
  93040. }
  93041. return 0;
  93042. }
  93043. SQLITE_PRIVATE int sqlite3FixExpr(
  93044. DbFixer *pFix, /* Context of the fixation */
  93045. Expr *pExpr /* The expression to be fixed to one database */
  93046. ){
  93047. while( pExpr ){
  93048. if( pExpr->op==TK_VARIABLE ){
  93049. if( pFix->pParse->db->init.busy ){
  93050. pExpr->op = TK_NULL;
  93051. }else{
  93052. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  93053. return 1;
  93054. }
  93055. }
  93056. if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
  93057. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93058. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  93059. }else{
  93060. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  93061. }
  93062. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  93063. return 1;
  93064. }
  93065. pExpr = pExpr->pLeft;
  93066. }
  93067. return 0;
  93068. }
  93069. SQLITE_PRIVATE int sqlite3FixExprList(
  93070. DbFixer *pFix, /* Context of the fixation */
  93071. ExprList *pList /* The expression to be fixed to one database */
  93072. ){
  93073. int i;
  93074. struct ExprList_item *pItem;
  93075. if( pList==0 ) return 0;
  93076. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  93077. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  93078. return 1;
  93079. }
  93080. }
  93081. return 0;
  93082. }
  93083. #endif
  93084. #ifndef SQLITE_OMIT_TRIGGER
  93085. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  93086. DbFixer *pFix, /* Context of the fixation */
  93087. TriggerStep *pStep /* The trigger step be fixed to one database */
  93088. ){
  93089. while( pStep ){
  93090. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  93091. return 1;
  93092. }
  93093. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  93094. return 1;
  93095. }
  93096. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  93097. return 1;
  93098. }
  93099. pStep = pStep->pNext;
  93100. }
  93101. return 0;
  93102. }
  93103. #endif
  93104. /************** End of attach.c **********************************************/
  93105. /************** Begin file auth.c ********************************************/
  93106. /*
  93107. ** 2003 January 11
  93108. **
  93109. ** The author disclaims copyright to this source code. In place of
  93110. ** a legal notice, here is a blessing:
  93111. **
  93112. ** May you do good and not evil.
  93113. ** May you find forgiveness for yourself and forgive others.
  93114. ** May you share freely, never taking more than you give.
  93115. **
  93116. *************************************************************************
  93117. ** This file contains code used to implement the sqlite3_set_authorizer()
  93118. ** API. This facility is an optional feature of the library. Embedded
  93119. ** systems that do not need this facility may omit it by recompiling
  93120. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  93121. */
  93122. /* #include "sqliteInt.h" */
  93123. /*
  93124. ** All of the code in this file may be omitted by defining a single
  93125. ** macro.
  93126. */
  93127. #ifndef SQLITE_OMIT_AUTHORIZATION
  93128. /*
  93129. ** Set or clear the access authorization function.
  93130. **
  93131. ** The access authorization function is be called during the compilation
  93132. ** phase to verify that the user has read and/or write access permission on
  93133. ** various fields of the database. The first argument to the auth function
  93134. ** is a copy of the 3rd argument to this routine. The second argument
  93135. ** to the auth function is one of these constants:
  93136. **
  93137. ** SQLITE_CREATE_INDEX
  93138. ** SQLITE_CREATE_TABLE
  93139. ** SQLITE_CREATE_TEMP_INDEX
  93140. ** SQLITE_CREATE_TEMP_TABLE
  93141. ** SQLITE_CREATE_TEMP_TRIGGER
  93142. ** SQLITE_CREATE_TEMP_VIEW
  93143. ** SQLITE_CREATE_TRIGGER
  93144. ** SQLITE_CREATE_VIEW
  93145. ** SQLITE_DELETE
  93146. ** SQLITE_DROP_INDEX
  93147. ** SQLITE_DROP_TABLE
  93148. ** SQLITE_DROP_TEMP_INDEX
  93149. ** SQLITE_DROP_TEMP_TABLE
  93150. ** SQLITE_DROP_TEMP_TRIGGER
  93151. ** SQLITE_DROP_TEMP_VIEW
  93152. ** SQLITE_DROP_TRIGGER
  93153. ** SQLITE_DROP_VIEW
  93154. ** SQLITE_INSERT
  93155. ** SQLITE_PRAGMA
  93156. ** SQLITE_READ
  93157. ** SQLITE_SELECT
  93158. ** SQLITE_TRANSACTION
  93159. ** SQLITE_UPDATE
  93160. **
  93161. ** The third and fourth arguments to the auth function are the name of
  93162. ** the table and the column that are being accessed. The auth function
  93163. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  93164. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  93165. ** means that the SQL statement will never-run - the sqlite3_exec() call
  93166. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  93167. ** should run but attempts to read the specified column will return NULL
  93168. ** and attempts to write the column will be ignored.
  93169. **
  93170. ** Setting the auth function to NULL disables this hook. The default
  93171. ** setting of the auth function is NULL.
  93172. */
  93173. SQLITE_API int sqlite3_set_authorizer(
  93174. sqlite3 *db,
  93175. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  93176. void *pArg
  93177. ){
  93178. #ifdef SQLITE_ENABLE_API_ARMOR
  93179. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  93180. #endif
  93181. sqlite3_mutex_enter(db->mutex);
  93182. db->xAuth = (sqlite3_xauth)xAuth;
  93183. db->pAuthArg = pArg;
  93184. sqlite3ExpirePreparedStatements(db);
  93185. sqlite3_mutex_leave(db->mutex);
  93186. return SQLITE_OK;
  93187. }
  93188. /*
  93189. ** Write an error message into pParse->zErrMsg that explains that the
  93190. ** user-supplied authorization function returned an illegal value.
  93191. */
  93192. static void sqliteAuthBadReturnCode(Parse *pParse){
  93193. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  93194. pParse->rc = SQLITE_ERROR;
  93195. }
  93196. /*
  93197. ** Invoke the authorization callback for permission to read column zCol from
  93198. ** table zTab in database zDb. This function assumes that an authorization
  93199. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  93200. **
  93201. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  93202. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  93203. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  93204. */
  93205. SQLITE_PRIVATE int sqlite3AuthReadCol(
  93206. Parse *pParse, /* The parser context */
  93207. const char *zTab, /* Table name */
  93208. const char *zCol, /* Column name */
  93209. int iDb /* Index of containing database. */
  93210. ){
  93211. sqlite3 *db = pParse->db; /* Database handle */
  93212. char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
  93213. int rc; /* Auth callback return code */
  93214. if( db->init.busy ) return SQLITE_OK;
  93215. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  93216. #ifdef SQLITE_USER_AUTHENTICATION
  93217. ,db->auth.zAuthUser
  93218. #endif
  93219. );
  93220. if( rc==SQLITE_DENY ){
  93221. if( db->nDb>2 || iDb!=0 ){
  93222. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  93223. }else{
  93224. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  93225. }
  93226. pParse->rc = SQLITE_AUTH;
  93227. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  93228. sqliteAuthBadReturnCode(pParse);
  93229. }
  93230. return rc;
  93231. }
  93232. /*
  93233. ** The pExpr should be a TK_COLUMN expression. The table referred to
  93234. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  93235. ** Check to see if it is OK to read this particular column.
  93236. **
  93237. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  93238. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  93239. ** then generate an error.
  93240. */
  93241. SQLITE_PRIVATE void sqlite3AuthRead(
  93242. Parse *pParse, /* The parser context */
  93243. Expr *pExpr, /* The expression to check authorization on */
  93244. Schema *pSchema, /* The schema of the expression */
  93245. SrcList *pTabList /* All table that pExpr might refer to */
  93246. ){
  93247. sqlite3 *db = pParse->db;
  93248. Table *pTab = 0; /* The table being read */
  93249. const char *zCol; /* Name of the column of the table */
  93250. int iSrc; /* Index in pTabList->a[] of table being read */
  93251. int iDb; /* The index of the database the expression refers to */
  93252. int iCol; /* Index of column in table */
  93253. if( db->xAuth==0 ) return;
  93254. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  93255. if( iDb<0 ){
  93256. /* An attempt to read a column out of a subquery or other
  93257. ** temporary table. */
  93258. return;
  93259. }
  93260. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  93261. if( pExpr->op==TK_TRIGGER ){
  93262. pTab = pParse->pTriggerTab;
  93263. }else{
  93264. assert( pTabList );
  93265. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  93266. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  93267. pTab = pTabList->a[iSrc].pTab;
  93268. break;
  93269. }
  93270. }
  93271. }
  93272. iCol = pExpr->iColumn;
  93273. if( NEVER(pTab==0) ) return;
  93274. if( iCol>=0 ){
  93275. assert( iCol<pTab->nCol );
  93276. zCol = pTab->aCol[iCol].zName;
  93277. }else if( pTab->iPKey>=0 ){
  93278. assert( pTab->iPKey<pTab->nCol );
  93279. zCol = pTab->aCol[pTab->iPKey].zName;
  93280. }else{
  93281. zCol = "ROWID";
  93282. }
  93283. assert( iDb>=0 && iDb<db->nDb );
  93284. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  93285. pExpr->op = TK_NULL;
  93286. }
  93287. }
  93288. /*
  93289. ** Do an authorization check using the code and arguments given. Return
  93290. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  93291. ** is returned, then the error count and error message in pParse are
  93292. ** modified appropriately.
  93293. */
  93294. SQLITE_PRIVATE int sqlite3AuthCheck(
  93295. Parse *pParse,
  93296. int code,
  93297. const char *zArg1,
  93298. const char *zArg2,
  93299. const char *zArg3
  93300. ){
  93301. sqlite3 *db = pParse->db;
  93302. int rc;
  93303. /* Don't do any authorization checks if the database is initialising
  93304. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  93305. */
  93306. if( db->init.busy || IN_DECLARE_VTAB ){
  93307. return SQLITE_OK;
  93308. }
  93309. if( db->xAuth==0 ){
  93310. return SQLITE_OK;
  93311. }
  93312. /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
  93313. ** callback are either NULL pointers or zero-terminated strings that
  93314. ** contain additional details about the action to be authorized.
  93315. **
  93316. ** The following testcase() macros show that any of the 3rd through 6th
  93317. ** parameters can be either NULL or a string. */
  93318. testcase( zArg1==0 );
  93319. testcase( zArg2==0 );
  93320. testcase( zArg3==0 );
  93321. testcase( pParse->zAuthContext==0 );
  93322. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  93323. #ifdef SQLITE_USER_AUTHENTICATION
  93324. ,db->auth.zAuthUser
  93325. #endif
  93326. );
  93327. if( rc==SQLITE_DENY ){
  93328. sqlite3ErrorMsg(pParse, "not authorized");
  93329. pParse->rc = SQLITE_AUTH;
  93330. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  93331. rc = SQLITE_DENY;
  93332. sqliteAuthBadReturnCode(pParse);
  93333. }
  93334. return rc;
  93335. }
  93336. /*
  93337. ** Push an authorization context. After this routine is called, the
  93338. ** zArg3 argument to authorization callbacks will be zContext until
  93339. ** popped. Or if pParse==0, this routine is a no-op.
  93340. */
  93341. SQLITE_PRIVATE void sqlite3AuthContextPush(
  93342. Parse *pParse,
  93343. AuthContext *pContext,
  93344. const char *zContext
  93345. ){
  93346. assert( pParse );
  93347. pContext->pParse = pParse;
  93348. pContext->zAuthContext = pParse->zAuthContext;
  93349. pParse->zAuthContext = zContext;
  93350. }
  93351. /*
  93352. ** Pop an authorization context that was previously pushed
  93353. ** by sqlite3AuthContextPush
  93354. */
  93355. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  93356. if( pContext->pParse ){
  93357. pContext->pParse->zAuthContext = pContext->zAuthContext;
  93358. pContext->pParse = 0;
  93359. }
  93360. }
  93361. #endif /* SQLITE_OMIT_AUTHORIZATION */
  93362. /************** End of auth.c ************************************************/
  93363. /************** Begin file build.c *******************************************/
  93364. /*
  93365. ** 2001 September 15
  93366. **
  93367. ** The author disclaims copyright to this source code. In place of
  93368. ** a legal notice, here is a blessing:
  93369. **
  93370. ** May you do good and not evil.
  93371. ** May you find forgiveness for yourself and forgive others.
  93372. ** May you share freely, never taking more than you give.
  93373. **
  93374. *************************************************************************
  93375. ** This file contains C code routines that are called by the SQLite parser
  93376. ** when syntax rules are reduced. The routines in this file handle the
  93377. ** following kinds of SQL syntax:
  93378. **
  93379. ** CREATE TABLE
  93380. ** DROP TABLE
  93381. ** CREATE INDEX
  93382. ** DROP INDEX
  93383. ** creating ID lists
  93384. ** BEGIN TRANSACTION
  93385. ** COMMIT
  93386. ** ROLLBACK
  93387. */
  93388. /* #include "sqliteInt.h" */
  93389. #ifndef SQLITE_OMIT_SHARED_CACHE
  93390. /*
  93391. ** The TableLock structure is only used by the sqlite3TableLock() and
  93392. ** codeTableLocks() functions.
  93393. */
  93394. struct TableLock {
  93395. int iDb; /* The database containing the table to be locked */
  93396. int iTab; /* The root page of the table to be locked */
  93397. u8 isWriteLock; /* True for write lock. False for a read lock */
  93398. const char *zLockName; /* Name of the table */
  93399. };
  93400. /*
  93401. ** Record the fact that we want to lock a table at run-time.
  93402. **
  93403. ** The table to be locked has root page iTab and is found in database iDb.
  93404. ** A read or a write lock can be taken depending on isWritelock.
  93405. **
  93406. ** This routine just records the fact that the lock is desired. The
  93407. ** code to make the lock occur is generated by a later call to
  93408. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  93409. */
  93410. SQLITE_PRIVATE void sqlite3TableLock(
  93411. Parse *pParse, /* Parsing context */
  93412. int iDb, /* Index of the database containing the table to lock */
  93413. int iTab, /* Root page number of the table to be locked */
  93414. u8 isWriteLock, /* True for a write lock */
  93415. const char *zName /* Name of the table to be locked */
  93416. ){
  93417. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  93418. int i;
  93419. int nBytes;
  93420. TableLock *p;
  93421. assert( iDb>=0 );
  93422. if( iDb==1 ) return;
  93423. if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
  93424. for(i=0; i<pToplevel->nTableLock; i++){
  93425. p = &pToplevel->aTableLock[i];
  93426. if( p->iDb==iDb && p->iTab==iTab ){
  93427. p->isWriteLock = (p->isWriteLock || isWriteLock);
  93428. return;
  93429. }
  93430. }
  93431. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  93432. pToplevel->aTableLock =
  93433. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  93434. if( pToplevel->aTableLock ){
  93435. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  93436. p->iDb = iDb;
  93437. p->iTab = iTab;
  93438. p->isWriteLock = isWriteLock;
  93439. p->zLockName = zName;
  93440. }else{
  93441. pToplevel->nTableLock = 0;
  93442. sqlite3OomFault(pToplevel->db);
  93443. }
  93444. }
  93445. /*
  93446. ** Code an OP_TableLock instruction for each table locked by the
  93447. ** statement (configured by calls to sqlite3TableLock()).
  93448. */
  93449. static void codeTableLocks(Parse *pParse){
  93450. int i;
  93451. Vdbe *pVdbe;
  93452. pVdbe = sqlite3GetVdbe(pParse);
  93453. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  93454. for(i=0; i<pParse->nTableLock; i++){
  93455. TableLock *p = &pParse->aTableLock[i];
  93456. int p1 = p->iDb;
  93457. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  93458. p->zLockName, P4_STATIC);
  93459. }
  93460. }
  93461. #else
  93462. #define codeTableLocks(x)
  93463. #endif
  93464. /*
  93465. ** Return TRUE if the given yDbMask object is empty - if it contains no
  93466. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  93467. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  93468. */
  93469. #if SQLITE_MAX_ATTACHED>30
  93470. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  93471. int i;
  93472. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  93473. return 1;
  93474. }
  93475. #endif
  93476. /*
  93477. ** This routine is called after a single SQL statement has been
  93478. ** parsed and a VDBE program to execute that statement has been
  93479. ** prepared. This routine puts the finishing touches on the
  93480. ** VDBE program and resets the pParse structure for the next
  93481. ** parse.
  93482. **
  93483. ** Note that if an error occurred, it might be the case that
  93484. ** no VDBE code was generated.
  93485. */
  93486. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  93487. sqlite3 *db;
  93488. Vdbe *v;
  93489. assert( pParse->pToplevel==0 );
  93490. db = pParse->db;
  93491. if( pParse->nested ) return;
  93492. if( db->mallocFailed || pParse->nErr ){
  93493. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  93494. return;
  93495. }
  93496. /* Begin by generating some termination code at the end of the
  93497. ** vdbe program
  93498. */
  93499. v = sqlite3GetVdbe(pParse);
  93500. assert( !pParse->isMultiWrite
  93501. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  93502. if( v ){
  93503. sqlite3VdbeAddOp0(v, OP_Halt);
  93504. #if SQLITE_USER_AUTHENTICATION
  93505. if( pParse->nTableLock>0 && db->init.busy==0 ){
  93506. sqlite3UserAuthInit(db);
  93507. if( db->auth.authLevel<UAUTH_User ){
  93508. sqlite3ErrorMsg(pParse, "user not authenticated");
  93509. pParse->rc = SQLITE_AUTH_USER;
  93510. return;
  93511. }
  93512. }
  93513. #endif
  93514. /* The cookie mask contains one bit for each database file open.
  93515. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  93516. ** set for each database that is used. Generate code to start a
  93517. ** transaction on each used database and to verify the schema cookie
  93518. ** on each used database.
  93519. */
  93520. if( db->mallocFailed==0
  93521. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  93522. ){
  93523. int iDb, i;
  93524. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  93525. sqlite3VdbeJumpHere(v, 0);
  93526. for(iDb=0; iDb<db->nDb; iDb++){
  93527. Schema *pSchema;
  93528. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  93529. sqlite3VdbeUsesBtree(v, iDb);
  93530. pSchema = db->aDb[iDb].pSchema;
  93531. sqlite3VdbeAddOp4Int(v,
  93532. OP_Transaction, /* Opcode */
  93533. iDb, /* P1 */
  93534. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  93535. pSchema->schema_cookie, /* P3 */
  93536. pSchema->iGeneration /* P4 */
  93537. );
  93538. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  93539. VdbeComment((v,
  93540. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  93541. }
  93542. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93543. for(i=0; i<pParse->nVtabLock; i++){
  93544. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  93545. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  93546. }
  93547. pParse->nVtabLock = 0;
  93548. #endif
  93549. /* Once all the cookies have been verified and transactions opened,
  93550. ** obtain the required table-locks. This is a no-op unless the
  93551. ** shared-cache feature is enabled.
  93552. */
  93553. codeTableLocks(pParse);
  93554. /* Initialize any AUTOINCREMENT data structures required.
  93555. */
  93556. sqlite3AutoincrementBegin(pParse);
  93557. /* Code constant expressions that where factored out of inner loops */
  93558. if( pParse->pConstExpr ){
  93559. ExprList *pEL = pParse->pConstExpr;
  93560. pParse->okConstFactor = 0;
  93561. for(i=0; i<pEL->nExpr; i++){
  93562. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  93563. }
  93564. }
  93565. /* Finally, jump back to the beginning of the executable code. */
  93566. sqlite3VdbeGoto(v, 1);
  93567. }
  93568. }
  93569. /* Get the VDBE program ready for execution
  93570. */
  93571. if( v && pParse->nErr==0 && !db->mallocFailed ){
  93572. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  93573. /* A minimum of one cursor is required if autoincrement is used
  93574. * See ticket [a696379c1f08866] */
  93575. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  93576. sqlite3VdbeMakeReady(v, pParse);
  93577. pParse->rc = SQLITE_DONE;
  93578. }else{
  93579. pParse->rc = SQLITE_ERROR;
  93580. }
  93581. }
  93582. /*
  93583. ** Run the parser and code generator recursively in order to generate
  93584. ** code for the SQL statement given onto the end of the pParse context
  93585. ** currently under construction. When the parser is run recursively
  93586. ** this way, the final OP_Halt is not appended and other initialization
  93587. ** and finalization steps are omitted because those are handling by the
  93588. ** outermost parser.
  93589. **
  93590. ** Not everything is nestable. This facility is designed to permit
  93591. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  93592. ** care if you decide to try to use this routine for some other purposes.
  93593. */
  93594. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  93595. va_list ap;
  93596. char *zSql;
  93597. char *zErrMsg = 0;
  93598. sqlite3 *db = pParse->db;
  93599. char saveBuf[PARSE_TAIL_SZ];
  93600. if( pParse->nErr ) return;
  93601. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  93602. va_start(ap, zFormat);
  93603. zSql = sqlite3VMPrintf(db, zFormat, ap);
  93604. va_end(ap);
  93605. if( zSql==0 ){
  93606. return; /* A malloc must have failed */
  93607. }
  93608. pParse->nested++;
  93609. memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  93610. memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  93611. sqlite3RunParser(pParse, zSql, &zErrMsg);
  93612. sqlite3DbFree(db, zErrMsg);
  93613. sqlite3DbFree(db, zSql);
  93614. memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  93615. pParse->nested--;
  93616. }
  93617. #if SQLITE_USER_AUTHENTICATION
  93618. /*
  93619. ** Return TRUE if zTable is the name of the system table that stores the
  93620. ** list of users and their access credentials.
  93621. */
  93622. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  93623. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  93624. }
  93625. #endif
  93626. /*
  93627. ** Locate the in-memory structure that describes a particular database
  93628. ** table given the name of that table and (optionally) the name of the
  93629. ** database containing the table. Return NULL if not found.
  93630. **
  93631. ** If zDatabase is 0, all databases are searched for the table and the
  93632. ** first matching table is returned. (No checking for duplicate table
  93633. ** names is done.) The search order is TEMP first, then MAIN, then any
  93634. ** auxiliary databases added using the ATTACH command.
  93635. **
  93636. ** See also sqlite3LocateTable().
  93637. */
  93638. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  93639. Table *p = 0;
  93640. int i;
  93641. /* All mutexes are required for schema access. Make sure we hold them. */
  93642. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  93643. #if SQLITE_USER_AUTHENTICATION
  93644. /* Only the admin user is allowed to know that the sqlite_user table
  93645. ** exists */
  93646. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  93647. return 0;
  93648. }
  93649. #endif
  93650. while(1){
  93651. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  93652. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  93653. if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
  93654. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  93655. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  93656. if( p ) return p;
  93657. }
  93658. }
  93659. /* Not found. If the name we were looking for was temp.sqlite_master
  93660. ** then change the name to sqlite_temp_master and try again. */
  93661. if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
  93662. if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
  93663. zName = TEMP_MASTER_NAME;
  93664. }
  93665. return 0;
  93666. }
  93667. /*
  93668. ** Locate the in-memory structure that describes a particular database
  93669. ** table given the name of that table and (optionally) the name of the
  93670. ** database containing the table. Return NULL if not found. Also leave an
  93671. ** error message in pParse->zErrMsg.
  93672. **
  93673. ** The difference between this routine and sqlite3FindTable() is that this
  93674. ** routine leaves an error message in pParse->zErrMsg where
  93675. ** sqlite3FindTable() does not.
  93676. */
  93677. SQLITE_PRIVATE Table *sqlite3LocateTable(
  93678. Parse *pParse, /* context in which to report errors */
  93679. u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
  93680. const char *zName, /* Name of the table we are looking for */
  93681. const char *zDbase /* Name of the database. Might be NULL */
  93682. ){
  93683. Table *p;
  93684. /* Read the database schema. If an error occurs, leave an error message
  93685. ** and code in pParse and return NULL. */
  93686. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  93687. return 0;
  93688. }
  93689. p = sqlite3FindTable(pParse->db, zName, zDbase);
  93690. if( p==0 ){
  93691. const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
  93692. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93693. if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
  93694. /* If zName is the not the name of a table in the schema created using
  93695. ** CREATE, then check to see if it is the name of an virtual table that
  93696. ** can be an eponymous virtual table. */
  93697. Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
  93698. if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
  93699. pMod = sqlite3PragmaVtabRegister(pParse->db, zName);
  93700. }
  93701. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  93702. return pMod->pEpoTab;
  93703. }
  93704. }
  93705. #endif
  93706. if( (flags & LOCATE_NOERR)==0 ){
  93707. if( zDbase ){
  93708. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  93709. }else{
  93710. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  93711. }
  93712. pParse->checkSchema = 1;
  93713. }
  93714. }
  93715. return p;
  93716. }
  93717. /*
  93718. ** Locate the table identified by *p.
  93719. **
  93720. ** This is a wrapper around sqlite3LocateTable(). The difference between
  93721. ** sqlite3LocateTable() and this function is that this function restricts
  93722. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  93723. ** non-NULL if it is part of a view or trigger program definition. See
  93724. ** sqlite3FixSrcList() for details.
  93725. */
  93726. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  93727. Parse *pParse,
  93728. u32 flags,
  93729. struct SrcList_item *p
  93730. ){
  93731. const char *zDb;
  93732. assert( p->pSchema==0 || p->zDatabase==0 );
  93733. if( p->pSchema ){
  93734. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  93735. zDb = pParse->db->aDb[iDb].zDbSName;
  93736. }else{
  93737. zDb = p->zDatabase;
  93738. }
  93739. return sqlite3LocateTable(pParse, flags, p->zName, zDb);
  93740. }
  93741. /*
  93742. ** Locate the in-memory structure that describes
  93743. ** a particular index given the name of that index
  93744. ** and the name of the database that contains the index.
  93745. ** Return NULL if not found.
  93746. **
  93747. ** If zDatabase is 0, all databases are searched for the
  93748. ** table and the first matching index is returned. (No checking
  93749. ** for duplicate index names is done.) The search order is
  93750. ** TEMP first, then MAIN, then any auxiliary databases added
  93751. ** using the ATTACH command.
  93752. */
  93753. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  93754. Index *p = 0;
  93755. int i;
  93756. /* All mutexes are required for schema access. Make sure we hold them. */
  93757. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  93758. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  93759. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  93760. Schema *pSchema = db->aDb[j].pSchema;
  93761. assert( pSchema );
  93762. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
  93763. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  93764. p = sqlite3HashFind(&pSchema->idxHash, zName);
  93765. if( p ) break;
  93766. }
  93767. return p;
  93768. }
  93769. /*
  93770. ** Reclaim the memory used by an index
  93771. */
  93772. static void freeIndex(sqlite3 *db, Index *p){
  93773. #ifndef SQLITE_OMIT_ANALYZE
  93774. sqlite3DeleteIndexSamples(db, p);
  93775. #endif
  93776. sqlite3ExprDelete(db, p->pPartIdxWhere);
  93777. sqlite3ExprListDelete(db, p->aColExpr);
  93778. sqlite3DbFree(db, p->zColAff);
  93779. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  93780. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  93781. sqlite3_free(p->aiRowEst);
  93782. #endif
  93783. sqlite3DbFree(db, p);
  93784. }
  93785. /*
  93786. ** For the index called zIdxName which is found in the database iDb,
  93787. ** unlike that index from its Table then remove the index from
  93788. ** the index hash table and free all memory structures associated
  93789. ** with the index.
  93790. */
  93791. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  93792. Index *pIndex;
  93793. Hash *pHash;
  93794. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93795. pHash = &db->aDb[iDb].pSchema->idxHash;
  93796. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  93797. if( ALWAYS(pIndex) ){
  93798. if( pIndex->pTable->pIndex==pIndex ){
  93799. pIndex->pTable->pIndex = pIndex->pNext;
  93800. }else{
  93801. Index *p;
  93802. /* Justification of ALWAYS(); The index must be on the list of
  93803. ** indices. */
  93804. p = pIndex->pTable->pIndex;
  93805. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  93806. if( ALWAYS(p && p->pNext==pIndex) ){
  93807. p->pNext = pIndex->pNext;
  93808. }
  93809. }
  93810. freeIndex(db, pIndex);
  93811. }
  93812. db->flags |= SQLITE_InternChanges;
  93813. }
  93814. /*
  93815. ** Look through the list of open database files in db->aDb[] and if
  93816. ** any have been closed, remove them from the list. Reallocate the
  93817. ** db->aDb[] structure to a smaller size, if possible.
  93818. **
  93819. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  93820. ** are never candidates for being collapsed.
  93821. */
  93822. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  93823. int i, j;
  93824. for(i=j=2; i<db->nDb; i++){
  93825. struct Db *pDb = &db->aDb[i];
  93826. if( pDb->pBt==0 ){
  93827. sqlite3DbFree(db, pDb->zDbSName);
  93828. pDb->zDbSName = 0;
  93829. continue;
  93830. }
  93831. if( j<i ){
  93832. db->aDb[j] = db->aDb[i];
  93833. }
  93834. j++;
  93835. }
  93836. db->nDb = j;
  93837. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  93838. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  93839. sqlite3DbFree(db, db->aDb);
  93840. db->aDb = db->aDbStatic;
  93841. }
  93842. }
  93843. /*
  93844. ** Reset the schema for the database at index iDb. Also reset the
  93845. ** TEMP schema.
  93846. */
  93847. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  93848. Db *pDb;
  93849. assert( iDb<db->nDb );
  93850. /* Case 1: Reset the single schema identified by iDb */
  93851. pDb = &db->aDb[iDb];
  93852. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93853. assert( pDb->pSchema!=0 );
  93854. sqlite3SchemaClear(pDb->pSchema);
  93855. /* If any database other than TEMP is reset, then also reset TEMP
  93856. ** since TEMP might be holding triggers that reference tables in the
  93857. ** other database.
  93858. */
  93859. if( iDb!=1 ){
  93860. pDb = &db->aDb[1];
  93861. assert( pDb->pSchema!=0 );
  93862. sqlite3SchemaClear(pDb->pSchema);
  93863. }
  93864. return;
  93865. }
  93866. /*
  93867. ** Erase all schema information from all attached databases (including
  93868. ** "main" and "temp") for a single database connection.
  93869. */
  93870. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  93871. int i;
  93872. sqlite3BtreeEnterAll(db);
  93873. for(i=0; i<db->nDb; i++){
  93874. Db *pDb = &db->aDb[i];
  93875. if( pDb->pSchema ){
  93876. sqlite3SchemaClear(pDb->pSchema);
  93877. }
  93878. }
  93879. db->flags &= ~SQLITE_InternChanges;
  93880. sqlite3VtabUnlockList(db);
  93881. sqlite3BtreeLeaveAll(db);
  93882. sqlite3CollapseDatabaseArray(db);
  93883. }
  93884. /*
  93885. ** This routine is called when a commit occurs.
  93886. */
  93887. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  93888. db->flags &= ~SQLITE_InternChanges;
  93889. }
  93890. /*
  93891. ** Delete memory allocated for the column names of a table or view (the
  93892. ** Table.aCol[] array).
  93893. */
  93894. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  93895. int i;
  93896. Column *pCol;
  93897. assert( pTable!=0 );
  93898. if( (pCol = pTable->aCol)!=0 ){
  93899. for(i=0; i<pTable->nCol; i++, pCol++){
  93900. sqlite3DbFree(db, pCol->zName);
  93901. sqlite3ExprDelete(db, pCol->pDflt);
  93902. sqlite3DbFree(db, pCol->zColl);
  93903. }
  93904. sqlite3DbFree(db, pTable->aCol);
  93905. }
  93906. }
  93907. /*
  93908. ** Remove the memory data structures associated with the given
  93909. ** Table. No changes are made to disk by this routine.
  93910. **
  93911. ** This routine just deletes the data structure. It does not unlink
  93912. ** the table data structure from the hash table. But it does destroy
  93913. ** memory structures of the indices and foreign keys associated with
  93914. ** the table.
  93915. **
  93916. ** The db parameter is optional. It is needed if the Table object
  93917. ** contains lookaside memory. (Table objects in the schema do not use
  93918. ** lookaside memory, but some ephemeral Table objects do.) Or the
  93919. ** db parameter can be used with db->pnBytesFreed to measure the memory
  93920. ** used by the Table object.
  93921. */
  93922. static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
  93923. Index *pIndex, *pNext;
  93924. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  93925. /* Record the number of outstanding lookaside allocations in schema Tables
  93926. ** prior to doing any free() operations. Since schema Tables do not use
  93927. ** lookaside, this number should not change. */
  93928. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  93929. db->lookaside.nOut : 0 );
  93930. /* Delete all indices associated with this table. */
  93931. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  93932. pNext = pIndex->pNext;
  93933. assert( pIndex->pSchema==pTable->pSchema
  93934. || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
  93935. if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
  93936. char *zName = pIndex->zName;
  93937. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  93938. &pIndex->pSchema->idxHash, zName, 0
  93939. );
  93940. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  93941. assert( pOld==pIndex || pOld==0 );
  93942. }
  93943. freeIndex(db, pIndex);
  93944. }
  93945. /* Delete any foreign keys attached to this table. */
  93946. sqlite3FkDelete(db, pTable);
  93947. /* Delete the Table structure itself.
  93948. */
  93949. sqlite3DeleteColumnNames(db, pTable);
  93950. sqlite3DbFree(db, pTable->zName);
  93951. sqlite3DbFree(db, pTable->zColAff);
  93952. sqlite3SelectDelete(db, pTable->pSelect);
  93953. sqlite3ExprListDelete(db, pTable->pCheck);
  93954. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93955. sqlite3VtabClear(db, pTable);
  93956. #endif
  93957. sqlite3DbFree(db, pTable);
  93958. /* Verify that no lookaside memory was used by schema tables */
  93959. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  93960. }
  93961. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  93962. /* Do not delete the table until the reference count reaches zero. */
  93963. if( !pTable ) return;
  93964. if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
  93965. deleteTable(db, pTable);
  93966. }
  93967. /*
  93968. ** Unlink the given table from the hash tables and the delete the
  93969. ** table structure with all its indices and foreign keys.
  93970. */
  93971. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  93972. Table *p;
  93973. Db *pDb;
  93974. assert( db!=0 );
  93975. assert( iDb>=0 && iDb<db->nDb );
  93976. assert( zTabName );
  93977. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93978. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  93979. pDb = &db->aDb[iDb];
  93980. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  93981. sqlite3DeleteTable(db, p);
  93982. db->flags |= SQLITE_InternChanges;
  93983. }
  93984. /*
  93985. ** Given a token, return a string that consists of the text of that
  93986. ** token. Space to hold the returned string
  93987. ** is obtained from sqliteMalloc() and must be freed by the calling
  93988. ** function.
  93989. **
  93990. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  93991. ** surround the body of the token are removed.
  93992. **
  93993. ** Tokens are often just pointers into the original SQL text and so
  93994. ** are not \000 terminated and are not persistent. The returned string
  93995. ** is \000 terminated and is persistent.
  93996. */
  93997. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  93998. char *zName;
  93999. if( pName ){
  94000. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  94001. sqlite3Dequote(zName);
  94002. }else{
  94003. zName = 0;
  94004. }
  94005. return zName;
  94006. }
  94007. /*
  94008. ** Open the sqlite_master table stored in database number iDb for
  94009. ** writing. The table is opened using cursor 0.
  94010. */
  94011. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  94012. Vdbe *v = sqlite3GetVdbe(p);
  94013. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
  94014. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  94015. if( p->nTab==0 ){
  94016. p->nTab = 1;
  94017. }
  94018. }
  94019. /*
  94020. ** Parameter zName points to a nul-terminated buffer containing the name
  94021. ** of a database ("main", "temp" or the name of an attached db). This
  94022. ** function returns the index of the named database in db->aDb[], or
  94023. ** -1 if the named db cannot be found.
  94024. */
  94025. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  94026. int i = -1; /* Database number */
  94027. if( zName ){
  94028. Db *pDb;
  94029. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  94030. if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
  94031. /* "main" is always an acceptable alias for the primary database
  94032. ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
  94033. if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
  94034. }
  94035. }
  94036. return i;
  94037. }
  94038. /*
  94039. ** The token *pName contains the name of a database (either "main" or
  94040. ** "temp" or the name of an attached db). This routine returns the
  94041. ** index of the named database in db->aDb[], or -1 if the named db
  94042. ** does not exist.
  94043. */
  94044. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  94045. int i; /* Database number */
  94046. char *zName; /* Name we are searching for */
  94047. zName = sqlite3NameFromToken(db, pName);
  94048. i = sqlite3FindDbName(db, zName);
  94049. sqlite3DbFree(db, zName);
  94050. return i;
  94051. }
  94052. /* The table or view or trigger name is passed to this routine via tokens
  94053. ** pName1 and pName2. If the table name was fully qualified, for example:
  94054. **
  94055. ** CREATE TABLE xxx.yyy (...);
  94056. **
  94057. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  94058. ** the table name is not fully qualified, i.e.:
  94059. **
  94060. ** CREATE TABLE yyy(...);
  94061. **
  94062. ** Then pName1 is set to "yyy" and pName2 is "".
  94063. **
  94064. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  94065. ** pName2) that stores the unqualified table name. The index of the
  94066. ** database "xxx" is returned.
  94067. */
  94068. SQLITE_PRIVATE int sqlite3TwoPartName(
  94069. Parse *pParse, /* Parsing and code generating context */
  94070. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  94071. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  94072. Token **pUnqual /* Write the unqualified object name here */
  94073. ){
  94074. int iDb; /* Database holding the object */
  94075. sqlite3 *db = pParse->db;
  94076. assert( pName2!=0 );
  94077. if( pName2->n>0 ){
  94078. if( db->init.busy ) {
  94079. sqlite3ErrorMsg(pParse, "corrupt database");
  94080. return -1;
  94081. }
  94082. *pUnqual = pName2;
  94083. iDb = sqlite3FindDb(db, pName1);
  94084. if( iDb<0 ){
  94085. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  94086. return -1;
  94087. }
  94088. }else{
  94089. assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0);
  94090. iDb = db->init.iDb;
  94091. *pUnqual = pName1;
  94092. }
  94093. return iDb;
  94094. }
  94095. /*
  94096. ** This routine is used to check if the UTF-8 string zName is a legal
  94097. ** unqualified name for a new schema object (table, index, view or
  94098. ** trigger). All names are legal except those that begin with the string
  94099. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  94100. ** is reserved for internal use.
  94101. */
  94102. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  94103. if( !pParse->db->init.busy && pParse->nested==0
  94104. && (pParse->db->flags & SQLITE_WriteSchema)==0
  94105. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  94106. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  94107. return SQLITE_ERROR;
  94108. }
  94109. return SQLITE_OK;
  94110. }
  94111. /*
  94112. ** Return the PRIMARY KEY index of a table
  94113. */
  94114. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  94115. Index *p;
  94116. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  94117. return p;
  94118. }
  94119. /*
  94120. ** Return the column of index pIdx that corresponds to table
  94121. ** column iCol. Return -1 if not found.
  94122. */
  94123. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  94124. int i;
  94125. for(i=0; i<pIdx->nColumn; i++){
  94126. if( iCol==pIdx->aiColumn[i] ) return i;
  94127. }
  94128. return -1;
  94129. }
  94130. /*
  94131. ** Begin constructing a new table representation in memory. This is
  94132. ** the first of several action routines that get called in response
  94133. ** to a CREATE TABLE statement. In particular, this routine is called
  94134. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  94135. ** flag is true if the table should be stored in the auxiliary database
  94136. ** file instead of in the main database file. This is normally the case
  94137. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  94138. ** CREATE and TABLE.
  94139. **
  94140. ** The new table record is initialized and put in pParse->pNewTable.
  94141. ** As more of the CREATE TABLE statement is parsed, additional action
  94142. ** routines will be called to add more information to this record.
  94143. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  94144. ** is called to complete the construction of the new table record.
  94145. */
  94146. SQLITE_PRIVATE void sqlite3StartTable(
  94147. Parse *pParse, /* Parser context */
  94148. Token *pName1, /* First part of the name of the table or view */
  94149. Token *pName2, /* Second part of the name of the table or view */
  94150. int isTemp, /* True if this is a TEMP table */
  94151. int isView, /* True if this is a VIEW */
  94152. int isVirtual, /* True if this is a VIRTUAL table */
  94153. int noErr /* Do nothing if table already exists */
  94154. ){
  94155. Table *pTable;
  94156. char *zName = 0; /* The name of the new table */
  94157. sqlite3 *db = pParse->db;
  94158. Vdbe *v;
  94159. int iDb; /* Database number to create the table in */
  94160. Token *pName; /* Unqualified name of the table to create */
  94161. if( db->init.busy && db->init.newTnum==1 ){
  94162. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  94163. iDb = db->init.iDb;
  94164. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  94165. pName = pName1;
  94166. }else{
  94167. /* The common case */
  94168. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  94169. if( iDb<0 ) return;
  94170. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  94171. /* If creating a temp table, the name may not be qualified. Unless
  94172. ** the database name is "temp" anyway. */
  94173. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  94174. return;
  94175. }
  94176. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  94177. zName = sqlite3NameFromToken(db, pName);
  94178. }
  94179. pParse->sNameToken = *pName;
  94180. if( zName==0 ) return;
  94181. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  94182. goto begin_table_error;
  94183. }
  94184. if( db->init.iDb==1 ) isTemp = 1;
  94185. #ifndef SQLITE_OMIT_AUTHORIZATION
  94186. assert( isTemp==0 || isTemp==1 );
  94187. assert( isView==0 || isView==1 );
  94188. {
  94189. static const u8 aCode[] = {
  94190. SQLITE_CREATE_TABLE,
  94191. SQLITE_CREATE_TEMP_TABLE,
  94192. SQLITE_CREATE_VIEW,
  94193. SQLITE_CREATE_TEMP_VIEW
  94194. };
  94195. char *zDb = db->aDb[iDb].zDbSName;
  94196. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  94197. goto begin_table_error;
  94198. }
  94199. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  94200. zName, 0, zDb) ){
  94201. goto begin_table_error;
  94202. }
  94203. }
  94204. #endif
  94205. /* Make sure the new table name does not collide with an existing
  94206. ** index or table name in the same database. Issue an error message if
  94207. ** it does. The exception is if the statement being parsed was passed
  94208. ** to an sqlite3_declare_vtab() call. In that case only the column names
  94209. ** and types will be used, so there is no need to test for namespace
  94210. ** collisions.
  94211. */
  94212. if( !IN_DECLARE_VTAB ){
  94213. char *zDb = db->aDb[iDb].zDbSName;
  94214. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  94215. goto begin_table_error;
  94216. }
  94217. pTable = sqlite3FindTable(db, zName, zDb);
  94218. if( pTable ){
  94219. if( !noErr ){
  94220. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  94221. }else{
  94222. assert( !db->init.busy || CORRUPT_DB );
  94223. sqlite3CodeVerifySchema(pParse, iDb);
  94224. }
  94225. goto begin_table_error;
  94226. }
  94227. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  94228. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  94229. goto begin_table_error;
  94230. }
  94231. }
  94232. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  94233. if( pTable==0 ){
  94234. assert( db->mallocFailed );
  94235. pParse->rc = SQLITE_NOMEM_BKPT;
  94236. pParse->nErr++;
  94237. goto begin_table_error;
  94238. }
  94239. pTable->zName = zName;
  94240. pTable->iPKey = -1;
  94241. pTable->pSchema = db->aDb[iDb].pSchema;
  94242. pTable->nTabRef = 1;
  94243. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  94244. assert( pParse->pNewTable==0 );
  94245. pParse->pNewTable = pTable;
  94246. /* If this is the magic sqlite_sequence table used by autoincrement,
  94247. ** then record a pointer to this table in the main database structure
  94248. ** so that INSERT can find the table easily.
  94249. */
  94250. #ifndef SQLITE_OMIT_AUTOINCREMENT
  94251. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  94252. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94253. pTable->pSchema->pSeqTab = pTable;
  94254. }
  94255. #endif
  94256. /* Begin generating the code that will insert the table record into
  94257. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  94258. ** and allocate the record number for the table entry now. Before any
  94259. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  94260. ** indices to be created and the table record must come before the
  94261. ** indices. Hence, the record number for the table must be allocated
  94262. ** now.
  94263. */
  94264. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  94265. int addr1;
  94266. int fileFormat;
  94267. int reg1, reg2, reg3;
  94268. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  94269. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  94270. sqlite3BeginWriteOperation(pParse, 1, iDb);
  94271. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94272. if( isVirtual ){
  94273. sqlite3VdbeAddOp0(v, OP_VBegin);
  94274. }
  94275. #endif
  94276. /* If the file format and encoding in the database have not been set,
  94277. ** set them now.
  94278. */
  94279. reg1 = pParse->regRowid = ++pParse->nMem;
  94280. reg2 = pParse->regRoot = ++pParse->nMem;
  94281. reg3 = ++pParse->nMem;
  94282. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  94283. sqlite3VdbeUsesBtree(v, iDb);
  94284. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  94285. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  94286. 1 : SQLITE_MAX_FILE_FORMAT;
  94287. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  94288. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  94289. sqlite3VdbeJumpHere(v, addr1);
  94290. /* This just creates a place-holder record in the sqlite_master table.
  94291. ** The record created does not contain anything yet. It will be replaced
  94292. ** by the real entry in code generated at sqlite3EndTable().
  94293. **
  94294. ** The rowid for the new entry is left in register pParse->regRowid.
  94295. ** The root page number of the new table is left in reg pParse->regRoot.
  94296. ** The rowid and root page number values are needed by the code that
  94297. ** sqlite3EndTable will generate.
  94298. */
  94299. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  94300. if( isView || isVirtual ){
  94301. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  94302. }else
  94303. #endif
  94304. {
  94305. pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  94306. }
  94307. sqlite3OpenMasterTable(pParse, iDb);
  94308. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  94309. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  94310. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  94311. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  94312. sqlite3VdbeAddOp0(v, OP_Close);
  94313. }
  94314. /* Normal (non-error) return. */
  94315. return;
  94316. /* If an error occurs, we jump here */
  94317. begin_table_error:
  94318. sqlite3DbFree(db, zName);
  94319. return;
  94320. }
  94321. /* Set properties of a table column based on the (magical)
  94322. ** name of the column.
  94323. */
  94324. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  94325. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  94326. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  94327. pCol->colFlags |= COLFLAG_HIDDEN;
  94328. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  94329. pTab->tabFlags |= TF_OOOHidden;
  94330. }
  94331. }
  94332. #endif
  94333. /*
  94334. ** Add a new column to the table currently being constructed.
  94335. **
  94336. ** The parser calls this routine once for each column declaration
  94337. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  94338. ** first to get things going. Then this routine is called for each
  94339. ** column.
  94340. */
  94341. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  94342. Table *p;
  94343. int i;
  94344. char *z;
  94345. char *zType;
  94346. Column *pCol;
  94347. sqlite3 *db = pParse->db;
  94348. if( (p = pParse->pNewTable)==0 ) return;
  94349. #if SQLITE_MAX_COLUMN
  94350. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  94351. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  94352. return;
  94353. }
  94354. #endif
  94355. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  94356. if( z==0 ) return;
  94357. memcpy(z, pName->z, pName->n);
  94358. z[pName->n] = 0;
  94359. sqlite3Dequote(z);
  94360. for(i=0; i<p->nCol; i++){
  94361. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  94362. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  94363. sqlite3DbFree(db, z);
  94364. return;
  94365. }
  94366. }
  94367. if( (p->nCol & 0x7)==0 ){
  94368. Column *aNew;
  94369. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  94370. if( aNew==0 ){
  94371. sqlite3DbFree(db, z);
  94372. return;
  94373. }
  94374. p->aCol = aNew;
  94375. }
  94376. pCol = &p->aCol[p->nCol];
  94377. memset(pCol, 0, sizeof(p->aCol[0]));
  94378. pCol->zName = z;
  94379. sqlite3ColumnPropertiesFromName(p, pCol);
  94380. if( pType->n==0 ){
  94381. /* If there is no type specified, columns have the default affinity
  94382. ** 'BLOB'. */
  94383. pCol->affinity = SQLITE_AFF_BLOB;
  94384. pCol->szEst = 1;
  94385. }else{
  94386. zType = z + sqlite3Strlen30(z) + 1;
  94387. memcpy(zType, pType->z, pType->n);
  94388. zType[pType->n] = 0;
  94389. sqlite3Dequote(zType);
  94390. pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
  94391. pCol->colFlags |= COLFLAG_HASTYPE;
  94392. }
  94393. p->nCol++;
  94394. pParse->constraintName.n = 0;
  94395. }
  94396. /*
  94397. ** This routine is called by the parser while in the middle of
  94398. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  94399. ** been seen on a column. This routine sets the notNull flag on
  94400. ** the column currently under construction.
  94401. */
  94402. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  94403. Table *p;
  94404. p = pParse->pNewTable;
  94405. if( p==0 || NEVER(p->nCol<1) ) return;
  94406. p->aCol[p->nCol-1].notNull = (u8)onError;
  94407. p->tabFlags |= TF_HasNotNull;
  94408. }
  94409. /*
  94410. ** Scan the column type name zType (length nType) and return the
  94411. ** associated affinity type.
  94412. **
  94413. ** This routine does a case-independent search of zType for the
  94414. ** substrings in the following table. If one of the substrings is
  94415. ** found, the corresponding affinity is returned. If zType contains
  94416. ** more than one of the substrings, entries toward the top of
  94417. ** the table take priority. For example, if zType is 'BLOBINT',
  94418. ** SQLITE_AFF_INTEGER is returned.
  94419. **
  94420. ** Substring | Affinity
  94421. ** --------------------------------
  94422. ** 'INT' | SQLITE_AFF_INTEGER
  94423. ** 'CHAR' | SQLITE_AFF_TEXT
  94424. ** 'CLOB' | SQLITE_AFF_TEXT
  94425. ** 'TEXT' | SQLITE_AFF_TEXT
  94426. ** 'BLOB' | SQLITE_AFF_BLOB
  94427. ** 'REAL' | SQLITE_AFF_REAL
  94428. ** 'FLOA' | SQLITE_AFF_REAL
  94429. ** 'DOUB' | SQLITE_AFF_REAL
  94430. **
  94431. ** If none of the substrings in the above table are found,
  94432. ** SQLITE_AFF_NUMERIC is returned.
  94433. */
  94434. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  94435. u32 h = 0;
  94436. char aff = SQLITE_AFF_NUMERIC;
  94437. const char *zChar = 0;
  94438. assert( zIn!=0 );
  94439. while( zIn[0] ){
  94440. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  94441. zIn++;
  94442. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  94443. aff = SQLITE_AFF_TEXT;
  94444. zChar = zIn;
  94445. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  94446. aff = SQLITE_AFF_TEXT;
  94447. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  94448. aff = SQLITE_AFF_TEXT;
  94449. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  94450. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  94451. aff = SQLITE_AFF_BLOB;
  94452. if( zIn[0]=='(' ) zChar = zIn;
  94453. #ifndef SQLITE_OMIT_FLOATING_POINT
  94454. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  94455. && aff==SQLITE_AFF_NUMERIC ){
  94456. aff = SQLITE_AFF_REAL;
  94457. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  94458. && aff==SQLITE_AFF_NUMERIC ){
  94459. aff = SQLITE_AFF_REAL;
  94460. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  94461. && aff==SQLITE_AFF_NUMERIC ){
  94462. aff = SQLITE_AFF_REAL;
  94463. #endif
  94464. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  94465. aff = SQLITE_AFF_INTEGER;
  94466. break;
  94467. }
  94468. }
  94469. /* If pszEst is not NULL, store an estimate of the field size. The
  94470. ** estimate is scaled so that the size of an integer is 1. */
  94471. if( pszEst ){
  94472. *pszEst = 1; /* default size is approx 4 bytes */
  94473. if( aff<SQLITE_AFF_NUMERIC ){
  94474. if( zChar ){
  94475. while( zChar[0] ){
  94476. if( sqlite3Isdigit(zChar[0]) ){
  94477. int v = 0;
  94478. sqlite3GetInt32(zChar, &v);
  94479. v = v/4 + 1;
  94480. if( v>255 ) v = 255;
  94481. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  94482. break;
  94483. }
  94484. zChar++;
  94485. }
  94486. }else{
  94487. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  94488. }
  94489. }
  94490. }
  94491. return aff;
  94492. }
  94493. /*
  94494. ** The expression is the default value for the most recently added column
  94495. ** of the table currently under construction.
  94496. **
  94497. ** Default value expressions must be constant. Raise an exception if this
  94498. ** is not the case.
  94499. **
  94500. ** This routine is called by the parser while in the middle of
  94501. ** parsing a CREATE TABLE statement.
  94502. */
  94503. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  94504. Table *p;
  94505. Column *pCol;
  94506. sqlite3 *db = pParse->db;
  94507. p = pParse->pNewTable;
  94508. if( p!=0 ){
  94509. pCol = &(p->aCol[p->nCol-1]);
  94510. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  94511. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  94512. pCol->zName);
  94513. }else{
  94514. /* A copy of pExpr is used instead of the original, as pExpr contains
  94515. ** tokens that point to volatile memory. The 'span' of the expression
  94516. ** is required by pragma table_info.
  94517. */
  94518. Expr x;
  94519. sqlite3ExprDelete(db, pCol->pDflt);
  94520. memset(&x, 0, sizeof(x));
  94521. x.op = TK_SPAN;
  94522. x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  94523. (int)(pSpan->zEnd - pSpan->zStart));
  94524. x.pLeft = pSpan->pExpr;
  94525. x.flags = EP_Skip;
  94526. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  94527. sqlite3DbFree(db, x.u.zToken);
  94528. }
  94529. }
  94530. sqlite3ExprDelete(db, pSpan->pExpr);
  94531. }
  94532. /*
  94533. ** Backwards Compatibility Hack:
  94534. **
  94535. ** Historical versions of SQLite accepted strings as column names in
  94536. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  94537. **
  94538. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  94539. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  94540. **
  94541. ** This is goofy. But to preserve backwards compatibility we continue to
  94542. ** accept it. This routine does the necessary conversion. It converts
  94543. ** the expression given in its argument from a TK_STRING into a TK_ID
  94544. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  94545. ** If the epxression is anything other than TK_STRING, the expression is
  94546. ** unchanged.
  94547. */
  94548. static void sqlite3StringToId(Expr *p){
  94549. if( p->op==TK_STRING ){
  94550. p->op = TK_ID;
  94551. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  94552. p->pLeft->op = TK_ID;
  94553. }
  94554. }
  94555. /*
  94556. ** Designate the PRIMARY KEY for the table. pList is a list of names
  94557. ** of columns that form the primary key. If pList is NULL, then the
  94558. ** most recently added column of the table is the primary key.
  94559. **
  94560. ** A table can have at most one primary key. If the table already has
  94561. ** a primary key (and this is the second primary key) then create an
  94562. ** error.
  94563. **
  94564. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  94565. ** then we will try to use that column as the rowid. Set the Table.iPKey
  94566. ** field of the table under construction to be the index of the
  94567. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  94568. ** no INTEGER PRIMARY KEY.
  94569. **
  94570. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  94571. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  94572. */
  94573. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  94574. Parse *pParse, /* Parsing context */
  94575. ExprList *pList, /* List of field names to be indexed */
  94576. int onError, /* What to do with a uniqueness conflict */
  94577. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  94578. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  94579. ){
  94580. Table *pTab = pParse->pNewTable;
  94581. Column *pCol = 0;
  94582. int iCol = -1, i;
  94583. int nTerm;
  94584. if( pTab==0 ) goto primary_key_exit;
  94585. if( pTab->tabFlags & TF_HasPrimaryKey ){
  94586. sqlite3ErrorMsg(pParse,
  94587. "table \"%s\" has more than one primary key", pTab->zName);
  94588. goto primary_key_exit;
  94589. }
  94590. pTab->tabFlags |= TF_HasPrimaryKey;
  94591. if( pList==0 ){
  94592. iCol = pTab->nCol - 1;
  94593. pCol = &pTab->aCol[iCol];
  94594. pCol->colFlags |= COLFLAG_PRIMKEY;
  94595. nTerm = 1;
  94596. }else{
  94597. nTerm = pList->nExpr;
  94598. for(i=0; i<nTerm; i++){
  94599. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  94600. assert( pCExpr!=0 );
  94601. sqlite3StringToId(pCExpr);
  94602. if( pCExpr->op==TK_ID ){
  94603. const char *zCName = pCExpr->u.zToken;
  94604. for(iCol=0; iCol<pTab->nCol; iCol++){
  94605. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  94606. pCol = &pTab->aCol[iCol];
  94607. pCol->colFlags |= COLFLAG_PRIMKEY;
  94608. break;
  94609. }
  94610. }
  94611. }
  94612. }
  94613. }
  94614. if( nTerm==1
  94615. && pCol
  94616. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  94617. && sortOrder!=SQLITE_SO_DESC
  94618. ){
  94619. pTab->iPKey = iCol;
  94620. pTab->keyConf = (u8)onError;
  94621. assert( autoInc==0 || autoInc==1 );
  94622. pTab->tabFlags |= autoInc*TF_Autoincrement;
  94623. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  94624. }else if( autoInc ){
  94625. #ifndef SQLITE_OMIT_AUTOINCREMENT
  94626. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  94627. "INTEGER PRIMARY KEY");
  94628. #endif
  94629. }else{
  94630. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  94631. 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
  94632. pList = 0;
  94633. }
  94634. primary_key_exit:
  94635. sqlite3ExprListDelete(pParse->db, pList);
  94636. return;
  94637. }
  94638. /*
  94639. ** Add a new CHECK constraint to the table currently under construction.
  94640. */
  94641. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  94642. Parse *pParse, /* Parsing context */
  94643. Expr *pCheckExpr /* The check expression */
  94644. ){
  94645. #ifndef SQLITE_OMIT_CHECK
  94646. Table *pTab = pParse->pNewTable;
  94647. sqlite3 *db = pParse->db;
  94648. if( pTab && !IN_DECLARE_VTAB
  94649. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  94650. ){
  94651. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  94652. if( pParse->constraintName.n ){
  94653. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  94654. }
  94655. }else
  94656. #endif
  94657. {
  94658. sqlite3ExprDelete(pParse->db, pCheckExpr);
  94659. }
  94660. }
  94661. /*
  94662. ** Set the collation function of the most recently parsed table column
  94663. ** to the CollSeq given.
  94664. */
  94665. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  94666. Table *p;
  94667. int i;
  94668. char *zColl; /* Dequoted name of collation sequence */
  94669. sqlite3 *db;
  94670. if( (p = pParse->pNewTable)==0 ) return;
  94671. i = p->nCol-1;
  94672. db = pParse->db;
  94673. zColl = sqlite3NameFromToken(db, pToken);
  94674. if( !zColl ) return;
  94675. if( sqlite3LocateCollSeq(pParse, zColl) ){
  94676. Index *pIdx;
  94677. sqlite3DbFree(db, p->aCol[i].zColl);
  94678. p->aCol[i].zColl = zColl;
  94679. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  94680. ** then an index may have been created on this column before the
  94681. ** collation type was added. Correct this if it is the case.
  94682. */
  94683. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  94684. assert( pIdx->nKeyCol==1 );
  94685. if( pIdx->aiColumn[0]==i ){
  94686. pIdx->azColl[0] = p->aCol[i].zColl;
  94687. }
  94688. }
  94689. }else{
  94690. sqlite3DbFree(db, zColl);
  94691. }
  94692. }
  94693. /*
  94694. ** This function returns the collation sequence for database native text
  94695. ** encoding identified by the string zName, length nName.
  94696. **
  94697. ** If the requested collation sequence is not available, or not available
  94698. ** in the database native encoding, the collation factory is invoked to
  94699. ** request it. If the collation factory does not supply such a sequence,
  94700. ** and the sequence is available in another text encoding, then that is
  94701. ** returned instead.
  94702. **
  94703. ** If no versions of the requested collations sequence are available, or
  94704. ** another error occurs, NULL is returned and an error message written into
  94705. ** pParse.
  94706. **
  94707. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  94708. ** invokes the collation factory if the named collation cannot be found
  94709. ** and generates an error message.
  94710. **
  94711. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  94712. */
  94713. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  94714. sqlite3 *db = pParse->db;
  94715. u8 enc = ENC(db);
  94716. u8 initbusy = db->init.busy;
  94717. CollSeq *pColl;
  94718. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  94719. if( !initbusy && (!pColl || !pColl->xCmp) ){
  94720. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  94721. }
  94722. return pColl;
  94723. }
  94724. /*
  94725. ** Generate code that will increment the schema cookie.
  94726. **
  94727. ** The schema cookie is used to determine when the schema for the
  94728. ** database changes. After each schema change, the cookie value
  94729. ** changes. When a process first reads the schema it records the
  94730. ** cookie. Thereafter, whenever it goes to access the database,
  94731. ** it checks the cookie to make sure the schema has not changed
  94732. ** since it was last read.
  94733. **
  94734. ** This plan is not completely bullet-proof. It is possible for
  94735. ** the schema to change multiple times and for the cookie to be
  94736. ** set back to prior value. But schema changes are infrequent
  94737. ** and the probability of hitting the same cookie value is only
  94738. ** 1 chance in 2^32. So we're safe enough.
  94739. **
  94740. ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
  94741. ** the schema-version whenever the schema changes.
  94742. */
  94743. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  94744. sqlite3 *db = pParse->db;
  94745. Vdbe *v = pParse->pVdbe;
  94746. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94747. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  94748. db->aDb[iDb].pSchema->schema_cookie+1);
  94749. }
  94750. /*
  94751. ** Measure the number of characters needed to output the given
  94752. ** identifier. The number returned includes any quotes used
  94753. ** but does not include the null terminator.
  94754. **
  94755. ** The estimate is conservative. It might be larger that what is
  94756. ** really needed.
  94757. */
  94758. static int identLength(const char *z){
  94759. int n;
  94760. for(n=0; *z; n++, z++){
  94761. if( *z=='"' ){ n++; }
  94762. }
  94763. return n + 2;
  94764. }
  94765. /*
  94766. ** The first parameter is a pointer to an output buffer. The second
  94767. ** parameter is a pointer to an integer that contains the offset at
  94768. ** which to write into the output buffer. This function copies the
  94769. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  94770. ** to the specified offset in the buffer and updates *pIdx to refer
  94771. ** to the first byte after the last byte written before returning.
  94772. **
  94773. ** If the string zSignedIdent consists entirely of alpha-numeric
  94774. ** characters, does not begin with a digit and is not an SQL keyword,
  94775. ** then it is copied to the output buffer exactly as it is. Otherwise,
  94776. ** it is quoted using double-quotes.
  94777. */
  94778. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  94779. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  94780. int i, j, needQuote;
  94781. i = *pIdx;
  94782. for(j=0; zIdent[j]; j++){
  94783. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  94784. }
  94785. needQuote = sqlite3Isdigit(zIdent[0])
  94786. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  94787. || zIdent[j]!=0
  94788. || j==0;
  94789. if( needQuote ) z[i++] = '"';
  94790. for(j=0; zIdent[j]; j++){
  94791. z[i++] = zIdent[j];
  94792. if( zIdent[j]=='"' ) z[i++] = '"';
  94793. }
  94794. if( needQuote ) z[i++] = '"';
  94795. z[i] = 0;
  94796. *pIdx = i;
  94797. }
  94798. /*
  94799. ** Generate a CREATE TABLE statement appropriate for the given
  94800. ** table. Memory to hold the text of the statement is obtained
  94801. ** from sqliteMalloc() and must be freed by the calling function.
  94802. */
  94803. static char *createTableStmt(sqlite3 *db, Table *p){
  94804. int i, k, n;
  94805. char *zStmt;
  94806. char *zSep, *zSep2, *zEnd;
  94807. Column *pCol;
  94808. n = 0;
  94809. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  94810. n += identLength(pCol->zName) + 5;
  94811. }
  94812. n += identLength(p->zName);
  94813. if( n<50 ){
  94814. zSep = "";
  94815. zSep2 = ",";
  94816. zEnd = ")";
  94817. }else{
  94818. zSep = "\n ";
  94819. zSep2 = ",\n ";
  94820. zEnd = "\n)";
  94821. }
  94822. n += 35 + 6*p->nCol;
  94823. zStmt = sqlite3DbMallocRaw(0, n);
  94824. if( zStmt==0 ){
  94825. sqlite3OomFault(db);
  94826. return 0;
  94827. }
  94828. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  94829. k = sqlite3Strlen30(zStmt);
  94830. identPut(zStmt, &k, p->zName);
  94831. zStmt[k++] = '(';
  94832. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  94833. static const char * const azType[] = {
  94834. /* SQLITE_AFF_BLOB */ "",
  94835. /* SQLITE_AFF_TEXT */ " TEXT",
  94836. /* SQLITE_AFF_NUMERIC */ " NUM",
  94837. /* SQLITE_AFF_INTEGER */ " INT",
  94838. /* SQLITE_AFF_REAL */ " REAL"
  94839. };
  94840. int len;
  94841. const char *zType;
  94842. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  94843. k += sqlite3Strlen30(&zStmt[k]);
  94844. zSep = zSep2;
  94845. identPut(zStmt, &k, pCol->zName);
  94846. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  94847. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  94848. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  94849. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  94850. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  94851. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  94852. testcase( pCol->affinity==SQLITE_AFF_REAL );
  94853. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  94854. len = sqlite3Strlen30(zType);
  94855. assert( pCol->affinity==SQLITE_AFF_BLOB
  94856. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  94857. memcpy(&zStmt[k], zType, len);
  94858. k += len;
  94859. assert( k<=n );
  94860. }
  94861. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  94862. return zStmt;
  94863. }
  94864. /*
  94865. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  94866. ** on success and SQLITE_NOMEM on an OOM error.
  94867. */
  94868. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  94869. char *zExtra;
  94870. int nByte;
  94871. if( pIdx->nColumn>=N ) return SQLITE_OK;
  94872. assert( pIdx->isResized==0 );
  94873. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  94874. zExtra = sqlite3DbMallocZero(db, nByte);
  94875. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  94876. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  94877. pIdx->azColl = (const char**)zExtra;
  94878. zExtra += sizeof(char*)*N;
  94879. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  94880. pIdx->aiColumn = (i16*)zExtra;
  94881. zExtra += sizeof(i16)*N;
  94882. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  94883. pIdx->aSortOrder = (u8*)zExtra;
  94884. pIdx->nColumn = N;
  94885. pIdx->isResized = 1;
  94886. return SQLITE_OK;
  94887. }
  94888. /*
  94889. ** Estimate the total row width for a table.
  94890. */
  94891. static void estimateTableWidth(Table *pTab){
  94892. unsigned wTable = 0;
  94893. const Column *pTabCol;
  94894. int i;
  94895. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  94896. wTable += pTabCol->szEst;
  94897. }
  94898. if( pTab->iPKey<0 ) wTable++;
  94899. pTab->szTabRow = sqlite3LogEst(wTable*4);
  94900. }
  94901. /*
  94902. ** Estimate the average size of a row for an index.
  94903. */
  94904. static void estimateIndexWidth(Index *pIdx){
  94905. unsigned wIndex = 0;
  94906. int i;
  94907. const Column *aCol = pIdx->pTable->aCol;
  94908. for(i=0; i<pIdx->nColumn; i++){
  94909. i16 x = pIdx->aiColumn[i];
  94910. assert( x<pIdx->pTable->nCol );
  94911. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  94912. }
  94913. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  94914. }
  94915. /* Return true if value x is found any of the first nCol entries of aiCol[]
  94916. */
  94917. static int hasColumn(const i16 *aiCol, int nCol, int x){
  94918. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  94919. return 0;
  94920. }
  94921. /*
  94922. ** This routine runs at the end of parsing a CREATE TABLE statement that
  94923. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  94924. ** internal schema data structures and the generated VDBE code so that they
  94925. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  94926. ** Changes include:
  94927. **
  94928. ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  94929. ** (2) Convert the OP_CreateTable into an OP_CreateIndex. There is
  94930. ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
  94931. ** data storage is a covering index btree.
  94932. ** (3) Bypass the creation of the sqlite_master table entry
  94933. ** for the PRIMARY KEY as the primary key index is now
  94934. ** identified by the sqlite_master table entry of the table itself.
  94935. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
  94936. ** schema to the rootpage from the main table.
  94937. ** (5) Add all table columns to the PRIMARY KEY Index object
  94938. ** so that the PRIMARY KEY is a covering index. The surplus
  94939. ** columns are part of KeyInfo.nXField and are not used for
  94940. ** sorting or lookup or uniqueness checks.
  94941. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  94942. ** indices with the PRIMARY KEY columns.
  94943. **
  94944. ** For virtual tables, only (1) is performed.
  94945. */
  94946. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  94947. Index *pIdx;
  94948. Index *pPk;
  94949. int nPk;
  94950. int i, j;
  94951. sqlite3 *db = pParse->db;
  94952. Vdbe *v = pParse->pVdbe;
  94953. /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
  94954. */
  94955. if( !db->init.imposterTable ){
  94956. for(i=0; i<pTab->nCol; i++){
  94957. if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
  94958. pTab->aCol[i].notNull = OE_Abort;
  94959. }
  94960. }
  94961. }
  94962. /* The remaining transformations only apply to b-tree tables, not to
  94963. ** virtual tables */
  94964. if( IN_DECLARE_VTAB ) return;
  94965. /* Convert the OP_CreateTable opcode that would normally create the
  94966. ** root-page for the table into an OP_CreateIndex opcode. The index
  94967. ** created will become the PRIMARY KEY index.
  94968. */
  94969. if( pParse->addrCrTab ){
  94970. assert( v );
  94971. sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
  94972. }
  94973. /* Locate the PRIMARY KEY index. Or, if this table was originally
  94974. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  94975. */
  94976. if( pTab->iPKey>=0 ){
  94977. ExprList *pList;
  94978. Token ipkToken;
  94979. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  94980. pList = sqlite3ExprListAppend(pParse, 0,
  94981. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  94982. if( pList==0 ) return;
  94983. pList->a[0].sortOrder = pParse->iPkSortOrder;
  94984. assert( pParse->pNewTable==pTab );
  94985. sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
  94986. SQLITE_IDXTYPE_PRIMARYKEY);
  94987. if( db->mallocFailed ) return;
  94988. pPk = sqlite3PrimaryKeyIndex(pTab);
  94989. pTab->iPKey = -1;
  94990. }else{
  94991. pPk = sqlite3PrimaryKeyIndex(pTab);
  94992. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  94993. ** table entry. This is only required if currently generating VDBE
  94994. ** code for a CREATE TABLE (not when parsing one as part of reading
  94995. ** a database schema). */
  94996. if( v ){
  94997. assert( db->init.busy==0 );
  94998. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  94999. }
  95000. /*
  95001. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  95002. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  95003. ** code assumes the PRIMARY KEY contains no repeated columns.
  95004. */
  95005. for(i=j=1; i<pPk->nKeyCol; i++){
  95006. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  95007. pPk->nColumn--;
  95008. }else{
  95009. pPk->aiColumn[j++] = pPk->aiColumn[i];
  95010. }
  95011. }
  95012. pPk->nKeyCol = j;
  95013. }
  95014. assert( pPk!=0 );
  95015. pPk->isCovering = 1;
  95016. if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
  95017. nPk = pPk->nKeyCol;
  95018. /* The root page of the PRIMARY KEY is the table root page */
  95019. pPk->tnum = pTab->tnum;
  95020. /* Update the in-memory representation of all UNIQUE indices by converting
  95021. ** the final rowid column into one or more columns of the PRIMARY KEY.
  95022. */
  95023. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95024. int n;
  95025. if( IsPrimaryKeyIndex(pIdx) ) continue;
  95026. for(i=n=0; i<nPk; i++){
  95027. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  95028. }
  95029. if( n==0 ){
  95030. /* This index is a superset of the primary key */
  95031. pIdx->nColumn = pIdx->nKeyCol;
  95032. continue;
  95033. }
  95034. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  95035. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  95036. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  95037. pIdx->aiColumn[j] = pPk->aiColumn[i];
  95038. pIdx->azColl[j] = pPk->azColl[i];
  95039. j++;
  95040. }
  95041. }
  95042. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  95043. assert( pIdx->nColumn>=j );
  95044. }
  95045. /* Add all table columns to the PRIMARY KEY index
  95046. */
  95047. if( nPk<pTab->nCol ){
  95048. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  95049. for(i=0, j=nPk; i<pTab->nCol; i++){
  95050. if( !hasColumn(pPk->aiColumn, j, i) ){
  95051. assert( j<pPk->nColumn );
  95052. pPk->aiColumn[j] = i;
  95053. pPk->azColl[j] = sqlite3StrBINARY;
  95054. j++;
  95055. }
  95056. }
  95057. assert( pPk->nColumn==j );
  95058. assert( pTab->nCol==j );
  95059. }else{
  95060. pPk->nColumn = pTab->nCol;
  95061. }
  95062. }
  95063. /*
  95064. ** This routine is called to report the final ")" that terminates
  95065. ** a CREATE TABLE statement.
  95066. **
  95067. ** The table structure that other action routines have been building
  95068. ** is added to the internal hash tables, assuming no errors have
  95069. ** occurred.
  95070. **
  95071. ** An entry for the table is made in the master table on disk, unless
  95072. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  95073. ** it means we are reading the sqlite_master table because we just
  95074. ** connected to the database or because the sqlite_master table has
  95075. ** recently changed, so the entry for this table already exists in
  95076. ** the sqlite_master table. We do not want to create it again.
  95077. **
  95078. ** If the pSelect argument is not NULL, it means that this routine
  95079. ** was called to create a table generated from a
  95080. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  95081. ** the new table will match the result set of the SELECT.
  95082. */
  95083. SQLITE_PRIVATE void sqlite3EndTable(
  95084. Parse *pParse, /* Parse context */
  95085. Token *pCons, /* The ',' token after the last column defn. */
  95086. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  95087. u8 tabOpts, /* Extra table options. Usually 0. */
  95088. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  95089. ){
  95090. Table *p; /* The new table */
  95091. sqlite3 *db = pParse->db; /* The database connection */
  95092. int iDb; /* Database in which the table lives */
  95093. Index *pIdx; /* An implied index of the table */
  95094. if( pEnd==0 && pSelect==0 ){
  95095. return;
  95096. }
  95097. assert( !db->mallocFailed );
  95098. p = pParse->pNewTable;
  95099. if( p==0 ) return;
  95100. assert( !db->init.busy || !pSelect );
  95101. /* If the db->init.busy is 1 it means we are reading the SQL off the
  95102. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  95103. ** So do not write to the disk again. Extract the root page number
  95104. ** for the table from the db->init.newTnum field. (The page number
  95105. ** should have been put there by the sqliteOpenCb routine.)
  95106. **
  95107. ** If the root page number is 1, that means this is the sqlite_master
  95108. ** table itself. So mark it read-only.
  95109. */
  95110. if( db->init.busy ){
  95111. p->tnum = db->init.newTnum;
  95112. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  95113. }
  95114. /* Special processing for WITHOUT ROWID Tables */
  95115. if( tabOpts & TF_WithoutRowid ){
  95116. if( (p->tabFlags & TF_Autoincrement) ){
  95117. sqlite3ErrorMsg(pParse,
  95118. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  95119. return;
  95120. }
  95121. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  95122. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  95123. }else{
  95124. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  95125. convertToWithoutRowidTable(pParse, p);
  95126. }
  95127. }
  95128. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  95129. #ifndef SQLITE_OMIT_CHECK
  95130. /* Resolve names in all CHECK constraint expressions.
  95131. */
  95132. if( p->pCheck ){
  95133. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  95134. }
  95135. #endif /* !defined(SQLITE_OMIT_CHECK) */
  95136. /* Estimate the average row size for the table and for all implied indices */
  95137. estimateTableWidth(p);
  95138. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  95139. estimateIndexWidth(pIdx);
  95140. }
  95141. /* If not initializing, then create a record for the new table
  95142. ** in the SQLITE_MASTER table of the database.
  95143. **
  95144. ** If this is a TEMPORARY table, write the entry into the auxiliary
  95145. ** file instead of into the main database file.
  95146. */
  95147. if( !db->init.busy ){
  95148. int n;
  95149. Vdbe *v;
  95150. char *zType; /* "view" or "table" */
  95151. char *zType2; /* "VIEW" or "TABLE" */
  95152. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  95153. v = sqlite3GetVdbe(pParse);
  95154. if( NEVER(v==0) ) return;
  95155. sqlite3VdbeAddOp1(v, OP_Close, 0);
  95156. /*
  95157. ** Initialize zType for the new view or table.
  95158. */
  95159. if( p->pSelect==0 ){
  95160. /* A regular table */
  95161. zType = "table";
  95162. zType2 = "TABLE";
  95163. #ifndef SQLITE_OMIT_VIEW
  95164. }else{
  95165. /* A view */
  95166. zType = "view";
  95167. zType2 = "VIEW";
  95168. #endif
  95169. }
  95170. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  95171. ** statement to populate the new table. The root-page number for the
  95172. ** new table is in register pParse->regRoot.
  95173. **
  95174. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  95175. ** suitable state to query for the column names and types to be used
  95176. ** by the new table.
  95177. **
  95178. ** A shared-cache write-lock is not required to write to the new table,
  95179. ** as a schema-lock must have already been obtained to create it. Since
  95180. ** a schema-lock excludes all other database users, the write-lock would
  95181. ** be redundant.
  95182. */
  95183. if( pSelect ){
  95184. SelectDest dest; /* Where the SELECT should store results */
  95185. int regYield; /* Register holding co-routine entry-point */
  95186. int addrTop; /* Top of the co-routine */
  95187. int regRec; /* A record to be insert into the new table */
  95188. int regRowid; /* Rowid of the next row to insert */
  95189. int addrInsLoop; /* Top of the loop for inserting rows */
  95190. Table *pSelTab; /* A table that describes the SELECT results */
  95191. regYield = ++pParse->nMem;
  95192. regRec = ++pParse->nMem;
  95193. regRowid = ++pParse->nMem;
  95194. assert(pParse->nTab==1);
  95195. sqlite3MayAbort(pParse);
  95196. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  95197. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  95198. pParse->nTab = 2;
  95199. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  95200. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  95201. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  95202. sqlite3Select(pParse, pSelect, &dest);
  95203. sqlite3VdbeEndCoroutine(v, regYield);
  95204. sqlite3VdbeJumpHere(v, addrTop - 1);
  95205. if( pParse->nErr ) return;
  95206. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  95207. if( pSelTab==0 ) return;
  95208. assert( p->aCol==0 );
  95209. p->nCol = pSelTab->nCol;
  95210. p->aCol = pSelTab->aCol;
  95211. pSelTab->nCol = 0;
  95212. pSelTab->aCol = 0;
  95213. sqlite3DeleteTable(db, pSelTab);
  95214. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  95215. VdbeCoverage(v);
  95216. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  95217. sqlite3TableAffinity(v, p, 0);
  95218. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  95219. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  95220. sqlite3VdbeGoto(v, addrInsLoop);
  95221. sqlite3VdbeJumpHere(v, addrInsLoop);
  95222. sqlite3VdbeAddOp1(v, OP_Close, 1);
  95223. }
  95224. /* Compute the complete text of the CREATE statement */
  95225. if( pSelect ){
  95226. zStmt = createTableStmt(db, p);
  95227. }else{
  95228. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  95229. n = (int)(pEnd2->z - pParse->sNameToken.z);
  95230. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  95231. zStmt = sqlite3MPrintf(db,
  95232. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  95233. );
  95234. }
  95235. /* A slot for the record has already been allocated in the
  95236. ** SQLITE_MASTER table. We just need to update that slot with all
  95237. ** the information we've collected.
  95238. */
  95239. sqlite3NestedParse(pParse,
  95240. "UPDATE %Q.%s "
  95241. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  95242. "WHERE rowid=#%d",
  95243. db->aDb[iDb].zDbSName, MASTER_NAME,
  95244. zType,
  95245. p->zName,
  95246. p->zName,
  95247. pParse->regRoot,
  95248. zStmt,
  95249. pParse->regRowid
  95250. );
  95251. sqlite3DbFree(db, zStmt);
  95252. sqlite3ChangeCookie(pParse, iDb);
  95253. #ifndef SQLITE_OMIT_AUTOINCREMENT
  95254. /* Check to see if we need to create an sqlite_sequence table for
  95255. ** keeping track of autoincrement keys.
  95256. */
  95257. if( (p->tabFlags & TF_Autoincrement)!=0 ){
  95258. Db *pDb = &db->aDb[iDb];
  95259. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95260. if( pDb->pSchema->pSeqTab==0 ){
  95261. sqlite3NestedParse(pParse,
  95262. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  95263. pDb->zDbSName
  95264. );
  95265. }
  95266. }
  95267. #endif
  95268. /* Reparse everything to update our internal data structures */
  95269. sqlite3VdbeAddParseSchemaOp(v, iDb,
  95270. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  95271. }
  95272. /* Add the table to the in-memory representation of the database.
  95273. */
  95274. if( db->init.busy ){
  95275. Table *pOld;
  95276. Schema *pSchema = p->pSchema;
  95277. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95278. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  95279. if( pOld ){
  95280. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  95281. sqlite3OomFault(db);
  95282. return;
  95283. }
  95284. pParse->pNewTable = 0;
  95285. db->flags |= SQLITE_InternChanges;
  95286. #ifndef SQLITE_OMIT_ALTERTABLE
  95287. if( !p->pSelect ){
  95288. const char *zName = (const char *)pParse->sNameToken.z;
  95289. int nName;
  95290. assert( !pSelect && pCons && pEnd );
  95291. if( pCons->z==0 ){
  95292. pCons = pEnd;
  95293. }
  95294. nName = (int)((const char *)pCons->z - zName);
  95295. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  95296. }
  95297. #endif
  95298. }
  95299. }
  95300. #ifndef SQLITE_OMIT_VIEW
  95301. /*
  95302. ** The parser calls this routine in order to create a new VIEW
  95303. */
  95304. SQLITE_PRIVATE void sqlite3CreateView(
  95305. Parse *pParse, /* The parsing context */
  95306. Token *pBegin, /* The CREATE token that begins the statement */
  95307. Token *pName1, /* The token that holds the name of the view */
  95308. Token *pName2, /* The token that holds the name of the view */
  95309. ExprList *pCNames, /* Optional list of view column names */
  95310. Select *pSelect, /* A SELECT statement that will become the new view */
  95311. int isTemp, /* TRUE for a TEMPORARY view */
  95312. int noErr /* Suppress error messages if VIEW already exists */
  95313. ){
  95314. Table *p;
  95315. int n;
  95316. const char *z;
  95317. Token sEnd;
  95318. DbFixer sFix;
  95319. Token *pName = 0;
  95320. int iDb;
  95321. sqlite3 *db = pParse->db;
  95322. if( pParse->nVar>0 ){
  95323. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  95324. goto create_view_fail;
  95325. }
  95326. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  95327. p = pParse->pNewTable;
  95328. if( p==0 || pParse->nErr ) goto create_view_fail;
  95329. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  95330. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  95331. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  95332. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  95333. /* Make a copy of the entire SELECT statement that defines the view.
  95334. ** This will force all the Expr.token.z values to be dynamically
  95335. ** allocated rather than point to the input string - which means that
  95336. ** they will persist after the current sqlite3_exec() call returns.
  95337. */
  95338. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  95339. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  95340. if( db->mallocFailed ) goto create_view_fail;
  95341. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  95342. ** the end.
  95343. */
  95344. sEnd = pParse->sLastToken;
  95345. assert( sEnd.z[0]!=0 );
  95346. if( sEnd.z[0]!=';' ){
  95347. sEnd.z += sEnd.n;
  95348. }
  95349. sEnd.n = 0;
  95350. n = (int)(sEnd.z - pBegin->z);
  95351. assert( n>0 );
  95352. z = pBegin->z;
  95353. while( sqlite3Isspace(z[n-1]) ){ n--; }
  95354. sEnd.z = &z[n-1];
  95355. sEnd.n = 1;
  95356. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  95357. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  95358. create_view_fail:
  95359. sqlite3SelectDelete(db, pSelect);
  95360. sqlite3ExprListDelete(db, pCNames);
  95361. return;
  95362. }
  95363. #endif /* SQLITE_OMIT_VIEW */
  95364. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  95365. /*
  95366. ** The Table structure pTable is really a VIEW. Fill in the names of
  95367. ** the columns of the view in the pTable structure. Return the number
  95368. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  95369. */
  95370. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  95371. Table *pSelTab; /* A fake table from which we get the result set */
  95372. Select *pSel; /* Copy of the SELECT that implements the view */
  95373. int nErr = 0; /* Number of errors encountered */
  95374. int n; /* Temporarily holds the number of cursors assigned */
  95375. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  95376. #ifndef SQLITE_OMIT_AUTHORIZATION
  95377. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  95378. #endif
  95379. assert( pTable );
  95380. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95381. if( sqlite3VtabCallConnect(pParse, pTable) ){
  95382. return SQLITE_ERROR;
  95383. }
  95384. if( IsVirtual(pTable) ) return 0;
  95385. #endif
  95386. #ifndef SQLITE_OMIT_VIEW
  95387. /* A positive nCol means the columns names for this view are
  95388. ** already known.
  95389. */
  95390. if( pTable->nCol>0 ) return 0;
  95391. /* A negative nCol is a special marker meaning that we are currently
  95392. ** trying to compute the column names. If we enter this routine with
  95393. ** a negative nCol, it means two or more views form a loop, like this:
  95394. **
  95395. ** CREATE VIEW one AS SELECT * FROM two;
  95396. ** CREATE VIEW two AS SELECT * FROM one;
  95397. **
  95398. ** Actually, the error above is now caught prior to reaching this point.
  95399. ** But the following test is still important as it does come up
  95400. ** in the following:
  95401. **
  95402. ** CREATE TABLE main.ex1(a);
  95403. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  95404. ** SELECT * FROM temp.ex1;
  95405. */
  95406. if( pTable->nCol<0 ){
  95407. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  95408. return 1;
  95409. }
  95410. assert( pTable->nCol>=0 );
  95411. /* If we get this far, it means we need to compute the table names.
  95412. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  95413. ** "*" elements in the results set of the view and will assign cursors
  95414. ** to the elements of the FROM clause. But we do not want these changes
  95415. ** to be permanent. So the computation is done on a copy of the SELECT
  95416. ** statement that defines the view.
  95417. */
  95418. assert( pTable->pSelect );
  95419. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  95420. if( pSel ){
  95421. n = pParse->nTab;
  95422. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  95423. pTable->nCol = -1;
  95424. db->lookaside.bDisable++;
  95425. #ifndef SQLITE_OMIT_AUTHORIZATION
  95426. xAuth = db->xAuth;
  95427. db->xAuth = 0;
  95428. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  95429. db->xAuth = xAuth;
  95430. #else
  95431. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  95432. #endif
  95433. pParse->nTab = n;
  95434. if( pTable->pCheck ){
  95435. /* CREATE VIEW name(arglist) AS ...
  95436. ** The names of the columns in the table are taken from
  95437. ** arglist which is stored in pTable->pCheck. The pCheck field
  95438. ** normally holds CHECK constraints on an ordinary table, but for
  95439. ** a VIEW it holds the list of column names.
  95440. */
  95441. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  95442. &pTable->nCol, &pTable->aCol);
  95443. if( db->mallocFailed==0
  95444. && pParse->nErr==0
  95445. && pTable->nCol==pSel->pEList->nExpr
  95446. ){
  95447. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
  95448. }
  95449. }else if( pSelTab ){
  95450. /* CREATE VIEW name AS... without an argument list. Construct
  95451. ** the column names from the SELECT statement that defines the view.
  95452. */
  95453. assert( pTable->aCol==0 );
  95454. pTable->nCol = pSelTab->nCol;
  95455. pTable->aCol = pSelTab->aCol;
  95456. pSelTab->nCol = 0;
  95457. pSelTab->aCol = 0;
  95458. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  95459. }else{
  95460. pTable->nCol = 0;
  95461. nErr++;
  95462. }
  95463. sqlite3DeleteTable(db, pSelTab);
  95464. sqlite3SelectDelete(db, pSel);
  95465. db->lookaside.bDisable--;
  95466. } else {
  95467. nErr++;
  95468. }
  95469. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  95470. #endif /* SQLITE_OMIT_VIEW */
  95471. return nErr;
  95472. }
  95473. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  95474. #ifndef SQLITE_OMIT_VIEW
  95475. /*
  95476. ** Clear the column names from every VIEW in database idx.
  95477. */
  95478. static void sqliteViewResetAll(sqlite3 *db, int idx){
  95479. HashElem *i;
  95480. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  95481. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  95482. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  95483. Table *pTab = sqliteHashData(i);
  95484. if( pTab->pSelect ){
  95485. sqlite3DeleteColumnNames(db, pTab);
  95486. pTab->aCol = 0;
  95487. pTab->nCol = 0;
  95488. }
  95489. }
  95490. DbClearProperty(db, idx, DB_UnresetViews);
  95491. }
  95492. #else
  95493. # define sqliteViewResetAll(A,B)
  95494. #endif /* SQLITE_OMIT_VIEW */
  95495. /*
  95496. ** This function is called by the VDBE to adjust the internal schema
  95497. ** used by SQLite when the btree layer moves a table root page. The
  95498. ** root-page of a table or index in database iDb has changed from iFrom
  95499. ** to iTo.
  95500. **
  95501. ** Ticket #1728: The symbol table might still contain information
  95502. ** on tables and/or indices that are the process of being deleted.
  95503. ** If you are unlucky, one of those deleted indices or tables might
  95504. ** have the same rootpage number as the real table or index that is
  95505. ** being moved. So we cannot stop searching after the first match
  95506. ** because the first match might be for one of the deleted indices
  95507. ** or tables and not the table/index that is actually being moved.
  95508. ** We must continue looping until all tables and indices with
  95509. ** rootpage==iFrom have been converted to have a rootpage of iTo
  95510. ** in order to be certain that we got the right one.
  95511. */
  95512. #ifndef SQLITE_OMIT_AUTOVACUUM
  95513. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  95514. HashElem *pElem;
  95515. Hash *pHash;
  95516. Db *pDb;
  95517. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95518. pDb = &db->aDb[iDb];
  95519. pHash = &pDb->pSchema->tblHash;
  95520. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  95521. Table *pTab = sqliteHashData(pElem);
  95522. if( pTab->tnum==iFrom ){
  95523. pTab->tnum = iTo;
  95524. }
  95525. }
  95526. pHash = &pDb->pSchema->idxHash;
  95527. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  95528. Index *pIdx = sqliteHashData(pElem);
  95529. if( pIdx->tnum==iFrom ){
  95530. pIdx->tnum = iTo;
  95531. }
  95532. }
  95533. }
  95534. #endif
  95535. /*
  95536. ** Write code to erase the table with root-page iTable from database iDb.
  95537. ** Also write code to modify the sqlite_master table and internal schema
  95538. ** if a root-page of another table is moved by the btree-layer whilst
  95539. ** erasing iTable (this can happen with an auto-vacuum database).
  95540. */
  95541. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  95542. Vdbe *v = sqlite3GetVdbe(pParse);
  95543. int r1 = sqlite3GetTempReg(pParse);
  95544. assert( iTable>1 );
  95545. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  95546. sqlite3MayAbort(pParse);
  95547. #ifndef SQLITE_OMIT_AUTOVACUUM
  95548. /* OP_Destroy stores an in integer r1. If this integer
  95549. ** is non-zero, then it is the root page number of a table moved to
  95550. ** location iTable. The following code modifies the sqlite_master table to
  95551. ** reflect this.
  95552. **
  95553. ** The "#NNN" in the SQL is a special constant that means whatever value
  95554. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  95555. ** token for additional information.
  95556. */
  95557. sqlite3NestedParse(pParse,
  95558. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  95559. pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
  95560. #endif
  95561. sqlite3ReleaseTempReg(pParse, r1);
  95562. }
  95563. /*
  95564. ** Write VDBE code to erase table pTab and all associated indices on disk.
  95565. ** Code to update the sqlite_master tables and internal schema definitions
  95566. ** in case a root-page belonging to another table is moved by the btree layer
  95567. ** is also added (this can happen with an auto-vacuum database).
  95568. */
  95569. static void destroyTable(Parse *pParse, Table *pTab){
  95570. #ifdef SQLITE_OMIT_AUTOVACUUM
  95571. Index *pIdx;
  95572. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  95573. destroyRootPage(pParse, pTab->tnum, iDb);
  95574. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95575. destroyRootPage(pParse, pIdx->tnum, iDb);
  95576. }
  95577. #else
  95578. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  95579. ** is not defined), then it is important to call OP_Destroy on the
  95580. ** table and index root-pages in order, starting with the numerically
  95581. ** largest root-page number. This guarantees that none of the root-pages
  95582. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  95583. ** following were coded:
  95584. **
  95585. ** OP_Destroy 4 0
  95586. ** ...
  95587. ** OP_Destroy 5 0
  95588. **
  95589. ** and root page 5 happened to be the largest root-page number in the
  95590. ** database, then root page 5 would be moved to page 4 by the
  95591. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  95592. ** a free-list page.
  95593. */
  95594. int iTab = pTab->tnum;
  95595. int iDestroyed = 0;
  95596. while( 1 ){
  95597. Index *pIdx;
  95598. int iLargest = 0;
  95599. if( iDestroyed==0 || iTab<iDestroyed ){
  95600. iLargest = iTab;
  95601. }
  95602. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95603. int iIdx = pIdx->tnum;
  95604. assert( pIdx->pSchema==pTab->pSchema );
  95605. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  95606. iLargest = iIdx;
  95607. }
  95608. }
  95609. if( iLargest==0 ){
  95610. return;
  95611. }else{
  95612. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  95613. assert( iDb>=0 && iDb<pParse->db->nDb );
  95614. destroyRootPage(pParse, iLargest, iDb);
  95615. iDestroyed = iLargest;
  95616. }
  95617. }
  95618. #endif
  95619. }
  95620. /*
  95621. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  95622. ** after a DROP INDEX or DROP TABLE command.
  95623. */
  95624. static void sqlite3ClearStatTables(
  95625. Parse *pParse, /* The parsing context */
  95626. int iDb, /* The database number */
  95627. const char *zType, /* "idx" or "tbl" */
  95628. const char *zName /* Name of index or table */
  95629. ){
  95630. int i;
  95631. const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  95632. for(i=1; i<=4; i++){
  95633. char zTab[24];
  95634. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  95635. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  95636. sqlite3NestedParse(pParse,
  95637. "DELETE FROM %Q.%s WHERE %s=%Q",
  95638. zDbName, zTab, zType, zName
  95639. );
  95640. }
  95641. }
  95642. }
  95643. /*
  95644. ** Generate code to drop a table.
  95645. */
  95646. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  95647. Vdbe *v;
  95648. sqlite3 *db = pParse->db;
  95649. Trigger *pTrigger;
  95650. Db *pDb = &db->aDb[iDb];
  95651. v = sqlite3GetVdbe(pParse);
  95652. assert( v!=0 );
  95653. sqlite3BeginWriteOperation(pParse, 1, iDb);
  95654. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95655. if( IsVirtual(pTab) ){
  95656. sqlite3VdbeAddOp0(v, OP_VBegin);
  95657. }
  95658. #endif
  95659. /* Drop all triggers associated with the table being dropped. Code
  95660. ** is generated to remove entries from sqlite_master and/or
  95661. ** sqlite_temp_master if required.
  95662. */
  95663. pTrigger = sqlite3TriggerList(pParse, pTab);
  95664. while( pTrigger ){
  95665. assert( pTrigger->pSchema==pTab->pSchema ||
  95666. pTrigger->pSchema==db->aDb[1].pSchema );
  95667. sqlite3DropTriggerPtr(pParse, pTrigger);
  95668. pTrigger = pTrigger->pNext;
  95669. }
  95670. #ifndef SQLITE_OMIT_AUTOINCREMENT
  95671. /* Remove any entries of the sqlite_sequence table associated with
  95672. ** the table being dropped. This is done before the table is dropped
  95673. ** at the btree level, in case the sqlite_sequence table needs to
  95674. ** move as a result of the drop (can happen in auto-vacuum mode).
  95675. */
  95676. if( pTab->tabFlags & TF_Autoincrement ){
  95677. sqlite3NestedParse(pParse,
  95678. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  95679. pDb->zDbSName, pTab->zName
  95680. );
  95681. }
  95682. #endif
  95683. /* Drop all SQLITE_MASTER table and index entries that refer to the
  95684. ** table. The program name loops through the master table and deletes
  95685. ** every row that refers to a table of the same name as the one being
  95686. ** dropped. Triggers are handled separately because a trigger can be
  95687. ** created in the temp database that refers to a table in another
  95688. ** database.
  95689. */
  95690. sqlite3NestedParse(pParse,
  95691. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  95692. pDb->zDbSName, MASTER_NAME, pTab->zName);
  95693. if( !isView && !IsVirtual(pTab) ){
  95694. destroyTable(pParse, pTab);
  95695. }
  95696. /* Remove the table entry from SQLite's internal schema and modify
  95697. ** the schema cookie.
  95698. */
  95699. if( IsVirtual(pTab) ){
  95700. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  95701. }
  95702. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  95703. sqlite3ChangeCookie(pParse, iDb);
  95704. sqliteViewResetAll(db, iDb);
  95705. }
  95706. /*
  95707. ** This routine is called to do the work of a DROP TABLE statement.
  95708. ** pName is the name of the table to be dropped.
  95709. */
  95710. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  95711. Table *pTab;
  95712. Vdbe *v;
  95713. sqlite3 *db = pParse->db;
  95714. int iDb;
  95715. if( db->mallocFailed ){
  95716. goto exit_drop_table;
  95717. }
  95718. assert( pParse->nErr==0 );
  95719. assert( pName->nSrc==1 );
  95720. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  95721. if( noErr ) db->suppressErr++;
  95722. assert( isView==0 || isView==LOCATE_VIEW );
  95723. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  95724. if( noErr ) db->suppressErr--;
  95725. if( pTab==0 ){
  95726. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  95727. goto exit_drop_table;
  95728. }
  95729. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95730. assert( iDb>=0 && iDb<db->nDb );
  95731. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  95732. ** it is initialized.
  95733. */
  95734. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  95735. goto exit_drop_table;
  95736. }
  95737. #ifndef SQLITE_OMIT_AUTHORIZATION
  95738. {
  95739. int code;
  95740. const char *zTab = SCHEMA_TABLE(iDb);
  95741. const char *zDb = db->aDb[iDb].zDbSName;
  95742. const char *zArg2 = 0;
  95743. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  95744. goto exit_drop_table;
  95745. }
  95746. if( isView ){
  95747. if( !OMIT_TEMPDB && iDb==1 ){
  95748. code = SQLITE_DROP_TEMP_VIEW;
  95749. }else{
  95750. code = SQLITE_DROP_VIEW;
  95751. }
  95752. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95753. }else if( IsVirtual(pTab) ){
  95754. code = SQLITE_DROP_VTABLE;
  95755. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  95756. #endif
  95757. }else{
  95758. if( !OMIT_TEMPDB && iDb==1 ){
  95759. code = SQLITE_DROP_TEMP_TABLE;
  95760. }else{
  95761. code = SQLITE_DROP_TABLE;
  95762. }
  95763. }
  95764. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  95765. goto exit_drop_table;
  95766. }
  95767. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  95768. goto exit_drop_table;
  95769. }
  95770. }
  95771. #endif
  95772. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  95773. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  95774. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  95775. goto exit_drop_table;
  95776. }
  95777. #ifndef SQLITE_OMIT_VIEW
  95778. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  95779. ** on a table.
  95780. */
  95781. if( isView && pTab->pSelect==0 ){
  95782. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  95783. goto exit_drop_table;
  95784. }
  95785. if( !isView && pTab->pSelect ){
  95786. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  95787. goto exit_drop_table;
  95788. }
  95789. #endif
  95790. /* Generate code to remove the table from the master table
  95791. ** on disk.
  95792. */
  95793. v = sqlite3GetVdbe(pParse);
  95794. if( v ){
  95795. sqlite3BeginWriteOperation(pParse, 1, iDb);
  95796. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  95797. sqlite3FkDropTable(pParse, pName, pTab);
  95798. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  95799. }
  95800. exit_drop_table:
  95801. sqlite3SrcListDelete(db, pName);
  95802. }
  95803. /*
  95804. ** This routine is called to create a new foreign key on the table
  95805. ** currently under construction. pFromCol determines which columns
  95806. ** in the current table point to the foreign key. If pFromCol==0 then
  95807. ** connect the key to the last column inserted. pTo is the name of
  95808. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  95809. ** of tables in the parent pTo table. flags contains all
  95810. ** information about the conflict resolution algorithms specified
  95811. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  95812. **
  95813. ** An FKey structure is created and added to the table currently
  95814. ** under construction in the pParse->pNewTable field.
  95815. **
  95816. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  95817. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  95818. */
  95819. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  95820. Parse *pParse, /* Parsing context */
  95821. ExprList *pFromCol, /* Columns in this table that point to other table */
  95822. Token *pTo, /* Name of the other table */
  95823. ExprList *pToCol, /* Columns in the other table */
  95824. int flags /* Conflict resolution algorithms. */
  95825. ){
  95826. sqlite3 *db = pParse->db;
  95827. #ifndef SQLITE_OMIT_FOREIGN_KEY
  95828. FKey *pFKey = 0;
  95829. FKey *pNextTo;
  95830. Table *p = pParse->pNewTable;
  95831. int nByte;
  95832. int i;
  95833. int nCol;
  95834. char *z;
  95835. assert( pTo!=0 );
  95836. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  95837. if( pFromCol==0 ){
  95838. int iCol = p->nCol-1;
  95839. if( NEVER(iCol<0) ) goto fk_end;
  95840. if( pToCol && pToCol->nExpr!=1 ){
  95841. sqlite3ErrorMsg(pParse, "foreign key on %s"
  95842. " should reference only one column of table %T",
  95843. p->aCol[iCol].zName, pTo);
  95844. goto fk_end;
  95845. }
  95846. nCol = 1;
  95847. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  95848. sqlite3ErrorMsg(pParse,
  95849. "number of columns in foreign key does not match the number of "
  95850. "columns in the referenced table");
  95851. goto fk_end;
  95852. }else{
  95853. nCol = pFromCol->nExpr;
  95854. }
  95855. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  95856. if( pToCol ){
  95857. for(i=0; i<pToCol->nExpr; i++){
  95858. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  95859. }
  95860. }
  95861. pFKey = sqlite3DbMallocZero(db, nByte );
  95862. if( pFKey==0 ){
  95863. goto fk_end;
  95864. }
  95865. pFKey->pFrom = p;
  95866. pFKey->pNextFrom = p->pFKey;
  95867. z = (char*)&pFKey->aCol[nCol];
  95868. pFKey->zTo = z;
  95869. memcpy(z, pTo->z, pTo->n);
  95870. z[pTo->n] = 0;
  95871. sqlite3Dequote(z);
  95872. z += pTo->n+1;
  95873. pFKey->nCol = nCol;
  95874. if( pFromCol==0 ){
  95875. pFKey->aCol[0].iFrom = p->nCol-1;
  95876. }else{
  95877. for(i=0; i<nCol; i++){
  95878. int j;
  95879. for(j=0; j<p->nCol; j++){
  95880. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  95881. pFKey->aCol[i].iFrom = j;
  95882. break;
  95883. }
  95884. }
  95885. if( j>=p->nCol ){
  95886. sqlite3ErrorMsg(pParse,
  95887. "unknown column \"%s\" in foreign key definition",
  95888. pFromCol->a[i].zName);
  95889. goto fk_end;
  95890. }
  95891. }
  95892. }
  95893. if( pToCol ){
  95894. for(i=0; i<nCol; i++){
  95895. int n = sqlite3Strlen30(pToCol->a[i].zName);
  95896. pFKey->aCol[i].zCol = z;
  95897. memcpy(z, pToCol->a[i].zName, n);
  95898. z[n] = 0;
  95899. z += n+1;
  95900. }
  95901. }
  95902. pFKey->isDeferred = 0;
  95903. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  95904. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  95905. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  95906. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  95907. pFKey->zTo, (void *)pFKey
  95908. );
  95909. if( pNextTo==pFKey ){
  95910. sqlite3OomFault(db);
  95911. goto fk_end;
  95912. }
  95913. if( pNextTo ){
  95914. assert( pNextTo->pPrevTo==0 );
  95915. pFKey->pNextTo = pNextTo;
  95916. pNextTo->pPrevTo = pFKey;
  95917. }
  95918. /* Link the foreign key to the table as the last step.
  95919. */
  95920. p->pFKey = pFKey;
  95921. pFKey = 0;
  95922. fk_end:
  95923. sqlite3DbFree(db, pFKey);
  95924. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  95925. sqlite3ExprListDelete(db, pFromCol);
  95926. sqlite3ExprListDelete(db, pToCol);
  95927. }
  95928. /*
  95929. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  95930. ** clause is seen as part of a foreign key definition. The isDeferred
  95931. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  95932. ** The behavior of the most recently created foreign key is adjusted
  95933. ** accordingly.
  95934. */
  95935. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  95936. #ifndef SQLITE_OMIT_FOREIGN_KEY
  95937. Table *pTab;
  95938. FKey *pFKey;
  95939. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  95940. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  95941. pFKey->isDeferred = (u8)isDeferred;
  95942. #endif
  95943. }
  95944. /*
  95945. ** Generate code that will erase and refill index *pIdx. This is
  95946. ** used to initialize a newly created index or to recompute the
  95947. ** content of an index in response to a REINDEX command.
  95948. **
  95949. ** if memRootPage is not negative, it means that the index is newly
  95950. ** created. The register specified by memRootPage contains the
  95951. ** root page number of the index. If memRootPage is negative, then
  95952. ** the index already exists and must be cleared before being refilled and
  95953. ** the root page number of the index is taken from pIndex->tnum.
  95954. */
  95955. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  95956. Table *pTab = pIndex->pTable; /* The table that is indexed */
  95957. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  95958. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  95959. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  95960. int addr1; /* Address of top of loop */
  95961. int addr2; /* Address to jump to for next iteration */
  95962. int tnum; /* Root page of index */
  95963. int iPartIdxLabel; /* Jump to this label to skip a row */
  95964. Vdbe *v; /* Generate code into this virtual machine */
  95965. KeyInfo *pKey; /* KeyInfo for index */
  95966. int regRecord; /* Register holding assembled index record */
  95967. sqlite3 *db = pParse->db; /* The database connection */
  95968. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  95969. #ifndef SQLITE_OMIT_AUTHORIZATION
  95970. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  95971. db->aDb[iDb].zDbSName ) ){
  95972. return;
  95973. }
  95974. #endif
  95975. /* Require a write-lock on the table to perform this operation */
  95976. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  95977. v = sqlite3GetVdbe(pParse);
  95978. if( v==0 ) return;
  95979. if( memRootPage>=0 ){
  95980. tnum = memRootPage;
  95981. }else{
  95982. tnum = pIndex->tnum;
  95983. }
  95984. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  95985. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  95986. /* Open the sorter cursor if we are to use one. */
  95987. iSorter = pParse->nTab++;
  95988. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  95989. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  95990. /* Open the table. Loop through all rows of the table, inserting index
  95991. ** records into the sorter. */
  95992. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  95993. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  95994. regRecord = sqlite3GetTempReg(pParse);
  95995. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  95996. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  95997. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  95998. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  95999. sqlite3VdbeJumpHere(v, addr1);
  96000. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  96001. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  96002. (char *)pKey, P4_KEYINFO);
  96003. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  96004. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  96005. if( IsUniqueIndex(pIndex) ){
  96006. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  96007. sqlite3VdbeGoto(v, j2);
  96008. addr2 = sqlite3VdbeCurrentAddr(v);
  96009. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  96010. pIndex->nKeyCol); VdbeCoverage(v);
  96011. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  96012. }else{
  96013. addr2 = sqlite3VdbeCurrentAddr(v);
  96014. }
  96015. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  96016. sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
  96017. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  96018. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  96019. sqlite3ReleaseTempReg(pParse, regRecord);
  96020. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  96021. sqlite3VdbeJumpHere(v, addr1);
  96022. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  96023. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  96024. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  96025. }
  96026. /*
  96027. ** Allocate heap space to hold an Index object with nCol columns.
  96028. **
  96029. ** Increase the allocation size to provide an extra nExtra bytes
  96030. ** of 8-byte aligned space after the Index object and return a
  96031. ** pointer to this extra space in *ppExtra.
  96032. */
  96033. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  96034. sqlite3 *db, /* Database connection */
  96035. i16 nCol, /* Total number of columns in the index */
  96036. int nExtra, /* Number of bytes of extra space to alloc */
  96037. char **ppExtra /* Pointer to the "extra" space */
  96038. ){
  96039. Index *p; /* Allocated index object */
  96040. int nByte; /* Bytes of space for Index object + arrays */
  96041. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  96042. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  96043. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  96044. sizeof(i16)*nCol + /* Index.aiColumn */
  96045. sizeof(u8)*nCol); /* Index.aSortOrder */
  96046. p = sqlite3DbMallocZero(db, nByte + nExtra);
  96047. if( p ){
  96048. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  96049. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  96050. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  96051. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  96052. p->aSortOrder = (u8*)pExtra;
  96053. p->nColumn = nCol;
  96054. p->nKeyCol = nCol - 1;
  96055. *ppExtra = ((char*)p) + nByte;
  96056. }
  96057. return p;
  96058. }
  96059. /*
  96060. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  96061. ** and pTblList is the name of the table that is to be indexed. Both will
  96062. ** be NULL for a primary key or an index that is created to satisfy a
  96063. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  96064. ** as the table to be indexed. pParse->pNewTable is a table that is
  96065. ** currently being constructed by a CREATE TABLE statement.
  96066. **
  96067. ** pList is a list of columns to be indexed. pList will be NULL if this
  96068. ** is a primary key or unique-constraint on the most recent column added
  96069. ** to the table currently under construction.
  96070. */
  96071. SQLITE_PRIVATE void sqlite3CreateIndex(
  96072. Parse *pParse, /* All information about this parse */
  96073. Token *pName1, /* First part of index name. May be NULL */
  96074. Token *pName2, /* Second part of index name. May be NULL */
  96075. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  96076. ExprList *pList, /* A list of columns to be indexed */
  96077. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  96078. Token *pStart, /* The CREATE token that begins this statement */
  96079. Expr *pPIWhere, /* WHERE clause for partial indices */
  96080. int sortOrder, /* Sort order of primary key when pList==NULL */
  96081. int ifNotExist, /* Omit error if index already exists */
  96082. u8 idxType /* The index type */
  96083. ){
  96084. Table *pTab = 0; /* Table to be indexed */
  96085. Index *pIndex = 0; /* The index to be created */
  96086. char *zName = 0; /* Name of the index */
  96087. int nName; /* Number of characters in zName */
  96088. int i, j;
  96089. DbFixer sFix; /* For assigning database names to pTable */
  96090. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  96091. sqlite3 *db = pParse->db;
  96092. Db *pDb; /* The specific table containing the indexed database */
  96093. int iDb; /* Index of the database that is being written */
  96094. Token *pName = 0; /* Unqualified name of the index to create */
  96095. struct ExprList_item *pListItem; /* For looping over pList */
  96096. int nExtra = 0; /* Space allocated for zExtra[] */
  96097. int nExtraCol; /* Number of extra columns needed */
  96098. char *zExtra = 0; /* Extra space after the Index object */
  96099. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  96100. if( db->mallocFailed || pParse->nErr>0 ){
  96101. goto exit_create_index;
  96102. }
  96103. if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
  96104. goto exit_create_index;
  96105. }
  96106. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  96107. goto exit_create_index;
  96108. }
  96109. /*
  96110. ** Find the table that is to be indexed. Return early if not found.
  96111. */
  96112. if( pTblName!=0 ){
  96113. /* Use the two-part index name to determine the database
  96114. ** to search for the table. 'Fix' the table name to this db
  96115. ** before looking up the table.
  96116. */
  96117. assert( pName1 && pName2 );
  96118. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  96119. if( iDb<0 ) goto exit_create_index;
  96120. assert( pName && pName->z );
  96121. #ifndef SQLITE_OMIT_TEMPDB
  96122. /* If the index name was unqualified, check if the table
  96123. ** is a temp table. If so, set the database to 1. Do not do this
  96124. ** if initialising a database schema.
  96125. */
  96126. if( !db->init.busy ){
  96127. pTab = sqlite3SrcListLookup(pParse, pTblName);
  96128. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  96129. iDb = 1;
  96130. }
  96131. }
  96132. #endif
  96133. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  96134. if( sqlite3FixSrcList(&sFix, pTblName) ){
  96135. /* Because the parser constructs pTblName from a single identifier,
  96136. ** sqlite3FixSrcList can never fail. */
  96137. assert(0);
  96138. }
  96139. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  96140. assert( db->mallocFailed==0 || pTab==0 );
  96141. if( pTab==0 ) goto exit_create_index;
  96142. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  96143. sqlite3ErrorMsg(pParse,
  96144. "cannot create a TEMP index on non-TEMP table \"%s\"",
  96145. pTab->zName);
  96146. goto exit_create_index;
  96147. }
  96148. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  96149. }else{
  96150. assert( pName==0 );
  96151. assert( pStart==0 );
  96152. pTab = pParse->pNewTable;
  96153. if( !pTab ) goto exit_create_index;
  96154. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  96155. }
  96156. pDb = &db->aDb[iDb];
  96157. assert( pTab!=0 );
  96158. assert( pParse->nErr==0 );
  96159. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  96160. && db->init.busy==0
  96161. #if SQLITE_USER_AUTHENTICATION
  96162. && sqlite3UserAuthTable(pTab->zName)==0
  96163. #endif
  96164. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  96165. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  96166. goto exit_create_index;
  96167. }
  96168. #ifndef SQLITE_OMIT_VIEW
  96169. if( pTab->pSelect ){
  96170. sqlite3ErrorMsg(pParse, "views may not be indexed");
  96171. goto exit_create_index;
  96172. }
  96173. #endif
  96174. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96175. if( IsVirtual(pTab) ){
  96176. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  96177. goto exit_create_index;
  96178. }
  96179. #endif
  96180. /*
  96181. ** Find the name of the index. Make sure there is not already another
  96182. ** index or table with the same name.
  96183. **
  96184. ** Exception: If we are reading the names of permanent indices from the
  96185. ** sqlite_master table (because some other process changed the schema) and
  96186. ** one of the index names collides with the name of a temporary table or
  96187. ** index, then we will continue to process this index.
  96188. **
  96189. ** If pName==0 it means that we are
  96190. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  96191. ** own name.
  96192. */
  96193. if( pName ){
  96194. zName = sqlite3NameFromToken(db, pName);
  96195. if( zName==0 ) goto exit_create_index;
  96196. assert( pName->z!=0 );
  96197. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  96198. goto exit_create_index;
  96199. }
  96200. if( !db->init.busy ){
  96201. if( sqlite3FindTable(db, zName, 0)!=0 ){
  96202. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  96203. goto exit_create_index;
  96204. }
  96205. }
  96206. if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  96207. if( !ifNotExist ){
  96208. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  96209. }else{
  96210. assert( !db->init.busy );
  96211. sqlite3CodeVerifySchema(pParse, iDb);
  96212. }
  96213. goto exit_create_index;
  96214. }
  96215. }else{
  96216. int n;
  96217. Index *pLoop;
  96218. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  96219. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  96220. if( zName==0 ){
  96221. goto exit_create_index;
  96222. }
  96223. /* Automatic index names generated from within sqlite3_declare_vtab()
  96224. ** must have names that are distinct from normal automatic index names.
  96225. ** The following statement converts "sqlite3_autoindex..." into
  96226. ** "sqlite3_butoindex..." in order to make the names distinct.
  96227. ** The "vtab_err.test" test demonstrates the need of this statement. */
  96228. if( IN_DECLARE_VTAB ) zName[7]++;
  96229. }
  96230. /* Check for authorization to create an index.
  96231. */
  96232. #ifndef SQLITE_OMIT_AUTHORIZATION
  96233. {
  96234. const char *zDb = pDb->zDbSName;
  96235. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  96236. goto exit_create_index;
  96237. }
  96238. i = SQLITE_CREATE_INDEX;
  96239. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  96240. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  96241. goto exit_create_index;
  96242. }
  96243. }
  96244. #endif
  96245. /* If pList==0, it means this routine was called to make a primary
  96246. ** key out of the last column added to the table under construction.
  96247. ** So create a fake list to simulate this.
  96248. */
  96249. if( pList==0 ){
  96250. Token prevCol;
  96251. sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
  96252. pList = sqlite3ExprListAppend(pParse, 0,
  96253. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  96254. if( pList==0 ) goto exit_create_index;
  96255. assert( pList->nExpr==1 );
  96256. sqlite3ExprListSetSortOrder(pList, sortOrder);
  96257. }else{
  96258. sqlite3ExprListCheckLength(pParse, pList, "index");
  96259. }
  96260. /* Figure out how many bytes of space are required to store explicitly
  96261. ** specified collation sequence names.
  96262. */
  96263. for(i=0; i<pList->nExpr; i++){
  96264. Expr *pExpr = pList->a[i].pExpr;
  96265. assert( pExpr!=0 );
  96266. if( pExpr->op==TK_COLLATE ){
  96267. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  96268. }
  96269. }
  96270. /*
  96271. ** Allocate the index structure.
  96272. */
  96273. nName = sqlite3Strlen30(zName);
  96274. nExtraCol = pPk ? pPk->nKeyCol : 1;
  96275. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  96276. nName + nExtra + 1, &zExtra);
  96277. if( db->mallocFailed ){
  96278. goto exit_create_index;
  96279. }
  96280. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  96281. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  96282. pIndex->zName = zExtra;
  96283. zExtra += nName + 1;
  96284. memcpy(pIndex->zName, zName, nName+1);
  96285. pIndex->pTable = pTab;
  96286. pIndex->onError = (u8)onError;
  96287. pIndex->uniqNotNull = onError!=OE_None;
  96288. pIndex->idxType = idxType;
  96289. pIndex->pSchema = db->aDb[iDb].pSchema;
  96290. pIndex->nKeyCol = pList->nExpr;
  96291. if( pPIWhere ){
  96292. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  96293. pIndex->pPartIdxWhere = pPIWhere;
  96294. pPIWhere = 0;
  96295. }
  96296. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  96297. /* Check to see if we should honor DESC requests on index columns
  96298. */
  96299. if( pDb->pSchema->file_format>=4 ){
  96300. sortOrderMask = -1; /* Honor DESC */
  96301. }else{
  96302. sortOrderMask = 0; /* Ignore DESC */
  96303. }
  96304. /* Analyze the list of expressions that form the terms of the index and
  96305. ** report any errors. In the common case where the expression is exactly
  96306. ** a table column, store that column in aiColumn[]. For general expressions,
  96307. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  96308. **
  96309. ** TODO: Issue a warning if two or more columns of the index are identical.
  96310. ** TODO: Issue a warning if the table primary key is used as part of the
  96311. ** index key.
  96312. */
  96313. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  96314. Expr *pCExpr; /* The i-th index expression */
  96315. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  96316. const char *zColl; /* Collation sequence name */
  96317. sqlite3StringToId(pListItem->pExpr);
  96318. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  96319. if( pParse->nErr ) goto exit_create_index;
  96320. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  96321. if( pCExpr->op!=TK_COLUMN ){
  96322. if( pTab==pParse->pNewTable ){
  96323. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  96324. "UNIQUE constraints");
  96325. goto exit_create_index;
  96326. }
  96327. if( pIndex->aColExpr==0 ){
  96328. ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
  96329. pIndex->aColExpr = pCopy;
  96330. if( !db->mallocFailed ){
  96331. assert( pCopy!=0 );
  96332. pListItem = &pCopy->a[i];
  96333. }
  96334. }
  96335. j = XN_EXPR;
  96336. pIndex->aiColumn[i] = XN_EXPR;
  96337. pIndex->uniqNotNull = 0;
  96338. }else{
  96339. j = pCExpr->iColumn;
  96340. assert( j<=0x7fff );
  96341. if( j<0 ){
  96342. j = pTab->iPKey;
  96343. }else if( pTab->aCol[j].notNull==0 ){
  96344. pIndex->uniqNotNull = 0;
  96345. }
  96346. pIndex->aiColumn[i] = (i16)j;
  96347. }
  96348. zColl = 0;
  96349. if( pListItem->pExpr->op==TK_COLLATE ){
  96350. int nColl;
  96351. zColl = pListItem->pExpr->u.zToken;
  96352. nColl = sqlite3Strlen30(zColl) + 1;
  96353. assert( nExtra>=nColl );
  96354. memcpy(zExtra, zColl, nColl);
  96355. zColl = zExtra;
  96356. zExtra += nColl;
  96357. nExtra -= nColl;
  96358. }else if( j>=0 ){
  96359. zColl = pTab->aCol[j].zColl;
  96360. }
  96361. if( !zColl ) zColl = sqlite3StrBINARY;
  96362. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  96363. goto exit_create_index;
  96364. }
  96365. pIndex->azColl[i] = zColl;
  96366. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  96367. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  96368. }
  96369. /* Append the table key to the end of the index. For WITHOUT ROWID
  96370. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  96371. ** normal tables (when pPk==0) this will be the rowid.
  96372. */
  96373. if( pPk ){
  96374. for(j=0; j<pPk->nKeyCol; j++){
  96375. int x = pPk->aiColumn[j];
  96376. assert( x>=0 );
  96377. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  96378. pIndex->nColumn--;
  96379. }else{
  96380. pIndex->aiColumn[i] = x;
  96381. pIndex->azColl[i] = pPk->azColl[j];
  96382. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  96383. i++;
  96384. }
  96385. }
  96386. assert( i==pIndex->nColumn );
  96387. }else{
  96388. pIndex->aiColumn[i] = XN_ROWID;
  96389. pIndex->azColl[i] = sqlite3StrBINARY;
  96390. }
  96391. sqlite3DefaultRowEst(pIndex);
  96392. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  96393. /* If this index contains every column of its table, then mark
  96394. ** it as a covering index */
  96395. assert( HasRowid(pTab)
  96396. || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
  96397. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  96398. pIndex->isCovering = 1;
  96399. for(j=0; j<pTab->nCol; j++){
  96400. if( j==pTab->iPKey ) continue;
  96401. if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
  96402. pIndex->isCovering = 0;
  96403. break;
  96404. }
  96405. }
  96406. if( pTab==pParse->pNewTable ){
  96407. /* This routine has been called to create an automatic index as a
  96408. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  96409. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  96410. ** i.e. one of:
  96411. **
  96412. ** CREATE TABLE t(x PRIMARY KEY, y);
  96413. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  96414. **
  96415. ** Either way, check to see if the table already has such an index. If
  96416. ** so, don't bother creating this one. This only applies to
  96417. ** automatically created indices. Users can do as they wish with
  96418. ** explicit indices.
  96419. **
  96420. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  96421. ** (and thus suppressing the second one) even if they have different
  96422. ** sort orders.
  96423. **
  96424. ** If there are different collating sequences or if the columns of
  96425. ** the constraint occur in different orders, then the constraints are
  96426. ** considered distinct and both result in separate indices.
  96427. */
  96428. Index *pIdx;
  96429. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  96430. int k;
  96431. assert( IsUniqueIndex(pIdx) );
  96432. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  96433. assert( IsUniqueIndex(pIndex) );
  96434. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  96435. for(k=0; k<pIdx->nKeyCol; k++){
  96436. const char *z1;
  96437. const char *z2;
  96438. assert( pIdx->aiColumn[k]>=0 );
  96439. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  96440. z1 = pIdx->azColl[k];
  96441. z2 = pIndex->azColl[k];
  96442. if( sqlite3StrICmp(z1, z2) ) break;
  96443. }
  96444. if( k==pIdx->nKeyCol ){
  96445. if( pIdx->onError!=pIndex->onError ){
  96446. /* This constraint creates the same index as a previous
  96447. ** constraint specified somewhere in the CREATE TABLE statement.
  96448. ** However the ON CONFLICT clauses are different. If both this
  96449. ** constraint and the previous equivalent constraint have explicit
  96450. ** ON CONFLICT clauses this is an error. Otherwise, use the
  96451. ** explicitly specified behavior for the index.
  96452. */
  96453. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  96454. sqlite3ErrorMsg(pParse,
  96455. "conflicting ON CONFLICT clauses specified", 0);
  96456. }
  96457. if( pIdx->onError==OE_Default ){
  96458. pIdx->onError = pIndex->onError;
  96459. }
  96460. }
  96461. if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
  96462. goto exit_create_index;
  96463. }
  96464. }
  96465. }
  96466. /* Link the new Index structure to its table and to the other
  96467. ** in-memory database structures.
  96468. */
  96469. assert( pParse->nErr==0 );
  96470. if( db->init.busy ){
  96471. Index *p;
  96472. assert( !IN_DECLARE_VTAB );
  96473. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  96474. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  96475. pIndex->zName, pIndex);
  96476. if( p ){
  96477. assert( p==pIndex ); /* Malloc must have failed */
  96478. sqlite3OomFault(db);
  96479. goto exit_create_index;
  96480. }
  96481. db->flags |= SQLITE_InternChanges;
  96482. if( pTblName!=0 ){
  96483. pIndex->tnum = db->init.newTnum;
  96484. }
  96485. }
  96486. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  96487. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  96488. ** emit code to allocate the index rootpage on disk and make an entry for
  96489. ** the index in the sqlite_master table and populate the index with
  96490. ** content. But, do not do this if we are simply reading the sqlite_master
  96491. ** table to parse the schema, or if this index is the PRIMARY KEY index
  96492. ** of a WITHOUT ROWID table.
  96493. **
  96494. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  96495. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  96496. ** has just been created, it contains no data and the index initialization
  96497. ** step can be skipped.
  96498. */
  96499. else if( HasRowid(pTab) || pTblName!=0 ){
  96500. Vdbe *v;
  96501. char *zStmt;
  96502. int iMem = ++pParse->nMem;
  96503. v = sqlite3GetVdbe(pParse);
  96504. if( v==0 ) goto exit_create_index;
  96505. sqlite3BeginWriteOperation(pParse, 1, iDb);
  96506. /* Create the rootpage for the index using CreateIndex. But before
  96507. ** doing so, code a Noop instruction and store its address in
  96508. ** Index.tnum. This is required in case this index is actually a
  96509. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  96510. ** that case the convertToWithoutRowidTable() routine will replace
  96511. ** the Noop with a Goto to jump over the VDBE code generated below. */
  96512. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  96513. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  96514. /* Gather the complete text of the CREATE INDEX statement into
  96515. ** the zStmt variable
  96516. */
  96517. if( pStart ){
  96518. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  96519. if( pName->z[n-1]==';' ) n--;
  96520. /* A named index with an explicit CREATE INDEX statement */
  96521. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  96522. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  96523. }else{
  96524. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  96525. /* zStmt = sqlite3MPrintf(""); */
  96526. zStmt = 0;
  96527. }
  96528. /* Add an entry in sqlite_master for this index
  96529. */
  96530. sqlite3NestedParse(pParse,
  96531. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  96532. db->aDb[iDb].zDbSName, MASTER_NAME,
  96533. pIndex->zName,
  96534. pTab->zName,
  96535. iMem,
  96536. zStmt
  96537. );
  96538. sqlite3DbFree(db, zStmt);
  96539. /* Fill the index with data and reparse the schema. Code an OP_Expire
  96540. ** to invalidate all pre-compiled statements.
  96541. */
  96542. if( pTblName ){
  96543. sqlite3RefillIndex(pParse, pIndex, iMem);
  96544. sqlite3ChangeCookie(pParse, iDb);
  96545. sqlite3VdbeAddParseSchemaOp(v, iDb,
  96546. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  96547. sqlite3VdbeAddOp0(v, OP_Expire);
  96548. }
  96549. sqlite3VdbeJumpHere(v, pIndex->tnum);
  96550. }
  96551. /* When adding an index to the list of indices for a table, make
  96552. ** sure all indices labeled OE_Replace come after all those labeled
  96553. ** OE_Ignore. This is necessary for the correct constraint check
  96554. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  96555. ** UPDATE and INSERT statements.
  96556. */
  96557. if( db->init.busy || pTblName==0 ){
  96558. if( onError!=OE_Replace || pTab->pIndex==0
  96559. || pTab->pIndex->onError==OE_Replace){
  96560. pIndex->pNext = pTab->pIndex;
  96561. pTab->pIndex = pIndex;
  96562. }else{
  96563. Index *pOther = pTab->pIndex;
  96564. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  96565. pOther = pOther->pNext;
  96566. }
  96567. pIndex->pNext = pOther->pNext;
  96568. pOther->pNext = pIndex;
  96569. }
  96570. pIndex = 0;
  96571. }
  96572. /* Clean up before exiting */
  96573. exit_create_index:
  96574. if( pIndex ) freeIndex(db, pIndex);
  96575. sqlite3ExprDelete(db, pPIWhere);
  96576. sqlite3ExprListDelete(db, pList);
  96577. sqlite3SrcListDelete(db, pTblName);
  96578. sqlite3DbFree(db, zName);
  96579. }
  96580. /*
  96581. ** Fill the Index.aiRowEst[] array with default information - information
  96582. ** to be used when we have not run the ANALYZE command.
  96583. **
  96584. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  96585. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  96586. ** number of rows in the table that match any particular value of the
  96587. ** first column of the index. aiRowEst[2] is an estimate of the number
  96588. ** of rows that match any particular combination of the first 2 columns
  96589. ** of the index. And so forth. It must always be the case that
  96590. *
  96591. ** aiRowEst[N]<=aiRowEst[N-1]
  96592. ** aiRowEst[N]>=1
  96593. **
  96594. ** Apart from that, we have little to go on besides intuition as to
  96595. ** how aiRowEst[] should be initialized. The numbers generated here
  96596. ** are based on typical values found in actual indices.
  96597. */
  96598. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  96599. /* 10, 9, 8, 7, 6 */
  96600. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  96601. LogEst *a = pIdx->aiRowLogEst;
  96602. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  96603. int i;
  96604. /* Indexes with default row estimates should not have stat1 data */
  96605. assert( !pIdx->hasStat1 );
  96606. /* Set the first entry (number of rows in the index) to the estimated
  96607. ** number of rows in the table, or half the number of rows in the table
  96608. ** for a partial index. But do not let the estimate drop below 10. */
  96609. a[0] = pIdx->pTable->nRowLogEst;
  96610. if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
  96611. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  96612. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  96613. ** 6 and each subsequent value (if any) is 5. */
  96614. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  96615. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  96616. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  96617. }
  96618. assert( 0==sqlite3LogEst(1) );
  96619. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  96620. }
  96621. /*
  96622. ** This routine will drop an existing named index. This routine
  96623. ** implements the DROP INDEX statement.
  96624. */
  96625. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  96626. Index *pIndex;
  96627. Vdbe *v;
  96628. sqlite3 *db = pParse->db;
  96629. int iDb;
  96630. assert( pParse->nErr==0 ); /* Never called with prior errors */
  96631. if( db->mallocFailed ){
  96632. goto exit_drop_index;
  96633. }
  96634. assert( pName->nSrc==1 );
  96635. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  96636. goto exit_drop_index;
  96637. }
  96638. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  96639. if( pIndex==0 ){
  96640. if( !ifExists ){
  96641. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  96642. }else{
  96643. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  96644. }
  96645. pParse->checkSchema = 1;
  96646. goto exit_drop_index;
  96647. }
  96648. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  96649. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  96650. "or PRIMARY KEY constraint cannot be dropped", 0);
  96651. goto exit_drop_index;
  96652. }
  96653. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  96654. #ifndef SQLITE_OMIT_AUTHORIZATION
  96655. {
  96656. int code = SQLITE_DROP_INDEX;
  96657. Table *pTab = pIndex->pTable;
  96658. const char *zDb = db->aDb[iDb].zDbSName;
  96659. const char *zTab = SCHEMA_TABLE(iDb);
  96660. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  96661. goto exit_drop_index;
  96662. }
  96663. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  96664. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  96665. goto exit_drop_index;
  96666. }
  96667. }
  96668. #endif
  96669. /* Generate code to remove the index and from the master table */
  96670. v = sqlite3GetVdbe(pParse);
  96671. if( v ){
  96672. sqlite3BeginWriteOperation(pParse, 1, iDb);
  96673. sqlite3NestedParse(pParse,
  96674. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  96675. db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
  96676. );
  96677. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  96678. sqlite3ChangeCookie(pParse, iDb);
  96679. destroyRootPage(pParse, pIndex->tnum, iDb);
  96680. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  96681. }
  96682. exit_drop_index:
  96683. sqlite3SrcListDelete(db, pName);
  96684. }
  96685. /*
  96686. ** pArray is a pointer to an array of objects. Each object in the
  96687. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  96688. ** to extend the array so that there is space for a new object at the end.
  96689. **
  96690. ** When this function is called, *pnEntry contains the current size of
  96691. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  96692. ** in total).
  96693. **
  96694. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  96695. ** space allocated for the new object is zeroed, *pnEntry updated to
  96696. ** reflect the new size of the array and a pointer to the new allocation
  96697. ** returned. *pIdx is set to the index of the new array entry in this case.
  96698. **
  96699. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  96700. ** unchanged and a copy of pArray returned.
  96701. */
  96702. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  96703. sqlite3 *db, /* Connection to notify of malloc failures */
  96704. void *pArray, /* Array of objects. Might be reallocated */
  96705. int szEntry, /* Size of each object in the array */
  96706. int *pnEntry, /* Number of objects currently in use */
  96707. int *pIdx /* Write the index of a new slot here */
  96708. ){
  96709. char *z;
  96710. int n = *pnEntry;
  96711. if( (n & (n-1))==0 ){
  96712. int sz = (n==0) ? 1 : 2*n;
  96713. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  96714. if( pNew==0 ){
  96715. *pIdx = -1;
  96716. return pArray;
  96717. }
  96718. pArray = pNew;
  96719. }
  96720. z = (char*)pArray;
  96721. memset(&z[n * szEntry], 0, szEntry);
  96722. *pIdx = n;
  96723. ++*pnEntry;
  96724. return pArray;
  96725. }
  96726. /*
  96727. ** Append a new element to the given IdList. Create a new IdList if
  96728. ** need be.
  96729. **
  96730. ** A new IdList is returned, or NULL if malloc() fails.
  96731. */
  96732. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  96733. int i;
  96734. if( pList==0 ){
  96735. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  96736. if( pList==0 ) return 0;
  96737. }
  96738. pList->a = sqlite3ArrayAllocate(
  96739. db,
  96740. pList->a,
  96741. sizeof(pList->a[0]),
  96742. &pList->nId,
  96743. &i
  96744. );
  96745. if( i<0 ){
  96746. sqlite3IdListDelete(db, pList);
  96747. return 0;
  96748. }
  96749. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  96750. return pList;
  96751. }
  96752. /*
  96753. ** Delete an IdList.
  96754. */
  96755. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  96756. int i;
  96757. if( pList==0 ) return;
  96758. for(i=0; i<pList->nId; i++){
  96759. sqlite3DbFree(db, pList->a[i].zName);
  96760. }
  96761. sqlite3DbFree(db, pList->a);
  96762. sqlite3DbFreeNN(db, pList);
  96763. }
  96764. /*
  96765. ** Return the index in pList of the identifier named zId. Return -1
  96766. ** if not found.
  96767. */
  96768. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  96769. int i;
  96770. if( pList==0 ) return -1;
  96771. for(i=0; i<pList->nId; i++){
  96772. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  96773. }
  96774. return -1;
  96775. }
  96776. /*
  96777. ** Expand the space allocated for the given SrcList object by
  96778. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  96779. ** New slots are zeroed.
  96780. **
  96781. ** For example, suppose a SrcList initially contains two entries: A,B.
  96782. ** To append 3 new entries onto the end, do this:
  96783. **
  96784. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  96785. **
  96786. ** After the call above it would contain: A, B, nil, nil, nil.
  96787. ** If the iStart argument had been 1 instead of 2, then the result
  96788. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  96789. ** the iStart value would be 0. The result then would
  96790. ** be: nil, nil, nil, A, B.
  96791. **
  96792. ** If a memory allocation fails the SrcList is unchanged. The
  96793. ** db->mallocFailed flag will be set to true.
  96794. */
  96795. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  96796. sqlite3 *db, /* Database connection to notify of OOM errors */
  96797. SrcList *pSrc, /* The SrcList to be enlarged */
  96798. int nExtra, /* Number of new slots to add to pSrc->a[] */
  96799. int iStart /* Index in pSrc->a[] of first new slot */
  96800. ){
  96801. int i;
  96802. /* Sanity checking on calling parameters */
  96803. assert( iStart>=0 );
  96804. assert( nExtra>=1 );
  96805. assert( pSrc!=0 );
  96806. assert( iStart<=pSrc->nSrc );
  96807. /* Allocate additional space if needed */
  96808. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  96809. SrcList *pNew;
  96810. int nAlloc = pSrc->nSrc*2+nExtra;
  96811. int nGot;
  96812. pNew = sqlite3DbRealloc(db, pSrc,
  96813. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  96814. if( pNew==0 ){
  96815. assert( db->mallocFailed );
  96816. return pSrc;
  96817. }
  96818. pSrc = pNew;
  96819. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  96820. pSrc->nAlloc = nGot;
  96821. }
  96822. /* Move existing slots that come after the newly inserted slots
  96823. ** out of the way */
  96824. for(i=pSrc->nSrc-1; i>=iStart; i--){
  96825. pSrc->a[i+nExtra] = pSrc->a[i];
  96826. }
  96827. pSrc->nSrc += nExtra;
  96828. /* Zero the newly allocated slots */
  96829. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  96830. for(i=iStart; i<iStart+nExtra; i++){
  96831. pSrc->a[i].iCursor = -1;
  96832. }
  96833. /* Return a pointer to the enlarged SrcList */
  96834. return pSrc;
  96835. }
  96836. /*
  96837. ** Append a new table name to the given SrcList. Create a new SrcList if
  96838. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  96839. **
  96840. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  96841. ** SrcList might be the same as the SrcList that was input or it might be
  96842. ** a new one. If an OOM error does occurs, then the prior value of pList
  96843. ** that is input to this routine is automatically freed.
  96844. **
  96845. ** If pDatabase is not null, it means that the table has an optional
  96846. ** database name prefix. Like this: "database.table". The pDatabase
  96847. ** points to the table name and the pTable points to the database name.
  96848. ** The SrcList.a[].zName field is filled with the table name which might
  96849. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  96850. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  96851. ** or with NULL if no database is specified.
  96852. **
  96853. ** In other words, if call like this:
  96854. **
  96855. ** sqlite3SrcListAppend(D,A,B,0);
  96856. **
  96857. ** Then B is a table name and the database name is unspecified. If called
  96858. ** like this:
  96859. **
  96860. ** sqlite3SrcListAppend(D,A,B,C);
  96861. **
  96862. ** Then C is the table name and B is the database name. If C is defined
  96863. ** then so is B. In other words, we never have a case where:
  96864. **
  96865. ** sqlite3SrcListAppend(D,A,0,C);
  96866. **
  96867. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  96868. ** before being added to the SrcList.
  96869. */
  96870. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  96871. sqlite3 *db, /* Connection to notify of malloc failures */
  96872. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  96873. Token *pTable, /* Table to append */
  96874. Token *pDatabase /* Database of the table */
  96875. ){
  96876. struct SrcList_item *pItem;
  96877. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  96878. assert( db!=0 );
  96879. if( pList==0 ){
  96880. pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
  96881. if( pList==0 ) return 0;
  96882. pList->nAlloc = 1;
  96883. pList->nSrc = 1;
  96884. memset(&pList->a[0], 0, sizeof(pList->a[0]));
  96885. pList->a[0].iCursor = -1;
  96886. }else{
  96887. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  96888. }
  96889. if( db->mallocFailed ){
  96890. sqlite3SrcListDelete(db, pList);
  96891. return 0;
  96892. }
  96893. pItem = &pList->a[pList->nSrc-1];
  96894. if( pDatabase && pDatabase->z==0 ){
  96895. pDatabase = 0;
  96896. }
  96897. if( pDatabase ){
  96898. Token *pTemp = pDatabase;
  96899. pDatabase = pTable;
  96900. pTable = pTemp;
  96901. }
  96902. pItem->zName = sqlite3NameFromToken(db, pTable);
  96903. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  96904. return pList;
  96905. }
  96906. /*
  96907. ** Assign VdbeCursor index numbers to all tables in a SrcList
  96908. */
  96909. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  96910. int i;
  96911. struct SrcList_item *pItem;
  96912. assert(pList || pParse->db->mallocFailed );
  96913. if( pList ){
  96914. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  96915. if( pItem->iCursor>=0 ) break;
  96916. pItem->iCursor = pParse->nTab++;
  96917. if( pItem->pSelect ){
  96918. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  96919. }
  96920. }
  96921. }
  96922. }
  96923. /*
  96924. ** Delete an entire SrcList including all its substructure.
  96925. */
  96926. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  96927. int i;
  96928. struct SrcList_item *pItem;
  96929. if( pList==0 ) return;
  96930. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  96931. sqlite3DbFree(db, pItem->zDatabase);
  96932. sqlite3DbFree(db, pItem->zName);
  96933. sqlite3DbFree(db, pItem->zAlias);
  96934. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  96935. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  96936. sqlite3DeleteTable(db, pItem->pTab);
  96937. sqlite3SelectDelete(db, pItem->pSelect);
  96938. sqlite3ExprDelete(db, pItem->pOn);
  96939. sqlite3IdListDelete(db, pItem->pUsing);
  96940. }
  96941. sqlite3DbFreeNN(db, pList);
  96942. }
  96943. /*
  96944. ** This routine is called by the parser to add a new term to the
  96945. ** end of a growing FROM clause. The "p" parameter is the part of
  96946. ** the FROM clause that has already been constructed. "p" is NULL
  96947. ** if this is the first term of the FROM clause. pTable and pDatabase
  96948. ** are the name of the table and database named in the FROM clause term.
  96949. ** pDatabase is NULL if the database name qualifier is missing - the
  96950. ** usual case. If the term has an alias, then pAlias points to the
  96951. ** alias token. If the term is a subquery, then pSubquery is the
  96952. ** SELECT statement that the subquery encodes. The pTable and
  96953. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  96954. ** parameters are the content of the ON and USING clauses.
  96955. **
  96956. ** Return a new SrcList which encodes is the FROM with the new
  96957. ** term added.
  96958. */
  96959. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  96960. Parse *pParse, /* Parsing context */
  96961. SrcList *p, /* The left part of the FROM clause already seen */
  96962. Token *pTable, /* Name of the table to add to the FROM clause */
  96963. Token *pDatabase, /* Name of the database containing pTable */
  96964. Token *pAlias, /* The right-hand side of the AS subexpression */
  96965. Select *pSubquery, /* A subquery used in place of a table name */
  96966. Expr *pOn, /* The ON clause of a join */
  96967. IdList *pUsing /* The USING clause of a join */
  96968. ){
  96969. struct SrcList_item *pItem;
  96970. sqlite3 *db = pParse->db;
  96971. if( !p && (pOn || pUsing) ){
  96972. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  96973. (pOn ? "ON" : "USING")
  96974. );
  96975. goto append_from_error;
  96976. }
  96977. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  96978. if( p==0 || NEVER(p->nSrc==0) ){
  96979. goto append_from_error;
  96980. }
  96981. pItem = &p->a[p->nSrc-1];
  96982. assert( pAlias!=0 );
  96983. if( pAlias->n ){
  96984. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  96985. }
  96986. pItem->pSelect = pSubquery;
  96987. pItem->pOn = pOn;
  96988. pItem->pUsing = pUsing;
  96989. return p;
  96990. append_from_error:
  96991. assert( p==0 );
  96992. sqlite3ExprDelete(db, pOn);
  96993. sqlite3IdListDelete(db, pUsing);
  96994. sqlite3SelectDelete(db, pSubquery);
  96995. return 0;
  96996. }
  96997. /*
  96998. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  96999. ** element of the source-list passed as the second argument.
  97000. */
  97001. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  97002. assert( pIndexedBy!=0 );
  97003. if( p && ALWAYS(p->nSrc>0) ){
  97004. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  97005. assert( pItem->fg.notIndexed==0 );
  97006. assert( pItem->fg.isIndexedBy==0 );
  97007. assert( pItem->fg.isTabFunc==0 );
  97008. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  97009. /* A "NOT INDEXED" clause was supplied. See parse.y
  97010. ** construct "indexed_opt" for details. */
  97011. pItem->fg.notIndexed = 1;
  97012. }else{
  97013. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  97014. pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
  97015. }
  97016. }
  97017. }
  97018. /*
  97019. ** Add the list of function arguments to the SrcList entry for a
  97020. ** table-valued-function.
  97021. */
  97022. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  97023. if( p ){
  97024. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  97025. assert( pItem->fg.notIndexed==0 );
  97026. assert( pItem->fg.isIndexedBy==0 );
  97027. assert( pItem->fg.isTabFunc==0 );
  97028. pItem->u1.pFuncArg = pList;
  97029. pItem->fg.isTabFunc = 1;
  97030. }else{
  97031. sqlite3ExprListDelete(pParse->db, pList);
  97032. }
  97033. }
  97034. /*
  97035. ** When building up a FROM clause in the parser, the join operator
  97036. ** is initially attached to the left operand. But the code generator
  97037. ** expects the join operator to be on the right operand. This routine
  97038. ** Shifts all join operators from left to right for an entire FROM
  97039. ** clause.
  97040. **
  97041. ** Example: Suppose the join is like this:
  97042. **
  97043. ** A natural cross join B
  97044. **
  97045. ** The operator is "natural cross join". The A and B operands are stored
  97046. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  97047. ** operator with A. This routine shifts that operator over to B.
  97048. */
  97049. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  97050. if( p ){
  97051. int i;
  97052. for(i=p->nSrc-1; i>0; i--){
  97053. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  97054. }
  97055. p->a[0].fg.jointype = 0;
  97056. }
  97057. }
  97058. /*
  97059. ** Generate VDBE code for a BEGIN statement.
  97060. */
  97061. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  97062. sqlite3 *db;
  97063. Vdbe *v;
  97064. int i;
  97065. assert( pParse!=0 );
  97066. db = pParse->db;
  97067. assert( db!=0 );
  97068. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  97069. return;
  97070. }
  97071. v = sqlite3GetVdbe(pParse);
  97072. if( !v ) return;
  97073. if( type!=TK_DEFERRED ){
  97074. for(i=0; i<db->nDb; i++){
  97075. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  97076. sqlite3VdbeUsesBtree(v, i);
  97077. }
  97078. }
  97079. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  97080. }
  97081. /*
  97082. ** Generate VDBE code for a COMMIT statement.
  97083. */
  97084. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  97085. Vdbe *v;
  97086. assert( pParse!=0 );
  97087. assert( pParse->db!=0 );
  97088. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  97089. return;
  97090. }
  97091. v = sqlite3GetVdbe(pParse);
  97092. if( v ){
  97093. sqlite3VdbeAddOp1(v, OP_AutoCommit, 1);
  97094. }
  97095. }
  97096. /*
  97097. ** Generate VDBE code for a ROLLBACK statement.
  97098. */
  97099. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  97100. Vdbe *v;
  97101. assert( pParse!=0 );
  97102. assert( pParse->db!=0 );
  97103. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  97104. return;
  97105. }
  97106. v = sqlite3GetVdbe(pParse);
  97107. if( v ){
  97108. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  97109. }
  97110. }
  97111. /*
  97112. ** This function is called by the parser when it parses a command to create,
  97113. ** release or rollback an SQL savepoint.
  97114. */
  97115. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  97116. char *zName = sqlite3NameFromToken(pParse->db, pName);
  97117. if( zName ){
  97118. Vdbe *v = sqlite3GetVdbe(pParse);
  97119. #ifndef SQLITE_OMIT_AUTHORIZATION
  97120. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  97121. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  97122. #endif
  97123. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  97124. sqlite3DbFree(pParse->db, zName);
  97125. return;
  97126. }
  97127. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  97128. }
  97129. }
  97130. /*
  97131. ** Make sure the TEMP database is open and available for use. Return
  97132. ** the number of errors. Leave any error messages in the pParse structure.
  97133. */
  97134. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  97135. sqlite3 *db = pParse->db;
  97136. if( db->aDb[1].pBt==0 && !pParse->explain ){
  97137. int rc;
  97138. Btree *pBt;
  97139. static const int flags =
  97140. SQLITE_OPEN_READWRITE |
  97141. SQLITE_OPEN_CREATE |
  97142. SQLITE_OPEN_EXCLUSIVE |
  97143. SQLITE_OPEN_DELETEONCLOSE |
  97144. SQLITE_OPEN_TEMP_DB;
  97145. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  97146. if( rc!=SQLITE_OK ){
  97147. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  97148. "file for storing temporary tables");
  97149. pParse->rc = rc;
  97150. return 1;
  97151. }
  97152. db->aDb[1].pBt = pBt;
  97153. assert( db->aDb[1].pSchema );
  97154. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  97155. sqlite3OomFault(db);
  97156. return 1;
  97157. }
  97158. }
  97159. return 0;
  97160. }
  97161. /*
  97162. ** Record the fact that the schema cookie will need to be verified
  97163. ** for database iDb. The code to actually verify the schema cookie
  97164. ** will occur at the end of the top-level VDBE and will be generated
  97165. ** later, by sqlite3FinishCoding().
  97166. */
  97167. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  97168. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97169. assert( iDb>=0 && iDb<pParse->db->nDb );
  97170. assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
  97171. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  97172. assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
  97173. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  97174. DbMaskSet(pToplevel->cookieMask, iDb);
  97175. if( !OMIT_TEMPDB && iDb==1 ){
  97176. sqlite3OpenTempDatabase(pToplevel);
  97177. }
  97178. }
  97179. }
  97180. /*
  97181. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  97182. ** attached database. Otherwise, invoke it for the database named zDb only.
  97183. */
  97184. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  97185. sqlite3 *db = pParse->db;
  97186. int i;
  97187. for(i=0; i<db->nDb; i++){
  97188. Db *pDb = &db->aDb[i];
  97189. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  97190. sqlite3CodeVerifySchema(pParse, i);
  97191. }
  97192. }
  97193. }
  97194. /*
  97195. ** Generate VDBE code that prepares for doing an operation that
  97196. ** might change the database.
  97197. **
  97198. ** This routine starts a new transaction if we are not already within
  97199. ** a transaction. If we are already within a transaction, then a checkpoint
  97200. ** is set if the setStatement parameter is true. A checkpoint should
  97201. ** be set for operations that might fail (due to a constraint) part of
  97202. ** the way through and which will need to undo some writes without having to
  97203. ** rollback the whole transaction. For operations where all constraints
  97204. ** can be checked before any changes are made to the database, it is never
  97205. ** necessary to undo a write and the checkpoint should not be set.
  97206. */
  97207. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  97208. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97209. sqlite3CodeVerifySchema(pParse, iDb);
  97210. DbMaskSet(pToplevel->writeMask, iDb);
  97211. pToplevel->isMultiWrite |= setStatement;
  97212. }
  97213. /*
  97214. ** Indicate that the statement currently under construction might write
  97215. ** more than one entry (example: deleting one row then inserting another,
  97216. ** inserting multiple rows in a table, or inserting a row and index entries.)
  97217. ** If an abort occurs after some of these writes have completed, then it will
  97218. ** be necessary to undo the completed writes.
  97219. */
  97220. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  97221. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97222. pToplevel->isMultiWrite = 1;
  97223. }
  97224. /*
  97225. ** The code generator calls this routine if is discovers that it is
  97226. ** possible to abort a statement prior to completion. In order to
  97227. ** perform this abort without corrupting the database, we need to make
  97228. ** sure that the statement is protected by a statement transaction.
  97229. **
  97230. ** Technically, we only need to set the mayAbort flag if the
  97231. ** isMultiWrite flag was previously set. There is a time dependency
  97232. ** such that the abort must occur after the multiwrite. This makes
  97233. ** some statements involving the REPLACE conflict resolution algorithm
  97234. ** go a little faster. But taking advantage of this time dependency
  97235. ** makes it more difficult to prove that the code is correct (in
  97236. ** particular, it prevents us from writing an effective
  97237. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  97238. ** to take the safe route and skip the optimization.
  97239. */
  97240. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  97241. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97242. pToplevel->mayAbort = 1;
  97243. }
  97244. /*
  97245. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  97246. ** error. The onError parameter determines which (if any) of the statement
  97247. ** and/or current transaction is rolled back.
  97248. */
  97249. SQLITE_PRIVATE void sqlite3HaltConstraint(
  97250. Parse *pParse, /* Parsing context */
  97251. int errCode, /* extended error code */
  97252. int onError, /* Constraint type */
  97253. char *p4, /* Error message */
  97254. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  97255. u8 p5Errmsg /* P5_ErrMsg type */
  97256. ){
  97257. Vdbe *v = sqlite3GetVdbe(pParse);
  97258. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  97259. if( onError==OE_Abort ){
  97260. sqlite3MayAbort(pParse);
  97261. }
  97262. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  97263. sqlite3VdbeChangeP5(v, p5Errmsg);
  97264. }
  97265. /*
  97266. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  97267. */
  97268. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  97269. Parse *pParse, /* Parsing context */
  97270. int onError, /* Constraint type */
  97271. Index *pIdx /* The index that triggers the constraint */
  97272. ){
  97273. char *zErr;
  97274. int j;
  97275. StrAccum errMsg;
  97276. Table *pTab = pIdx->pTable;
  97277. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  97278. if( pIdx->aColExpr ){
  97279. sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
  97280. }else{
  97281. for(j=0; j<pIdx->nKeyCol; j++){
  97282. char *zCol;
  97283. assert( pIdx->aiColumn[j]>=0 );
  97284. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  97285. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  97286. sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
  97287. }
  97288. }
  97289. zErr = sqlite3StrAccumFinish(&errMsg);
  97290. sqlite3HaltConstraint(pParse,
  97291. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  97292. : SQLITE_CONSTRAINT_UNIQUE,
  97293. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  97294. }
  97295. /*
  97296. ** Code an OP_Halt due to non-unique rowid.
  97297. */
  97298. SQLITE_PRIVATE void sqlite3RowidConstraint(
  97299. Parse *pParse, /* Parsing context */
  97300. int onError, /* Conflict resolution algorithm */
  97301. Table *pTab /* The table with the non-unique rowid */
  97302. ){
  97303. char *zMsg;
  97304. int rc;
  97305. if( pTab->iPKey>=0 ){
  97306. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  97307. pTab->aCol[pTab->iPKey].zName);
  97308. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  97309. }else{
  97310. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  97311. rc = SQLITE_CONSTRAINT_ROWID;
  97312. }
  97313. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  97314. P5_ConstraintUnique);
  97315. }
  97316. /*
  97317. ** Check to see if pIndex uses the collating sequence pColl. Return
  97318. ** true if it does and false if it does not.
  97319. */
  97320. #ifndef SQLITE_OMIT_REINDEX
  97321. static int collationMatch(const char *zColl, Index *pIndex){
  97322. int i;
  97323. assert( zColl!=0 );
  97324. for(i=0; i<pIndex->nColumn; i++){
  97325. const char *z = pIndex->azColl[i];
  97326. assert( z!=0 || pIndex->aiColumn[i]<0 );
  97327. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  97328. return 1;
  97329. }
  97330. }
  97331. return 0;
  97332. }
  97333. #endif
  97334. /*
  97335. ** Recompute all indices of pTab that use the collating sequence pColl.
  97336. ** If pColl==0 then recompute all indices of pTab.
  97337. */
  97338. #ifndef SQLITE_OMIT_REINDEX
  97339. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  97340. Index *pIndex; /* An index associated with pTab */
  97341. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  97342. if( zColl==0 || collationMatch(zColl, pIndex) ){
  97343. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  97344. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97345. sqlite3RefillIndex(pParse, pIndex, -1);
  97346. }
  97347. }
  97348. }
  97349. #endif
  97350. /*
  97351. ** Recompute all indices of all tables in all databases where the
  97352. ** indices use the collating sequence pColl. If pColl==0 then recompute
  97353. ** all indices everywhere.
  97354. */
  97355. #ifndef SQLITE_OMIT_REINDEX
  97356. static void reindexDatabases(Parse *pParse, char const *zColl){
  97357. Db *pDb; /* A single database */
  97358. int iDb; /* The database index number */
  97359. sqlite3 *db = pParse->db; /* The database connection */
  97360. HashElem *k; /* For looping over tables in pDb */
  97361. Table *pTab; /* A table in the database */
  97362. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  97363. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  97364. assert( pDb!=0 );
  97365. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  97366. pTab = (Table*)sqliteHashData(k);
  97367. reindexTable(pParse, pTab, zColl);
  97368. }
  97369. }
  97370. }
  97371. #endif
  97372. /*
  97373. ** Generate code for the REINDEX command.
  97374. **
  97375. ** REINDEX -- 1
  97376. ** REINDEX <collation> -- 2
  97377. ** REINDEX ?<database>.?<tablename> -- 3
  97378. ** REINDEX ?<database>.?<indexname> -- 4
  97379. **
  97380. ** Form 1 causes all indices in all attached databases to be rebuilt.
  97381. ** Form 2 rebuilds all indices in all databases that use the named
  97382. ** collating function. Forms 3 and 4 rebuild the named index or all
  97383. ** indices associated with the named table.
  97384. */
  97385. #ifndef SQLITE_OMIT_REINDEX
  97386. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  97387. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  97388. char *z; /* Name of a table or index */
  97389. const char *zDb; /* Name of the database */
  97390. Table *pTab; /* A table in the database */
  97391. Index *pIndex; /* An index associated with pTab */
  97392. int iDb; /* The database index number */
  97393. sqlite3 *db = pParse->db; /* The database connection */
  97394. Token *pObjName; /* Name of the table or index to be reindexed */
  97395. /* Read the database schema. If an error occurs, leave an error message
  97396. ** and code in pParse and return NULL. */
  97397. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  97398. return;
  97399. }
  97400. if( pName1==0 ){
  97401. reindexDatabases(pParse, 0);
  97402. return;
  97403. }else if( NEVER(pName2==0) || pName2->z==0 ){
  97404. char *zColl;
  97405. assert( pName1->z );
  97406. zColl = sqlite3NameFromToken(pParse->db, pName1);
  97407. if( !zColl ) return;
  97408. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  97409. if( pColl ){
  97410. reindexDatabases(pParse, zColl);
  97411. sqlite3DbFree(db, zColl);
  97412. return;
  97413. }
  97414. sqlite3DbFree(db, zColl);
  97415. }
  97416. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  97417. if( iDb<0 ) return;
  97418. z = sqlite3NameFromToken(db, pObjName);
  97419. if( z==0 ) return;
  97420. zDb = db->aDb[iDb].zDbSName;
  97421. pTab = sqlite3FindTable(db, z, zDb);
  97422. if( pTab ){
  97423. reindexTable(pParse, pTab, 0);
  97424. sqlite3DbFree(db, z);
  97425. return;
  97426. }
  97427. pIndex = sqlite3FindIndex(db, z, zDb);
  97428. sqlite3DbFree(db, z);
  97429. if( pIndex ){
  97430. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97431. sqlite3RefillIndex(pParse, pIndex, -1);
  97432. return;
  97433. }
  97434. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  97435. }
  97436. #endif
  97437. /*
  97438. ** Return a KeyInfo structure that is appropriate for the given Index.
  97439. **
  97440. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  97441. ** when it has finished using it.
  97442. */
  97443. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  97444. int i;
  97445. int nCol = pIdx->nColumn;
  97446. int nKey = pIdx->nKeyCol;
  97447. KeyInfo *pKey;
  97448. if( pParse->nErr ) return 0;
  97449. if( pIdx->uniqNotNull ){
  97450. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  97451. }else{
  97452. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  97453. }
  97454. if( pKey ){
  97455. assert( sqlite3KeyInfoIsWriteable(pKey) );
  97456. for(i=0; i<nCol; i++){
  97457. const char *zColl = pIdx->azColl[i];
  97458. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  97459. sqlite3LocateCollSeq(pParse, zColl);
  97460. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  97461. }
  97462. if( pParse->nErr ){
  97463. sqlite3KeyInfoUnref(pKey);
  97464. pKey = 0;
  97465. }
  97466. }
  97467. return pKey;
  97468. }
  97469. #ifndef SQLITE_OMIT_CTE
  97470. /*
  97471. ** This routine is invoked once per CTE by the parser while parsing a
  97472. ** WITH clause.
  97473. */
  97474. SQLITE_PRIVATE With *sqlite3WithAdd(
  97475. Parse *pParse, /* Parsing context */
  97476. With *pWith, /* Existing WITH clause, or NULL */
  97477. Token *pName, /* Name of the common-table */
  97478. ExprList *pArglist, /* Optional column name list for the table */
  97479. Select *pQuery /* Query used to initialize the table */
  97480. ){
  97481. sqlite3 *db = pParse->db;
  97482. With *pNew;
  97483. char *zName;
  97484. /* Check that the CTE name is unique within this WITH clause. If
  97485. ** not, store an error in the Parse structure. */
  97486. zName = sqlite3NameFromToken(pParse->db, pName);
  97487. if( zName && pWith ){
  97488. int i;
  97489. for(i=0; i<pWith->nCte; i++){
  97490. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  97491. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  97492. }
  97493. }
  97494. }
  97495. if( pWith ){
  97496. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  97497. pNew = sqlite3DbRealloc(db, pWith, nByte);
  97498. }else{
  97499. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  97500. }
  97501. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  97502. if( db->mallocFailed ){
  97503. sqlite3ExprListDelete(db, pArglist);
  97504. sqlite3SelectDelete(db, pQuery);
  97505. sqlite3DbFree(db, zName);
  97506. pNew = pWith;
  97507. }else{
  97508. pNew->a[pNew->nCte].pSelect = pQuery;
  97509. pNew->a[pNew->nCte].pCols = pArglist;
  97510. pNew->a[pNew->nCte].zName = zName;
  97511. pNew->a[pNew->nCte].zCteErr = 0;
  97512. pNew->nCte++;
  97513. }
  97514. return pNew;
  97515. }
  97516. /*
  97517. ** Free the contents of the With object passed as the second argument.
  97518. */
  97519. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  97520. if( pWith ){
  97521. int i;
  97522. for(i=0; i<pWith->nCte; i++){
  97523. struct Cte *pCte = &pWith->a[i];
  97524. sqlite3ExprListDelete(db, pCte->pCols);
  97525. sqlite3SelectDelete(db, pCte->pSelect);
  97526. sqlite3DbFree(db, pCte->zName);
  97527. }
  97528. sqlite3DbFree(db, pWith);
  97529. }
  97530. }
  97531. #endif /* !defined(SQLITE_OMIT_CTE) */
  97532. /************** End of build.c ***********************************************/
  97533. /************** Begin file callback.c ****************************************/
  97534. /*
  97535. ** 2005 May 23
  97536. **
  97537. ** The author disclaims copyright to this source code. In place of
  97538. ** a legal notice, here is a blessing:
  97539. **
  97540. ** May you do good and not evil.
  97541. ** May you find forgiveness for yourself and forgive others.
  97542. ** May you share freely, never taking more than you give.
  97543. **
  97544. *************************************************************************
  97545. **
  97546. ** This file contains functions used to access the internal hash tables
  97547. ** of user defined functions and collation sequences.
  97548. */
  97549. /* #include "sqliteInt.h" */
  97550. /*
  97551. ** Invoke the 'collation needed' callback to request a collation sequence
  97552. ** in the encoding enc of name zName, length nName.
  97553. */
  97554. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  97555. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  97556. if( db->xCollNeeded ){
  97557. char *zExternal = sqlite3DbStrDup(db, zName);
  97558. if( !zExternal ) return;
  97559. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  97560. sqlite3DbFree(db, zExternal);
  97561. }
  97562. #ifndef SQLITE_OMIT_UTF16
  97563. if( db->xCollNeeded16 ){
  97564. char const *zExternal;
  97565. sqlite3_value *pTmp = sqlite3ValueNew(db);
  97566. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  97567. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  97568. if( zExternal ){
  97569. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  97570. }
  97571. sqlite3ValueFree(pTmp);
  97572. }
  97573. #endif
  97574. }
  97575. /*
  97576. ** This routine is called if the collation factory fails to deliver a
  97577. ** collation function in the best encoding but there may be other versions
  97578. ** of this collation function (for other text encodings) available. Use one
  97579. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  97580. ** possible.
  97581. */
  97582. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  97583. CollSeq *pColl2;
  97584. char *z = pColl->zName;
  97585. int i;
  97586. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  97587. for(i=0; i<3; i++){
  97588. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  97589. if( pColl2->xCmp!=0 ){
  97590. memcpy(pColl, pColl2, sizeof(CollSeq));
  97591. pColl->xDel = 0; /* Do not copy the destructor */
  97592. return SQLITE_OK;
  97593. }
  97594. }
  97595. return SQLITE_ERROR;
  97596. }
  97597. /*
  97598. ** This function is responsible for invoking the collation factory callback
  97599. ** or substituting a collation sequence of a different encoding when the
  97600. ** requested collation sequence is not available in the desired encoding.
  97601. **
  97602. ** If it is not NULL, then pColl must point to the database native encoding
  97603. ** collation sequence with name zName, length nName.
  97604. **
  97605. ** The return value is either the collation sequence to be used in database
  97606. ** db for collation type name zName, length nName, or NULL, if no collation
  97607. ** sequence can be found. If no collation is found, leave an error message.
  97608. **
  97609. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  97610. */
  97611. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  97612. Parse *pParse, /* Parsing context */
  97613. u8 enc, /* The desired encoding for the collating sequence */
  97614. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  97615. const char *zName /* Collating sequence name */
  97616. ){
  97617. CollSeq *p;
  97618. sqlite3 *db = pParse->db;
  97619. p = pColl;
  97620. if( !p ){
  97621. p = sqlite3FindCollSeq(db, enc, zName, 0);
  97622. }
  97623. if( !p || !p->xCmp ){
  97624. /* No collation sequence of this type for this encoding is registered.
  97625. ** Call the collation factory to see if it can supply us with one.
  97626. */
  97627. callCollNeeded(db, enc, zName);
  97628. p = sqlite3FindCollSeq(db, enc, zName, 0);
  97629. }
  97630. if( p && !p->xCmp && synthCollSeq(db, p) ){
  97631. p = 0;
  97632. }
  97633. assert( !p || p->xCmp );
  97634. if( p==0 ){
  97635. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  97636. }
  97637. return p;
  97638. }
  97639. /*
  97640. ** This routine is called on a collation sequence before it is used to
  97641. ** check that it is defined. An undefined collation sequence exists when
  97642. ** a database is loaded that contains references to collation sequences
  97643. ** that have not been defined by sqlite3_create_collation() etc.
  97644. **
  97645. ** If required, this routine calls the 'collation needed' callback to
  97646. ** request a definition of the collating sequence. If this doesn't work,
  97647. ** an equivalent collating sequence that uses a text encoding different
  97648. ** from the main database is substituted, if one is available.
  97649. */
  97650. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  97651. if( pColl ){
  97652. const char *zName = pColl->zName;
  97653. sqlite3 *db = pParse->db;
  97654. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  97655. if( !p ){
  97656. return SQLITE_ERROR;
  97657. }
  97658. assert( p==pColl );
  97659. }
  97660. return SQLITE_OK;
  97661. }
  97662. /*
  97663. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  97664. ** specified by zName and nName is not found and parameter 'create' is
  97665. ** true, then create a new entry. Otherwise return NULL.
  97666. **
  97667. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  97668. ** array of three CollSeq structures. The first is the collation sequence
  97669. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  97670. **
  97671. ** Stored immediately after the three collation sequences is a copy of
  97672. ** the collation sequence name. A pointer to this string is stored in
  97673. ** each collation sequence structure.
  97674. */
  97675. static CollSeq *findCollSeqEntry(
  97676. sqlite3 *db, /* Database connection */
  97677. const char *zName, /* Name of the collating sequence */
  97678. int create /* Create a new entry if true */
  97679. ){
  97680. CollSeq *pColl;
  97681. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  97682. if( 0==pColl && create ){
  97683. int nName = sqlite3Strlen30(zName);
  97684. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
  97685. if( pColl ){
  97686. CollSeq *pDel = 0;
  97687. pColl[0].zName = (char*)&pColl[3];
  97688. pColl[0].enc = SQLITE_UTF8;
  97689. pColl[1].zName = (char*)&pColl[3];
  97690. pColl[1].enc = SQLITE_UTF16LE;
  97691. pColl[2].zName = (char*)&pColl[3];
  97692. pColl[2].enc = SQLITE_UTF16BE;
  97693. memcpy(pColl[0].zName, zName, nName);
  97694. pColl[0].zName[nName] = 0;
  97695. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  97696. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  97697. ** return the pColl pointer to be deleted (because it wasn't added
  97698. ** to the hash table).
  97699. */
  97700. assert( pDel==0 || pDel==pColl );
  97701. if( pDel!=0 ){
  97702. sqlite3OomFault(db);
  97703. sqlite3DbFree(db, pDel);
  97704. pColl = 0;
  97705. }
  97706. }
  97707. }
  97708. return pColl;
  97709. }
  97710. /*
  97711. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  97712. ** Return the CollSeq* pointer for the collation sequence named zName
  97713. ** for the encoding 'enc' from the database 'db'.
  97714. **
  97715. ** If the entry specified is not found and 'create' is true, then create a
  97716. ** new entry. Otherwise return NULL.
  97717. **
  97718. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  97719. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  97720. ** if necessary and generates an error message if the collating sequence
  97721. ** cannot be found.
  97722. **
  97723. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  97724. */
  97725. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  97726. sqlite3 *db,
  97727. u8 enc,
  97728. const char *zName,
  97729. int create
  97730. ){
  97731. CollSeq *pColl;
  97732. if( zName ){
  97733. pColl = findCollSeqEntry(db, zName, create);
  97734. }else{
  97735. pColl = db->pDfltColl;
  97736. }
  97737. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  97738. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  97739. if( pColl ) pColl += enc-1;
  97740. return pColl;
  97741. }
  97742. /* During the search for the best function definition, this procedure
  97743. ** is called to test how well the function passed as the first argument
  97744. ** matches the request for a function with nArg arguments in a system
  97745. ** that uses encoding enc. The value returned indicates how well the
  97746. ** request is matched. A higher value indicates a better match.
  97747. **
  97748. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  97749. ** is also -1. In other words, we are searching for a function that
  97750. ** takes a variable number of arguments.
  97751. **
  97752. ** If nArg is -2 that means that we are searching for any function
  97753. ** regardless of the number of arguments it uses, so return a positive
  97754. ** match score for any
  97755. **
  97756. ** The returned value is always between 0 and 6, as follows:
  97757. **
  97758. ** 0: Not a match.
  97759. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  97760. ** 2: UTF16 byte order change required and function takes any number of args.
  97761. ** 3: encoding matches and function takes any number of arguments
  97762. ** 4: UTF8/16 conversion required - argument count matches exactly
  97763. ** 5: UTF16 byte order conversion required - argument count matches exactly
  97764. ** 6: Perfect match: encoding and argument count match exactly.
  97765. **
  97766. ** If nArg==(-2) then any function with a non-null xSFunc is
  97767. ** a perfect match and any function with xSFunc NULL is
  97768. ** a non-match.
  97769. */
  97770. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  97771. static int matchQuality(
  97772. FuncDef *p, /* The function we are evaluating for match quality */
  97773. int nArg, /* Desired number of arguments. (-1)==any */
  97774. u8 enc /* Desired text encoding */
  97775. ){
  97776. int match;
  97777. /* nArg of -2 is a special case */
  97778. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  97779. /* Wrong number of arguments means "no match" */
  97780. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  97781. /* Give a better score to a function with a specific number of arguments
  97782. ** than to function that accepts any number of arguments. */
  97783. if( p->nArg==nArg ){
  97784. match = 4;
  97785. }else{
  97786. match = 1;
  97787. }
  97788. /* Bonus points if the text encoding matches */
  97789. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  97790. match += 2; /* Exact encoding match */
  97791. }else if( (enc & p->funcFlags & 2)!=0 ){
  97792. match += 1; /* Both are UTF16, but with different byte orders */
  97793. }
  97794. return match;
  97795. }
  97796. /*
  97797. ** Search a FuncDefHash for a function with the given name. Return
  97798. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  97799. */
  97800. static FuncDef *functionSearch(
  97801. int h, /* Hash of the name */
  97802. const char *zFunc /* Name of function */
  97803. ){
  97804. FuncDef *p;
  97805. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  97806. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  97807. return p;
  97808. }
  97809. }
  97810. return 0;
  97811. }
  97812. /*
  97813. ** Insert a new FuncDef into a FuncDefHash hash table.
  97814. */
  97815. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  97816. FuncDef *aDef, /* List of global functions to be inserted */
  97817. int nDef /* Length of the apDef[] list */
  97818. ){
  97819. int i;
  97820. for(i=0; i<nDef; i++){
  97821. FuncDef *pOther;
  97822. const char *zName = aDef[i].zName;
  97823. int nName = sqlite3Strlen30(zName);
  97824. int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
  97825. pOther = functionSearch(h, zName);
  97826. if( pOther ){
  97827. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  97828. aDef[i].pNext = pOther->pNext;
  97829. pOther->pNext = &aDef[i];
  97830. }else{
  97831. aDef[i].pNext = 0;
  97832. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  97833. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  97834. }
  97835. }
  97836. }
  97837. /*
  97838. ** Locate a user function given a name, a number of arguments and a flag
  97839. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  97840. ** pointer to the FuncDef structure that defines that function, or return
  97841. ** NULL if the function does not exist.
  97842. **
  97843. ** If the createFlag argument is true, then a new (blank) FuncDef
  97844. ** structure is created and liked into the "db" structure if a
  97845. ** no matching function previously existed.
  97846. **
  97847. ** If nArg is -2, then the first valid function found is returned. A
  97848. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  97849. ** case is used to see if zName is a valid function name for some number
  97850. ** of arguments. If nArg is -2, then createFlag must be 0.
  97851. **
  97852. ** If createFlag is false, then a function with the required name and
  97853. ** number of arguments may be returned even if the eTextRep flag does not
  97854. ** match that requested.
  97855. */
  97856. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  97857. sqlite3 *db, /* An open database */
  97858. const char *zName, /* Name of the function. zero-terminated */
  97859. int nArg, /* Number of arguments. -1 means any number */
  97860. u8 enc, /* Preferred text encoding */
  97861. u8 createFlag /* Create new entry if true and does not otherwise exist */
  97862. ){
  97863. FuncDef *p; /* Iterator variable */
  97864. FuncDef *pBest = 0; /* Best match found so far */
  97865. int bestScore = 0; /* Score of best match */
  97866. int h; /* Hash value */
  97867. int nName; /* Length of the name */
  97868. assert( nArg>=(-2) );
  97869. assert( nArg>=(-1) || createFlag==0 );
  97870. nName = sqlite3Strlen30(zName);
  97871. /* First search for a match amongst the application-defined functions.
  97872. */
  97873. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  97874. while( p ){
  97875. int score = matchQuality(p, nArg, enc);
  97876. if( score>bestScore ){
  97877. pBest = p;
  97878. bestScore = score;
  97879. }
  97880. p = p->pNext;
  97881. }
  97882. /* If no match is found, search the built-in functions.
  97883. **
  97884. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  97885. ** functions even if a prior app-defined function was found. And give
  97886. ** priority to built-in functions.
  97887. **
  97888. ** Except, if createFlag is true, that means that we are trying to
  97889. ** install a new function. Whatever FuncDef structure is returned it will
  97890. ** have fields overwritten with new information appropriate for the
  97891. ** new function. But the FuncDefs for built-in functions are read-only.
  97892. ** So we must not search for built-ins when creating a new function.
  97893. */
  97894. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  97895. bestScore = 0;
  97896. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
  97897. p = functionSearch(h, zName);
  97898. while( p ){
  97899. int score = matchQuality(p, nArg, enc);
  97900. if( score>bestScore ){
  97901. pBest = p;
  97902. bestScore = score;
  97903. }
  97904. p = p->pNext;
  97905. }
  97906. }
  97907. /* If the createFlag parameter is true and the search did not reveal an
  97908. ** exact match for the name, number of arguments and encoding, then add a
  97909. ** new entry to the hash table and return it.
  97910. */
  97911. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  97912. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  97913. FuncDef *pOther;
  97914. pBest->zName = (const char*)&pBest[1];
  97915. pBest->nArg = (u16)nArg;
  97916. pBest->funcFlags = enc;
  97917. memcpy((char*)&pBest[1], zName, nName+1);
  97918. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  97919. if( pOther==pBest ){
  97920. sqlite3DbFree(db, pBest);
  97921. sqlite3OomFault(db);
  97922. return 0;
  97923. }else{
  97924. pBest->pNext = pOther;
  97925. }
  97926. }
  97927. if( pBest && (pBest->xSFunc || createFlag) ){
  97928. return pBest;
  97929. }
  97930. return 0;
  97931. }
  97932. /*
  97933. ** Free all resources held by the schema structure. The void* argument points
  97934. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  97935. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  97936. ** of the schema hash tables).
  97937. **
  97938. ** The Schema.cache_size variable is not cleared.
  97939. */
  97940. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  97941. Hash temp1;
  97942. Hash temp2;
  97943. HashElem *pElem;
  97944. Schema *pSchema = (Schema *)p;
  97945. temp1 = pSchema->tblHash;
  97946. temp2 = pSchema->trigHash;
  97947. sqlite3HashInit(&pSchema->trigHash);
  97948. sqlite3HashClear(&pSchema->idxHash);
  97949. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  97950. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  97951. }
  97952. sqlite3HashClear(&temp2);
  97953. sqlite3HashInit(&pSchema->tblHash);
  97954. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  97955. Table *pTab = sqliteHashData(pElem);
  97956. sqlite3DeleteTable(0, pTab);
  97957. }
  97958. sqlite3HashClear(&temp1);
  97959. sqlite3HashClear(&pSchema->fkeyHash);
  97960. pSchema->pSeqTab = 0;
  97961. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  97962. pSchema->iGeneration++;
  97963. pSchema->schemaFlags &= ~DB_SchemaLoaded;
  97964. }
  97965. }
  97966. /*
  97967. ** Find and return the schema associated with a BTree. Create
  97968. ** a new one if necessary.
  97969. */
  97970. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  97971. Schema * p;
  97972. if( pBt ){
  97973. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  97974. }else{
  97975. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  97976. }
  97977. if( !p ){
  97978. sqlite3OomFault(db);
  97979. }else if ( 0==p->file_format ){
  97980. sqlite3HashInit(&p->tblHash);
  97981. sqlite3HashInit(&p->idxHash);
  97982. sqlite3HashInit(&p->trigHash);
  97983. sqlite3HashInit(&p->fkeyHash);
  97984. p->enc = SQLITE_UTF8;
  97985. }
  97986. return p;
  97987. }
  97988. /************** End of callback.c ********************************************/
  97989. /************** Begin file delete.c ******************************************/
  97990. /*
  97991. ** 2001 September 15
  97992. **
  97993. ** The author disclaims copyright to this source code. In place of
  97994. ** a legal notice, here is a blessing:
  97995. **
  97996. ** May you do good and not evil.
  97997. ** May you find forgiveness for yourself and forgive others.
  97998. ** May you share freely, never taking more than you give.
  97999. **
  98000. *************************************************************************
  98001. ** This file contains C code routines that are called by the parser
  98002. ** in order to generate code for DELETE FROM statements.
  98003. */
  98004. /* #include "sqliteInt.h" */
  98005. /*
  98006. ** While a SrcList can in general represent multiple tables and subqueries
  98007. ** (as in the FROM clause of a SELECT statement) in this case it contains
  98008. ** the name of a single table, as one might find in an INSERT, DELETE,
  98009. ** or UPDATE statement. Look up that table in the symbol table and
  98010. ** return a pointer. Set an error message and return NULL if the table
  98011. ** name is not found or if any other error occurs.
  98012. **
  98013. ** The following fields are initialized appropriate in pSrc:
  98014. **
  98015. ** pSrc->a[0].pTab Pointer to the Table object
  98016. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  98017. **
  98018. */
  98019. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  98020. struct SrcList_item *pItem = pSrc->a;
  98021. Table *pTab;
  98022. assert( pItem && pSrc->nSrc==1 );
  98023. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  98024. sqlite3DeleteTable(pParse->db, pItem->pTab);
  98025. pItem->pTab = pTab;
  98026. if( pTab ){
  98027. pTab->nTabRef++;
  98028. }
  98029. if( sqlite3IndexedByLookup(pParse, pItem) ){
  98030. pTab = 0;
  98031. }
  98032. return pTab;
  98033. }
  98034. /*
  98035. ** Check to make sure the given table is writable. If it is not
  98036. ** writable, generate an error message and return 1. If it is
  98037. ** writable return 0;
  98038. */
  98039. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  98040. /* A table is not writable under the following circumstances:
  98041. **
  98042. ** 1) It is a virtual table and no implementation of the xUpdate method
  98043. ** has been provided, or
  98044. ** 2) It is a system table (i.e. sqlite_master), this call is not
  98045. ** part of a nested parse and writable_schema pragma has not
  98046. ** been specified.
  98047. **
  98048. ** In either case leave an error message in pParse and return non-zero.
  98049. */
  98050. if( ( IsVirtual(pTab)
  98051. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  98052. || ( (pTab->tabFlags & TF_Readonly)!=0
  98053. && (pParse->db->flags & SQLITE_WriteSchema)==0
  98054. && pParse->nested==0 )
  98055. ){
  98056. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  98057. return 1;
  98058. }
  98059. #ifndef SQLITE_OMIT_VIEW
  98060. if( !viewOk && pTab->pSelect ){
  98061. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  98062. return 1;
  98063. }
  98064. #endif
  98065. return 0;
  98066. }
  98067. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  98068. /*
  98069. ** Evaluate a view and store its result in an ephemeral table. The
  98070. ** pWhere argument is an optional WHERE clause that restricts the
  98071. ** set of rows in the view that are to be added to the ephemeral table.
  98072. */
  98073. SQLITE_PRIVATE void sqlite3MaterializeView(
  98074. Parse *pParse, /* Parsing context */
  98075. Table *pView, /* View definition */
  98076. Expr *pWhere, /* Optional WHERE clause to be added */
  98077. int iCur /* Cursor number for ephemeral table */
  98078. ){
  98079. SelectDest dest;
  98080. Select *pSel;
  98081. SrcList *pFrom;
  98082. sqlite3 *db = pParse->db;
  98083. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  98084. pWhere = sqlite3ExprDup(db, pWhere, 0);
  98085. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  98086. if( pFrom ){
  98087. assert( pFrom->nSrc==1 );
  98088. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  98089. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
  98090. assert( pFrom->a[0].pOn==0 );
  98091. assert( pFrom->a[0].pUsing==0 );
  98092. }
  98093. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
  98094. SF_IncludeHidden, 0, 0);
  98095. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  98096. sqlite3Select(pParse, pSel, &dest);
  98097. sqlite3SelectDelete(db, pSel);
  98098. }
  98099. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  98100. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  98101. /*
  98102. ** Generate an expression tree to implement the WHERE, ORDER BY,
  98103. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  98104. **
  98105. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  98106. ** \__________________________/
  98107. ** pLimitWhere (pInClause)
  98108. */
  98109. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  98110. Parse *pParse, /* The parser context */
  98111. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  98112. Expr *pWhere, /* The WHERE clause. May be null */
  98113. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  98114. Expr *pLimit, /* The LIMIT clause. May be null */
  98115. Expr *pOffset, /* The OFFSET clause. May be null */
  98116. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  98117. ){
  98118. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  98119. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  98120. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  98121. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  98122. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  98123. Select *pSelect = NULL; /* Complete SELECT tree */
  98124. /* Check that there isn't an ORDER BY without a LIMIT clause.
  98125. */
  98126. if( pOrderBy && (pLimit == 0) ) {
  98127. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  98128. goto limit_where_cleanup;
  98129. }
  98130. /* We only need to generate a select expression if there
  98131. ** is a limit/offset term to enforce.
  98132. */
  98133. if( pLimit == 0 ) {
  98134. /* if pLimit is null, pOffset will always be null as well. */
  98135. assert( pOffset == 0 );
  98136. return pWhere;
  98137. }
  98138. /* Generate a select expression tree to enforce the limit/offset
  98139. ** term for the DELETE or UPDATE statement. For example:
  98140. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  98141. ** becomes:
  98142. ** DELETE FROM table_a WHERE rowid IN (
  98143. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  98144. ** );
  98145. */
  98146. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  98147. if( pSelectRowid == 0 ) goto limit_where_cleanup;
  98148. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  98149. if( pEList == 0 ) goto limit_where_cleanup;
  98150. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  98151. ** and the SELECT subtree. */
  98152. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  98153. if( pSelectSrc == 0 ) {
  98154. sqlite3ExprListDelete(pParse->db, pEList);
  98155. goto limit_where_cleanup;
  98156. }
  98157. /* generate the SELECT expression tree. */
  98158. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  98159. pOrderBy,0,pLimit,pOffset);
  98160. if( pSelect == 0 ) return 0;
  98161. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  98162. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  98163. pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0) : 0;
  98164. sqlite3PExprAddSelect(pParse, pInClause, pSelect);
  98165. return pInClause;
  98166. limit_where_cleanup:
  98167. sqlite3ExprDelete(pParse->db, pWhere);
  98168. sqlite3ExprListDelete(pParse->db, pOrderBy);
  98169. sqlite3ExprDelete(pParse->db, pLimit);
  98170. sqlite3ExprDelete(pParse->db, pOffset);
  98171. return 0;
  98172. }
  98173. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  98174. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  98175. /*
  98176. ** Generate code for a DELETE FROM statement.
  98177. **
  98178. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  98179. ** \________/ \________________/
  98180. ** pTabList pWhere
  98181. */
  98182. SQLITE_PRIVATE void sqlite3DeleteFrom(
  98183. Parse *pParse, /* The parser context */
  98184. SrcList *pTabList, /* The table from which we should delete things */
  98185. Expr *pWhere /* The WHERE clause. May be null */
  98186. ){
  98187. Vdbe *v; /* The virtual database engine */
  98188. Table *pTab; /* The table from which records will be deleted */
  98189. int i; /* Loop counter */
  98190. WhereInfo *pWInfo; /* Information about the WHERE clause */
  98191. Index *pIdx; /* For looping over indices of the table */
  98192. int iTabCur; /* Cursor number for the table */
  98193. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  98194. int iIdxCur = 0; /* Cursor number of the first index */
  98195. int nIdx; /* Number of indices */
  98196. sqlite3 *db; /* Main database structure */
  98197. AuthContext sContext; /* Authorization context */
  98198. NameContext sNC; /* Name context to resolve expressions in */
  98199. int iDb; /* Database number */
  98200. int memCnt = -1; /* Memory cell used for change counting */
  98201. int rcauth; /* Value returned by authorization callback */
  98202. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  98203. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  98204. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  98205. Index *pPk; /* The PRIMARY KEY index on the table */
  98206. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  98207. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  98208. int iKey; /* Memory cell holding key of row to be deleted */
  98209. i16 nKey; /* Number of memory cells in the row key */
  98210. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  98211. int iRowSet = 0; /* Register for rowset of rows to delete */
  98212. int addrBypass = 0; /* Address of jump over the delete logic */
  98213. int addrLoop = 0; /* Top of the delete loop */
  98214. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  98215. int bComplex; /* True if there are triggers or FKs or
  98216. ** subqueries in the WHERE clause */
  98217. #ifndef SQLITE_OMIT_TRIGGER
  98218. int isView; /* True if attempting to delete from a view */
  98219. Trigger *pTrigger; /* List of table triggers, if required */
  98220. #endif
  98221. memset(&sContext, 0, sizeof(sContext));
  98222. db = pParse->db;
  98223. if( pParse->nErr || db->mallocFailed ){
  98224. goto delete_from_cleanup;
  98225. }
  98226. assert( pTabList->nSrc==1 );
  98227. /* Locate the table which we want to delete. This table has to be
  98228. ** put in an SrcList structure because some of the subroutines we
  98229. ** will be calling are designed to work with multiple tables and expect
  98230. ** an SrcList* parameter instead of just a Table* parameter.
  98231. */
  98232. pTab = sqlite3SrcListLookup(pParse, pTabList);
  98233. if( pTab==0 ) goto delete_from_cleanup;
  98234. /* Figure out if we have any triggers and if the table being
  98235. ** deleted from is a view
  98236. */
  98237. #ifndef SQLITE_OMIT_TRIGGER
  98238. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  98239. isView = pTab->pSelect!=0;
  98240. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  98241. #else
  98242. # define pTrigger 0
  98243. # define isView 0
  98244. #endif
  98245. #ifdef SQLITE_OMIT_VIEW
  98246. # undef isView
  98247. # define isView 0
  98248. #endif
  98249. /* If pTab is really a view, make sure it has been initialized.
  98250. */
  98251. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  98252. goto delete_from_cleanup;
  98253. }
  98254. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  98255. goto delete_from_cleanup;
  98256. }
  98257. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  98258. assert( iDb<db->nDb );
  98259. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
  98260. db->aDb[iDb].zDbSName);
  98261. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  98262. if( rcauth==SQLITE_DENY ){
  98263. goto delete_from_cleanup;
  98264. }
  98265. assert(!isView || pTrigger);
  98266. /* Assign cursor numbers to the table and all its indices.
  98267. */
  98268. assert( pTabList->nSrc==1 );
  98269. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  98270. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  98271. pParse->nTab++;
  98272. }
  98273. /* Start the view context
  98274. */
  98275. if( isView ){
  98276. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  98277. }
  98278. /* Begin generating code.
  98279. */
  98280. v = sqlite3GetVdbe(pParse);
  98281. if( v==0 ){
  98282. goto delete_from_cleanup;
  98283. }
  98284. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  98285. sqlite3BeginWriteOperation(pParse, 1, iDb);
  98286. /* If we are trying to delete from a view, realize that view into
  98287. ** an ephemeral table.
  98288. */
  98289. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  98290. if( isView ){
  98291. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  98292. iDataCur = iIdxCur = iTabCur;
  98293. }
  98294. #endif
  98295. /* Resolve the column names in the WHERE clause.
  98296. */
  98297. memset(&sNC, 0, sizeof(sNC));
  98298. sNC.pParse = pParse;
  98299. sNC.pSrcList = pTabList;
  98300. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  98301. goto delete_from_cleanup;
  98302. }
  98303. /* Initialize the counter of the number of rows deleted, if
  98304. ** we are counting rows.
  98305. */
  98306. if( db->flags & SQLITE_CountRows ){
  98307. memCnt = ++pParse->nMem;
  98308. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  98309. }
  98310. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  98311. /* Special case: A DELETE without a WHERE clause deletes everything.
  98312. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  98313. ** this optimization caused the row change count (the value returned by
  98314. ** API function sqlite3_count_changes) to be set incorrectly.
  98315. **
  98316. ** The "rcauth==SQLITE_OK" terms is the
  98317. ** IMPLEMENATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
  98318. ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
  98319. ** the truncate optimization is disabled and all rows are deleted
  98320. ** individually.
  98321. */
  98322. if( rcauth==SQLITE_OK
  98323. && pWhere==0
  98324. && !bComplex
  98325. && !IsVirtual(pTab)
  98326. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  98327. && db->xPreUpdateCallback==0
  98328. #endif
  98329. ){
  98330. assert( !isView );
  98331. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  98332. if( HasRowid(pTab) ){
  98333. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  98334. pTab->zName, P4_STATIC);
  98335. }
  98336. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  98337. assert( pIdx->pSchema==pTab->pSchema );
  98338. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  98339. }
  98340. }else
  98341. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  98342. {
  98343. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
  98344. if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
  98345. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  98346. if( HasRowid(pTab) ){
  98347. /* For a rowid table, initialize the RowSet to an empty set */
  98348. pPk = 0;
  98349. nPk = 1;
  98350. iRowSet = ++pParse->nMem;
  98351. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  98352. }else{
  98353. /* For a WITHOUT ROWID table, create an ephemeral table used to
  98354. ** hold all primary keys for rows to be deleted. */
  98355. pPk = sqlite3PrimaryKeyIndex(pTab);
  98356. assert( pPk!=0 );
  98357. nPk = pPk->nKeyCol;
  98358. iPk = pParse->nMem+1;
  98359. pParse->nMem += nPk;
  98360. iEphCur = pParse->nTab++;
  98361. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  98362. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  98363. }
  98364. /* Construct a query to find the rowid or primary key for every row
  98365. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  98366. ** to indicate the strategy used to implement this delete:
  98367. **
  98368. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  98369. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  98370. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  98371. */
  98372. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  98373. if( pWInfo==0 ) goto delete_from_cleanup;
  98374. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  98375. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  98376. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  98377. /* Keep track of the number of rows to be deleted */
  98378. if( db->flags & SQLITE_CountRows ){
  98379. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  98380. }
  98381. /* Extract the rowid or primary key for the current row */
  98382. if( pPk ){
  98383. for(i=0; i<nPk; i++){
  98384. assert( pPk->aiColumn[i]>=0 );
  98385. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  98386. pPk->aiColumn[i], iPk+i);
  98387. }
  98388. iKey = iPk;
  98389. }else{
  98390. iKey = pParse->nMem + 1;
  98391. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  98392. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  98393. }
  98394. if( eOnePass!=ONEPASS_OFF ){
  98395. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  98396. ** one, so just keep it in its register(s) and fall through to the
  98397. ** delete code. */
  98398. nKey = nPk; /* OP_Found will use an unpacked key */
  98399. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  98400. if( aToOpen==0 ){
  98401. sqlite3WhereEnd(pWInfo);
  98402. goto delete_from_cleanup;
  98403. }
  98404. memset(aToOpen, 1, nIdx+1);
  98405. aToOpen[nIdx+1] = 0;
  98406. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  98407. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  98408. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  98409. }else{
  98410. if( pPk ){
  98411. /* Add the PK key for this row to the temporary table */
  98412. iKey = ++pParse->nMem;
  98413. nKey = 0; /* Zero tells OP_Found to use a composite key */
  98414. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  98415. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  98416. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
  98417. }else{
  98418. /* Add the rowid of the row to be deleted to the RowSet */
  98419. nKey = 1; /* OP_Seek always uses a single rowid */
  98420. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  98421. }
  98422. }
  98423. /* If this DELETE cannot use the ONEPASS strategy, this is the
  98424. ** end of the WHERE loop */
  98425. if( eOnePass!=ONEPASS_OFF ){
  98426. addrBypass = sqlite3VdbeMakeLabel(v);
  98427. }else{
  98428. sqlite3WhereEnd(pWInfo);
  98429. }
  98430. /* Unless this is a view, open cursors for the table we are
  98431. ** deleting from and all its indices. If this is a view, then the
  98432. ** only effect this statement has is to fire the INSTEAD OF
  98433. ** triggers.
  98434. */
  98435. if( !isView ){
  98436. int iAddrOnce = 0;
  98437. if( eOnePass==ONEPASS_MULTI ){
  98438. iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  98439. }
  98440. testcase( IsVirtual(pTab) );
  98441. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  98442. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  98443. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  98444. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  98445. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  98446. }
  98447. /* Set up a loop over the rowids/primary-keys that were found in the
  98448. ** where-clause loop above.
  98449. */
  98450. if( eOnePass!=ONEPASS_OFF ){
  98451. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  98452. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  98453. assert( pPk!=0 || pTab->pSelect!=0 );
  98454. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  98455. VdbeCoverage(v);
  98456. }
  98457. }else if( pPk ){
  98458. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  98459. sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
  98460. assert( nKey==0 ); /* OP_Found will use a composite key */
  98461. }else{
  98462. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  98463. VdbeCoverage(v);
  98464. assert( nKey==1 );
  98465. }
  98466. /* Delete the row */
  98467. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98468. if( IsVirtual(pTab) ){
  98469. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  98470. sqlite3VtabMakeWritable(pParse, pTab);
  98471. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  98472. sqlite3VdbeChangeP5(v, OE_Abort);
  98473. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  98474. sqlite3MayAbort(pParse);
  98475. if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
  98476. pParse->isMultiWrite = 0;
  98477. }
  98478. }else
  98479. #endif
  98480. {
  98481. int count = (pParse->nested==0); /* True to count changes */
  98482. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  98483. iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
  98484. }
  98485. /* End of the loop over all rowids/primary-keys. */
  98486. if( eOnePass!=ONEPASS_OFF ){
  98487. sqlite3VdbeResolveLabel(v, addrBypass);
  98488. sqlite3WhereEnd(pWInfo);
  98489. }else if( pPk ){
  98490. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  98491. sqlite3VdbeJumpHere(v, addrLoop);
  98492. }else{
  98493. sqlite3VdbeGoto(v, addrLoop);
  98494. sqlite3VdbeJumpHere(v, addrLoop);
  98495. }
  98496. } /* End non-truncate path */
  98497. /* Update the sqlite_sequence table by storing the content of the
  98498. ** maximum rowid counter values recorded while inserting into
  98499. ** autoincrement tables.
  98500. */
  98501. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  98502. sqlite3AutoincrementEnd(pParse);
  98503. }
  98504. /* Return the number of rows that were deleted. If this routine is
  98505. ** generating code because of a call to sqlite3NestedParse(), do not
  98506. ** invoke the callback function.
  98507. */
  98508. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  98509. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  98510. sqlite3VdbeSetNumCols(v, 1);
  98511. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  98512. }
  98513. delete_from_cleanup:
  98514. sqlite3AuthContextPop(&sContext);
  98515. sqlite3SrcListDelete(db, pTabList);
  98516. sqlite3ExprDelete(db, pWhere);
  98517. sqlite3DbFree(db, aToOpen);
  98518. return;
  98519. }
  98520. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  98521. ** they may interfere with compilation of other functions in this file
  98522. ** (or in another file, if this file becomes part of the amalgamation). */
  98523. #ifdef isView
  98524. #undef isView
  98525. #endif
  98526. #ifdef pTrigger
  98527. #undef pTrigger
  98528. #endif
  98529. /*
  98530. ** This routine generates VDBE code that causes a single row of a
  98531. ** single table to be deleted. Both the original table entry and
  98532. ** all indices are removed.
  98533. **
  98534. ** Preconditions:
  98535. **
  98536. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  98537. ** store for the table. (This will be either the table itself,
  98538. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  98539. ** of a WITHOUT ROWID table.)
  98540. **
  98541. ** 2. Read/write cursors for all indices of pTab must be open as
  98542. ** cursor number iIdxCur+i for the i-th index.
  98543. **
  98544. ** 3. The primary key for the row to be deleted must be stored in a
  98545. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  98546. ** that a search record formed from OP_MakeRecord is contained in the
  98547. ** single memory location iPk.
  98548. **
  98549. ** eMode:
  98550. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  98551. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  98552. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  98553. ** then this function must seek iDataCur to the entry identified by iPk
  98554. ** and nPk before reading from it.
  98555. **
  98556. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  98557. ** of a ONEPASS delete that affects multiple rows. In this case, if
  98558. ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
  98559. ** iDataCur, then its position should be preserved following the delete
  98560. ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
  98561. ** position of iDataCur should be preserved instead.
  98562. **
  98563. ** iIdxNoSeek:
  98564. ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
  98565. ** then it identifies an index cursor (from within array of cursors
  98566. ** starting at iIdxCur) that already points to the index entry to be deleted.
  98567. ** Except, this optimization is disabled if there are BEFORE triggers since
  98568. ** the trigger body might have moved the cursor.
  98569. */
  98570. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  98571. Parse *pParse, /* Parsing context */
  98572. Table *pTab, /* Table containing the row to be deleted */
  98573. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  98574. int iDataCur, /* Cursor from which column data is extracted */
  98575. int iIdxCur, /* First index cursor */
  98576. int iPk, /* First memory cell containing the PRIMARY KEY */
  98577. i16 nPk, /* Number of PRIMARY KEY memory cells */
  98578. u8 count, /* If non-zero, increment the row change counter */
  98579. u8 onconf, /* Default ON CONFLICT policy for triggers */
  98580. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  98581. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  98582. ){
  98583. Vdbe *v = pParse->pVdbe; /* Vdbe */
  98584. int iOld = 0; /* First register in OLD.* array */
  98585. int iLabel; /* Label resolved to end of generated code */
  98586. u8 opSeek; /* Seek opcode */
  98587. /* Vdbe is guaranteed to have been allocated by this stage. */
  98588. assert( v );
  98589. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  98590. iDataCur, iIdxCur, iPk, (int)nPk));
  98591. /* Seek cursor iCur to the row to delete. If this row no longer exists
  98592. ** (this can happen if a trigger program has already deleted it), do
  98593. ** not attempt to delete it or fire any DELETE triggers. */
  98594. iLabel = sqlite3VdbeMakeLabel(v);
  98595. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  98596. if( eMode==ONEPASS_OFF ){
  98597. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  98598. VdbeCoverageIf(v, opSeek==OP_NotExists);
  98599. VdbeCoverageIf(v, opSeek==OP_NotFound);
  98600. }
  98601. /* If there are any triggers to fire, allocate a range of registers to
  98602. ** use for the old.* references in the triggers. */
  98603. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  98604. u32 mask; /* Mask of OLD.* columns in use */
  98605. int iCol; /* Iterator used while populating OLD.* */
  98606. int addrStart; /* Start of BEFORE trigger programs */
  98607. /* TODO: Could use temporary registers here. Also could attempt to
  98608. ** avoid copying the contents of the rowid register. */
  98609. mask = sqlite3TriggerColmask(
  98610. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  98611. );
  98612. mask |= sqlite3FkOldmask(pParse, pTab);
  98613. iOld = pParse->nMem+1;
  98614. pParse->nMem += (1 + pTab->nCol);
  98615. /* Populate the OLD.* pseudo-table register array. These values will be
  98616. ** used by any BEFORE and AFTER triggers that exist. */
  98617. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  98618. for(iCol=0; iCol<pTab->nCol; iCol++){
  98619. testcase( mask!=0xffffffff && iCol==31 );
  98620. testcase( mask!=0xffffffff && iCol==32 );
  98621. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  98622. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  98623. }
  98624. }
  98625. /* Invoke BEFORE DELETE trigger programs. */
  98626. addrStart = sqlite3VdbeCurrentAddr(v);
  98627. sqlite3CodeRowTrigger(pParse, pTrigger,
  98628. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  98629. );
  98630. /* If any BEFORE triggers were coded, then seek the cursor to the
  98631. ** row to be deleted again. It may be that the BEFORE triggers moved
  98632. ** the cursor or already deleted the row that the cursor was
  98633. ** pointing to.
  98634. **
  98635. ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
  98636. ** may have moved that cursor.
  98637. */
  98638. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  98639. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  98640. VdbeCoverageIf(v, opSeek==OP_NotExists);
  98641. VdbeCoverageIf(v, opSeek==OP_NotFound);
  98642. testcase( iIdxNoSeek>=0 );
  98643. iIdxNoSeek = -1;
  98644. }
  98645. /* Do FK processing. This call checks that any FK constraints that
  98646. ** refer to this table (i.e. constraints attached to other tables)
  98647. ** are not violated by deleting this row. */
  98648. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  98649. }
  98650. /* Delete the index and table entries. Skip this step if pTab is really
  98651. ** a view (in which case the only effect of the DELETE statement is to
  98652. ** fire the INSTEAD OF triggers).
  98653. **
  98654. ** If variable 'count' is non-zero, then this OP_Delete instruction should
  98655. ** invoke the update-hook. The pre-update-hook, on the other hand should
  98656. ** be invoked unless table pTab is a system table. The difference is that
  98657. ** the update-hook is not invoked for rows removed by REPLACE, but the
  98658. ** pre-update-hook is.
  98659. */
  98660. if( pTab->pSelect==0 ){
  98661. u8 p5 = 0;
  98662. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  98663. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  98664. if( pParse->nested==0 ){
  98665. sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
  98666. }
  98667. if( eMode!=ONEPASS_OFF ){
  98668. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  98669. }
  98670. if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
  98671. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  98672. }
  98673. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  98674. sqlite3VdbeChangeP5(v, p5);
  98675. }
  98676. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  98677. ** handle rows (possibly in other tables) that refer via a foreign key
  98678. ** to the row just deleted. */
  98679. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  98680. /* Invoke AFTER DELETE trigger programs. */
  98681. sqlite3CodeRowTrigger(pParse, pTrigger,
  98682. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  98683. );
  98684. /* Jump here if the row had already been deleted before any BEFORE
  98685. ** trigger programs were invoked. Or if a trigger program throws a
  98686. ** RAISE(IGNORE) exception. */
  98687. sqlite3VdbeResolveLabel(v, iLabel);
  98688. VdbeModuleComment((v, "END: GenRowDel()"));
  98689. }
  98690. /*
  98691. ** This routine generates VDBE code that causes the deletion of all
  98692. ** index entries associated with a single row of a single table, pTab
  98693. **
  98694. ** Preconditions:
  98695. **
  98696. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  98697. ** btree for the table pTab. (This will be either the table itself
  98698. ** for rowid tables or to the primary key index for WITHOUT ROWID
  98699. ** tables.)
  98700. **
  98701. ** 2. Read/write cursors for all indices of pTab must be open as
  98702. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  98703. ** index is the 0-th index.)
  98704. **
  98705. ** 3. The "iDataCur" cursor must be already be positioned on the row
  98706. ** that is to be deleted.
  98707. */
  98708. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  98709. Parse *pParse, /* Parsing and code generating context */
  98710. Table *pTab, /* Table containing the row to be deleted */
  98711. int iDataCur, /* Cursor of table holding data. */
  98712. int iIdxCur, /* First index cursor */
  98713. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  98714. int iIdxNoSeek /* Do not delete from this cursor */
  98715. ){
  98716. int i; /* Index loop counter */
  98717. int r1 = -1; /* Register holding an index key */
  98718. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  98719. Index *pIdx; /* Current index */
  98720. Index *pPrior = 0; /* Prior index */
  98721. Vdbe *v; /* The prepared statement under construction */
  98722. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  98723. v = pParse->pVdbe;
  98724. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  98725. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  98726. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  98727. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  98728. if( pIdx==pPk ) continue;
  98729. if( iIdxCur+i==iIdxNoSeek ) continue;
  98730. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  98731. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  98732. &iPartIdxLabel, pPrior, r1);
  98733. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  98734. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  98735. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  98736. pPrior = pIdx;
  98737. }
  98738. }
  98739. /*
  98740. ** Generate code that will assemble an index key and stores it in register
  98741. ** regOut. The key with be for index pIdx which is an index on pTab.
  98742. ** iCur is the index of a cursor open on the pTab table and pointing to
  98743. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  98744. ** iCur must be the cursor of the PRIMARY KEY index.
  98745. **
  98746. ** Return a register number which is the first in a block of
  98747. ** registers that holds the elements of the index key. The
  98748. ** block of registers has already been deallocated by the time
  98749. ** this routine returns.
  98750. **
  98751. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  98752. ** to that label if pIdx is a partial index that should be skipped.
  98753. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  98754. ** A partial index should be skipped if its WHERE clause evaluates
  98755. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  98756. ** will be set to zero which is an empty label that is ignored by
  98757. ** sqlite3ResolvePartIdxLabel().
  98758. **
  98759. ** The pPrior and regPrior parameters are used to implement a cache to
  98760. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  98761. ** a pointer to a different index for which an index key has just been
  98762. ** computed into register regPrior. If the current pIdx index is generating
  98763. ** its key into the same sequence of registers and if pPrior and pIdx share
  98764. ** a column in common, then the register corresponding to that column already
  98765. ** holds the correct value and the loading of that register is skipped.
  98766. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  98767. ** on a table with multiple indices, and especially with the ROWID or
  98768. ** PRIMARY KEY columns of the index.
  98769. */
  98770. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  98771. Parse *pParse, /* Parsing context */
  98772. Index *pIdx, /* The index for which to generate a key */
  98773. int iDataCur, /* Cursor number from which to take column data */
  98774. int regOut, /* Put the new key into this register if not 0 */
  98775. int prefixOnly, /* Compute only a unique prefix of the key */
  98776. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  98777. Index *pPrior, /* Previously generated index key */
  98778. int regPrior /* Register holding previous generated key */
  98779. ){
  98780. Vdbe *v = pParse->pVdbe;
  98781. int j;
  98782. int regBase;
  98783. int nCol;
  98784. if( piPartIdxLabel ){
  98785. if( pIdx->pPartIdxWhere ){
  98786. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  98787. pParse->iSelfTab = iDataCur;
  98788. sqlite3ExprCachePush(pParse);
  98789. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  98790. SQLITE_JUMPIFNULL);
  98791. }else{
  98792. *piPartIdxLabel = 0;
  98793. }
  98794. }
  98795. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  98796. regBase = sqlite3GetTempRange(pParse, nCol);
  98797. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  98798. for(j=0; j<nCol; j++){
  98799. if( pPrior
  98800. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  98801. && pPrior->aiColumn[j]!=XN_EXPR
  98802. ){
  98803. /* This column was already computed by the previous index */
  98804. continue;
  98805. }
  98806. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  98807. /* If the column affinity is REAL but the number is an integer, then it
  98808. ** might be stored in the table as an integer (using a compact
  98809. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  98810. ** But we are getting ready to store this value back into an index, where
  98811. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  98812. ** opcode if it is present */
  98813. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  98814. }
  98815. if( regOut ){
  98816. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  98817. if( pIdx->pTable->pSelect ){
  98818. const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
  98819. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  98820. }
  98821. }
  98822. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  98823. return regBase;
  98824. }
  98825. /*
  98826. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  98827. ** because it was a partial index, then this routine should be called to
  98828. ** resolve that label.
  98829. */
  98830. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  98831. if( iLabel ){
  98832. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  98833. sqlite3ExprCachePop(pParse);
  98834. }
  98835. }
  98836. /************** End of delete.c **********************************************/
  98837. /************** Begin file func.c ********************************************/
  98838. /*
  98839. ** 2002 February 23
  98840. **
  98841. ** The author disclaims copyright to this source code. In place of
  98842. ** a legal notice, here is a blessing:
  98843. **
  98844. ** May you do good and not evil.
  98845. ** May you find forgiveness for yourself and forgive others.
  98846. ** May you share freely, never taking more than you give.
  98847. **
  98848. *************************************************************************
  98849. ** This file contains the C-language implementations for many of the SQL
  98850. ** functions of SQLite. (Some function, and in particular the date and
  98851. ** time functions, are implemented separately.)
  98852. */
  98853. /* #include "sqliteInt.h" */
  98854. /* #include <stdlib.h> */
  98855. /* #include <assert.h> */
  98856. /* #include "vdbeInt.h" */
  98857. /*
  98858. ** Return the collating function associated with a function.
  98859. */
  98860. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  98861. VdbeOp *pOp;
  98862. assert( context->pVdbe!=0 );
  98863. pOp = &context->pVdbe->aOp[context->iOp-1];
  98864. assert( pOp->opcode==OP_CollSeq );
  98865. assert( pOp->p4type==P4_COLLSEQ );
  98866. return pOp->p4.pColl;
  98867. }
  98868. /*
  98869. ** Indicate that the accumulator load should be skipped on this
  98870. ** iteration of the aggregate loop.
  98871. */
  98872. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  98873. context->skipFlag = 1;
  98874. }
  98875. /*
  98876. ** Implementation of the non-aggregate min() and max() functions
  98877. */
  98878. static void minmaxFunc(
  98879. sqlite3_context *context,
  98880. int argc,
  98881. sqlite3_value **argv
  98882. ){
  98883. int i;
  98884. int mask; /* 0 for min() or 0xffffffff for max() */
  98885. int iBest;
  98886. CollSeq *pColl;
  98887. assert( argc>1 );
  98888. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  98889. pColl = sqlite3GetFuncCollSeq(context);
  98890. assert( pColl );
  98891. assert( mask==-1 || mask==0 );
  98892. iBest = 0;
  98893. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  98894. for(i=1; i<argc; i++){
  98895. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  98896. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  98897. testcase( mask==0 );
  98898. iBest = i;
  98899. }
  98900. }
  98901. sqlite3_result_value(context, argv[iBest]);
  98902. }
  98903. /*
  98904. ** Return the type of the argument.
  98905. */
  98906. static void typeofFunc(
  98907. sqlite3_context *context,
  98908. int NotUsed,
  98909. sqlite3_value **argv
  98910. ){
  98911. const char *z = 0;
  98912. UNUSED_PARAMETER(NotUsed);
  98913. switch( sqlite3_value_type(argv[0]) ){
  98914. case SQLITE_INTEGER: z = "integer"; break;
  98915. case SQLITE_TEXT: z = "text"; break;
  98916. case SQLITE_FLOAT: z = "real"; break;
  98917. case SQLITE_BLOB: z = "blob"; break;
  98918. default: z = "null"; break;
  98919. }
  98920. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  98921. }
  98922. /*
  98923. ** Implementation of the length() function
  98924. */
  98925. static void lengthFunc(
  98926. sqlite3_context *context,
  98927. int argc,
  98928. sqlite3_value **argv
  98929. ){
  98930. int len;
  98931. assert( argc==1 );
  98932. UNUSED_PARAMETER(argc);
  98933. switch( sqlite3_value_type(argv[0]) ){
  98934. case SQLITE_BLOB:
  98935. case SQLITE_INTEGER:
  98936. case SQLITE_FLOAT: {
  98937. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  98938. break;
  98939. }
  98940. case SQLITE_TEXT: {
  98941. const unsigned char *z = sqlite3_value_text(argv[0]);
  98942. if( z==0 ) return;
  98943. len = 0;
  98944. while( *z ){
  98945. len++;
  98946. SQLITE_SKIP_UTF8(z);
  98947. }
  98948. sqlite3_result_int(context, len);
  98949. break;
  98950. }
  98951. default: {
  98952. sqlite3_result_null(context);
  98953. break;
  98954. }
  98955. }
  98956. }
  98957. /*
  98958. ** Implementation of the abs() function.
  98959. **
  98960. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  98961. ** the numeric argument X.
  98962. */
  98963. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  98964. assert( argc==1 );
  98965. UNUSED_PARAMETER(argc);
  98966. switch( sqlite3_value_type(argv[0]) ){
  98967. case SQLITE_INTEGER: {
  98968. i64 iVal = sqlite3_value_int64(argv[0]);
  98969. if( iVal<0 ){
  98970. if( iVal==SMALLEST_INT64 ){
  98971. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  98972. ** then abs(X) throws an integer overflow error since there is no
  98973. ** equivalent positive 64-bit two complement value. */
  98974. sqlite3_result_error(context, "integer overflow", -1);
  98975. return;
  98976. }
  98977. iVal = -iVal;
  98978. }
  98979. sqlite3_result_int64(context, iVal);
  98980. break;
  98981. }
  98982. case SQLITE_NULL: {
  98983. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  98984. sqlite3_result_null(context);
  98985. break;
  98986. }
  98987. default: {
  98988. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  98989. ** something that can be converted into a number, we have:
  98990. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  98991. ** that cannot be converted to a numeric value.
  98992. */
  98993. double rVal = sqlite3_value_double(argv[0]);
  98994. if( rVal<0 ) rVal = -rVal;
  98995. sqlite3_result_double(context, rVal);
  98996. break;
  98997. }
  98998. }
  98999. }
  99000. /*
  99001. ** Implementation of the instr() function.
  99002. **
  99003. ** instr(haystack,needle) finds the first occurrence of needle
  99004. ** in haystack and returns the number of previous characters plus 1,
  99005. ** or 0 if needle does not occur within haystack.
  99006. **
  99007. ** If both haystack and needle are BLOBs, then the result is one more than
  99008. ** the number of bytes in haystack prior to the first occurrence of needle,
  99009. ** or 0 if needle never occurs in haystack.
  99010. */
  99011. static void instrFunc(
  99012. sqlite3_context *context,
  99013. int argc,
  99014. sqlite3_value **argv
  99015. ){
  99016. const unsigned char *zHaystack;
  99017. const unsigned char *zNeedle;
  99018. int nHaystack;
  99019. int nNeedle;
  99020. int typeHaystack, typeNeedle;
  99021. int N = 1;
  99022. int isText;
  99023. UNUSED_PARAMETER(argc);
  99024. typeHaystack = sqlite3_value_type(argv[0]);
  99025. typeNeedle = sqlite3_value_type(argv[1]);
  99026. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  99027. nHaystack = sqlite3_value_bytes(argv[0]);
  99028. nNeedle = sqlite3_value_bytes(argv[1]);
  99029. if( nNeedle>0 ){
  99030. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  99031. zHaystack = sqlite3_value_blob(argv[0]);
  99032. zNeedle = sqlite3_value_blob(argv[1]);
  99033. isText = 0;
  99034. }else{
  99035. zHaystack = sqlite3_value_text(argv[0]);
  99036. zNeedle = sqlite3_value_text(argv[1]);
  99037. isText = 1;
  99038. }
  99039. if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
  99040. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  99041. N++;
  99042. do{
  99043. nHaystack--;
  99044. zHaystack++;
  99045. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  99046. }
  99047. if( nNeedle>nHaystack ) N = 0;
  99048. }
  99049. sqlite3_result_int(context, N);
  99050. }
  99051. /*
  99052. ** Implementation of the printf() function.
  99053. */
  99054. static void printfFunc(
  99055. sqlite3_context *context,
  99056. int argc,
  99057. sqlite3_value **argv
  99058. ){
  99059. PrintfArguments x;
  99060. StrAccum str;
  99061. const char *zFormat;
  99062. int n;
  99063. sqlite3 *db = sqlite3_context_db_handle(context);
  99064. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  99065. x.nArg = argc-1;
  99066. x.nUsed = 0;
  99067. x.apArg = argv+1;
  99068. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  99069. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  99070. sqlite3XPrintf(&str, zFormat, &x);
  99071. n = str.nChar;
  99072. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  99073. SQLITE_DYNAMIC);
  99074. }
  99075. }
  99076. /*
  99077. ** Implementation of the substr() function.
  99078. **
  99079. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  99080. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  99081. ** of x. If x is text, then we actually count UTF-8 characters.
  99082. ** If x is a blob, then we count bytes.
  99083. **
  99084. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  99085. **
  99086. ** If p2 is negative, return the p2 characters preceding p1.
  99087. */
  99088. static void substrFunc(
  99089. sqlite3_context *context,
  99090. int argc,
  99091. sqlite3_value **argv
  99092. ){
  99093. const unsigned char *z;
  99094. const unsigned char *z2;
  99095. int len;
  99096. int p0type;
  99097. i64 p1, p2;
  99098. int negP2 = 0;
  99099. assert( argc==3 || argc==2 );
  99100. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  99101. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  99102. ){
  99103. return;
  99104. }
  99105. p0type = sqlite3_value_type(argv[0]);
  99106. p1 = sqlite3_value_int(argv[1]);
  99107. if( p0type==SQLITE_BLOB ){
  99108. len = sqlite3_value_bytes(argv[0]);
  99109. z = sqlite3_value_blob(argv[0]);
  99110. if( z==0 ) return;
  99111. assert( len==sqlite3_value_bytes(argv[0]) );
  99112. }else{
  99113. z = sqlite3_value_text(argv[0]);
  99114. if( z==0 ) return;
  99115. len = 0;
  99116. if( p1<0 ){
  99117. for(z2=z; *z2; len++){
  99118. SQLITE_SKIP_UTF8(z2);
  99119. }
  99120. }
  99121. }
  99122. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  99123. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  99124. ** as substr(X,1,N) - it returns the first N characters of X. This
  99125. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  99126. ** from 2009-02-02 for compatibility of applications that exploited the
  99127. ** old buggy behavior. */
  99128. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  99129. #endif
  99130. if( argc==3 ){
  99131. p2 = sqlite3_value_int(argv[2]);
  99132. if( p2<0 ){
  99133. p2 = -p2;
  99134. negP2 = 1;
  99135. }
  99136. }else{
  99137. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  99138. }
  99139. if( p1<0 ){
  99140. p1 += len;
  99141. if( p1<0 ){
  99142. p2 += p1;
  99143. if( p2<0 ) p2 = 0;
  99144. p1 = 0;
  99145. }
  99146. }else if( p1>0 ){
  99147. p1--;
  99148. }else if( p2>0 ){
  99149. p2--;
  99150. }
  99151. if( negP2 ){
  99152. p1 -= p2;
  99153. if( p1<0 ){
  99154. p2 += p1;
  99155. p1 = 0;
  99156. }
  99157. }
  99158. assert( p1>=0 && p2>=0 );
  99159. if( p0type!=SQLITE_BLOB ){
  99160. while( *z && p1 ){
  99161. SQLITE_SKIP_UTF8(z);
  99162. p1--;
  99163. }
  99164. for(z2=z; *z2 && p2; p2--){
  99165. SQLITE_SKIP_UTF8(z2);
  99166. }
  99167. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  99168. SQLITE_UTF8);
  99169. }else{
  99170. if( p1+p2>len ){
  99171. p2 = len-p1;
  99172. if( p2<0 ) p2 = 0;
  99173. }
  99174. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  99175. }
  99176. }
  99177. /*
  99178. ** Implementation of the round() function
  99179. */
  99180. #ifndef SQLITE_OMIT_FLOATING_POINT
  99181. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  99182. int n = 0;
  99183. double r;
  99184. char *zBuf;
  99185. assert( argc==1 || argc==2 );
  99186. if( argc==2 ){
  99187. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  99188. n = sqlite3_value_int(argv[1]);
  99189. if( n>30 ) n = 30;
  99190. if( n<0 ) n = 0;
  99191. }
  99192. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  99193. r = sqlite3_value_double(argv[0]);
  99194. /* If Y==0 and X will fit in a 64-bit int,
  99195. ** handle the rounding directly,
  99196. ** otherwise use printf.
  99197. */
  99198. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  99199. r = (double)((sqlite_int64)(r+0.5));
  99200. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  99201. r = -(double)((sqlite_int64)((-r)+0.5));
  99202. }else{
  99203. zBuf = sqlite3_mprintf("%.*f",n,r);
  99204. if( zBuf==0 ){
  99205. sqlite3_result_error_nomem(context);
  99206. return;
  99207. }
  99208. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  99209. sqlite3_free(zBuf);
  99210. }
  99211. sqlite3_result_double(context, r);
  99212. }
  99213. #endif
  99214. /*
  99215. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  99216. ** allocation fails, call sqlite3_result_error_nomem() to notify
  99217. ** the database handle that malloc() has failed and return NULL.
  99218. ** If nByte is larger than the maximum string or blob length, then
  99219. ** raise an SQLITE_TOOBIG exception and return NULL.
  99220. */
  99221. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  99222. char *z;
  99223. sqlite3 *db = sqlite3_context_db_handle(context);
  99224. assert( nByte>0 );
  99225. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  99226. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  99227. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  99228. sqlite3_result_error_toobig(context);
  99229. z = 0;
  99230. }else{
  99231. z = sqlite3Malloc(nByte);
  99232. if( !z ){
  99233. sqlite3_result_error_nomem(context);
  99234. }
  99235. }
  99236. return z;
  99237. }
  99238. /*
  99239. ** Implementation of the upper() and lower() SQL functions.
  99240. */
  99241. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  99242. char *z1;
  99243. const char *z2;
  99244. int i, n;
  99245. UNUSED_PARAMETER(argc);
  99246. z2 = (char*)sqlite3_value_text(argv[0]);
  99247. n = sqlite3_value_bytes(argv[0]);
  99248. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  99249. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  99250. if( z2 ){
  99251. z1 = contextMalloc(context, ((i64)n)+1);
  99252. if( z1 ){
  99253. for(i=0; i<n; i++){
  99254. z1[i] = (char)sqlite3Toupper(z2[i]);
  99255. }
  99256. sqlite3_result_text(context, z1, n, sqlite3_free);
  99257. }
  99258. }
  99259. }
  99260. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  99261. char *z1;
  99262. const char *z2;
  99263. int i, n;
  99264. UNUSED_PARAMETER(argc);
  99265. z2 = (char*)sqlite3_value_text(argv[0]);
  99266. n = sqlite3_value_bytes(argv[0]);
  99267. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  99268. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  99269. if( z2 ){
  99270. z1 = contextMalloc(context, ((i64)n)+1);
  99271. if( z1 ){
  99272. for(i=0; i<n; i++){
  99273. z1[i] = sqlite3Tolower(z2[i]);
  99274. }
  99275. sqlite3_result_text(context, z1, n, sqlite3_free);
  99276. }
  99277. }
  99278. }
  99279. /*
  99280. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  99281. ** as VDBE code so that unused argument values do not have to be computed.
  99282. ** However, we still need some kind of function implementation for this
  99283. ** routines in the function table. The noopFunc macro provides this.
  99284. ** noopFunc will never be called so it doesn't matter what the implementation
  99285. ** is. We might as well use the "version()" function as a substitute.
  99286. */
  99287. #define noopFunc versionFunc /* Substitute function - never called */
  99288. /*
  99289. ** Implementation of random(). Return a random integer.
  99290. */
  99291. static void randomFunc(
  99292. sqlite3_context *context,
  99293. int NotUsed,
  99294. sqlite3_value **NotUsed2
  99295. ){
  99296. sqlite_int64 r;
  99297. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99298. sqlite3_randomness(sizeof(r), &r);
  99299. if( r<0 ){
  99300. /* We need to prevent a random number of 0x8000000000000000
  99301. ** (or -9223372036854775808) since when you do abs() of that
  99302. ** number of you get the same value back again. To do this
  99303. ** in a way that is testable, mask the sign bit off of negative
  99304. ** values, resulting in a positive value. Then take the
  99305. ** 2s complement of that positive value. The end result can
  99306. ** therefore be no less than -9223372036854775807.
  99307. */
  99308. r = -(r & LARGEST_INT64);
  99309. }
  99310. sqlite3_result_int64(context, r);
  99311. }
  99312. /*
  99313. ** Implementation of randomblob(N). Return a random blob
  99314. ** that is N bytes long.
  99315. */
  99316. static void randomBlob(
  99317. sqlite3_context *context,
  99318. int argc,
  99319. sqlite3_value **argv
  99320. ){
  99321. int n;
  99322. unsigned char *p;
  99323. assert( argc==1 );
  99324. UNUSED_PARAMETER(argc);
  99325. n = sqlite3_value_int(argv[0]);
  99326. if( n<1 ){
  99327. n = 1;
  99328. }
  99329. p = contextMalloc(context, n);
  99330. if( p ){
  99331. sqlite3_randomness(n, p);
  99332. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  99333. }
  99334. }
  99335. /*
  99336. ** Implementation of the last_insert_rowid() SQL function. The return
  99337. ** value is the same as the sqlite3_last_insert_rowid() API function.
  99338. */
  99339. static void last_insert_rowid(
  99340. sqlite3_context *context,
  99341. int NotUsed,
  99342. sqlite3_value **NotUsed2
  99343. ){
  99344. sqlite3 *db = sqlite3_context_db_handle(context);
  99345. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99346. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  99347. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  99348. ** function. */
  99349. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  99350. }
  99351. /*
  99352. ** Implementation of the changes() SQL function.
  99353. **
  99354. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  99355. ** around the sqlite3_changes() C/C++ function and hence follows the same
  99356. ** rules for counting changes.
  99357. */
  99358. static void changes(
  99359. sqlite3_context *context,
  99360. int NotUsed,
  99361. sqlite3_value **NotUsed2
  99362. ){
  99363. sqlite3 *db = sqlite3_context_db_handle(context);
  99364. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99365. sqlite3_result_int(context, sqlite3_changes(db));
  99366. }
  99367. /*
  99368. ** Implementation of the total_changes() SQL function. The return value is
  99369. ** the same as the sqlite3_total_changes() API function.
  99370. */
  99371. static void total_changes(
  99372. sqlite3_context *context,
  99373. int NotUsed,
  99374. sqlite3_value **NotUsed2
  99375. ){
  99376. sqlite3 *db = sqlite3_context_db_handle(context);
  99377. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99378. /* IMP: R-52756-41993 This function is a wrapper around the
  99379. ** sqlite3_total_changes() C/C++ interface. */
  99380. sqlite3_result_int(context, sqlite3_total_changes(db));
  99381. }
  99382. /*
  99383. ** A structure defining how to do GLOB-style comparisons.
  99384. */
  99385. struct compareInfo {
  99386. u8 matchAll; /* "*" or "%" */
  99387. u8 matchOne; /* "?" or "_" */
  99388. u8 matchSet; /* "[" or 0 */
  99389. u8 noCase; /* true to ignore case differences */
  99390. };
  99391. /*
  99392. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  99393. ** character is exactly one byte in size. Also, provde the Utf8Read()
  99394. ** macro for fast reading of the next character in the common case where
  99395. ** the next character is ASCII.
  99396. */
  99397. #if defined(SQLITE_EBCDIC)
  99398. # define sqlite3Utf8Read(A) (*((*A)++))
  99399. # define Utf8Read(A) (*(A++))
  99400. #else
  99401. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  99402. #endif
  99403. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  99404. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  99405. ** case. Thus 'a' LIKE 'A' would be true. */
  99406. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  99407. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  99408. ** is case sensitive causing 'a' LIKE 'A' to be false */
  99409. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  99410. /*
  99411. ** Possible error returns from patternMatch()
  99412. */
  99413. #define SQLITE_MATCH 0
  99414. #define SQLITE_NOMATCH 1
  99415. #define SQLITE_NOWILDCARDMATCH 2
  99416. /*
  99417. ** Compare two UTF-8 strings for equality where the first string is
  99418. ** a GLOB or LIKE expression. Return values:
  99419. **
  99420. ** SQLITE_MATCH: Match
  99421. ** SQLITE_NOMATCH: No match
  99422. ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
  99423. **
  99424. ** Globbing rules:
  99425. **
  99426. ** '*' Matches any sequence of zero or more characters.
  99427. **
  99428. ** '?' Matches exactly one character.
  99429. **
  99430. ** [...] Matches one character from the enclosed list of
  99431. ** characters.
  99432. **
  99433. ** [^...] Matches one character not in the enclosed list.
  99434. **
  99435. ** With the [...] and [^...] matching, a ']' character can be included
  99436. ** in the list by making it the first character after '[' or '^'. A
  99437. ** range of characters can be specified using '-'. Example:
  99438. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  99439. ** it the last character in the list.
  99440. **
  99441. ** Like matching rules:
  99442. **
  99443. ** '%' Matches any sequence of zero or more characters
  99444. **
  99445. *** '_' Matches any one character
  99446. **
  99447. ** Ec Where E is the "esc" character and c is any other
  99448. ** character, including '%', '_', and esc, match exactly c.
  99449. **
  99450. ** The comments within this routine usually assume glob matching.
  99451. **
  99452. ** This routine is usually quick, but can be N**2 in the worst case.
  99453. */
  99454. static int patternCompare(
  99455. const u8 *zPattern, /* The glob pattern */
  99456. const u8 *zString, /* The string to compare against the glob */
  99457. const struct compareInfo *pInfo, /* Information about how to do the compare */
  99458. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  99459. ){
  99460. u32 c, c2; /* Next pattern and input string chars */
  99461. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  99462. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  99463. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  99464. const u8 *zEscaped = 0; /* One past the last escaped input char */
  99465. while( (c = Utf8Read(zPattern))!=0 ){
  99466. if( c==matchAll ){ /* Match "*" */
  99467. /* Skip over multiple "*" characters in the pattern. If there
  99468. ** are also "?" characters, skip those as well, but consume a
  99469. ** single character of the input string for each "?" skipped */
  99470. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  99471. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  99472. return SQLITE_NOWILDCARDMATCH;
  99473. }
  99474. }
  99475. if( c==0 ){
  99476. return SQLITE_MATCH; /* "*" at the end of the pattern matches */
  99477. }else if( c==matchOther ){
  99478. if( pInfo->matchSet==0 ){
  99479. c = sqlite3Utf8Read(&zPattern);
  99480. if( c==0 ) return SQLITE_NOWILDCARDMATCH;
  99481. }else{
  99482. /* "[...]" immediately follows the "*". We have to do a slow
  99483. ** recursive search in this case, but it is an unusual case. */
  99484. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  99485. while( *zString ){
  99486. int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
  99487. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  99488. SQLITE_SKIP_UTF8(zString);
  99489. }
  99490. return SQLITE_NOWILDCARDMATCH;
  99491. }
  99492. }
  99493. /* At this point variable c contains the first character of the
  99494. ** pattern string past the "*". Search in the input string for the
  99495. ** first matching character and recursively continue the match from
  99496. ** that point.
  99497. **
  99498. ** For a case-insensitive search, set variable cx to be the same as
  99499. ** c but in the other case and search the input string for either
  99500. ** c or cx.
  99501. */
  99502. if( c<=0x80 ){
  99503. u32 cx;
  99504. int bMatch;
  99505. if( noCase ){
  99506. cx = sqlite3Toupper(c);
  99507. c = sqlite3Tolower(c);
  99508. }else{
  99509. cx = c;
  99510. }
  99511. while( (c2 = *(zString++))!=0 ){
  99512. if( c2!=c && c2!=cx ) continue;
  99513. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  99514. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  99515. }
  99516. }else{
  99517. int bMatch;
  99518. while( (c2 = Utf8Read(zString))!=0 ){
  99519. if( c2!=c ) continue;
  99520. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  99521. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  99522. }
  99523. }
  99524. return SQLITE_NOWILDCARDMATCH;
  99525. }
  99526. if( c==matchOther ){
  99527. if( pInfo->matchSet==0 ){
  99528. c = sqlite3Utf8Read(&zPattern);
  99529. if( c==0 ) return SQLITE_NOMATCH;
  99530. zEscaped = zPattern;
  99531. }else{
  99532. u32 prior_c = 0;
  99533. int seen = 0;
  99534. int invert = 0;
  99535. c = sqlite3Utf8Read(&zString);
  99536. if( c==0 ) return SQLITE_NOMATCH;
  99537. c2 = sqlite3Utf8Read(&zPattern);
  99538. if( c2=='^' ){
  99539. invert = 1;
  99540. c2 = sqlite3Utf8Read(&zPattern);
  99541. }
  99542. if( c2==']' ){
  99543. if( c==']' ) seen = 1;
  99544. c2 = sqlite3Utf8Read(&zPattern);
  99545. }
  99546. while( c2 && c2!=']' ){
  99547. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  99548. c2 = sqlite3Utf8Read(&zPattern);
  99549. if( c>=prior_c && c<=c2 ) seen = 1;
  99550. prior_c = 0;
  99551. }else{
  99552. if( c==c2 ){
  99553. seen = 1;
  99554. }
  99555. prior_c = c2;
  99556. }
  99557. c2 = sqlite3Utf8Read(&zPattern);
  99558. }
  99559. if( c2==0 || (seen ^ invert)==0 ){
  99560. return SQLITE_NOMATCH;
  99561. }
  99562. continue;
  99563. }
  99564. }
  99565. c2 = Utf8Read(zString);
  99566. if( c==c2 ) continue;
  99567. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
  99568. continue;
  99569. }
  99570. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  99571. return SQLITE_NOMATCH;
  99572. }
  99573. return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
  99574. }
  99575. /*
  99576. ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
  99577. ** non-zero if there is no match.
  99578. */
  99579. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  99580. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
  99581. }
  99582. /*
  99583. ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
  99584. ** a miss - like strcmp().
  99585. */
  99586. SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  99587. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
  99588. }
  99589. /*
  99590. ** Count the number of times that the LIKE operator (or GLOB which is
  99591. ** just a variation of LIKE) gets called. This is used for testing
  99592. ** only.
  99593. */
  99594. #ifdef SQLITE_TEST
  99595. SQLITE_API int sqlite3_like_count = 0;
  99596. #endif
  99597. /*
  99598. ** Implementation of the like() SQL function. This function implements
  99599. ** the build-in LIKE operator. The first argument to the function is the
  99600. ** pattern and the second argument is the string. So, the SQL statements:
  99601. **
  99602. ** A LIKE B
  99603. **
  99604. ** is implemented as like(B,A).
  99605. **
  99606. ** This same function (with a different compareInfo structure) computes
  99607. ** the GLOB operator.
  99608. */
  99609. static void likeFunc(
  99610. sqlite3_context *context,
  99611. int argc,
  99612. sqlite3_value **argv
  99613. ){
  99614. const unsigned char *zA, *zB;
  99615. u32 escape;
  99616. int nPat;
  99617. sqlite3 *db = sqlite3_context_db_handle(context);
  99618. struct compareInfo *pInfo = sqlite3_user_data(context);
  99619. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  99620. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  99621. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  99622. ){
  99623. #ifdef SQLITE_TEST
  99624. sqlite3_like_count++;
  99625. #endif
  99626. sqlite3_result_int(context, 0);
  99627. return;
  99628. }
  99629. #endif
  99630. zB = sqlite3_value_text(argv[0]);
  99631. zA = sqlite3_value_text(argv[1]);
  99632. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  99633. ** of deep recursion and N*N behavior in patternCompare().
  99634. */
  99635. nPat = sqlite3_value_bytes(argv[0]);
  99636. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  99637. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  99638. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  99639. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  99640. return;
  99641. }
  99642. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  99643. if( argc==3 ){
  99644. /* The escape character string must consist of a single UTF-8 character.
  99645. ** Otherwise, return an error.
  99646. */
  99647. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  99648. if( zEsc==0 ) return;
  99649. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  99650. sqlite3_result_error(context,
  99651. "ESCAPE expression must be a single character", -1);
  99652. return;
  99653. }
  99654. escape = sqlite3Utf8Read(&zEsc);
  99655. }else{
  99656. escape = pInfo->matchSet;
  99657. }
  99658. if( zA && zB ){
  99659. #ifdef SQLITE_TEST
  99660. sqlite3_like_count++;
  99661. #endif
  99662. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
  99663. }
  99664. }
  99665. /*
  99666. ** Implementation of the NULLIF(x,y) function. The result is the first
  99667. ** argument if the arguments are different. The result is NULL if the
  99668. ** arguments are equal to each other.
  99669. */
  99670. static void nullifFunc(
  99671. sqlite3_context *context,
  99672. int NotUsed,
  99673. sqlite3_value **argv
  99674. ){
  99675. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  99676. UNUSED_PARAMETER(NotUsed);
  99677. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  99678. sqlite3_result_value(context, argv[0]);
  99679. }
  99680. }
  99681. /*
  99682. ** Implementation of the sqlite_version() function. The result is the version
  99683. ** of the SQLite library that is running.
  99684. */
  99685. static void versionFunc(
  99686. sqlite3_context *context,
  99687. int NotUsed,
  99688. sqlite3_value **NotUsed2
  99689. ){
  99690. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99691. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  99692. ** sqlite3_libversion() C-interface. */
  99693. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  99694. }
  99695. /*
  99696. ** Implementation of the sqlite_source_id() function. The result is a string
  99697. ** that identifies the particular version of the source code used to build
  99698. ** SQLite.
  99699. */
  99700. static void sourceidFunc(
  99701. sqlite3_context *context,
  99702. int NotUsed,
  99703. sqlite3_value **NotUsed2
  99704. ){
  99705. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99706. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  99707. ** sqlite3_sourceid() C interface. */
  99708. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  99709. }
  99710. /*
  99711. ** Implementation of the sqlite_log() function. This is a wrapper around
  99712. ** sqlite3_log(). The return value is NULL. The function exists purely for
  99713. ** its side-effects.
  99714. */
  99715. static void errlogFunc(
  99716. sqlite3_context *context,
  99717. int argc,
  99718. sqlite3_value **argv
  99719. ){
  99720. UNUSED_PARAMETER(argc);
  99721. UNUSED_PARAMETER(context);
  99722. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  99723. }
  99724. /*
  99725. ** Implementation of the sqlite_compileoption_used() function.
  99726. ** The result is an integer that identifies if the compiler option
  99727. ** was used to build SQLite.
  99728. */
  99729. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  99730. static void compileoptionusedFunc(
  99731. sqlite3_context *context,
  99732. int argc,
  99733. sqlite3_value **argv
  99734. ){
  99735. const char *zOptName;
  99736. assert( argc==1 );
  99737. UNUSED_PARAMETER(argc);
  99738. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  99739. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  99740. ** function.
  99741. */
  99742. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  99743. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  99744. }
  99745. }
  99746. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  99747. /*
  99748. ** Implementation of the sqlite_compileoption_get() function.
  99749. ** The result is a string that identifies the compiler options
  99750. ** used to build SQLite.
  99751. */
  99752. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  99753. static void compileoptiongetFunc(
  99754. sqlite3_context *context,
  99755. int argc,
  99756. sqlite3_value **argv
  99757. ){
  99758. int n;
  99759. assert( argc==1 );
  99760. UNUSED_PARAMETER(argc);
  99761. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  99762. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  99763. */
  99764. n = sqlite3_value_int(argv[0]);
  99765. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  99766. }
  99767. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  99768. /* Array for converting from half-bytes (nybbles) into ASCII hex
  99769. ** digits. */
  99770. static const char hexdigits[] = {
  99771. '0', '1', '2', '3', '4', '5', '6', '7',
  99772. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  99773. };
  99774. /*
  99775. ** Implementation of the QUOTE() function. This function takes a single
  99776. ** argument. If the argument is numeric, the return value is the same as
  99777. ** the argument. If the argument is NULL, the return value is the string
  99778. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  99779. ** single-quote escapes.
  99780. */
  99781. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  99782. assert( argc==1 );
  99783. UNUSED_PARAMETER(argc);
  99784. switch( sqlite3_value_type(argv[0]) ){
  99785. case SQLITE_FLOAT: {
  99786. double r1, r2;
  99787. char zBuf[50];
  99788. r1 = sqlite3_value_double(argv[0]);
  99789. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  99790. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  99791. if( r1!=r2 ){
  99792. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  99793. }
  99794. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  99795. break;
  99796. }
  99797. case SQLITE_INTEGER: {
  99798. sqlite3_result_value(context, argv[0]);
  99799. break;
  99800. }
  99801. case SQLITE_BLOB: {
  99802. char *zText = 0;
  99803. char const *zBlob = sqlite3_value_blob(argv[0]);
  99804. int nBlob = sqlite3_value_bytes(argv[0]);
  99805. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  99806. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  99807. if( zText ){
  99808. int i;
  99809. for(i=0; i<nBlob; i++){
  99810. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  99811. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  99812. }
  99813. zText[(nBlob*2)+2] = '\'';
  99814. zText[(nBlob*2)+3] = '\0';
  99815. zText[0] = 'X';
  99816. zText[1] = '\'';
  99817. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  99818. sqlite3_free(zText);
  99819. }
  99820. break;
  99821. }
  99822. case SQLITE_TEXT: {
  99823. int i,j;
  99824. u64 n;
  99825. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  99826. char *z;
  99827. if( zArg==0 ) return;
  99828. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  99829. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  99830. if( z ){
  99831. z[0] = '\'';
  99832. for(i=0, j=1; zArg[i]; i++){
  99833. z[j++] = zArg[i];
  99834. if( zArg[i]=='\'' ){
  99835. z[j++] = '\'';
  99836. }
  99837. }
  99838. z[j++] = '\'';
  99839. z[j] = 0;
  99840. sqlite3_result_text(context, z, j, sqlite3_free);
  99841. }
  99842. break;
  99843. }
  99844. default: {
  99845. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  99846. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  99847. break;
  99848. }
  99849. }
  99850. }
  99851. /*
  99852. ** The unicode() function. Return the integer unicode code-point value
  99853. ** for the first character of the input string.
  99854. */
  99855. static void unicodeFunc(
  99856. sqlite3_context *context,
  99857. int argc,
  99858. sqlite3_value **argv
  99859. ){
  99860. const unsigned char *z = sqlite3_value_text(argv[0]);
  99861. (void)argc;
  99862. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  99863. }
  99864. /*
  99865. ** The char() function takes zero or more arguments, each of which is
  99866. ** an integer. It constructs a string where each character of the string
  99867. ** is the unicode character for the corresponding integer argument.
  99868. */
  99869. static void charFunc(
  99870. sqlite3_context *context,
  99871. int argc,
  99872. sqlite3_value **argv
  99873. ){
  99874. unsigned char *z, *zOut;
  99875. int i;
  99876. zOut = z = sqlite3_malloc64( argc*4+1 );
  99877. if( z==0 ){
  99878. sqlite3_result_error_nomem(context);
  99879. return;
  99880. }
  99881. for(i=0; i<argc; i++){
  99882. sqlite3_int64 x;
  99883. unsigned c;
  99884. x = sqlite3_value_int64(argv[i]);
  99885. if( x<0 || x>0x10ffff ) x = 0xfffd;
  99886. c = (unsigned)(x & 0x1fffff);
  99887. if( c<0x00080 ){
  99888. *zOut++ = (u8)(c&0xFF);
  99889. }else if( c<0x00800 ){
  99890. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  99891. *zOut++ = 0x80 + (u8)(c & 0x3F);
  99892. }else if( c<0x10000 ){
  99893. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  99894. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  99895. *zOut++ = 0x80 + (u8)(c & 0x3F);
  99896. }else{
  99897. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  99898. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  99899. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  99900. *zOut++ = 0x80 + (u8)(c & 0x3F);
  99901. } \
  99902. }
  99903. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  99904. }
  99905. /*
  99906. ** The hex() function. Interpret the argument as a blob. Return
  99907. ** a hexadecimal rendering as text.
  99908. */
  99909. static void hexFunc(
  99910. sqlite3_context *context,
  99911. int argc,
  99912. sqlite3_value **argv
  99913. ){
  99914. int i, n;
  99915. const unsigned char *pBlob;
  99916. char *zHex, *z;
  99917. assert( argc==1 );
  99918. UNUSED_PARAMETER(argc);
  99919. pBlob = sqlite3_value_blob(argv[0]);
  99920. n = sqlite3_value_bytes(argv[0]);
  99921. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  99922. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  99923. if( zHex ){
  99924. for(i=0; i<n; i++, pBlob++){
  99925. unsigned char c = *pBlob;
  99926. *(z++) = hexdigits[(c>>4)&0xf];
  99927. *(z++) = hexdigits[c&0xf];
  99928. }
  99929. *z = 0;
  99930. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  99931. }
  99932. }
  99933. /*
  99934. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  99935. */
  99936. static void zeroblobFunc(
  99937. sqlite3_context *context,
  99938. int argc,
  99939. sqlite3_value **argv
  99940. ){
  99941. i64 n;
  99942. int rc;
  99943. assert( argc==1 );
  99944. UNUSED_PARAMETER(argc);
  99945. n = sqlite3_value_int64(argv[0]);
  99946. if( n<0 ) n = 0;
  99947. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  99948. if( rc ){
  99949. sqlite3_result_error_code(context, rc);
  99950. }
  99951. }
  99952. /*
  99953. ** The replace() function. Three arguments are all strings: call
  99954. ** them A, B, and C. The result is also a string which is derived
  99955. ** from A by replacing every occurrence of B with C. The match
  99956. ** must be exact. Collating sequences are not used.
  99957. */
  99958. static void replaceFunc(
  99959. sqlite3_context *context,
  99960. int argc,
  99961. sqlite3_value **argv
  99962. ){
  99963. const unsigned char *zStr; /* The input string A */
  99964. const unsigned char *zPattern; /* The pattern string B */
  99965. const unsigned char *zRep; /* The replacement string C */
  99966. unsigned char *zOut; /* The output */
  99967. int nStr; /* Size of zStr */
  99968. int nPattern; /* Size of zPattern */
  99969. int nRep; /* Size of zRep */
  99970. i64 nOut; /* Maximum size of zOut */
  99971. int loopLimit; /* Last zStr[] that might match zPattern[] */
  99972. int i, j; /* Loop counters */
  99973. assert( argc==3 );
  99974. UNUSED_PARAMETER(argc);
  99975. zStr = sqlite3_value_text(argv[0]);
  99976. if( zStr==0 ) return;
  99977. nStr = sqlite3_value_bytes(argv[0]);
  99978. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  99979. zPattern = sqlite3_value_text(argv[1]);
  99980. if( zPattern==0 ){
  99981. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  99982. || sqlite3_context_db_handle(context)->mallocFailed );
  99983. return;
  99984. }
  99985. if( zPattern[0]==0 ){
  99986. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  99987. sqlite3_result_value(context, argv[0]);
  99988. return;
  99989. }
  99990. nPattern = sqlite3_value_bytes(argv[1]);
  99991. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  99992. zRep = sqlite3_value_text(argv[2]);
  99993. if( zRep==0 ) return;
  99994. nRep = sqlite3_value_bytes(argv[2]);
  99995. assert( zRep==sqlite3_value_text(argv[2]) );
  99996. nOut = nStr + 1;
  99997. assert( nOut<SQLITE_MAX_LENGTH );
  99998. zOut = contextMalloc(context, (i64)nOut);
  99999. if( zOut==0 ){
  100000. return;
  100001. }
  100002. loopLimit = nStr - nPattern;
  100003. for(i=j=0; i<=loopLimit; i++){
  100004. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  100005. zOut[j++] = zStr[i];
  100006. }else{
  100007. u8 *zOld;
  100008. sqlite3 *db = sqlite3_context_db_handle(context);
  100009. nOut += nRep - nPattern;
  100010. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  100011. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  100012. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  100013. sqlite3_result_error_toobig(context);
  100014. sqlite3_free(zOut);
  100015. return;
  100016. }
  100017. zOld = zOut;
  100018. zOut = sqlite3_realloc64(zOut, (int)nOut);
  100019. if( zOut==0 ){
  100020. sqlite3_result_error_nomem(context);
  100021. sqlite3_free(zOld);
  100022. return;
  100023. }
  100024. memcpy(&zOut[j], zRep, nRep);
  100025. j += nRep;
  100026. i += nPattern-1;
  100027. }
  100028. }
  100029. assert( j+nStr-i+1==nOut );
  100030. memcpy(&zOut[j], &zStr[i], nStr-i);
  100031. j += nStr - i;
  100032. assert( j<=nOut );
  100033. zOut[j] = 0;
  100034. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  100035. }
  100036. /*
  100037. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  100038. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  100039. */
  100040. static void trimFunc(
  100041. sqlite3_context *context,
  100042. int argc,
  100043. sqlite3_value **argv
  100044. ){
  100045. const unsigned char *zIn; /* Input string */
  100046. const unsigned char *zCharSet; /* Set of characters to trim */
  100047. int nIn; /* Number of bytes in input */
  100048. int flags; /* 1: trimleft 2: trimright 3: trim */
  100049. int i; /* Loop counter */
  100050. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  100051. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  100052. int nChar; /* Number of characters in zCharSet */
  100053. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  100054. return;
  100055. }
  100056. zIn = sqlite3_value_text(argv[0]);
  100057. if( zIn==0 ) return;
  100058. nIn = sqlite3_value_bytes(argv[0]);
  100059. assert( zIn==sqlite3_value_text(argv[0]) );
  100060. if( argc==1 ){
  100061. static const unsigned char lenOne[] = { 1 };
  100062. static unsigned char * const azOne[] = { (u8*)" " };
  100063. nChar = 1;
  100064. aLen = (u8*)lenOne;
  100065. azChar = (unsigned char **)azOne;
  100066. zCharSet = 0;
  100067. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  100068. return;
  100069. }else{
  100070. const unsigned char *z;
  100071. for(z=zCharSet, nChar=0; *z; nChar++){
  100072. SQLITE_SKIP_UTF8(z);
  100073. }
  100074. if( nChar>0 ){
  100075. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  100076. if( azChar==0 ){
  100077. return;
  100078. }
  100079. aLen = (unsigned char*)&azChar[nChar];
  100080. for(z=zCharSet, nChar=0; *z; nChar++){
  100081. azChar[nChar] = (unsigned char *)z;
  100082. SQLITE_SKIP_UTF8(z);
  100083. aLen[nChar] = (u8)(z - azChar[nChar]);
  100084. }
  100085. }
  100086. }
  100087. if( nChar>0 ){
  100088. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  100089. if( flags & 1 ){
  100090. while( nIn>0 ){
  100091. int len = 0;
  100092. for(i=0; i<nChar; i++){
  100093. len = aLen[i];
  100094. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  100095. }
  100096. if( i>=nChar ) break;
  100097. zIn += len;
  100098. nIn -= len;
  100099. }
  100100. }
  100101. if( flags & 2 ){
  100102. while( nIn>0 ){
  100103. int len = 0;
  100104. for(i=0; i<nChar; i++){
  100105. len = aLen[i];
  100106. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  100107. }
  100108. if( i>=nChar ) break;
  100109. nIn -= len;
  100110. }
  100111. }
  100112. if( zCharSet ){
  100113. sqlite3_free(azChar);
  100114. }
  100115. }
  100116. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  100117. }
  100118. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  100119. /*
  100120. ** The "unknown" function is automatically substituted in place of
  100121. ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
  100122. ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
  100123. ** When the "sqlite3" command-line shell is built using this functionality,
  100124. ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
  100125. ** involving application-defined functions to be examined in a generic
  100126. ** sqlite3 shell.
  100127. */
  100128. static void unknownFunc(
  100129. sqlite3_context *context,
  100130. int argc,
  100131. sqlite3_value **argv
  100132. ){
  100133. /* no-op */
  100134. }
  100135. #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
  100136. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  100137. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  100138. ** when SQLite is built.
  100139. */
  100140. #ifdef SQLITE_SOUNDEX
  100141. /*
  100142. ** Compute the soundex encoding of a word.
  100143. **
  100144. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  100145. ** soundex encoding of the string X.
  100146. */
  100147. static void soundexFunc(
  100148. sqlite3_context *context,
  100149. int argc,
  100150. sqlite3_value **argv
  100151. ){
  100152. char zResult[8];
  100153. const u8 *zIn;
  100154. int i, j;
  100155. static const unsigned char iCode[] = {
  100156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  100157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  100158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  100159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  100160. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  100161. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  100162. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  100163. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  100164. };
  100165. assert( argc==1 );
  100166. zIn = (u8*)sqlite3_value_text(argv[0]);
  100167. if( zIn==0 ) zIn = (u8*)"";
  100168. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  100169. if( zIn[i] ){
  100170. u8 prevcode = iCode[zIn[i]&0x7f];
  100171. zResult[0] = sqlite3Toupper(zIn[i]);
  100172. for(j=1; j<4 && zIn[i]; i++){
  100173. int code = iCode[zIn[i]&0x7f];
  100174. if( code>0 ){
  100175. if( code!=prevcode ){
  100176. prevcode = code;
  100177. zResult[j++] = code + '0';
  100178. }
  100179. }else{
  100180. prevcode = 0;
  100181. }
  100182. }
  100183. while( j<4 ){
  100184. zResult[j++] = '0';
  100185. }
  100186. zResult[j] = 0;
  100187. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  100188. }else{
  100189. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  100190. ** is NULL or contains no ASCII alphabetic characters. */
  100191. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  100192. }
  100193. }
  100194. #endif /* SQLITE_SOUNDEX */
  100195. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  100196. /*
  100197. ** A function that loads a shared-library extension then returns NULL.
  100198. */
  100199. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  100200. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  100201. const char *zProc;
  100202. sqlite3 *db = sqlite3_context_db_handle(context);
  100203. char *zErrMsg = 0;
  100204. /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
  100205. ** flag is set. See the sqlite3_enable_load_extension() API.
  100206. */
  100207. if( (db->flags & SQLITE_LoadExtFunc)==0 ){
  100208. sqlite3_result_error(context, "not authorized", -1);
  100209. return;
  100210. }
  100211. if( argc==2 ){
  100212. zProc = (const char *)sqlite3_value_text(argv[1]);
  100213. }else{
  100214. zProc = 0;
  100215. }
  100216. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  100217. sqlite3_result_error(context, zErrMsg, -1);
  100218. sqlite3_free(zErrMsg);
  100219. }
  100220. }
  100221. #endif
  100222. /*
  100223. ** An instance of the following structure holds the context of a
  100224. ** sum() or avg() aggregate computation.
  100225. */
  100226. typedef struct SumCtx SumCtx;
  100227. struct SumCtx {
  100228. double rSum; /* Floating point sum */
  100229. i64 iSum; /* Integer sum */
  100230. i64 cnt; /* Number of elements summed */
  100231. u8 overflow; /* True if integer overflow seen */
  100232. u8 approx; /* True if non-integer value was input to the sum */
  100233. };
  100234. /*
  100235. ** Routines used to compute the sum, average, and total.
  100236. **
  100237. ** The SUM() function follows the (broken) SQL standard which means
  100238. ** that it returns NULL if it sums over no inputs. TOTAL returns
  100239. ** 0.0 in that case. In addition, TOTAL always returns a float where
  100240. ** SUM might return an integer if it never encounters a floating point
  100241. ** value. TOTAL never fails, but SUM might through an exception if
  100242. ** it overflows an integer.
  100243. */
  100244. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  100245. SumCtx *p;
  100246. int type;
  100247. assert( argc==1 );
  100248. UNUSED_PARAMETER(argc);
  100249. p = sqlite3_aggregate_context(context, sizeof(*p));
  100250. type = sqlite3_value_numeric_type(argv[0]);
  100251. if( p && type!=SQLITE_NULL ){
  100252. p->cnt++;
  100253. if( type==SQLITE_INTEGER ){
  100254. i64 v = sqlite3_value_int64(argv[0]);
  100255. p->rSum += v;
  100256. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  100257. p->overflow = 1;
  100258. }
  100259. }else{
  100260. p->rSum += sqlite3_value_double(argv[0]);
  100261. p->approx = 1;
  100262. }
  100263. }
  100264. }
  100265. static void sumFinalize(sqlite3_context *context){
  100266. SumCtx *p;
  100267. p = sqlite3_aggregate_context(context, 0);
  100268. if( p && p->cnt>0 ){
  100269. if( p->overflow ){
  100270. sqlite3_result_error(context,"integer overflow",-1);
  100271. }else if( p->approx ){
  100272. sqlite3_result_double(context, p->rSum);
  100273. }else{
  100274. sqlite3_result_int64(context, p->iSum);
  100275. }
  100276. }
  100277. }
  100278. static void avgFinalize(sqlite3_context *context){
  100279. SumCtx *p;
  100280. p = sqlite3_aggregate_context(context, 0);
  100281. if( p && p->cnt>0 ){
  100282. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  100283. }
  100284. }
  100285. static void totalFinalize(sqlite3_context *context){
  100286. SumCtx *p;
  100287. p = sqlite3_aggregate_context(context, 0);
  100288. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  100289. sqlite3_result_double(context, p ? p->rSum : (double)0);
  100290. }
  100291. /*
  100292. ** The following structure keeps track of state information for the
  100293. ** count() aggregate function.
  100294. */
  100295. typedef struct CountCtx CountCtx;
  100296. struct CountCtx {
  100297. i64 n;
  100298. };
  100299. /*
  100300. ** Routines to implement the count() aggregate function.
  100301. */
  100302. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  100303. CountCtx *p;
  100304. p = sqlite3_aggregate_context(context, sizeof(*p));
  100305. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  100306. p->n++;
  100307. }
  100308. #ifndef SQLITE_OMIT_DEPRECATED
  100309. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  100310. ** sure it still operates correctly, verify that its count agrees with our
  100311. ** internal count when using count(*) and when the total count can be
  100312. ** expressed as a 32-bit integer. */
  100313. assert( argc==1 || p==0 || p->n>0x7fffffff
  100314. || p->n==sqlite3_aggregate_count(context) );
  100315. #endif
  100316. }
  100317. static void countFinalize(sqlite3_context *context){
  100318. CountCtx *p;
  100319. p = sqlite3_aggregate_context(context, 0);
  100320. sqlite3_result_int64(context, p ? p->n : 0);
  100321. }
  100322. /*
  100323. ** Routines to implement min() and max() aggregate functions.
  100324. */
  100325. static void minmaxStep(
  100326. sqlite3_context *context,
  100327. int NotUsed,
  100328. sqlite3_value **argv
  100329. ){
  100330. Mem *pArg = (Mem *)argv[0];
  100331. Mem *pBest;
  100332. UNUSED_PARAMETER(NotUsed);
  100333. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  100334. if( !pBest ) return;
  100335. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  100336. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  100337. }else if( pBest->flags ){
  100338. int max;
  100339. int cmp;
  100340. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  100341. /* This step function is used for both the min() and max() aggregates,
  100342. ** the only difference between the two being that the sense of the
  100343. ** comparison is inverted. For the max() aggregate, the
  100344. ** sqlite3_user_data() function returns (void *)-1. For min() it
  100345. ** returns (void *)db, where db is the sqlite3* database pointer.
  100346. ** Therefore the next statement sets variable 'max' to 1 for the max()
  100347. ** aggregate, or 0 for min().
  100348. */
  100349. max = sqlite3_user_data(context)!=0;
  100350. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  100351. if( (max && cmp<0) || (!max && cmp>0) ){
  100352. sqlite3VdbeMemCopy(pBest, pArg);
  100353. }else{
  100354. sqlite3SkipAccumulatorLoad(context);
  100355. }
  100356. }else{
  100357. pBest->db = sqlite3_context_db_handle(context);
  100358. sqlite3VdbeMemCopy(pBest, pArg);
  100359. }
  100360. }
  100361. static void minMaxFinalize(sqlite3_context *context){
  100362. sqlite3_value *pRes;
  100363. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  100364. if( pRes ){
  100365. if( pRes->flags ){
  100366. sqlite3_result_value(context, pRes);
  100367. }
  100368. sqlite3VdbeMemRelease(pRes);
  100369. }
  100370. }
  100371. /*
  100372. ** group_concat(EXPR, ?SEPARATOR?)
  100373. */
  100374. static void groupConcatStep(
  100375. sqlite3_context *context,
  100376. int argc,
  100377. sqlite3_value **argv
  100378. ){
  100379. const char *zVal;
  100380. StrAccum *pAccum;
  100381. const char *zSep;
  100382. int nVal, nSep;
  100383. assert( argc==1 || argc==2 );
  100384. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  100385. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  100386. if( pAccum ){
  100387. sqlite3 *db = sqlite3_context_db_handle(context);
  100388. int firstTerm = pAccum->mxAlloc==0;
  100389. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  100390. if( !firstTerm ){
  100391. if( argc==2 ){
  100392. zSep = (char*)sqlite3_value_text(argv[1]);
  100393. nSep = sqlite3_value_bytes(argv[1]);
  100394. }else{
  100395. zSep = ",";
  100396. nSep = 1;
  100397. }
  100398. if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  100399. }
  100400. zVal = (char*)sqlite3_value_text(argv[0]);
  100401. nVal = sqlite3_value_bytes(argv[0]);
  100402. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  100403. }
  100404. }
  100405. static void groupConcatFinalize(sqlite3_context *context){
  100406. StrAccum *pAccum;
  100407. pAccum = sqlite3_aggregate_context(context, 0);
  100408. if( pAccum ){
  100409. if( pAccum->accError==STRACCUM_TOOBIG ){
  100410. sqlite3_result_error_toobig(context);
  100411. }else if( pAccum->accError==STRACCUM_NOMEM ){
  100412. sqlite3_result_error_nomem(context);
  100413. }else{
  100414. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  100415. sqlite3_free);
  100416. }
  100417. }
  100418. }
  100419. /*
  100420. ** This routine does per-connection function registration. Most
  100421. ** of the built-in functions above are part of the global function set.
  100422. ** This routine only deals with those that are not global.
  100423. */
  100424. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  100425. int rc = sqlite3_overload_function(db, "MATCH", 2);
  100426. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  100427. if( rc==SQLITE_NOMEM ){
  100428. sqlite3OomFault(db);
  100429. }
  100430. }
  100431. /*
  100432. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  100433. */
  100434. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  100435. FuncDef *pDef;
  100436. pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
  100437. if( ALWAYS(pDef) ){
  100438. pDef->funcFlags |= flagVal;
  100439. }
  100440. }
  100441. /*
  100442. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  100443. ** parameter determines whether or not the LIKE operator is case
  100444. ** sensitive. GLOB is always case sensitive.
  100445. */
  100446. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  100447. struct compareInfo *pInfo;
  100448. if( caseSensitive ){
  100449. pInfo = (struct compareInfo*)&likeInfoAlt;
  100450. }else{
  100451. pInfo = (struct compareInfo*)&likeInfoNorm;
  100452. }
  100453. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  100454. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  100455. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  100456. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  100457. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  100458. setLikeOptFlag(db, "like",
  100459. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  100460. }
  100461. /*
  100462. ** pExpr points to an expression which implements a function. If
  100463. ** it is appropriate to apply the LIKE optimization to that function
  100464. ** then set aWc[0] through aWc[2] to the wildcard characters and
  100465. ** return TRUE. If the function is not a LIKE-style function then
  100466. ** return FALSE.
  100467. **
  100468. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  100469. ** the function (default for LIKE). If the function makes the distinction
  100470. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  100471. ** false.
  100472. */
  100473. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  100474. FuncDef *pDef;
  100475. if( pExpr->op!=TK_FUNCTION
  100476. || !pExpr->x.pList
  100477. || pExpr->x.pList->nExpr!=2
  100478. ){
  100479. return 0;
  100480. }
  100481. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  100482. pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
  100483. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  100484. return 0;
  100485. }
  100486. /* The memcpy() statement assumes that the wildcard characters are
  100487. ** the first three statements in the compareInfo structure. The
  100488. ** asserts() that follow verify that assumption
  100489. */
  100490. memcpy(aWc, pDef->pUserData, 3);
  100491. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  100492. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  100493. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  100494. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  100495. return 1;
  100496. }
  100497. /*
  100498. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  100499. ** to the global function hash table. This occurs at start-time (as
  100500. ** a consequence of calling sqlite3_initialize()).
  100501. **
  100502. ** After this routine runs
  100503. */
  100504. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  100505. /*
  100506. ** The following array holds FuncDef structures for all of the functions
  100507. ** defined in this file.
  100508. **
  100509. ** The array cannot be constant since changes are made to the
  100510. ** FuncDef.pHash elements at start-time. The elements of this array
  100511. ** are read-only after initialization is complete.
  100512. **
  100513. ** For peak efficiency, put the most frequently used function last.
  100514. */
  100515. static FuncDef aBuiltinFunc[] = {
  100516. #ifdef SQLITE_SOUNDEX
  100517. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  100518. #endif
  100519. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  100520. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  100521. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  100522. #endif
  100523. #if SQLITE_USER_AUTHENTICATION
  100524. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  100525. #endif
  100526. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  100527. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  100528. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  100529. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  100530. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  100531. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  100532. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  100533. #ifdef SQLITE_DEBUG
  100534. FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY),
  100535. #endif
  100536. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  100537. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  100538. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  100539. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  100540. FUNCTION(trim, 1, 3, 0, trimFunc ),
  100541. FUNCTION(trim, 2, 3, 0, trimFunc ),
  100542. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  100543. FUNCTION(min, 0, 0, 1, 0 ),
  100544. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  100545. SQLITE_FUNC_MINMAX ),
  100546. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  100547. FUNCTION(max, 0, 1, 1, 0 ),
  100548. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  100549. SQLITE_FUNC_MINMAX ),
  100550. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  100551. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  100552. FUNCTION(instr, 2, 0, 0, instrFunc ),
  100553. FUNCTION(printf, -1, 0, 0, printfFunc ),
  100554. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  100555. FUNCTION(char, -1, 0, 0, charFunc ),
  100556. FUNCTION(abs, 1, 0, 0, absFunc ),
  100557. #ifndef SQLITE_OMIT_FLOATING_POINT
  100558. FUNCTION(round, 1, 0, 0, roundFunc ),
  100559. FUNCTION(round, 2, 0, 0, roundFunc ),
  100560. #endif
  100561. FUNCTION(upper, 1, 0, 0, upperFunc ),
  100562. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  100563. FUNCTION(hex, 1, 0, 0, hexFunc ),
  100564. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  100565. VFUNCTION(random, 0, 0, 0, randomFunc ),
  100566. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  100567. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  100568. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  100569. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  100570. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  100571. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  100572. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  100573. VFUNCTION(changes, 0, 0, 0, changes ),
  100574. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  100575. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  100576. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  100577. FUNCTION(substr, 2, 0, 0, substrFunc ),
  100578. FUNCTION(substr, 3, 0, 0, substrFunc ),
  100579. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  100580. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  100581. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  100582. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  100583. SQLITE_FUNC_COUNT ),
  100584. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  100585. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  100586. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  100587. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  100588. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  100589. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  100590. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  100591. #else
  100592. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  100593. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  100594. #endif
  100595. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  100596. FUNCTION(unknown, -1, 0, 0, unknownFunc ),
  100597. #endif
  100598. FUNCTION(coalesce, 1, 0, 0, 0 ),
  100599. FUNCTION(coalesce, 0, 0, 0, 0 ),
  100600. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  100601. };
  100602. #ifndef SQLITE_OMIT_ALTERTABLE
  100603. sqlite3AlterFunctions();
  100604. #endif
  100605. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  100606. sqlite3AnalyzeFunctions();
  100607. #endif
  100608. sqlite3RegisterDateTimeFunctions();
  100609. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  100610. #if 0 /* Enable to print out how the built-in functions are hashed */
  100611. {
  100612. int i;
  100613. FuncDef *p;
  100614. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  100615. printf("FUNC-HASH %02d:", i);
  100616. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  100617. int n = sqlite3Strlen30(p->zName);
  100618. int h = p->zName[0] + n;
  100619. printf(" %s(%d)", p->zName, h);
  100620. }
  100621. printf("\n");
  100622. }
  100623. }
  100624. #endif
  100625. }
  100626. /************** End of func.c ************************************************/
  100627. /************** Begin file fkey.c ********************************************/
  100628. /*
  100629. **
  100630. ** The author disclaims copyright to this source code. In place of
  100631. ** a legal notice, here is a blessing:
  100632. **
  100633. ** May you do good and not evil.
  100634. ** May you find forgiveness for yourself and forgive others.
  100635. ** May you share freely, never taking more than you give.
  100636. **
  100637. *************************************************************************
  100638. ** This file contains code used by the compiler to add foreign key
  100639. ** support to compiled SQL statements.
  100640. */
  100641. /* #include "sqliteInt.h" */
  100642. #ifndef SQLITE_OMIT_FOREIGN_KEY
  100643. #ifndef SQLITE_OMIT_TRIGGER
  100644. /*
  100645. ** Deferred and Immediate FKs
  100646. ** --------------------------
  100647. **
  100648. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  100649. ** If an immediate foreign key constraint is violated,
  100650. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  100651. ** statement transaction rolled back. If a
  100652. ** deferred foreign key constraint is violated, no action is taken
  100653. ** immediately. However if the application attempts to commit the
  100654. ** transaction before fixing the constraint violation, the attempt fails.
  100655. **
  100656. ** Deferred constraints are implemented using a simple counter associated
  100657. ** with the database handle. The counter is set to zero each time a
  100658. ** database transaction is opened. Each time a statement is executed
  100659. ** that causes a foreign key violation, the counter is incremented. Each
  100660. ** time a statement is executed that removes an existing violation from
  100661. ** the database, the counter is decremented. When the transaction is
  100662. ** committed, the commit fails if the current value of the counter is
  100663. ** greater than zero. This scheme has two big drawbacks:
  100664. **
  100665. ** * When a commit fails due to a deferred foreign key constraint,
  100666. ** there is no way to tell which foreign constraint is not satisfied,
  100667. ** or which row it is not satisfied for.
  100668. **
  100669. ** * If the database contains foreign key violations when the
  100670. ** transaction is opened, this may cause the mechanism to malfunction.
  100671. **
  100672. ** Despite these problems, this approach is adopted as it seems simpler
  100673. ** than the alternatives.
  100674. **
  100675. ** INSERT operations:
  100676. **
  100677. ** I.1) For each FK for which the table is the child table, search
  100678. ** the parent table for a match. If none is found increment the
  100679. ** constraint counter.
  100680. **
  100681. ** I.2) For each FK for which the table is the parent table,
  100682. ** search the child table for rows that correspond to the new
  100683. ** row in the parent table. Decrement the counter for each row
  100684. ** found (as the constraint is now satisfied).
  100685. **
  100686. ** DELETE operations:
  100687. **
  100688. ** D.1) For each FK for which the table is the child table,
  100689. ** search the parent table for a row that corresponds to the
  100690. ** deleted row in the child table. If such a row is not found,
  100691. ** decrement the counter.
  100692. **
  100693. ** D.2) For each FK for which the table is the parent table, search
  100694. ** the child table for rows that correspond to the deleted row
  100695. ** in the parent table. For each found increment the counter.
  100696. **
  100697. ** UPDATE operations:
  100698. **
  100699. ** An UPDATE command requires that all 4 steps above are taken, but only
  100700. ** for FK constraints for which the affected columns are actually
  100701. ** modified (values must be compared at runtime).
  100702. **
  100703. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  100704. ** This simplifies the implementation a bit.
  100705. **
  100706. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  100707. ** resolution is considered to delete rows before the new row is inserted.
  100708. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  100709. ** is thrown, even if the FK constraint would be satisfied after the new
  100710. ** row is inserted.
  100711. **
  100712. ** Immediate constraints are usually handled similarly. The only difference
  100713. ** is that the counter used is stored as part of each individual statement
  100714. ** object (struct Vdbe). If, after the statement has run, its immediate
  100715. ** constraint counter is greater than zero,
  100716. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  100717. ** and the statement transaction is rolled back. An exception is an INSERT
  100718. ** statement that inserts a single row only (no triggers). In this case,
  100719. ** instead of using a counter, an exception is thrown immediately if the
  100720. ** INSERT violates a foreign key constraint. This is necessary as such
  100721. ** an INSERT does not open a statement transaction.
  100722. **
  100723. ** TODO: How should dropping a table be handled? How should renaming a
  100724. ** table be handled?
  100725. **
  100726. **
  100727. ** Query API Notes
  100728. ** ---------------
  100729. **
  100730. ** Before coding an UPDATE or DELETE row operation, the code-generator
  100731. ** for those two operations needs to know whether or not the operation
  100732. ** requires any FK processing and, if so, which columns of the original
  100733. ** row are required by the FK processing VDBE code (i.e. if FKs were
  100734. ** implemented using triggers, which of the old.* columns would be
  100735. ** accessed). No information is required by the code-generator before
  100736. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  100737. ** generation code to query for this information are:
  100738. **
  100739. ** sqlite3FkRequired() - Test to see if FK processing is required.
  100740. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  100741. **
  100742. **
  100743. ** Externally accessible module functions
  100744. ** --------------------------------------
  100745. **
  100746. ** sqlite3FkCheck() - Check for foreign key violations.
  100747. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  100748. ** sqlite3FkDelete() - Delete an FKey structure.
  100749. */
  100750. /*
  100751. ** VDBE Calling Convention
  100752. ** -----------------------
  100753. **
  100754. ** Example:
  100755. **
  100756. ** For the following INSERT statement:
  100757. **
  100758. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  100759. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  100760. **
  100761. ** Register (x): 2 (type integer)
  100762. ** Register (x+1): 1 (type integer)
  100763. ** Register (x+2): NULL (type NULL)
  100764. ** Register (x+3): 3.1 (type real)
  100765. */
  100766. /*
  100767. ** A foreign key constraint requires that the key columns in the parent
  100768. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  100769. ** Given that pParent is the parent table for foreign key constraint pFKey,
  100770. ** search the schema for a unique index on the parent key columns.
  100771. **
  100772. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  100773. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  100774. ** is set to point to the unique index.
  100775. **
  100776. ** If the parent key consists of a single column (the foreign key constraint
  100777. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  100778. ** Otherwise, it is set to point to an allocated array of size N, where
  100779. ** N is the number of columns in the parent key. The first element of the
  100780. ** array is the index of the child table column that is mapped by the FK
  100781. ** constraint to the parent table column stored in the left-most column
  100782. ** of index *ppIdx. The second element of the array is the index of the
  100783. ** child table column that corresponds to the second left-most column of
  100784. ** *ppIdx, and so on.
  100785. **
  100786. ** If the required index cannot be found, either because:
  100787. **
  100788. ** 1) The named parent key columns do not exist, or
  100789. **
  100790. ** 2) The named parent key columns do exist, but are not subject to a
  100791. ** UNIQUE or PRIMARY KEY constraint, or
  100792. **
  100793. ** 3) No parent key columns were provided explicitly as part of the
  100794. ** foreign key definition, and the parent table does not have a
  100795. ** PRIMARY KEY, or
  100796. **
  100797. ** 4) No parent key columns were provided explicitly as part of the
  100798. ** foreign key definition, and the PRIMARY KEY of the parent table
  100799. ** consists of a different number of columns to the child key in
  100800. ** the child table.
  100801. **
  100802. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  100803. ** into pParse. If an OOM error occurs, non-zero is returned and the
  100804. ** pParse->db->mallocFailed flag is set.
  100805. */
  100806. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  100807. Parse *pParse, /* Parse context to store any error in */
  100808. Table *pParent, /* Parent table of FK constraint pFKey */
  100809. FKey *pFKey, /* Foreign key to find index for */
  100810. Index **ppIdx, /* OUT: Unique index on parent table */
  100811. int **paiCol /* OUT: Map of index columns in pFKey */
  100812. ){
  100813. Index *pIdx = 0; /* Value to return via *ppIdx */
  100814. int *aiCol = 0; /* Value to return via *paiCol */
  100815. int nCol = pFKey->nCol; /* Number of columns in parent key */
  100816. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  100817. /* The caller is responsible for zeroing output parameters. */
  100818. assert( ppIdx && *ppIdx==0 );
  100819. assert( !paiCol || *paiCol==0 );
  100820. assert( pParse );
  100821. /* If this is a non-composite (single column) foreign key, check if it
  100822. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  100823. ** and *paiCol set to zero and return early.
  100824. **
  100825. ** Otherwise, for a composite foreign key (more than one column), allocate
  100826. ** space for the aiCol array (returned via output parameter *paiCol).
  100827. ** Non-composite foreign keys do not require the aiCol array.
  100828. */
  100829. if( nCol==1 ){
  100830. /* The FK maps to the IPK if any of the following are true:
  100831. **
  100832. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  100833. ** mapped to the primary key of table pParent, or
  100834. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  100835. ** PRIMARY KEY.
  100836. */
  100837. if( pParent->iPKey>=0 ){
  100838. if( !zKey ) return 0;
  100839. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  100840. }
  100841. }else if( paiCol ){
  100842. assert( nCol>1 );
  100843. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  100844. if( !aiCol ) return 1;
  100845. *paiCol = aiCol;
  100846. }
  100847. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  100848. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
  100849. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  100850. ** of columns. If each indexed column corresponds to a foreign key
  100851. ** column of pFKey, then this index is a winner. */
  100852. if( zKey==0 ){
  100853. /* If zKey is NULL, then this foreign key is implicitly mapped to
  100854. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  100855. ** identified by the test. */
  100856. if( IsPrimaryKeyIndex(pIdx) ){
  100857. if( aiCol ){
  100858. int i;
  100859. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  100860. }
  100861. break;
  100862. }
  100863. }else{
  100864. /* If zKey is non-NULL, then this foreign key was declared to
  100865. ** map to an explicit list of columns in table pParent. Check if this
  100866. ** index matches those columns. Also, check that the index uses
  100867. ** the default collation sequences for each column. */
  100868. int i, j;
  100869. for(i=0; i<nCol; i++){
  100870. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  100871. const char *zDfltColl; /* Def. collation for column */
  100872. char *zIdxCol; /* Name of indexed column */
  100873. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  100874. /* If the index uses a collation sequence that is different from
  100875. ** the default collation sequence for the column, this index is
  100876. ** unusable. Bail out early in this case. */
  100877. zDfltColl = pParent->aCol[iCol].zColl;
  100878. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  100879. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  100880. zIdxCol = pParent->aCol[iCol].zName;
  100881. for(j=0; j<nCol; j++){
  100882. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  100883. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  100884. break;
  100885. }
  100886. }
  100887. if( j==nCol ) break;
  100888. }
  100889. if( i==nCol ) break; /* pIdx is usable */
  100890. }
  100891. }
  100892. }
  100893. if( !pIdx ){
  100894. if( !pParse->disableTriggers ){
  100895. sqlite3ErrorMsg(pParse,
  100896. "foreign key mismatch - \"%w\" referencing \"%w\"",
  100897. pFKey->pFrom->zName, pFKey->zTo);
  100898. }
  100899. sqlite3DbFree(pParse->db, aiCol);
  100900. return 1;
  100901. }
  100902. *ppIdx = pIdx;
  100903. return 0;
  100904. }
  100905. /*
  100906. ** This function is called when a row is inserted into or deleted from the
  100907. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  100908. ** on the child table of pFKey, this function is invoked twice for each row
  100909. ** affected - once to "delete" the old row, and then again to "insert" the
  100910. ** new row.
  100911. **
  100912. ** Each time it is called, this function generates VDBE code to locate the
  100913. ** row in the parent table that corresponds to the row being inserted into
  100914. ** or deleted from the child table. If the parent row can be found, no
  100915. ** special action is taken. Otherwise, if the parent row can *not* be
  100916. ** found in the parent table:
  100917. **
  100918. ** Operation | FK type | Action taken
  100919. ** --------------------------------------------------------------------------
  100920. ** INSERT immediate Increment the "immediate constraint counter".
  100921. **
  100922. ** DELETE immediate Decrement the "immediate constraint counter".
  100923. **
  100924. ** INSERT deferred Increment the "deferred constraint counter".
  100925. **
  100926. ** DELETE deferred Decrement the "deferred constraint counter".
  100927. **
  100928. ** These operations are identified in the comment at the top of this file
  100929. ** (fkey.c) as "I.1" and "D.1".
  100930. */
  100931. static void fkLookupParent(
  100932. Parse *pParse, /* Parse context */
  100933. int iDb, /* Index of database housing pTab */
  100934. Table *pTab, /* Parent table of FK pFKey */
  100935. Index *pIdx, /* Unique index on parent key columns in pTab */
  100936. FKey *pFKey, /* Foreign key constraint */
  100937. int *aiCol, /* Map from parent key columns to child table columns */
  100938. int regData, /* Address of array containing child table row */
  100939. int nIncr, /* Increment constraint counter by this */
  100940. int isIgnore /* If true, pretend pTab contains all NULL values */
  100941. ){
  100942. int i; /* Iterator variable */
  100943. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  100944. int iCur = pParse->nTab - 1; /* Cursor number to use */
  100945. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  100946. /* If nIncr is less than zero, then check at runtime if there are any
  100947. ** outstanding constraints to resolve. If there are not, there is no need
  100948. ** to check if deleting this row resolves any outstanding violations.
  100949. **
  100950. ** Check if any of the key columns in the child table row are NULL. If
  100951. ** any are, then the constraint is considered satisfied. No need to
  100952. ** search for a matching row in the parent table. */
  100953. if( nIncr<0 ){
  100954. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  100955. VdbeCoverage(v);
  100956. }
  100957. for(i=0; i<pFKey->nCol; i++){
  100958. int iReg = aiCol[i] + regData + 1;
  100959. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  100960. }
  100961. if( isIgnore==0 ){
  100962. if( pIdx==0 ){
  100963. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  100964. ** column of the parent table (table pTab). */
  100965. int iMustBeInt; /* Address of MustBeInt instruction */
  100966. int regTemp = sqlite3GetTempReg(pParse);
  100967. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  100968. ** apply the affinity of the parent key). If this fails, then there
  100969. ** is no matching parent key. Before using MustBeInt, make a copy of
  100970. ** the value. Otherwise, the value inserted into the child key column
  100971. ** will have INTEGER affinity applied to it, which may not be correct. */
  100972. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  100973. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  100974. VdbeCoverage(v);
  100975. /* If the parent table is the same as the child table, and we are about
  100976. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  100977. ** then check if the row being inserted matches itself. If so, do not
  100978. ** increment the constraint-counter. */
  100979. if( pTab==pFKey->pFrom && nIncr==1 ){
  100980. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  100981. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  100982. }
  100983. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  100984. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  100985. sqlite3VdbeGoto(v, iOk);
  100986. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  100987. sqlite3VdbeJumpHere(v, iMustBeInt);
  100988. sqlite3ReleaseTempReg(pParse, regTemp);
  100989. }else{
  100990. int nCol = pFKey->nCol;
  100991. int regTemp = sqlite3GetTempRange(pParse, nCol);
  100992. int regRec = sqlite3GetTempReg(pParse);
  100993. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  100994. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  100995. for(i=0; i<nCol; i++){
  100996. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  100997. }
  100998. /* If the parent table is the same as the child table, and we are about
  100999. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  101000. ** then check if the row being inserted matches itself. If so, do not
  101001. ** increment the constraint-counter.
  101002. **
  101003. ** If any of the parent-key values are NULL, then the row cannot match
  101004. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  101005. ** of the parent-key values are NULL (at this point it is known that
  101006. ** none of the child key values are).
  101007. */
  101008. if( pTab==pFKey->pFrom && nIncr==1 ){
  101009. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  101010. for(i=0; i<nCol; i++){
  101011. int iChild = aiCol[i]+1+regData;
  101012. int iParent = pIdx->aiColumn[i]+1+regData;
  101013. assert( pIdx->aiColumn[i]>=0 );
  101014. assert( aiCol[i]!=pTab->iPKey );
  101015. if( pIdx->aiColumn[i]==pTab->iPKey ){
  101016. /* The parent key is a composite key that includes the IPK column */
  101017. iParent = regData;
  101018. }
  101019. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  101020. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  101021. }
  101022. sqlite3VdbeGoto(v, iOk);
  101023. }
  101024. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  101025. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  101026. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  101027. sqlite3ReleaseTempReg(pParse, regRec);
  101028. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  101029. }
  101030. }
  101031. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  101032. && !pParse->pToplevel
  101033. && !pParse->isMultiWrite
  101034. ){
  101035. /* Special case: If this is an INSERT statement that will insert exactly
  101036. ** one row into the table, raise a constraint immediately instead of
  101037. ** incrementing a counter. This is necessary as the VM code is being
  101038. ** generated for will not open a statement transaction. */
  101039. assert( nIncr==1 );
  101040. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  101041. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  101042. }else{
  101043. if( nIncr>0 && pFKey->isDeferred==0 ){
  101044. sqlite3MayAbort(pParse);
  101045. }
  101046. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  101047. }
  101048. sqlite3VdbeResolveLabel(v, iOk);
  101049. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  101050. }
  101051. /*
  101052. ** Return an Expr object that refers to a memory register corresponding
  101053. ** to column iCol of table pTab.
  101054. **
  101055. ** regBase is the first of an array of register that contains the data
  101056. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  101057. ** column. regBase+2 holds the second column, and so forth.
  101058. */
  101059. static Expr *exprTableRegister(
  101060. Parse *pParse, /* Parsing and code generating context */
  101061. Table *pTab, /* The table whose content is at r[regBase]... */
  101062. int regBase, /* Contents of table pTab */
  101063. i16 iCol /* Which column of pTab is desired */
  101064. ){
  101065. Expr *pExpr;
  101066. Column *pCol;
  101067. const char *zColl;
  101068. sqlite3 *db = pParse->db;
  101069. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  101070. if( pExpr ){
  101071. if( iCol>=0 && iCol!=pTab->iPKey ){
  101072. pCol = &pTab->aCol[iCol];
  101073. pExpr->iTable = regBase + iCol + 1;
  101074. pExpr->affinity = pCol->affinity;
  101075. zColl = pCol->zColl;
  101076. if( zColl==0 ) zColl = db->pDfltColl->zName;
  101077. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  101078. }else{
  101079. pExpr->iTable = regBase;
  101080. pExpr->affinity = SQLITE_AFF_INTEGER;
  101081. }
  101082. }
  101083. return pExpr;
  101084. }
  101085. /*
  101086. ** Return an Expr object that refers to column iCol of table pTab which
  101087. ** has cursor iCur.
  101088. */
  101089. static Expr *exprTableColumn(
  101090. sqlite3 *db, /* The database connection */
  101091. Table *pTab, /* The table whose column is desired */
  101092. int iCursor, /* The open cursor on the table */
  101093. i16 iCol /* The column that is wanted */
  101094. ){
  101095. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  101096. if( pExpr ){
  101097. pExpr->pTab = pTab;
  101098. pExpr->iTable = iCursor;
  101099. pExpr->iColumn = iCol;
  101100. }
  101101. return pExpr;
  101102. }
  101103. /*
  101104. ** This function is called to generate code executed when a row is deleted
  101105. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  101106. ** deferred, when a row is inserted into the same table. When generating
  101107. ** code for an SQL UPDATE operation, this function may be called twice -
  101108. ** once to "delete" the old row and once to "insert" the new row.
  101109. **
  101110. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  101111. ** the number of FK violations in the db) or +1 when deleting one (as this
  101112. ** may increase the number of FK constraint problems).
  101113. **
  101114. ** The code generated by this function scans through the rows in the child
  101115. ** table that correspond to the parent table row being deleted or inserted.
  101116. ** For each child row found, one of the following actions is taken:
  101117. **
  101118. ** Operation | FK type | Action taken
  101119. ** --------------------------------------------------------------------------
  101120. ** DELETE immediate Increment the "immediate constraint counter".
  101121. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  101122. ** throw a "FOREIGN KEY constraint failed" exception.
  101123. **
  101124. ** INSERT immediate Decrement the "immediate constraint counter".
  101125. **
  101126. ** DELETE deferred Increment the "deferred constraint counter".
  101127. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  101128. ** throw a "FOREIGN KEY constraint failed" exception.
  101129. **
  101130. ** INSERT deferred Decrement the "deferred constraint counter".
  101131. **
  101132. ** These operations are identified in the comment at the top of this file
  101133. ** (fkey.c) as "I.2" and "D.2".
  101134. */
  101135. static void fkScanChildren(
  101136. Parse *pParse, /* Parse context */
  101137. SrcList *pSrc, /* The child table to be scanned */
  101138. Table *pTab, /* The parent table */
  101139. Index *pIdx, /* Index on parent covering the foreign key */
  101140. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  101141. int *aiCol, /* Map from pIdx cols to child table cols */
  101142. int regData, /* Parent row data starts here */
  101143. int nIncr /* Amount to increment deferred counter by */
  101144. ){
  101145. sqlite3 *db = pParse->db; /* Database handle */
  101146. int i; /* Iterator variable */
  101147. Expr *pWhere = 0; /* WHERE clause to scan with */
  101148. NameContext sNameContext; /* Context used to resolve WHERE clause */
  101149. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  101150. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  101151. Vdbe *v = sqlite3GetVdbe(pParse);
  101152. assert( pIdx==0 || pIdx->pTable==pTab );
  101153. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  101154. assert( pIdx!=0 || pFKey->nCol==1 );
  101155. assert( pIdx!=0 || HasRowid(pTab) );
  101156. if( nIncr<0 ){
  101157. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  101158. VdbeCoverage(v);
  101159. }
  101160. /* Create an Expr object representing an SQL expression like:
  101161. **
  101162. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  101163. **
  101164. ** The collation sequence used for the comparison should be that of
  101165. ** the parent key columns. The affinity of the parent key column should
  101166. ** be applied to each child key value before the comparison takes place.
  101167. */
  101168. for(i=0; i<pFKey->nCol; i++){
  101169. Expr *pLeft; /* Value from parent table row */
  101170. Expr *pRight; /* Column ref to child table */
  101171. Expr *pEq; /* Expression (pLeft = pRight) */
  101172. i16 iCol; /* Index of column in child table */
  101173. const char *zCol; /* Name of column in child table */
  101174. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  101175. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  101176. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  101177. assert( iCol>=0 );
  101178. zCol = pFKey->pFrom->aCol[iCol].zName;
  101179. pRight = sqlite3Expr(db, TK_ID, zCol);
  101180. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  101181. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  101182. }
  101183. /* If the child table is the same as the parent table, then add terms
  101184. ** to the WHERE clause that prevent this entry from being scanned.
  101185. ** The added WHERE clause terms are like this:
  101186. **
  101187. ** $current_rowid!=rowid
  101188. ** NOT( $current_a==a AND $current_b==b AND ... )
  101189. **
  101190. ** The first form is used for rowid tables. The second form is used
  101191. ** for WITHOUT ROWID tables. In the second form, the primary key is
  101192. ** (a,b,...)
  101193. */
  101194. if( pTab==pFKey->pFrom && nIncr>0 ){
  101195. Expr *pNe; /* Expression (pLeft != pRight) */
  101196. Expr *pLeft; /* Value from parent table row */
  101197. Expr *pRight; /* Column ref to child table */
  101198. if( HasRowid(pTab) ){
  101199. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  101200. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  101201. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
  101202. }else{
  101203. Expr *pEq, *pAll = 0;
  101204. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  101205. assert( pIdx!=0 );
  101206. for(i=0; i<pPk->nKeyCol; i++){
  101207. i16 iCol = pIdx->aiColumn[i];
  101208. assert( iCol>=0 );
  101209. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  101210. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  101211. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  101212. pAll = sqlite3ExprAnd(db, pAll, pEq);
  101213. }
  101214. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
  101215. }
  101216. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  101217. }
  101218. /* Resolve the references in the WHERE clause. */
  101219. memset(&sNameContext, 0, sizeof(NameContext));
  101220. sNameContext.pSrcList = pSrc;
  101221. sNameContext.pParse = pParse;
  101222. sqlite3ResolveExprNames(&sNameContext, pWhere);
  101223. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  101224. ** clause. For each row found, increment either the deferred or immediate
  101225. ** foreign key constraint counter. */
  101226. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  101227. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  101228. if( pWInfo ){
  101229. sqlite3WhereEnd(pWInfo);
  101230. }
  101231. /* Clean up the WHERE clause constructed above. */
  101232. sqlite3ExprDelete(db, pWhere);
  101233. if( iFkIfZero ){
  101234. sqlite3VdbeJumpHere(v, iFkIfZero);
  101235. }
  101236. }
  101237. /*
  101238. ** This function returns a linked list of FKey objects (connected by
  101239. ** FKey.pNextTo) holding all children of table pTab. For example,
  101240. ** given the following schema:
  101241. **
  101242. ** CREATE TABLE t1(a PRIMARY KEY);
  101243. ** CREATE TABLE t2(b REFERENCES t1(a);
  101244. **
  101245. ** Calling this function with table "t1" as an argument returns a pointer
  101246. ** to the FKey structure representing the foreign key constraint on table
  101247. ** "t2". Calling this function with "t2" as the argument would return a
  101248. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  101249. ** table).
  101250. */
  101251. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  101252. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  101253. }
  101254. /*
  101255. ** The second argument is a Trigger structure allocated by the
  101256. ** fkActionTrigger() routine. This function deletes the Trigger structure
  101257. ** and all of its sub-components.
  101258. **
  101259. ** The Trigger structure or any of its sub-components may be allocated from
  101260. ** the lookaside buffer belonging to database handle dbMem.
  101261. */
  101262. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  101263. if( p ){
  101264. TriggerStep *pStep = p->step_list;
  101265. sqlite3ExprDelete(dbMem, pStep->pWhere);
  101266. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  101267. sqlite3SelectDelete(dbMem, pStep->pSelect);
  101268. sqlite3ExprDelete(dbMem, p->pWhen);
  101269. sqlite3DbFree(dbMem, p);
  101270. }
  101271. }
  101272. /*
  101273. ** This function is called to generate code that runs when table pTab is
  101274. ** being dropped from the database. The SrcList passed as the second argument
  101275. ** to this function contains a single entry guaranteed to resolve to
  101276. ** table pTab.
  101277. **
  101278. ** Normally, no code is required. However, if either
  101279. **
  101280. ** (a) The table is the parent table of a FK constraint, or
  101281. ** (b) The table is the child table of a deferred FK constraint and it is
  101282. ** determined at runtime that there are outstanding deferred FK
  101283. ** constraint violations in the database,
  101284. **
  101285. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  101286. ** the table from the database. Triggers are disabled while running this
  101287. ** DELETE, but foreign key actions are not.
  101288. */
  101289. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  101290. sqlite3 *db = pParse->db;
  101291. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  101292. int iSkip = 0;
  101293. Vdbe *v = sqlite3GetVdbe(pParse);
  101294. assert( v ); /* VDBE has already been allocated */
  101295. if( sqlite3FkReferences(pTab)==0 ){
  101296. /* Search for a deferred foreign key constraint for which this table
  101297. ** is the child table. If one cannot be found, return without
  101298. ** generating any VDBE code. If one can be found, then jump over
  101299. ** the entire DELETE if there are no outstanding deferred constraints
  101300. ** when this statement is run. */
  101301. FKey *p;
  101302. for(p=pTab->pFKey; p; p=p->pNextFrom){
  101303. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  101304. }
  101305. if( !p ) return;
  101306. iSkip = sqlite3VdbeMakeLabel(v);
  101307. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  101308. }
  101309. pParse->disableTriggers = 1;
  101310. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  101311. pParse->disableTriggers = 0;
  101312. /* If the DELETE has generated immediate foreign key constraint
  101313. ** violations, halt the VDBE and return an error at this point, before
  101314. ** any modifications to the schema are made. This is because statement
  101315. ** transactions are not able to rollback schema changes.
  101316. **
  101317. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  101318. ** the statement transaction will not be rolled back even if FK
  101319. ** constraints are violated.
  101320. */
  101321. if( (db->flags & SQLITE_DeferFKs)==0 ){
  101322. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  101323. VdbeCoverage(v);
  101324. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  101325. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  101326. }
  101327. if( iSkip ){
  101328. sqlite3VdbeResolveLabel(v, iSkip);
  101329. }
  101330. }
  101331. }
  101332. /*
  101333. ** The second argument points to an FKey object representing a foreign key
  101334. ** for which pTab is the child table. An UPDATE statement against pTab
  101335. ** is currently being processed. For each column of the table that is
  101336. ** actually updated, the corresponding element in the aChange[] array
  101337. ** is zero or greater (if a column is unmodified the corresponding element
  101338. ** is set to -1). If the rowid column is modified by the UPDATE statement
  101339. ** the bChngRowid argument is non-zero.
  101340. **
  101341. ** This function returns true if any of the columns that are part of the
  101342. ** child key for FK constraint *p are modified.
  101343. */
  101344. static int fkChildIsModified(
  101345. Table *pTab, /* Table being updated */
  101346. FKey *p, /* Foreign key for which pTab is the child */
  101347. int *aChange, /* Array indicating modified columns */
  101348. int bChngRowid /* True if rowid is modified by this update */
  101349. ){
  101350. int i;
  101351. for(i=0; i<p->nCol; i++){
  101352. int iChildKey = p->aCol[i].iFrom;
  101353. if( aChange[iChildKey]>=0 ) return 1;
  101354. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  101355. }
  101356. return 0;
  101357. }
  101358. /*
  101359. ** The second argument points to an FKey object representing a foreign key
  101360. ** for which pTab is the parent table. An UPDATE statement against pTab
  101361. ** is currently being processed. For each column of the table that is
  101362. ** actually updated, the corresponding element in the aChange[] array
  101363. ** is zero or greater (if a column is unmodified the corresponding element
  101364. ** is set to -1). If the rowid column is modified by the UPDATE statement
  101365. ** the bChngRowid argument is non-zero.
  101366. **
  101367. ** This function returns true if any of the columns that are part of the
  101368. ** parent key for FK constraint *p are modified.
  101369. */
  101370. static int fkParentIsModified(
  101371. Table *pTab,
  101372. FKey *p,
  101373. int *aChange,
  101374. int bChngRowid
  101375. ){
  101376. int i;
  101377. for(i=0; i<p->nCol; i++){
  101378. char *zKey = p->aCol[i].zCol;
  101379. int iKey;
  101380. for(iKey=0; iKey<pTab->nCol; iKey++){
  101381. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  101382. Column *pCol = &pTab->aCol[iKey];
  101383. if( zKey ){
  101384. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  101385. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  101386. return 1;
  101387. }
  101388. }
  101389. }
  101390. }
  101391. return 0;
  101392. }
  101393. /*
  101394. ** Return true if the parser passed as the first argument is being
  101395. ** used to code a trigger that is really a "SET NULL" action belonging
  101396. ** to trigger pFKey.
  101397. */
  101398. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  101399. Parse *pTop = sqlite3ParseToplevel(pParse);
  101400. if( pTop->pTriggerPrg ){
  101401. Trigger *p = pTop->pTriggerPrg->pTrigger;
  101402. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  101403. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  101404. ){
  101405. return 1;
  101406. }
  101407. }
  101408. return 0;
  101409. }
  101410. /*
  101411. ** This function is called when inserting, deleting or updating a row of
  101412. ** table pTab to generate VDBE code to perform foreign key constraint
  101413. ** processing for the operation.
  101414. **
  101415. ** For a DELETE operation, parameter regOld is passed the index of the
  101416. ** first register in an array of (pTab->nCol+1) registers containing the
  101417. ** rowid of the row being deleted, followed by each of the column values
  101418. ** of the row being deleted, from left to right. Parameter regNew is passed
  101419. ** zero in this case.
  101420. **
  101421. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  101422. ** first register of an array of (pTab->nCol+1) registers containing the new
  101423. ** row data.
  101424. **
  101425. ** For an UPDATE operation, this function is called twice. Once before
  101426. ** the original record is deleted from the table using the calling convention
  101427. ** described for DELETE. Then again after the original record is deleted
  101428. ** but before the new record is inserted using the INSERT convention.
  101429. */
  101430. SQLITE_PRIVATE void sqlite3FkCheck(
  101431. Parse *pParse, /* Parse context */
  101432. Table *pTab, /* Row is being deleted from this table */
  101433. int regOld, /* Previous row data is stored here */
  101434. int regNew, /* New row data is stored here */
  101435. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  101436. int bChngRowid /* True if rowid is UPDATEd */
  101437. ){
  101438. sqlite3 *db = pParse->db; /* Database handle */
  101439. FKey *pFKey; /* Used to iterate through FKs */
  101440. int iDb; /* Index of database containing pTab */
  101441. const char *zDb; /* Name of database containing pTab */
  101442. int isIgnoreErrors = pParse->disableTriggers;
  101443. /* Exactly one of regOld and regNew should be non-zero. */
  101444. assert( (regOld==0)!=(regNew==0) );
  101445. /* If foreign-keys are disabled, this function is a no-op. */
  101446. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  101447. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  101448. zDb = db->aDb[iDb].zDbSName;
  101449. /* Loop through all the foreign key constraints for which pTab is the
  101450. ** child table (the table that the foreign key definition is part of). */
  101451. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  101452. Table *pTo; /* Parent table of foreign key pFKey */
  101453. Index *pIdx = 0; /* Index on key columns in pTo */
  101454. int *aiFree = 0;
  101455. int *aiCol;
  101456. int iCol;
  101457. int i;
  101458. int bIgnore = 0;
  101459. if( aChange
  101460. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  101461. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  101462. ){
  101463. continue;
  101464. }
  101465. /* Find the parent table of this foreign key. Also find a unique index
  101466. ** on the parent key columns in the parent table. If either of these
  101467. ** schema items cannot be located, set an error in pParse and return
  101468. ** early. */
  101469. if( pParse->disableTriggers ){
  101470. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  101471. }else{
  101472. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  101473. }
  101474. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  101475. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  101476. if( !isIgnoreErrors || db->mallocFailed ) return;
  101477. if( pTo==0 ){
  101478. /* If isIgnoreErrors is true, then a table is being dropped. In this
  101479. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  101480. ** before actually dropping it in order to check FK constraints.
  101481. ** If the parent table of an FK constraint on the current table is
  101482. ** missing, behave as if it is empty. i.e. decrement the relevant
  101483. ** FK counter for each row of the current table with non-NULL keys.
  101484. */
  101485. Vdbe *v = sqlite3GetVdbe(pParse);
  101486. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  101487. for(i=0; i<pFKey->nCol; i++){
  101488. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  101489. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  101490. }
  101491. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  101492. }
  101493. continue;
  101494. }
  101495. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  101496. if( aiFree ){
  101497. aiCol = aiFree;
  101498. }else{
  101499. iCol = pFKey->aCol[0].iFrom;
  101500. aiCol = &iCol;
  101501. }
  101502. for(i=0; i<pFKey->nCol; i++){
  101503. if( aiCol[i]==pTab->iPKey ){
  101504. aiCol[i] = -1;
  101505. }
  101506. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  101507. #ifndef SQLITE_OMIT_AUTHORIZATION
  101508. /* Request permission to read the parent key columns. If the
  101509. ** authorization callback returns SQLITE_IGNORE, behave as if any
  101510. ** values read from the parent table are NULL. */
  101511. if( db->xAuth ){
  101512. int rcauth;
  101513. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  101514. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  101515. bIgnore = (rcauth==SQLITE_IGNORE);
  101516. }
  101517. #endif
  101518. }
  101519. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  101520. ** a cursor to use to search the unique index on the parent key columns
  101521. ** in the parent table. */
  101522. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  101523. pParse->nTab++;
  101524. if( regOld!=0 ){
  101525. /* A row is being removed from the child table. Search for the parent.
  101526. ** If the parent does not exist, removing the child row resolves an
  101527. ** outstanding foreign key constraint violation. */
  101528. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  101529. }
  101530. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  101531. /* A row is being added to the child table. If a parent row cannot
  101532. ** be found, adding the child row has violated the FK constraint.
  101533. **
  101534. ** If this operation is being performed as part of a trigger program
  101535. ** that is actually a "SET NULL" action belonging to this very
  101536. ** foreign key, then omit this scan altogether. As all child key
  101537. ** values are guaranteed to be NULL, it is not possible for adding
  101538. ** this row to cause an FK violation. */
  101539. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  101540. }
  101541. sqlite3DbFree(db, aiFree);
  101542. }
  101543. /* Loop through all the foreign key constraints that refer to this table.
  101544. ** (the "child" constraints) */
  101545. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  101546. Index *pIdx = 0; /* Foreign key index for pFKey */
  101547. SrcList *pSrc;
  101548. int *aiCol = 0;
  101549. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  101550. continue;
  101551. }
  101552. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  101553. && !pParse->pToplevel && !pParse->isMultiWrite
  101554. ){
  101555. assert( regOld==0 && regNew!=0 );
  101556. /* Inserting a single row into a parent table cannot cause (or fix)
  101557. ** an immediate foreign key violation. So do nothing in this case. */
  101558. continue;
  101559. }
  101560. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  101561. if( !isIgnoreErrors || db->mallocFailed ) return;
  101562. continue;
  101563. }
  101564. assert( aiCol || pFKey->nCol==1 );
  101565. /* Create a SrcList structure containing the child table. We need the
  101566. ** child table as a SrcList for sqlite3WhereBegin() */
  101567. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  101568. if( pSrc ){
  101569. struct SrcList_item *pItem = pSrc->a;
  101570. pItem->pTab = pFKey->pFrom;
  101571. pItem->zName = pFKey->pFrom->zName;
  101572. pItem->pTab->nTabRef++;
  101573. pItem->iCursor = pParse->nTab++;
  101574. if( regNew!=0 ){
  101575. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  101576. }
  101577. if( regOld!=0 ){
  101578. int eAction = pFKey->aAction[aChange!=0];
  101579. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  101580. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  101581. ** action applies, then any foreign key violations caused by
  101582. ** removing the parent key will be rectified by the action trigger.
  101583. ** So do not set the "may-abort" flag in this case.
  101584. **
  101585. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  101586. ** may-abort flag will eventually be set on this statement anyway
  101587. ** (when this function is called as part of processing the UPDATE
  101588. ** within the action trigger).
  101589. **
  101590. ** Note 2: At first glance it may seem like SQLite could simply omit
  101591. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  101592. ** applies. The trouble starts if the CASCADE or SET NULL action
  101593. ** trigger causes other triggers or action rules attached to the
  101594. ** child table to fire. In these cases the fk constraint counters
  101595. ** might be set incorrectly if any OP_FkCounter related scans are
  101596. ** omitted. */
  101597. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  101598. sqlite3MayAbort(pParse);
  101599. }
  101600. }
  101601. pItem->zName = 0;
  101602. sqlite3SrcListDelete(db, pSrc);
  101603. }
  101604. sqlite3DbFree(db, aiCol);
  101605. }
  101606. }
  101607. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  101608. /*
  101609. ** This function is called before generating code to update or delete a
  101610. ** row contained in table pTab.
  101611. */
  101612. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  101613. Parse *pParse, /* Parse context */
  101614. Table *pTab /* Table being modified */
  101615. ){
  101616. u32 mask = 0;
  101617. if( pParse->db->flags&SQLITE_ForeignKeys ){
  101618. FKey *p;
  101619. int i;
  101620. for(p=pTab->pFKey; p; p=p->pNextFrom){
  101621. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  101622. }
  101623. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  101624. Index *pIdx = 0;
  101625. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  101626. if( pIdx ){
  101627. for(i=0; i<pIdx->nKeyCol; i++){
  101628. assert( pIdx->aiColumn[i]>=0 );
  101629. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  101630. }
  101631. }
  101632. }
  101633. }
  101634. return mask;
  101635. }
  101636. /*
  101637. ** This function is called before generating code to update or delete a
  101638. ** row contained in table pTab. If the operation is a DELETE, then
  101639. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  101640. ** to an array of size N, where N is the number of columns in table pTab.
  101641. ** If the i'th column is not modified by the UPDATE, then the corresponding
  101642. ** entry in the aChange[] array is set to -1. If the column is modified,
  101643. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  101644. ** UPDATE statement modifies the rowid fields of the table.
  101645. **
  101646. ** If any foreign key processing will be required, this function returns
  101647. ** non-zero. If there is no foreign key related processing, this function
  101648. ** returns zero.
  101649. **
  101650. ** For an UPDATE, this function returns 2 if:
  101651. **
  101652. ** * There are any FKs for which pTab is the child and the parent table, or
  101653. ** * the UPDATE modifies one or more parent keys for which the action is
  101654. ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
  101655. **
  101656. ** Or, assuming some other foreign key processing is required, 1.
  101657. */
  101658. SQLITE_PRIVATE int sqlite3FkRequired(
  101659. Parse *pParse, /* Parse context */
  101660. Table *pTab, /* Table being modified */
  101661. int *aChange, /* Non-NULL for UPDATE operations */
  101662. int chngRowid /* True for UPDATE that affects rowid */
  101663. ){
  101664. int eRet = 0;
  101665. if( pParse->db->flags&SQLITE_ForeignKeys ){
  101666. if( !aChange ){
  101667. /* A DELETE operation. Foreign key processing is required if the
  101668. ** table in question is either the child or parent table for any
  101669. ** foreign key constraint. */
  101670. eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
  101671. }else{
  101672. /* This is an UPDATE. Foreign key processing is only required if the
  101673. ** operation modifies one or more child or parent key columns. */
  101674. FKey *p;
  101675. /* Check if any child key columns are being modified. */
  101676. for(p=pTab->pFKey; p; p=p->pNextFrom){
  101677. if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
  101678. if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
  101679. eRet = 1;
  101680. }
  101681. }
  101682. /* Check if any parent key columns are being modified. */
  101683. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  101684. if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
  101685. if( p->aAction[1]!=OE_None ) return 2;
  101686. eRet = 1;
  101687. }
  101688. }
  101689. }
  101690. }
  101691. return eRet;
  101692. }
  101693. /*
  101694. ** This function is called when an UPDATE or DELETE operation is being
  101695. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  101696. ** If the current operation is an UPDATE, then the pChanges parameter is
  101697. ** passed a pointer to the list of columns being modified. If it is a
  101698. ** DELETE, pChanges is passed a NULL pointer.
  101699. **
  101700. ** It returns a pointer to a Trigger structure containing a trigger
  101701. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  101702. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  101703. ** returned (these actions require no special handling by the triggers
  101704. ** sub-system, code for them is created by fkScanChildren()).
  101705. **
  101706. ** For example, if pFKey is the foreign key and pTab is table "p" in
  101707. ** the following schema:
  101708. **
  101709. ** CREATE TABLE p(pk PRIMARY KEY);
  101710. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  101711. **
  101712. ** then the returned trigger structure is equivalent to:
  101713. **
  101714. ** CREATE TRIGGER ... DELETE ON p BEGIN
  101715. ** DELETE FROM c WHERE ck = old.pk;
  101716. ** END;
  101717. **
  101718. ** The returned pointer is cached as part of the foreign key object. It
  101719. ** is eventually freed along with the rest of the foreign key object by
  101720. ** sqlite3FkDelete().
  101721. */
  101722. static Trigger *fkActionTrigger(
  101723. Parse *pParse, /* Parse context */
  101724. Table *pTab, /* Table being updated or deleted from */
  101725. FKey *pFKey, /* Foreign key to get action for */
  101726. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  101727. ){
  101728. sqlite3 *db = pParse->db; /* Database handle */
  101729. int action; /* One of OE_None, OE_Cascade etc. */
  101730. Trigger *pTrigger; /* Trigger definition to return */
  101731. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  101732. action = pFKey->aAction[iAction];
  101733. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  101734. return 0;
  101735. }
  101736. pTrigger = pFKey->apTrigger[iAction];
  101737. if( action!=OE_None && !pTrigger ){
  101738. char const *zFrom; /* Name of child table */
  101739. int nFrom; /* Length in bytes of zFrom */
  101740. Index *pIdx = 0; /* Parent key index for this FK */
  101741. int *aiCol = 0; /* child table cols -> parent key cols */
  101742. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  101743. Expr *pWhere = 0; /* WHERE clause of trigger step */
  101744. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  101745. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  101746. int i; /* Iterator variable */
  101747. Expr *pWhen = 0; /* WHEN clause for the trigger */
  101748. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  101749. assert( aiCol || pFKey->nCol==1 );
  101750. for(i=0; i<pFKey->nCol; i++){
  101751. Token tOld = { "old", 3 }; /* Literal "old" token */
  101752. Token tNew = { "new", 3 }; /* Literal "new" token */
  101753. Token tFromCol; /* Name of column in child table */
  101754. Token tToCol; /* Name of column in parent table */
  101755. int iFromCol; /* Idx of column in child table */
  101756. Expr *pEq; /* tFromCol = OLD.tToCol */
  101757. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  101758. assert( iFromCol>=0 );
  101759. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  101760. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  101761. sqlite3TokenInit(&tToCol,
  101762. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  101763. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  101764. /* Create the expression "OLD.zToCol = zFromCol". It is important
  101765. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  101766. ** that the affinity and collation sequence associated with the
  101767. ** parent table are used for the comparison. */
  101768. pEq = sqlite3PExpr(pParse, TK_EQ,
  101769. sqlite3PExpr(pParse, TK_DOT,
  101770. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  101771. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  101772. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  101773. );
  101774. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  101775. /* For ON UPDATE, construct the next term of the WHEN clause.
  101776. ** The final WHEN clause will be like this:
  101777. **
  101778. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  101779. */
  101780. if( pChanges ){
  101781. pEq = sqlite3PExpr(pParse, TK_IS,
  101782. sqlite3PExpr(pParse, TK_DOT,
  101783. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  101784. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  101785. sqlite3PExpr(pParse, TK_DOT,
  101786. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  101787. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
  101788. );
  101789. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  101790. }
  101791. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  101792. Expr *pNew;
  101793. if( action==OE_Cascade ){
  101794. pNew = sqlite3PExpr(pParse, TK_DOT,
  101795. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  101796. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
  101797. }else if( action==OE_SetDflt ){
  101798. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  101799. if( pDflt ){
  101800. pNew = sqlite3ExprDup(db, pDflt, 0);
  101801. }else{
  101802. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  101803. }
  101804. }else{
  101805. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  101806. }
  101807. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  101808. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  101809. }
  101810. }
  101811. sqlite3DbFree(db, aiCol);
  101812. zFrom = pFKey->pFrom->zName;
  101813. nFrom = sqlite3Strlen30(zFrom);
  101814. if( action==OE_Restrict ){
  101815. Token tFrom;
  101816. Expr *pRaise;
  101817. tFrom.z = zFrom;
  101818. tFrom.n = nFrom;
  101819. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  101820. if( pRaise ){
  101821. pRaise->affinity = OE_Abort;
  101822. }
  101823. pSelect = sqlite3SelectNew(pParse,
  101824. sqlite3ExprListAppend(pParse, 0, pRaise),
  101825. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  101826. pWhere,
  101827. 0, 0, 0, 0, 0, 0
  101828. );
  101829. pWhere = 0;
  101830. }
  101831. /* Disable lookaside memory allocation */
  101832. db->lookaside.bDisable++;
  101833. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  101834. sizeof(Trigger) + /* struct Trigger */
  101835. sizeof(TriggerStep) + /* Single step in trigger program */
  101836. nFrom + 1 /* Space for pStep->zTarget */
  101837. );
  101838. if( pTrigger ){
  101839. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  101840. pStep->zTarget = (char *)&pStep[1];
  101841. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  101842. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  101843. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  101844. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  101845. if( pWhen ){
  101846. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
  101847. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  101848. }
  101849. }
  101850. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  101851. db->lookaside.bDisable--;
  101852. sqlite3ExprDelete(db, pWhere);
  101853. sqlite3ExprDelete(db, pWhen);
  101854. sqlite3ExprListDelete(db, pList);
  101855. sqlite3SelectDelete(db, pSelect);
  101856. if( db->mallocFailed==1 ){
  101857. fkTriggerDelete(db, pTrigger);
  101858. return 0;
  101859. }
  101860. assert( pStep!=0 );
  101861. switch( action ){
  101862. case OE_Restrict:
  101863. pStep->op = TK_SELECT;
  101864. break;
  101865. case OE_Cascade:
  101866. if( !pChanges ){
  101867. pStep->op = TK_DELETE;
  101868. break;
  101869. }
  101870. default:
  101871. pStep->op = TK_UPDATE;
  101872. }
  101873. pStep->pTrig = pTrigger;
  101874. pTrigger->pSchema = pTab->pSchema;
  101875. pTrigger->pTabSchema = pTab->pSchema;
  101876. pFKey->apTrigger[iAction] = pTrigger;
  101877. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  101878. }
  101879. return pTrigger;
  101880. }
  101881. /*
  101882. ** This function is called when deleting or updating a row to implement
  101883. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  101884. */
  101885. SQLITE_PRIVATE void sqlite3FkActions(
  101886. Parse *pParse, /* Parse context */
  101887. Table *pTab, /* Table being updated or deleted from */
  101888. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  101889. int regOld, /* Address of array containing old row */
  101890. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  101891. int bChngRowid /* True if rowid is UPDATEd */
  101892. ){
  101893. /* If foreign-key support is enabled, iterate through all FKs that
  101894. ** refer to table pTab. If there is an action associated with the FK
  101895. ** for this operation (either update or delete), invoke the associated
  101896. ** trigger sub-program. */
  101897. if( pParse->db->flags&SQLITE_ForeignKeys ){
  101898. FKey *pFKey; /* Iterator variable */
  101899. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  101900. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  101901. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  101902. if( pAct ){
  101903. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  101904. }
  101905. }
  101906. }
  101907. }
  101908. }
  101909. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  101910. /*
  101911. ** Free all memory associated with foreign key definitions attached to
  101912. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  101913. ** hash table.
  101914. */
  101915. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  101916. FKey *pFKey; /* Iterator variable */
  101917. FKey *pNext; /* Copy of pFKey->pNextFrom */
  101918. assert( db==0 || IsVirtual(pTab)
  101919. || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  101920. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  101921. /* Remove the FK from the fkeyHash hash table. */
  101922. if( !db || db->pnBytesFreed==0 ){
  101923. if( pFKey->pPrevTo ){
  101924. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  101925. }else{
  101926. void *p = (void *)pFKey->pNextTo;
  101927. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  101928. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  101929. }
  101930. if( pFKey->pNextTo ){
  101931. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  101932. }
  101933. }
  101934. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  101935. ** classified as either immediate or deferred.
  101936. */
  101937. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  101938. /* Delete any triggers created to implement actions for this FK. */
  101939. #ifndef SQLITE_OMIT_TRIGGER
  101940. fkTriggerDelete(db, pFKey->apTrigger[0]);
  101941. fkTriggerDelete(db, pFKey->apTrigger[1]);
  101942. #endif
  101943. pNext = pFKey->pNextFrom;
  101944. sqlite3DbFree(db, pFKey);
  101945. }
  101946. }
  101947. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  101948. /************** End of fkey.c ************************************************/
  101949. /************** Begin file insert.c ******************************************/
  101950. /*
  101951. ** 2001 September 15
  101952. **
  101953. ** The author disclaims copyright to this source code. In place of
  101954. ** a legal notice, here is a blessing:
  101955. **
  101956. ** May you do good and not evil.
  101957. ** May you find forgiveness for yourself and forgive others.
  101958. ** May you share freely, never taking more than you give.
  101959. **
  101960. *************************************************************************
  101961. ** This file contains C code routines that are called by the parser
  101962. ** to handle INSERT statements in SQLite.
  101963. */
  101964. /* #include "sqliteInt.h" */
  101965. /*
  101966. ** Generate code that will
  101967. **
  101968. ** (1) acquire a lock for table pTab then
  101969. ** (2) open pTab as cursor iCur.
  101970. **
  101971. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  101972. ** for that table that is actually opened.
  101973. */
  101974. SQLITE_PRIVATE void sqlite3OpenTable(
  101975. Parse *pParse, /* Generate code into this VDBE */
  101976. int iCur, /* The cursor number of the table */
  101977. int iDb, /* The database index in sqlite3.aDb[] */
  101978. Table *pTab, /* The table to be opened */
  101979. int opcode /* OP_OpenRead or OP_OpenWrite */
  101980. ){
  101981. Vdbe *v;
  101982. assert( !IsVirtual(pTab) );
  101983. v = sqlite3GetVdbe(pParse);
  101984. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  101985. sqlite3TableLock(pParse, iDb, pTab->tnum,
  101986. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  101987. if( HasRowid(pTab) ){
  101988. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  101989. VdbeComment((v, "%s", pTab->zName));
  101990. }else{
  101991. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  101992. assert( pPk!=0 );
  101993. assert( pPk->tnum==pTab->tnum );
  101994. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  101995. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  101996. VdbeComment((v, "%s", pTab->zName));
  101997. }
  101998. }
  101999. /*
  102000. ** Return a pointer to the column affinity string associated with index
  102001. ** pIdx. A column affinity string has one character for each column in
  102002. ** the table, according to the affinity of the column:
  102003. **
  102004. ** Character Column affinity
  102005. ** ------------------------------
  102006. ** 'A' BLOB
  102007. ** 'B' TEXT
  102008. ** 'C' NUMERIC
  102009. ** 'D' INTEGER
  102010. ** 'F' REAL
  102011. **
  102012. ** An extra 'D' is appended to the end of the string to cover the
  102013. ** rowid that appears as the last column in every index.
  102014. **
  102015. ** Memory for the buffer containing the column index affinity string
  102016. ** is managed along with the rest of the Index structure. It will be
  102017. ** released when sqlite3DeleteIndex() is called.
  102018. */
  102019. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  102020. if( !pIdx->zColAff ){
  102021. /* The first time a column affinity string for a particular index is
  102022. ** required, it is allocated and populated here. It is then stored as
  102023. ** a member of the Index structure for subsequent use.
  102024. **
  102025. ** The column affinity string will eventually be deleted by
  102026. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  102027. ** up.
  102028. */
  102029. int n;
  102030. Table *pTab = pIdx->pTable;
  102031. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  102032. if( !pIdx->zColAff ){
  102033. sqlite3OomFault(db);
  102034. return 0;
  102035. }
  102036. for(n=0; n<pIdx->nColumn; n++){
  102037. i16 x = pIdx->aiColumn[n];
  102038. if( x>=0 ){
  102039. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  102040. }else if( x==XN_ROWID ){
  102041. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  102042. }else{
  102043. char aff;
  102044. assert( x==XN_EXPR );
  102045. assert( pIdx->aColExpr!=0 );
  102046. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  102047. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  102048. pIdx->zColAff[n] = aff;
  102049. }
  102050. }
  102051. pIdx->zColAff[n] = 0;
  102052. }
  102053. return pIdx->zColAff;
  102054. }
  102055. /*
  102056. ** Compute the affinity string for table pTab, if it has not already been
  102057. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  102058. **
  102059. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  102060. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  102061. ** for register iReg and following. Or if affinities exists and iReg==0,
  102062. ** then just set the P4 operand of the previous opcode (which should be
  102063. ** an OP_MakeRecord) to the affinity string.
  102064. **
  102065. ** A column affinity string has one character per column:
  102066. **
  102067. ** Character Column affinity
  102068. ** ------------------------------
  102069. ** 'A' BLOB
  102070. ** 'B' TEXT
  102071. ** 'C' NUMERIC
  102072. ** 'D' INTEGER
  102073. ** 'E' REAL
  102074. */
  102075. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  102076. int i;
  102077. char *zColAff = pTab->zColAff;
  102078. if( zColAff==0 ){
  102079. sqlite3 *db = sqlite3VdbeDb(v);
  102080. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  102081. if( !zColAff ){
  102082. sqlite3OomFault(db);
  102083. return;
  102084. }
  102085. for(i=0; i<pTab->nCol; i++){
  102086. zColAff[i] = pTab->aCol[i].affinity;
  102087. }
  102088. do{
  102089. zColAff[i--] = 0;
  102090. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  102091. pTab->zColAff = zColAff;
  102092. }
  102093. i = sqlite3Strlen30(zColAff);
  102094. if( i ){
  102095. if( iReg ){
  102096. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  102097. }else{
  102098. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  102099. }
  102100. }
  102101. }
  102102. /*
  102103. ** Return non-zero if the table pTab in database iDb or any of its indices
  102104. ** have been opened at any point in the VDBE program. This is used to see if
  102105. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  102106. ** run without using a temporary table for the results of the SELECT.
  102107. */
  102108. static int readsTable(Parse *p, int iDb, Table *pTab){
  102109. Vdbe *v = sqlite3GetVdbe(p);
  102110. int i;
  102111. int iEnd = sqlite3VdbeCurrentAddr(v);
  102112. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102113. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  102114. #endif
  102115. for(i=1; i<iEnd; i++){
  102116. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  102117. assert( pOp!=0 );
  102118. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  102119. Index *pIndex;
  102120. int tnum = pOp->p2;
  102121. if( tnum==pTab->tnum ){
  102122. return 1;
  102123. }
  102124. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  102125. if( tnum==pIndex->tnum ){
  102126. return 1;
  102127. }
  102128. }
  102129. }
  102130. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102131. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  102132. assert( pOp->p4.pVtab!=0 );
  102133. assert( pOp->p4type==P4_VTAB );
  102134. return 1;
  102135. }
  102136. #endif
  102137. }
  102138. return 0;
  102139. }
  102140. #ifndef SQLITE_OMIT_AUTOINCREMENT
  102141. /*
  102142. ** Locate or create an AutoincInfo structure associated with table pTab
  102143. ** which is in database iDb. Return the register number for the register
  102144. ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
  102145. ** table. (Also return zero when doing a VACUUM since we do not want to
  102146. ** update the AUTOINCREMENT counters during a VACUUM.)
  102147. **
  102148. ** There is at most one AutoincInfo structure per table even if the
  102149. ** same table is autoincremented multiple times due to inserts within
  102150. ** triggers. A new AutoincInfo structure is created if this is the
  102151. ** first use of table pTab. On 2nd and subsequent uses, the original
  102152. ** AutoincInfo structure is used.
  102153. **
  102154. ** Three memory locations are allocated:
  102155. **
  102156. ** (1) Register to hold the name of the pTab table.
  102157. ** (2) Register to hold the maximum ROWID of pTab.
  102158. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  102159. **
  102160. ** The 2nd register is the one that is returned. That is all the
  102161. ** insert routine needs to know about.
  102162. */
  102163. static int autoIncBegin(
  102164. Parse *pParse, /* Parsing context */
  102165. int iDb, /* Index of the database holding pTab */
  102166. Table *pTab /* The table we are writing to */
  102167. ){
  102168. int memId = 0; /* Register holding maximum rowid */
  102169. if( (pTab->tabFlags & TF_Autoincrement)!=0
  102170. && (pParse->db->flags & SQLITE_Vacuum)==0
  102171. ){
  102172. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  102173. AutoincInfo *pInfo;
  102174. pInfo = pToplevel->pAinc;
  102175. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  102176. if( pInfo==0 ){
  102177. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  102178. if( pInfo==0 ) return 0;
  102179. pInfo->pNext = pToplevel->pAinc;
  102180. pToplevel->pAinc = pInfo;
  102181. pInfo->pTab = pTab;
  102182. pInfo->iDb = iDb;
  102183. pToplevel->nMem++; /* Register to hold name of table */
  102184. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  102185. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  102186. }
  102187. memId = pInfo->regCtr;
  102188. }
  102189. return memId;
  102190. }
  102191. /*
  102192. ** This routine generates code that will initialize all of the
  102193. ** register used by the autoincrement tracker.
  102194. */
  102195. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  102196. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  102197. sqlite3 *db = pParse->db; /* The database connection */
  102198. Db *pDb; /* Database only autoinc table */
  102199. int memId; /* Register holding max rowid */
  102200. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  102201. /* This routine is never called during trigger-generation. It is
  102202. ** only called from the top-level */
  102203. assert( pParse->pTriggerTab==0 );
  102204. assert( sqlite3IsToplevel(pParse) );
  102205. assert( v ); /* We failed long ago if this is not so */
  102206. for(p = pParse->pAinc; p; p = p->pNext){
  102207. static const int iLn = VDBE_OFFSET_LINENO(2);
  102208. static const VdbeOpList autoInc[] = {
  102209. /* 0 */ {OP_Null, 0, 0, 0},
  102210. /* 1 */ {OP_Rewind, 0, 9, 0},
  102211. /* 2 */ {OP_Column, 0, 0, 0},
  102212. /* 3 */ {OP_Ne, 0, 7, 0},
  102213. /* 4 */ {OP_Rowid, 0, 0, 0},
  102214. /* 5 */ {OP_Column, 0, 1, 0},
  102215. /* 6 */ {OP_Goto, 0, 9, 0},
  102216. /* 7 */ {OP_Next, 0, 2, 0},
  102217. /* 8 */ {OP_Integer, 0, 0, 0},
  102218. /* 9 */ {OP_Close, 0, 0, 0}
  102219. };
  102220. VdbeOp *aOp;
  102221. pDb = &db->aDb[p->iDb];
  102222. memId = p->regCtr;
  102223. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  102224. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  102225. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  102226. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  102227. if( aOp==0 ) break;
  102228. aOp[0].p2 = memId;
  102229. aOp[0].p3 = memId+1;
  102230. aOp[2].p3 = memId;
  102231. aOp[3].p1 = memId-1;
  102232. aOp[3].p3 = memId;
  102233. aOp[3].p5 = SQLITE_JUMPIFNULL;
  102234. aOp[4].p2 = memId+1;
  102235. aOp[5].p3 = memId;
  102236. aOp[8].p2 = memId;
  102237. }
  102238. }
  102239. /*
  102240. ** Update the maximum rowid for an autoincrement calculation.
  102241. **
  102242. ** This routine should be called when the regRowid register holds a
  102243. ** new rowid that is about to be inserted. If that new rowid is
  102244. ** larger than the maximum rowid in the memId memory cell, then the
  102245. ** memory cell is updated.
  102246. */
  102247. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  102248. if( memId>0 ){
  102249. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  102250. }
  102251. }
  102252. /*
  102253. ** This routine generates the code needed to write autoincrement
  102254. ** maximum rowid values back into the sqlite_sequence register.
  102255. ** Every statement that might do an INSERT into an autoincrement
  102256. ** table (either directly or through triggers) needs to call this
  102257. ** routine just before the "exit" code.
  102258. */
  102259. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  102260. AutoincInfo *p;
  102261. Vdbe *v = pParse->pVdbe;
  102262. sqlite3 *db = pParse->db;
  102263. assert( v );
  102264. for(p = pParse->pAinc; p; p = p->pNext){
  102265. static const int iLn = VDBE_OFFSET_LINENO(2);
  102266. static const VdbeOpList autoIncEnd[] = {
  102267. /* 0 */ {OP_NotNull, 0, 2, 0},
  102268. /* 1 */ {OP_NewRowid, 0, 0, 0},
  102269. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  102270. /* 3 */ {OP_Insert, 0, 0, 0},
  102271. /* 4 */ {OP_Close, 0, 0, 0}
  102272. };
  102273. VdbeOp *aOp;
  102274. Db *pDb = &db->aDb[p->iDb];
  102275. int iRec;
  102276. int memId = p->regCtr;
  102277. iRec = sqlite3GetTempReg(pParse);
  102278. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  102279. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  102280. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  102281. if( aOp==0 ) break;
  102282. aOp[0].p1 = memId+1;
  102283. aOp[1].p2 = memId+1;
  102284. aOp[2].p1 = memId-1;
  102285. aOp[2].p3 = iRec;
  102286. aOp[3].p2 = iRec;
  102287. aOp[3].p3 = memId+1;
  102288. aOp[3].p5 = OPFLAG_APPEND;
  102289. sqlite3ReleaseTempReg(pParse, iRec);
  102290. }
  102291. }
  102292. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  102293. if( pParse->pAinc ) autoIncrementEnd(pParse);
  102294. }
  102295. #else
  102296. /*
  102297. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  102298. ** above are all no-ops
  102299. */
  102300. # define autoIncBegin(A,B,C) (0)
  102301. # define autoIncStep(A,B,C)
  102302. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  102303. /* Forward declaration */
  102304. static int xferOptimization(
  102305. Parse *pParse, /* Parser context */
  102306. Table *pDest, /* The table we are inserting into */
  102307. Select *pSelect, /* A SELECT statement to use as the data source */
  102308. int onError, /* How to handle constraint errors */
  102309. int iDbDest /* The database of pDest */
  102310. );
  102311. /*
  102312. ** This routine is called to handle SQL of the following forms:
  102313. **
  102314. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  102315. ** insert into TABLE (IDLIST) select
  102316. ** insert into TABLE (IDLIST) default values
  102317. **
  102318. ** The IDLIST following the table name is always optional. If omitted,
  102319. ** then a list of all (non-hidden) columns for the table is substituted.
  102320. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  102321. ** is omitted.
  102322. **
  102323. ** For the pSelect parameter holds the values to be inserted for the
  102324. ** first two forms shown above. A VALUES clause is really just short-hand
  102325. ** for a SELECT statement that omits the FROM clause and everything else
  102326. ** that follows. If the pSelect parameter is NULL, that means that the
  102327. ** DEFAULT VALUES form of the INSERT statement is intended.
  102328. **
  102329. ** The code generated follows one of four templates. For a simple
  102330. ** insert with data coming from a single-row VALUES clause, the code executes
  102331. ** once straight down through. Pseudo-code follows (we call this
  102332. ** the "1st template"):
  102333. **
  102334. ** open write cursor to <table> and its indices
  102335. ** put VALUES clause expressions into registers
  102336. ** write the resulting record into <table>
  102337. ** cleanup
  102338. **
  102339. ** The three remaining templates assume the statement is of the form
  102340. **
  102341. ** INSERT INTO <table> SELECT ...
  102342. **
  102343. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  102344. ** in other words if the SELECT pulls all columns from a single table
  102345. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  102346. ** if <table2> and <table1> are distinct tables but have identical
  102347. ** schemas, including all the same indices, then a special optimization
  102348. ** is invoked that copies raw records from <table2> over to <table1>.
  102349. ** See the xferOptimization() function for the implementation of this
  102350. ** template. This is the 2nd template.
  102351. **
  102352. ** open a write cursor to <table>
  102353. ** open read cursor on <table2>
  102354. ** transfer all records in <table2> over to <table>
  102355. ** close cursors
  102356. ** foreach index on <table>
  102357. ** open a write cursor on the <table> index
  102358. ** open a read cursor on the corresponding <table2> index
  102359. ** transfer all records from the read to the write cursors
  102360. ** close cursors
  102361. ** end foreach
  102362. **
  102363. ** The 3rd template is for when the second template does not apply
  102364. ** and the SELECT clause does not read from <table> at any time.
  102365. ** The generated code follows this template:
  102366. **
  102367. ** X <- A
  102368. ** goto B
  102369. ** A: setup for the SELECT
  102370. ** loop over the rows in the SELECT
  102371. ** load values into registers R..R+n
  102372. ** yield X
  102373. ** end loop
  102374. ** cleanup after the SELECT
  102375. ** end-coroutine X
  102376. ** B: open write cursor to <table> and its indices
  102377. ** C: yield X, at EOF goto D
  102378. ** insert the select result into <table> from R..R+n
  102379. ** goto C
  102380. ** D: cleanup
  102381. **
  102382. ** The 4th template is used if the insert statement takes its
  102383. ** values from a SELECT but the data is being inserted into a table
  102384. ** that is also read as part of the SELECT. In the third form,
  102385. ** we have to use an intermediate table to store the results of
  102386. ** the select. The template is like this:
  102387. **
  102388. ** X <- A
  102389. ** goto B
  102390. ** A: setup for the SELECT
  102391. ** loop over the tables in the SELECT
  102392. ** load value into register R..R+n
  102393. ** yield X
  102394. ** end loop
  102395. ** cleanup after the SELECT
  102396. ** end co-routine R
  102397. ** B: open temp table
  102398. ** L: yield X, at EOF goto M
  102399. ** insert row from R..R+n into temp table
  102400. ** goto L
  102401. ** M: open write cursor to <table> and its indices
  102402. ** rewind temp table
  102403. ** C: loop over rows of intermediate table
  102404. ** transfer values form intermediate table into <table>
  102405. ** end loop
  102406. ** D: cleanup
  102407. */
  102408. SQLITE_PRIVATE void sqlite3Insert(
  102409. Parse *pParse, /* Parser context */
  102410. SrcList *pTabList, /* Name of table into which we are inserting */
  102411. Select *pSelect, /* A SELECT statement to use as the data source */
  102412. IdList *pColumn, /* Column names corresponding to IDLIST. */
  102413. int onError /* How to handle constraint errors */
  102414. ){
  102415. sqlite3 *db; /* The main database structure */
  102416. Table *pTab; /* The table to insert into. aka TABLE */
  102417. char *zTab; /* Name of the table into which we are inserting */
  102418. int i, j; /* Loop counters */
  102419. Vdbe *v; /* Generate code into this virtual machine */
  102420. Index *pIdx; /* For looping over indices of the table */
  102421. int nColumn; /* Number of columns in the data */
  102422. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  102423. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  102424. int iIdxCur = 0; /* First index cursor */
  102425. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  102426. int endOfLoop; /* Label for the end of the insertion loop */
  102427. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  102428. int addrInsTop = 0; /* Jump to label "D" */
  102429. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  102430. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  102431. int iDb; /* Index of database holding TABLE */
  102432. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  102433. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  102434. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  102435. u8 bIdListInOrder; /* True if IDLIST is in table order */
  102436. ExprList *pList = 0; /* List of VALUES() to be inserted */
  102437. /* Register allocations */
  102438. int regFromSelect = 0;/* Base register for data coming from SELECT */
  102439. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  102440. int regRowCount = 0; /* Memory cell used for the row counter */
  102441. int regIns; /* Block of regs holding rowid+data being inserted */
  102442. int regRowid; /* registers holding insert rowid */
  102443. int regData; /* register holding first column to insert */
  102444. int *aRegIdx = 0; /* One register allocated to each index */
  102445. #ifndef SQLITE_OMIT_TRIGGER
  102446. int isView; /* True if attempting to insert into a view */
  102447. Trigger *pTrigger; /* List of triggers on pTab, if required */
  102448. int tmask; /* Mask of trigger times */
  102449. #endif
  102450. db = pParse->db;
  102451. memset(&dest, 0, sizeof(dest));
  102452. if( pParse->nErr || db->mallocFailed ){
  102453. goto insert_cleanup;
  102454. }
  102455. /* If the Select object is really just a simple VALUES() list with a
  102456. ** single row (the common case) then keep that one row of values
  102457. ** and discard the other (unused) parts of the pSelect object
  102458. */
  102459. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  102460. pList = pSelect->pEList;
  102461. pSelect->pEList = 0;
  102462. sqlite3SelectDelete(db, pSelect);
  102463. pSelect = 0;
  102464. }
  102465. /* Locate the table into which we will be inserting new information.
  102466. */
  102467. assert( pTabList->nSrc==1 );
  102468. zTab = pTabList->a[0].zName;
  102469. if( NEVER(zTab==0) ) goto insert_cleanup;
  102470. pTab = sqlite3SrcListLookup(pParse, pTabList);
  102471. if( pTab==0 ){
  102472. goto insert_cleanup;
  102473. }
  102474. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102475. assert( iDb<db->nDb );
  102476. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
  102477. db->aDb[iDb].zDbSName) ){
  102478. goto insert_cleanup;
  102479. }
  102480. withoutRowid = !HasRowid(pTab);
  102481. /* Figure out if we have any triggers and if the table being
  102482. ** inserted into is a view
  102483. */
  102484. #ifndef SQLITE_OMIT_TRIGGER
  102485. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  102486. isView = pTab->pSelect!=0;
  102487. #else
  102488. # define pTrigger 0
  102489. # define tmask 0
  102490. # define isView 0
  102491. #endif
  102492. #ifdef SQLITE_OMIT_VIEW
  102493. # undef isView
  102494. # define isView 0
  102495. #endif
  102496. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  102497. /* If pTab is really a view, make sure it has been initialized.
  102498. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  102499. */
  102500. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  102501. goto insert_cleanup;
  102502. }
  102503. /* Cannot insert into a read-only table.
  102504. */
  102505. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  102506. goto insert_cleanup;
  102507. }
  102508. /* Allocate a VDBE
  102509. */
  102510. v = sqlite3GetVdbe(pParse);
  102511. if( v==0 ) goto insert_cleanup;
  102512. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  102513. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  102514. #ifndef SQLITE_OMIT_XFER_OPT
  102515. /* If the statement is of the form
  102516. **
  102517. ** INSERT INTO <table1> SELECT * FROM <table2>;
  102518. **
  102519. ** Then special optimizations can be applied that make the transfer
  102520. ** very fast and which reduce fragmentation of indices.
  102521. **
  102522. ** This is the 2nd template.
  102523. */
  102524. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  102525. assert( !pTrigger );
  102526. assert( pList==0 );
  102527. goto insert_end;
  102528. }
  102529. #endif /* SQLITE_OMIT_XFER_OPT */
  102530. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  102531. ** sqlite_sequence table and store it in memory cell regAutoinc.
  102532. */
  102533. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  102534. /* Allocate registers for holding the rowid of the new row,
  102535. ** the content of the new row, and the assembled row record.
  102536. */
  102537. regRowid = regIns = pParse->nMem+1;
  102538. pParse->nMem += pTab->nCol + 1;
  102539. if( IsVirtual(pTab) ){
  102540. regRowid++;
  102541. pParse->nMem++;
  102542. }
  102543. regData = regRowid+1;
  102544. /* If the INSERT statement included an IDLIST term, then make sure
  102545. ** all elements of the IDLIST really are columns of the table and
  102546. ** remember the column indices.
  102547. **
  102548. ** If the table has an INTEGER PRIMARY KEY column and that column
  102549. ** is named in the IDLIST, then record in the ipkColumn variable
  102550. ** the index into IDLIST of the primary key column. ipkColumn is
  102551. ** the index of the primary key as it appears in IDLIST, not as
  102552. ** is appears in the original table. (The index of the INTEGER
  102553. ** PRIMARY KEY in the original table is pTab->iPKey.)
  102554. */
  102555. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  102556. if( pColumn ){
  102557. for(i=0; i<pColumn->nId; i++){
  102558. pColumn->a[i].idx = -1;
  102559. }
  102560. for(i=0; i<pColumn->nId; i++){
  102561. for(j=0; j<pTab->nCol; j++){
  102562. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  102563. pColumn->a[i].idx = j;
  102564. if( i!=j ) bIdListInOrder = 0;
  102565. if( j==pTab->iPKey ){
  102566. ipkColumn = i; assert( !withoutRowid );
  102567. }
  102568. break;
  102569. }
  102570. }
  102571. if( j>=pTab->nCol ){
  102572. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  102573. ipkColumn = i;
  102574. bIdListInOrder = 0;
  102575. }else{
  102576. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  102577. pTabList, 0, pColumn->a[i].zName);
  102578. pParse->checkSchema = 1;
  102579. goto insert_cleanup;
  102580. }
  102581. }
  102582. }
  102583. }
  102584. /* Figure out how many columns of data are supplied. If the data
  102585. ** is coming from a SELECT statement, then generate a co-routine that
  102586. ** produces a single row of the SELECT on each invocation. The
  102587. ** co-routine is the common header to the 3rd and 4th templates.
  102588. */
  102589. if( pSelect ){
  102590. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  102591. ** Generate a co-routine to run the SELECT. */
  102592. int regYield; /* Register holding co-routine entry-point */
  102593. int addrTop; /* Top of the co-routine */
  102594. int rc; /* Result code */
  102595. regYield = ++pParse->nMem;
  102596. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  102597. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  102598. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  102599. dest.iSdst = bIdListInOrder ? regData : 0;
  102600. dest.nSdst = pTab->nCol;
  102601. rc = sqlite3Select(pParse, pSelect, &dest);
  102602. regFromSelect = dest.iSdst;
  102603. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  102604. sqlite3VdbeEndCoroutine(v, regYield);
  102605. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  102606. assert( pSelect->pEList );
  102607. nColumn = pSelect->pEList->nExpr;
  102608. /* Set useTempTable to TRUE if the result of the SELECT statement
  102609. ** should be written into a temporary table (template 4). Set to
  102610. ** FALSE if each output row of the SELECT can be written directly into
  102611. ** the destination table (template 3).
  102612. **
  102613. ** A temp table must be used if the table being updated is also one
  102614. ** of the tables being read by the SELECT statement. Also use a
  102615. ** temp table in the case of row triggers.
  102616. */
  102617. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  102618. useTempTable = 1;
  102619. }
  102620. if( useTempTable ){
  102621. /* Invoke the coroutine to extract information from the SELECT
  102622. ** and add it to a transient table srcTab. The code generated
  102623. ** here is from the 4th template:
  102624. **
  102625. ** B: open temp table
  102626. ** L: yield X, goto M at EOF
  102627. ** insert row from R..R+n into temp table
  102628. ** goto L
  102629. ** M: ...
  102630. */
  102631. int regRec; /* Register to hold packed record */
  102632. int regTempRowid; /* Register to hold temp table ROWID */
  102633. int addrL; /* Label "L" */
  102634. srcTab = pParse->nTab++;
  102635. regRec = sqlite3GetTempReg(pParse);
  102636. regTempRowid = sqlite3GetTempReg(pParse);
  102637. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  102638. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  102639. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  102640. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  102641. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  102642. sqlite3VdbeGoto(v, addrL);
  102643. sqlite3VdbeJumpHere(v, addrL);
  102644. sqlite3ReleaseTempReg(pParse, regRec);
  102645. sqlite3ReleaseTempReg(pParse, regTempRowid);
  102646. }
  102647. }else{
  102648. /* This is the case if the data for the INSERT is coming from a
  102649. ** single-row VALUES clause
  102650. */
  102651. NameContext sNC;
  102652. memset(&sNC, 0, sizeof(sNC));
  102653. sNC.pParse = pParse;
  102654. srcTab = -1;
  102655. assert( useTempTable==0 );
  102656. if( pList ){
  102657. nColumn = pList->nExpr;
  102658. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  102659. goto insert_cleanup;
  102660. }
  102661. }else{
  102662. nColumn = 0;
  102663. }
  102664. }
  102665. /* If there is no IDLIST term but the table has an integer primary
  102666. ** key, the set the ipkColumn variable to the integer primary key
  102667. ** column index in the original table definition.
  102668. */
  102669. if( pColumn==0 && nColumn>0 ){
  102670. ipkColumn = pTab->iPKey;
  102671. }
  102672. /* Make sure the number of columns in the source data matches the number
  102673. ** of columns to be inserted into the table.
  102674. */
  102675. for(i=0; i<pTab->nCol; i++){
  102676. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  102677. }
  102678. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  102679. sqlite3ErrorMsg(pParse,
  102680. "table %S has %d columns but %d values were supplied",
  102681. pTabList, 0, pTab->nCol-nHidden, nColumn);
  102682. goto insert_cleanup;
  102683. }
  102684. if( pColumn!=0 && nColumn!=pColumn->nId ){
  102685. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  102686. goto insert_cleanup;
  102687. }
  102688. /* Initialize the count of rows to be inserted
  102689. */
  102690. if( db->flags & SQLITE_CountRows ){
  102691. regRowCount = ++pParse->nMem;
  102692. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  102693. }
  102694. /* If this is not a view, open the table and and all indices */
  102695. if( !isView ){
  102696. int nIdx;
  102697. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  102698. &iDataCur, &iIdxCur);
  102699. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
  102700. if( aRegIdx==0 ){
  102701. goto insert_cleanup;
  102702. }
  102703. for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
  102704. assert( pIdx );
  102705. aRegIdx[i] = ++pParse->nMem;
  102706. pParse->nMem += pIdx->nColumn;
  102707. }
  102708. }
  102709. /* This is the top of the main insertion loop */
  102710. if( useTempTable ){
  102711. /* This block codes the top of loop only. The complete loop is the
  102712. ** following pseudocode (template 4):
  102713. **
  102714. ** rewind temp table, if empty goto D
  102715. ** C: loop over rows of intermediate table
  102716. ** transfer values form intermediate table into <table>
  102717. ** end loop
  102718. ** D: ...
  102719. */
  102720. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  102721. addrCont = sqlite3VdbeCurrentAddr(v);
  102722. }else if( pSelect ){
  102723. /* This block codes the top of loop only. The complete loop is the
  102724. ** following pseudocode (template 3):
  102725. **
  102726. ** C: yield X, at EOF goto D
  102727. ** insert the select result into <table> from R..R+n
  102728. ** goto C
  102729. ** D: ...
  102730. */
  102731. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  102732. VdbeCoverage(v);
  102733. }
  102734. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  102735. */
  102736. endOfLoop = sqlite3VdbeMakeLabel(v);
  102737. if( tmask & TRIGGER_BEFORE ){
  102738. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  102739. /* build the NEW.* reference row. Note that if there is an INTEGER
  102740. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  102741. ** translated into a unique ID for the row. But on a BEFORE trigger,
  102742. ** we do not know what the unique ID will be (because the insert has
  102743. ** not happened yet) so we substitute a rowid of -1
  102744. */
  102745. if( ipkColumn<0 ){
  102746. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  102747. }else{
  102748. int addr1;
  102749. assert( !withoutRowid );
  102750. if( useTempTable ){
  102751. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  102752. }else{
  102753. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  102754. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  102755. }
  102756. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  102757. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  102758. sqlite3VdbeJumpHere(v, addr1);
  102759. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  102760. }
  102761. /* Cannot have triggers on a virtual table. If it were possible,
  102762. ** this block would have to account for hidden column.
  102763. */
  102764. assert( !IsVirtual(pTab) );
  102765. /* Create the new column data
  102766. */
  102767. for(i=j=0; i<pTab->nCol; i++){
  102768. if( pColumn ){
  102769. for(j=0; j<pColumn->nId; j++){
  102770. if( pColumn->a[j].idx==i ) break;
  102771. }
  102772. }
  102773. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  102774. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  102775. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  102776. }else if( useTempTable ){
  102777. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  102778. }else{
  102779. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  102780. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  102781. }
  102782. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  102783. }
  102784. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  102785. ** do not attempt any conversions before assembling the record.
  102786. ** If this is a real table, attempt conversions as required by the
  102787. ** table column affinities.
  102788. */
  102789. if( !isView ){
  102790. sqlite3TableAffinity(v, pTab, regCols+1);
  102791. }
  102792. /* Fire BEFORE or INSTEAD OF triggers */
  102793. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  102794. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  102795. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  102796. }
  102797. /* Compute the content of the next row to insert into a range of
  102798. ** registers beginning at regIns.
  102799. */
  102800. if( !isView ){
  102801. if( IsVirtual(pTab) ){
  102802. /* The row that the VUpdate opcode will delete: none */
  102803. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  102804. }
  102805. if( ipkColumn>=0 ){
  102806. if( useTempTable ){
  102807. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  102808. }else if( pSelect ){
  102809. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  102810. }else{
  102811. VdbeOp *pOp;
  102812. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  102813. pOp = sqlite3VdbeGetOp(v, -1);
  102814. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  102815. appendFlag = 1;
  102816. pOp->opcode = OP_NewRowid;
  102817. pOp->p1 = iDataCur;
  102818. pOp->p2 = regRowid;
  102819. pOp->p3 = regAutoinc;
  102820. }
  102821. }
  102822. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  102823. ** to generate a unique primary key value.
  102824. */
  102825. if( !appendFlag ){
  102826. int addr1;
  102827. if( !IsVirtual(pTab) ){
  102828. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  102829. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  102830. sqlite3VdbeJumpHere(v, addr1);
  102831. }else{
  102832. addr1 = sqlite3VdbeCurrentAddr(v);
  102833. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  102834. }
  102835. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  102836. }
  102837. }else if( IsVirtual(pTab) || withoutRowid ){
  102838. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  102839. }else{
  102840. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  102841. appendFlag = 1;
  102842. }
  102843. autoIncStep(pParse, regAutoinc, regRowid);
  102844. /* Compute data for all columns of the new entry, beginning
  102845. ** with the first column.
  102846. */
  102847. nHidden = 0;
  102848. for(i=0; i<pTab->nCol; i++){
  102849. int iRegStore = regRowid+1+i;
  102850. if( i==pTab->iPKey ){
  102851. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  102852. ** Whenever this column is read, the rowid will be substituted
  102853. ** in its place. Hence, fill this column with a NULL to avoid
  102854. ** taking up data space with information that will never be used.
  102855. ** As there may be shallow copies of this value, make it a soft-NULL */
  102856. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  102857. continue;
  102858. }
  102859. if( pColumn==0 ){
  102860. if( IsHiddenColumn(&pTab->aCol[i]) ){
  102861. j = -1;
  102862. nHidden++;
  102863. }else{
  102864. j = i - nHidden;
  102865. }
  102866. }else{
  102867. for(j=0; j<pColumn->nId; j++){
  102868. if( pColumn->a[j].idx==i ) break;
  102869. }
  102870. }
  102871. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  102872. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  102873. }else if( useTempTable ){
  102874. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  102875. }else if( pSelect ){
  102876. if( regFromSelect!=regData ){
  102877. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  102878. }
  102879. }else{
  102880. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  102881. }
  102882. }
  102883. /* Generate code to check constraints and generate index keys and
  102884. ** do the insertion.
  102885. */
  102886. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102887. if( IsVirtual(pTab) ){
  102888. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  102889. sqlite3VtabMakeWritable(pParse, pTab);
  102890. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  102891. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  102892. sqlite3MayAbort(pParse);
  102893. }else
  102894. #endif
  102895. {
  102896. int isReplace; /* Set to true if constraints may cause a replace */
  102897. int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
  102898. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  102899. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
  102900. );
  102901. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  102902. /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  102903. ** constraints or (b) there are no triggers and this table is not a
  102904. ** parent table in a foreign key constraint. It is safe to set the
  102905. ** flag in the second case as if any REPLACE constraint is hit, an
  102906. ** OP_Delete or OP_IdxDelete instruction will be executed on each
  102907. ** cursor that is disturbed. And these instructions both clear the
  102908. ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  102909. ** functionality. */
  102910. bUseSeek = (isReplace==0 || (pTrigger==0 &&
  102911. ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
  102912. ));
  102913. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  102914. regIns, aRegIdx, 0, appendFlag, bUseSeek
  102915. );
  102916. }
  102917. }
  102918. /* Update the count of rows that are inserted
  102919. */
  102920. if( (db->flags & SQLITE_CountRows)!=0 ){
  102921. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  102922. }
  102923. if( pTrigger ){
  102924. /* Code AFTER triggers */
  102925. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  102926. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  102927. }
  102928. /* The bottom of the main insertion loop, if the data source
  102929. ** is a SELECT statement.
  102930. */
  102931. sqlite3VdbeResolveLabel(v, endOfLoop);
  102932. if( useTempTable ){
  102933. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  102934. sqlite3VdbeJumpHere(v, addrInsTop);
  102935. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  102936. }else if( pSelect ){
  102937. sqlite3VdbeGoto(v, addrCont);
  102938. sqlite3VdbeJumpHere(v, addrInsTop);
  102939. }
  102940. insert_end:
  102941. /* Update the sqlite_sequence table by storing the content of the
  102942. ** maximum rowid counter values recorded while inserting into
  102943. ** autoincrement tables.
  102944. */
  102945. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  102946. sqlite3AutoincrementEnd(pParse);
  102947. }
  102948. /*
  102949. ** Return the number of rows inserted. If this routine is
  102950. ** generating code because of a call to sqlite3NestedParse(), do not
  102951. ** invoke the callback function.
  102952. */
  102953. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  102954. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  102955. sqlite3VdbeSetNumCols(v, 1);
  102956. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  102957. }
  102958. insert_cleanup:
  102959. sqlite3SrcListDelete(db, pTabList);
  102960. sqlite3ExprListDelete(db, pList);
  102961. sqlite3SelectDelete(db, pSelect);
  102962. sqlite3IdListDelete(db, pColumn);
  102963. sqlite3DbFree(db, aRegIdx);
  102964. }
  102965. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  102966. ** they may interfere with compilation of other functions in this file
  102967. ** (or in another file, if this file becomes part of the amalgamation). */
  102968. #ifdef isView
  102969. #undef isView
  102970. #endif
  102971. #ifdef pTrigger
  102972. #undef pTrigger
  102973. #endif
  102974. #ifdef tmask
  102975. #undef tmask
  102976. #endif
  102977. /*
  102978. ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
  102979. */
  102980. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  102981. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  102982. /* This is the Walker callback from checkConstraintUnchanged(). Set
  102983. ** bit 0x01 of pWalker->eCode if
  102984. ** pWalker->eCode to 0 if this expression node references any of the
  102985. ** columns that are being modifed by an UPDATE statement.
  102986. */
  102987. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  102988. if( pExpr->op==TK_COLUMN ){
  102989. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  102990. if( pExpr->iColumn>=0 ){
  102991. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  102992. pWalker->eCode |= CKCNSTRNT_COLUMN;
  102993. }
  102994. }else{
  102995. pWalker->eCode |= CKCNSTRNT_ROWID;
  102996. }
  102997. }
  102998. return WRC_Continue;
  102999. }
  103000. /*
  103001. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  103002. ** only columns that are modified by the UPDATE are those for which
  103003. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  103004. **
  103005. ** Return true if CHECK constraint pExpr does not use any of the
  103006. ** changing columns (or the rowid if it is changing). In other words,
  103007. ** return true if this CHECK constraint can be skipped when validating
  103008. ** the new row in the UPDATE statement.
  103009. */
  103010. static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
  103011. Walker w;
  103012. memset(&w, 0, sizeof(w));
  103013. w.eCode = 0;
  103014. w.xExprCallback = checkConstraintExprNode;
  103015. w.u.aiCol = aiChng;
  103016. sqlite3WalkExpr(&w, pExpr);
  103017. if( !chngRowid ){
  103018. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  103019. w.eCode &= ~CKCNSTRNT_ROWID;
  103020. }
  103021. testcase( w.eCode==0 );
  103022. testcase( w.eCode==CKCNSTRNT_COLUMN );
  103023. testcase( w.eCode==CKCNSTRNT_ROWID );
  103024. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  103025. return !w.eCode;
  103026. }
  103027. /*
  103028. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  103029. ** on table pTab.
  103030. **
  103031. ** The regNewData parameter is the first register in a range that contains
  103032. ** the data to be inserted or the data after the update. There will be
  103033. ** pTab->nCol+1 registers in this range. The first register (the one
  103034. ** that regNewData points to) will contain the new rowid, or NULL in the
  103035. ** case of a WITHOUT ROWID table. The second register in the range will
  103036. ** contain the content of the first table column. The third register will
  103037. ** contain the content of the second table column. And so forth.
  103038. **
  103039. ** The regOldData parameter is similar to regNewData except that it contains
  103040. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  103041. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  103042. ** checking regOldData for zero.
  103043. **
  103044. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  103045. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  103046. ** might be modified by the UPDATE. If pkChng is false, then the key of
  103047. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  103048. **
  103049. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  103050. ** was explicitly specified as part of the INSERT statement. If pkChng
  103051. ** is zero, it means that the either rowid is computed automatically or
  103052. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  103053. ** pkChng will only be true if the INSERT statement provides an integer
  103054. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  103055. **
  103056. ** The code generated by this routine will store new index entries into
  103057. ** registers identified by aRegIdx[]. No index entry is created for
  103058. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  103059. ** the same as the order of indices on the linked list of indices
  103060. ** at pTab->pIndex.
  103061. **
  103062. ** The caller must have already opened writeable cursors on the main
  103063. ** table and all applicable indices (that is to say, all indices for which
  103064. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  103065. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  103066. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  103067. ** for the first index in the pTab->pIndex list. Cursors for other indices
  103068. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  103069. **
  103070. ** This routine also generates code to check constraints. NOT NULL,
  103071. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  103072. ** then the appropriate action is performed. There are five possible
  103073. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  103074. **
  103075. ** Constraint type Action What Happens
  103076. ** --------------- ---------- ----------------------------------------
  103077. ** any ROLLBACK The current transaction is rolled back and
  103078. ** sqlite3_step() returns immediately with a
  103079. ** return code of SQLITE_CONSTRAINT.
  103080. **
  103081. ** any ABORT Back out changes from the current command
  103082. ** only (do not do a complete rollback) then
  103083. ** cause sqlite3_step() to return immediately
  103084. ** with SQLITE_CONSTRAINT.
  103085. **
  103086. ** any FAIL Sqlite3_step() returns immediately with a
  103087. ** return code of SQLITE_CONSTRAINT. The
  103088. ** transaction is not rolled back and any
  103089. ** changes to prior rows are retained.
  103090. **
  103091. ** any IGNORE The attempt in insert or update the current
  103092. ** row is skipped, without throwing an error.
  103093. ** Processing continues with the next row.
  103094. ** (There is an immediate jump to ignoreDest.)
  103095. **
  103096. ** NOT NULL REPLACE The NULL value is replace by the default
  103097. ** value for that column. If the default value
  103098. ** is NULL, the action is the same as ABORT.
  103099. **
  103100. ** UNIQUE REPLACE The other row that conflicts with the row
  103101. ** being inserted is removed.
  103102. **
  103103. ** CHECK REPLACE Illegal. The results in an exception.
  103104. **
  103105. ** Which action to take is determined by the overrideError parameter.
  103106. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  103107. ** is used. Or if pParse->onError==OE_Default then the onError value
  103108. ** for the constraint is used.
  103109. */
  103110. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  103111. Parse *pParse, /* The parser context */
  103112. Table *pTab, /* The table being inserted or updated */
  103113. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  103114. int iDataCur, /* Canonical data cursor (main table or PK index) */
  103115. int iIdxCur, /* First index cursor */
  103116. int regNewData, /* First register in a range holding values to insert */
  103117. int regOldData, /* Previous content. 0 for INSERTs */
  103118. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  103119. u8 overrideError, /* Override onError to this if not OE_Default */
  103120. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  103121. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  103122. int *aiChng /* column i is unchanged if aiChng[i]<0 */
  103123. ){
  103124. Vdbe *v; /* VDBE under constrution */
  103125. Index *pIdx; /* Pointer to one of the indices */
  103126. Index *pPk = 0; /* The PRIMARY KEY index */
  103127. sqlite3 *db; /* Database connection */
  103128. int i; /* loop counter */
  103129. int ix; /* Index loop counter */
  103130. int nCol; /* Number of columns */
  103131. int onError; /* Conflict resolution strategy */
  103132. int addr1; /* Address of jump instruction */
  103133. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  103134. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  103135. int ipkTop = 0; /* Top of the rowid change constraint check */
  103136. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  103137. u8 isUpdate; /* True if this is an UPDATE operation */
  103138. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  103139. isUpdate = regOldData!=0;
  103140. db = pParse->db;
  103141. v = sqlite3GetVdbe(pParse);
  103142. assert( v!=0 );
  103143. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  103144. nCol = pTab->nCol;
  103145. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  103146. ** normal rowid tables. nPkField is the number of key fields in the
  103147. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  103148. ** number of fields in the true primary key of the table. */
  103149. if( HasRowid(pTab) ){
  103150. pPk = 0;
  103151. nPkField = 1;
  103152. }else{
  103153. pPk = sqlite3PrimaryKeyIndex(pTab);
  103154. nPkField = pPk->nKeyCol;
  103155. }
  103156. /* Record that this module has started */
  103157. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  103158. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  103159. /* Test all NOT NULL constraints.
  103160. */
  103161. for(i=0; i<nCol; i++){
  103162. if( i==pTab->iPKey ){
  103163. continue; /* ROWID is never NULL */
  103164. }
  103165. if( aiChng && aiChng[i]<0 ){
  103166. /* Don't bother checking for NOT NULL on columns that do not change */
  103167. continue;
  103168. }
  103169. onError = pTab->aCol[i].notNull;
  103170. if( onError==OE_None ) continue; /* This column is allowed to be NULL */
  103171. if( overrideError!=OE_Default ){
  103172. onError = overrideError;
  103173. }else if( onError==OE_Default ){
  103174. onError = OE_Abort;
  103175. }
  103176. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  103177. onError = OE_Abort;
  103178. }
  103179. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  103180. || onError==OE_Ignore || onError==OE_Replace );
  103181. switch( onError ){
  103182. case OE_Abort:
  103183. sqlite3MayAbort(pParse);
  103184. /* Fall through */
  103185. case OE_Rollback:
  103186. case OE_Fail: {
  103187. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  103188. pTab->aCol[i].zName);
  103189. sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  103190. regNewData+1+i);
  103191. sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  103192. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  103193. VdbeCoverage(v);
  103194. break;
  103195. }
  103196. case OE_Ignore: {
  103197. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  103198. VdbeCoverage(v);
  103199. break;
  103200. }
  103201. default: {
  103202. assert( onError==OE_Replace );
  103203. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  103204. VdbeCoverage(v);
  103205. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  103206. sqlite3VdbeJumpHere(v, addr1);
  103207. break;
  103208. }
  103209. }
  103210. }
  103211. /* Test all CHECK constraints
  103212. */
  103213. #ifndef SQLITE_OMIT_CHECK
  103214. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  103215. ExprList *pCheck = pTab->pCheck;
  103216. pParse->ckBase = regNewData+1;
  103217. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  103218. for(i=0; i<pCheck->nExpr; i++){
  103219. int allOk;
  103220. Expr *pExpr = pCheck->a[i].pExpr;
  103221. if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
  103222. allOk = sqlite3VdbeMakeLabel(v);
  103223. sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  103224. if( onError==OE_Ignore ){
  103225. sqlite3VdbeGoto(v, ignoreDest);
  103226. }else{
  103227. char *zName = pCheck->a[i].zName;
  103228. if( zName==0 ) zName = pTab->zName;
  103229. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  103230. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  103231. onError, zName, P4_TRANSIENT,
  103232. P5_ConstraintCheck);
  103233. }
  103234. sqlite3VdbeResolveLabel(v, allOk);
  103235. }
  103236. }
  103237. #endif /* !defined(SQLITE_OMIT_CHECK) */
  103238. /* If rowid is changing, make sure the new rowid does not previously
  103239. ** exist in the table.
  103240. */
  103241. if( pkChng && pPk==0 ){
  103242. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  103243. /* Figure out what action to take in case of a rowid collision */
  103244. onError = pTab->keyConf;
  103245. if( overrideError!=OE_Default ){
  103246. onError = overrideError;
  103247. }else if( onError==OE_Default ){
  103248. onError = OE_Abort;
  103249. }
  103250. if( isUpdate ){
  103251. /* pkChng!=0 does not mean that the rowid has changed, only that
  103252. ** it might have changed. Skip the conflict logic below if the rowid
  103253. ** is unchanged. */
  103254. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  103255. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  103256. VdbeCoverage(v);
  103257. }
  103258. /* If the response to a rowid conflict is REPLACE but the response
  103259. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  103260. ** to defer the running of the rowid conflict checking until after
  103261. ** the UNIQUE constraints have run.
  103262. */
  103263. if( onError==OE_Replace && overrideError!=OE_Replace ){
  103264. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  103265. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  103266. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  103267. break;
  103268. }
  103269. }
  103270. }
  103271. /* Check to see if the new rowid already exists in the table. Skip
  103272. ** the following conflict logic if it does not. */
  103273. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  103274. VdbeCoverage(v);
  103275. /* Generate code that deals with a rowid collision */
  103276. switch( onError ){
  103277. default: {
  103278. onError = OE_Abort;
  103279. /* Fall thru into the next case */
  103280. }
  103281. case OE_Rollback:
  103282. case OE_Abort:
  103283. case OE_Fail: {
  103284. sqlite3RowidConstraint(pParse, onError, pTab);
  103285. break;
  103286. }
  103287. case OE_Replace: {
  103288. /* If there are DELETE triggers on this table and the
  103289. ** recursive-triggers flag is set, call GenerateRowDelete() to
  103290. ** remove the conflicting row from the table. This will fire
  103291. ** the triggers and remove both the table and index b-tree entries.
  103292. **
  103293. ** Otherwise, if there are no triggers or the recursive-triggers
  103294. ** flag is not set, but the table has one or more indexes, call
  103295. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  103296. ** only. The table b-tree entry will be replaced by the new entry
  103297. ** when it is inserted.
  103298. **
  103299. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  103300. ** also invoke MultiWrite() to indicate that this VDBE may require
  103301. ** statement rollback (if the statement is aborted after the delete
  103302. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  103303. ** but being more selective here allows statements like:
  103304. **
  103305. ** REPLACE INTO t(rowid) VALUES($newrowid)
  103306. **
  103307. ** to run without a statement journal if there are no indexes on the
  103308. ** table.
  103309. */
  103310. Trigger *pTrigger = 0;
  103311. if( db->flags&SQLITE_RecTriggers ){
  103312. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  103313. }
  103314. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  103315. sqlite3MultiWrite(pParse);
  103316. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  103317. regNewData, 1, 0, OE_Replace, 1, -1);
  103318. }else{
  103319. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  103320. if( HasRowid(pTab) ){
  103321. /* This OP_Delete opcode fires the pre-update-hook only. It does
  103322. ** not modify the b-tree. It is more efficient to let the coming
  103323. ** OP_Insert replace the existing entry than it is to delete the
  103324. ** existing entry and then insert a new one. */
  103325. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  103326. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  103327. }
  103328. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  103329. if( pTab->pIndex ){
  103330. sqlite3MultiWrite(pParse);
  103331. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  103332. }
  103333. }
  103334. seenReplace = 1;
  103335. break;
  103336. }
  103337. case OE_Ignore: {
  103338. /*assert( seenReplace==0 );*/
  103339. sqlite3VdbeGoto(v, ignoreDest);
  103340. break;
  103341. }
  103342. }
  103343. sqlite3VdbeResolveLabel(v, addrRowidOk);
  103344. if( ipkTop ){
  103345. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  103346. sqlite3VdbeJumpHere(v, ipkTop);
  103347. }
  103348. }
  103349. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  103350. ** index and making sure that duplicate entries do not already exist.
  103351. ** Compute the revised record entries for indices as we go.
  103352. **
  103353. ** This loop also handles the case of the PRIMARY KEY index for a
  103354. ** WITHOUT ROWID table.
  103355. */
  103356. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  103357. int regIdx; /* Range of registers hold conent for pIdx */
  103358. int regR; /* Range of registers holding conflicting PK */
  103359. int iThisCur; /* Cursor for this UNIQUE index */
  103360. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  103361. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  103362. if( bAffinityDone==0 ){
  103363. sqlite3TableAffinity(v, pTab, regNewData+1);
  103364. bAffinityDone = 1;
  103365. }
  103366. iThisCur = iIdxCur+ix;
  103367. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  103368. /* Skip partial indices for which the WHERE clause is not true */
  103369. if( pIdx->pPartIdxWhere ){
  103370. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  103371. pParse->ckBase = regNewData+1;
  103372. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  103373. SQLITE_JUMPIFNULL);
  103374. pParse->ckBase = 0;
  103375. }
  103376. /* Create a record for this index entry as it should appear after
  103377. ** the insert or update. Store that record in the aRegIdx[ix] register
  103378. */
  103379. regIdx = aRegIdx[ix]+1;
  103380. for(i=0; i<pIdx->nColumn; i++){
  103381. int iField = pIdx->aiColumn[i];
  103382. int x;
  103383. if( iField==XN_EXPR ){
  103384. pParse->ckBase = regNewData+1;
  103385. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  103386. pParse->ckBase = 0;
  103387. VdbeComment((v, "%s column %d", pIdx->zName, i));
  103388. }else{
  103389. if( iField==XN_ROWID || iField==pTab->iPKey ){
  103390. x = regNewData;
  103391. }else{
  103392. x = iField + regNewData + 1;
  103393. }
  103394. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  103395. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  103396. }
  103397. }
  103398. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  103399. VdbeComment((v, "for %s", pIdx->zName));
  103400. #ifdef SQLITE_ENABLE_NULL_TRIM
  103401. if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
  103402. #endif
  103403. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  103404. ** of a WITHOUT ROWID table and there has been no change the
  103405. ** primary key, then no collision is possible. The collision detection
  103406. ** logic below can all be skipped. */
  103407. if( isUpdate && pPk==pIdx && pkChng==0 ){
  103408. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  103409. continue;
  103410. }
  103411. /* Find out what action to take in case there is a uniqueness conflict */
  103412. onError = pIdx->onError;
  103413. if( onError==OE_None ){
  103414. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  103415. continue; /* pIdx is not a UNIQUE index */
  103416. }
  103417. if( overrideError!=OE_Default ){
  103418. onError = overrideError;
  103419. }else if( onError==OE_Default ){
  103420. onError = OE_Abort;
  103421. }
  103422. /* Collision detection may be omitted if all of the following are true:
  103423. ** (1) The conflict resolution algorithm is REPLACE
  103424. ** (2) The table is a WITHOUT ROWID table
  103425. ** (3) There are no secondary indexes on the table
  103426. ** (4) No delete triggers need to be fired if there is a conflict
  103427. ** (5) No FK constraint counters need to be updated if a conflict occurs.
  103428. */
  103429. if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
  103430. && pPk==pIdx /* Condition 2 */
  103431. && onError==OE_Replace /* Condition 1 */
  103432. && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
  103433. 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
  103434. && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
  103435. (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
  103436. ){
  103437. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  103438. continue;
  103439. }
  103440. /* Check to see if the new index entry will be unique */
  103441. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  103442. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  103443. /* Generate code to handle collisions */
  103444. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  103445. if( isUpdate || onError==OE_Replace ){
  103446. if( HasRowid(pTab) ){
  103447. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  103448. /* Conflict only if the rowid of the existing index entry
  103449. ** is different from old-rowid */
  103450. if( isUpdate ){
  103451. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  103452. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  103453. VdbeCoverage(v);
  103454. }
  103455. }else{
  103456. int x;
  103457. /* Extract the PRIMARY KEY from the end of the index entry and
  103458. ** store it in registers regR..regR+nPk-1 */
  103459. if( pIdx!=pPk ){
  103460. for(i=0; i<pPk->nKeyCol; i++){
  103461. assert( pPk->aiColumn[i]>=0 );
  103462. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  103463. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  103464. VdbeComment((v, "%s.%s", pTab->zName,
  103465. pTab->aCol[pPk->aiColumn[i]].zName));
  103466. }
  103467. }
  103468. if( isUpdate ){
  103469. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  103470. ** table, only conflict if the new PRIMARY KEY values are actually
  103471. ** different from the old.
  103472. **
  103473. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  103474. ** of the matched index row are different from the original PRIMARY
  103475. ** KEY values of this row before the update. */
  103476. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  103477. int op = OP_Ne;
  103478. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  103479. for(i=0; i<pPk->nKeyCol; i++){
  103480. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  103481. x = pPk->aiColumn[i];
  103482. assert( x>=0 );
  103483. if( i==(pPk->nKeyCol-1) ){
  103484. addrJump = addrUniqueOk;
  103485. op = OP_Eq;
  103486. }
  103487. sqlite3VdbeAddOp4(v, op,
  103488. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  103489. );
  103490. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  103491. VdbeCoverageIf(v, op==OP_Eq);
  103492. VdbeCoverageIf(v, op==OP_Ne);
  103493. }
  103494. }
  103495. }
  103496. }
  103497. /* Generate code that executes if the new index entry is not unique */
  103498. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  103499. || onError==OE_Ignore || onError==OE_Replace );
  103500. switch( onError ){
  103501. case OE_Rollback:
  103502. case OE_Abort:
  103503. case OE_Fail: {
  103504. sqlite3UniqueConstraint(pParse, onError, pIdx);
  103505. break;
  103506. }
  103507. case OE_Ignore: {
  103508. sqlite3VdbeGoto(v, ignoreDest);
  103509. break;
  103510. }
  103511. default: {
  103512. Trigger *pTrigger = 0;
  103513. assert( onError==OE_Replace );
  103514. sqlite3MultiWrite(pParse);
  103515. if( db->flags&SQLITE_RecTriggers ){
  103516. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  103517. }
  103518. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  103519. regR, nPkField, 0, OE_Replace,
  103520. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
  103521. seenReplace = 1;
  103522. break;
  103523. }
  103524. }
  103525. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  103526. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  103527. }
  103528. if( ipkTop ){
  103529. sqlite3VdbeGoto(v, ipkTop+1);
  103530. sqlite3VdbeJumpHere(v, ipkBottom);
  103531. }
  103532. *pbMayReplace = seenReplace;
  103533. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  103534. }
  103535. #ifdef SQLITE_ENABLE_NULL_TRIM
  103536. /*
  103537. ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
  103538. ** to be the number of columns in table pTab that must not be NULL-trimmed.
  103539. **
  103540. ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
  103541. */
  103542. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
  103543. u16 i;
  103544. /* Records with omitted columns are only allowed for schema format
  103545. ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
  103546. if( pTab->pSchema->file_format<2 ) return;
  103547. for(i=pTab->nCol-1; i>0; i--){
  103548. if( pTab->aCol[i].pDflt!=0 ) break;
  103549. if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
  103550. }
  103551. sqlite3VdbeChangeP5(v, i+1);
  103552. }
  103553. #endif
  103554. /*
  103555. ** This routine generates code to finish the INSERT or UPDATE operation
  103556. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  103557. ** A consecutive range of registers starting at regNewData contains the
  103558. ** rowid and the content to be inserted.
  103559. **
  103560. ** The arguments to this routine should be the same as the first six
  103561. ** arguments to sqlite3GenerateConstraintChecks.
  103562. */
  103563. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  103564. Parse *pParse, /* The parser context */
  103565. Table *pTab, /* the table into which we are inserting */
  103566. int iDataCur, /* Cursor of the canonical data source */
  103567. int iIdxCur, /* First index cursor */
  103568. int regNewData, /* Range of content */
  103569. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  103570. int update_flags, /* True for UPDATE, False for INSERT */
  103571. int appendBias, /* True if this is likely to be an append */
  103572. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  103573. ){
  103574. Vdbe *v; /* Prepared statements under construction */
  103575. Index *pIdx; /* An index being inserted or updated */
  103576. u8 pik_flags; /* flag values passed to the btree insert */
  103577. int regData; /* Content registers (after the rowid) */
  103578. int regRec; /* Register holding assembled record for the table */
  103579. int i; /* Loop counter */
  103580. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  103581. assert( update_flags==0
  103582. || update_flags==OPFLAG_ISUPDATE
  103583. || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
  103584. );
  103585. v = sqlite3GetVdbe(pParse);
  103586. assert( v!=0 );
  103587. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  103588. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  103589. if( aRegIdx[i]==0 ) continue;
  103590. bAffinityDone = 1;
  103591. if( pIdx->pPartIdxWhere ){
  103592. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  103593. VdbeCoverage(v);
  103594. }
  103595. pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
  103596. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  103597. assert( pParse->nested==0 );
  103598. pik_flags |= OPFLAG_NCHANGE;
  103599. pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
  103600. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  103601. if( update_flags==0 ){
  103602. sqlite3VdbeAddOp4(v, OP_InsertInt,
  103603. iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
  103604. );
  103605. sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
  103606. }
  103607. #endif
  103608. }
  103609. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
  103610. aRegIdx[i]+1,
  103611. pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
  103612. sqlite3VdbeChangeP5(v, pik_flags);
  103613. }
  103614. if( !HasRowid(pTab) ) return;
  103615. regData = regNewData + 1;
  103616. regRec = sqlite3GetTempReg(pParse);
  103617. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  103618. sqlite3SetMakeRecordP5(v, pTab);
  103619. if( !bAffinityDone ){
  103620. sqlite3TableAffinity(v, pTab, 0);
  103621. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  103622. }
  103623. if( pParse->nested ){
  103624. pik_flags = 0;
  103625. }else{
  103626. pik_flags = OPFLAG_NCHANGE;
  103627. pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
  103628. }
  103629. if( appendBias ){
  103630. pik_flags |= OPFLAG_APPEND;
  103631. }
  103632. if( useSeekResult ){
  103633. pik_flags |= OPFLAG_USESEEKRESULT;
  103634. }
  103635. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  103636. if( !pParse->nested ){
  103637. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  103638. }
  103639. sqlite3VdbeChangeP5(v, pik_flags);
  103640. }
  103641. /*
  103642. ** Allocate cursors for the pTab table and all its indices and generate
  103643. ** code to open and initialized those cursors.
  103644. **
  103645. ** The cursor for the object that contains the complete data (normally
  103646. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  103647. ** ROWID table) is returned in *piDataCur. The first index cursor is
  103648. ** returned in *piIdxCur. The number of indices is returned.
  103649. **
  103650. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  103651. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  103652. ** If iBase is negative, then allocate the next available cursor.
  103653. **
  103654. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  103655. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  103656. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  103657. ** pTab->pIndex list.
  103658. **
  103659. ** If pTab is a virtual table, then this routine is a no-op and the
  103660. ** *piDataCur and *piIdxCur values are left uninitialized.
  103661. */
  103662. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  103663. Parse *pParse, /* Parsing context */
  103664. Table *pTab, /* Table to be opened */
  103665. int op, /* OP_OpenRead or OP_OpenWrite */
  103666. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  103667. int iBase, /* Use this for the table cursor, if there is one */
  103668. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  103669. int *piDataCur, /* Write the database source cursor number here */
  103670. int *piIdxCur /* Write the first index cursor number here */
  103671. ){
  103672. int i;
  103673. int iDb;
  103674. int iDataCur;
  103675. Index *pIdx;
  103676. Vdbe *v;
  103677. assert( op==OP_OpenRead || op==OP_OpenWrite );
  103678. assert( op==OP_OpenWrite || p5==0 );
  103679. if( IsVirtual(pTab) ){
  103680. /* This routine is a no-op for virtual tables. Leave the output
  103681. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  103682. ** can detect if they are used by mistake in the caller. */
  103683. return 0;
  103684. }
  103685. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  103686. v = sqlite3GetVdbe(pParse);
  103687. assert( v!=0 );
  103688. if( iBase<0 ) iBase = pParse->nTab;
  103689. iDataCur = iBase++;
  103690. if( piDataCur ) *piDataCur = iDataCur;
  103691. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  103692. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  103693. }else{
  103694. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  103695. }
  103696. if( piIdxCur ) *piIdxCur = iBase;
  103697. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  103698. int iIdxCur = iBase++;
  103699. assert( pIdx->pSchema==pTab->pSchema );
  103700. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  103701. if( piDataCur ) *piDataCur = iIdxCur;
  103702. p5 = 0;
  103703. }
  103704. if( aToOpen==0 || aToOpen[i+1] ){
  103705. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  103706. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  103707. sqlite3VdbeChangeP5(v, p5);
  103708. VdbeComment((v, "%s", pIdx->zName));
  103709. }
  103710. }
  103711. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  103712. return i;
  103713. }
  103714. #ifdef SQLITE_TEST
  103715. /*
  103716. ** The following global variable is incremented whenever the
  103717. ** transfer optimization is used. This is used for testing
  103718. ** purposes only - to make sure the transfer optimization really
  103719. ** is happening when it is supposed to.
  103720. */
  103721. SQLITE_API int sqlite3_xferopt_count;
  103722. #endif /* SQLITE_TEST */
  103723. #ifndef SQLITE_OMIT_XFER_OPT
  103724. /*
  103725. ** Check to see if index pSrc is compatible as a source of data
  103726. ** for index pDest in an insert transfer optimization. The rules
  103727. ** for a compatible index:
  103728. **
  103729. ** * The index is over the same set of columns
  103730. ** * The same DESC and ASC markings occurs on all columns
  103731. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  103732. ** * The same collating sequence on each column
  103733. ** * The index has the exact same WHERE clause
  103734. */
  103735. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  103736. int i;
  103737. assert( pDest && pSrc );
  103738. assert( pDest->pTable!=pSrc->pTable );
  103739. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  103740. return 0; /* Different number of columns */
  103741. }
  103742. if( pDest->onError!=pSrc->onError ){
  103743. return 0; /* Different conflict resolution strategies */
  103744. }
  103745. for(i=0; i<pSrc->nKeyCol; i++){
  103746. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  103747. return 0; /* Different columns indexed */
  103748. }
  103749. if( pSrc->aiColumn[i]==XN_EXPR ){
  103750. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  103751. if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
  103752. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  103753. return 0; /* Different expressions in the index */
  103754. }
  103755. }
  103756. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  103757. return 0; /* Different sort orders */
  103758. }
  103759. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  103760. return 0; /* Different collating sequences */
  103761. }
  103762. }
  103763. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  103764. return 0; /* Different WHERE clauses */
  103765. }
  103766. /* If no test above fails then the indices must be compatible */
  103767. return 1;
  103768. }
  103769. /*
  103770. ** Attempt the transfer optimization on INSERTs of the form
  103771. **
  103772. ** INSERT INTO tab1 SELECT * FROM tab2;
  103773. **
  103774. ** The xfer optimization transfers raw records from tab2 over to tab1.
  103775. ** Columns are not decoded and reassembled, which greatly improves
  103776. ** performance. Raw index records are transferred in the same way.
  103777. **
  103778. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  103779. ** There are lots of rules for determining compatibility - see comments
  103780. ** embedded in the code for details.
  103781. **
  103782. ** This routine returns TRUE if the optimization is guaranteed to be used.
  103783. ** Sometimes the xfer optimization will only work if the destination table
  103784. ** is empty - a factor that can only be determined at run-time. In that
  103785. ** case, this routine generates code for the xfer optimization but also
  103786. ** does a test to see if the destination table is empty and jumps over the
  103787. ** xfer optimization code if the test fails. In that case, this routine
  103788. ** returns FALSE so that the caller will know to go ahead and generate
  103789. ** an unoptimized transfer. This routine also returns FALSE if there
  103790. ** is no chance that the xfer optimization can be applied.
  103791. **
  103792. ** This optimization is particularly useful at making VACUUM run faster.
  103793. */
  103794. static int xferOptimization(
  103795. Parse *pParse, /* Parser context */
  103796. Table *pDest, /* The table we are inserting into */
  103797. Select *pSelect, /* A SELECT statement to use as the data source */
  103798. int onError, /* How to handle constraint errors */
  103799. int iDbDest /* The database of pDest */
  103800. ){
  103801. sqlite3 *db = pParse->db;
  103802. ExprList *pEList; /* The result set of the SELECT */
  103803. Table *pSrc; /* The table in the FROM clause of SELECT */
  103804. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  103805. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  103806. int i; /* Loop counter */
  103807. int iDbSrc; /* The database of pSrc */
  103808. int iSrc, iDest; /* Cursors from source and destination */
  103809. int addr1, addr2; /* Loop addresses */
  103810. int emptyDestTest = 0; /* Address of test for empty pDest */
  103811. int emptySrcTest = 0; /* Address of test for empty pSrc */
  103812. Vdbe *v; /* The VDBE we are building */
  103813. int regAutoinc; /* Memory register used by AUTOINC */
  103814. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  103815. int regData, regRowid; /* Registers holding data and rowid */
  103816. if( pSelect==0 ){
  103817. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  103818. }
  103819. if( pParse->pWith || pSelect->pWith ){
  103820. /* Do not attempt to process this query if there are an WITH clauses
  103821. ** attached to it. Proceeding may generate a false "no such table: xxx"
  103822. ** error if pSelect reads from a CTE named "xxx". */
  103823. return 0;
  103824. }
  103825. if( sqlite3TriggerList(pParse, pDest) ){
  103826. return 0; /* tab1 must not have triggers */
  103827. }
  103828. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103829. if( IsVirtual(pDest) ){
  103830. return 0; /* tab1 must not be a virtual table */
  103831. }
  103832. #endif
  103833. if( onError==OE_Default ){
  103834. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  103835. if( onError==OE_Default ) onError = OE_Abort;
  103836. }
  103837. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  103838. if( pSelect->pSrc->nSrc!=1 ){
  103839. return 0; /* FROM clause must have exactly one term */
  103840. }
  103841. if( pSelect->pSrc->a[0].pSelect ){
  103842. return 0; /* FROM clause cannot contain a subquery */
  103843. }
  103844. if( pSelect->pWhere ){
  103845. return 0; /* SELECT may not have a WHERE clause */
  103846. }
  103847. if( pSelect->pOrderBy ){
  103848. return 0; /* SELECT may not have an ORDER BY clause */
  103849. }
  103850. /* Do not need to test for a HAVING clause. If HAVING is present but
  103851. ** there is no ORDER BY, we will get an error. */
  103852. if( pSelect->pGroupBy ){
  103853. return 0; /* SELECT may not have a GROUP BY clause */
  103854. }
  103855. if( pSelect->pLimit ){
  103856. return 0; /* SELECT may not have a LIMIT clause */
  103857. }
  103858. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  103859. if( pSelect->pPrior ){
  103860. return 0; /* SELECT may not be a compound query */
  103861. }
  103862. if( pSelect->selFlags & SF_Distinct ){
  103863. return 0; /* SELECT may not be DISTINCT */
  103864. }
  103865. pEList = pSelect->pEList;
  103866. assert( pEList!=0 );
  103867. if( pEList->nExpr!=1 ){
  103868. return 0; /* The result set must have exactly one column */
  103869. }
  103870. assert( pEList->a[0].pExpr );
  103871. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  103872. return 0; /* The result set must be the special operator "*" */
  103873. }
  103874. /* At this point we have established that the statement is of the
  103875. ** correct syntactic form to participate in this optimization. Now
  103876. ** we have to check the semantics.
  103877. */
  103878. pItem = pSelect->pSrc->a;
  103879. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  103880. if( pSrc==0 ){
  103881. return 0; /* FROM clause does not contain a real table */
  103882. }
  103883. if( pSrc==pDest ){
  103884. return 0; /* tab1 and tab2 may not be the same table */
  103885. }
  103886. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  103887. return 0; /* source and destination must both be WITHOUT ROWID or not */
  103888. }
  103889. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103890. if( IsVirtual(pSrc) ){
  103891. return 0; /* tab2 must not be a virtual table */
  103892. }
  103893. #endif
  103894. if( pSrc->pSelect ){
  103895. return 0; /* tab2 may not be a view */
  103896. }
  103897. if( pDest->nCol!=pSrc->nCol ){
  103898. return 0; /* Number of columns must be the same in tab1 and tab2 */
  103899. }
  103900. if( pDest->iPKey!=pSrc->iPKey ){
  103901. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  103902. }
  103903. for(i=0; i<pDest->nCol; i++){
  103904. Column *pDestCol = &pDest->aCol[i];
  103905. Column *pSrcCol = &pSrc->aCol[i];
  103906. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  103907. if( (db->flags & SQLITE_Vacuum)==0
  103908. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  103909. ){
  103910. return 0; /* Neither table may have __hidden__ columns */
  103911. }
  103912. #endif
  103913. if( pDestCol->affinity!=pSrcCol->affinity ){
  103914. return 0; /* Affinity must be the same on all columns */
  103915. }
  103916. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  103917. return 0; /* Collating sequence must be the same on all columns */
  103918. }
  103919. if( pDestCol->notNull && !pSrcCol->notNull ){
  103920. return 0; /* tab2 must be NOT NULL if tab1 is */
  103921. }
  103922. /* Default values for second and subsequent columns need to match. */
  103923. if( i>0 ){
  103924. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  103925. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  103926. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  103927. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  103928. pSrcCol->pDflt->u.zToken)!=0)
  103929. ){
  103930. return 0; /* Default values must be the same for all columns */
  103931. }
  103932. }
  103933. }
  103934. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  103935. if( IsUniqueIndex(pDestIdx) ){
  103936. destHasUniqueIdx = 1;
  103937. }
  103938. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  103939. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  103940. }
  103941. if( pSrcIdx==0 ){
  103942. return 0; /* pDestIdx has no corresponding index in pSrc */
  103943. }
  103944. }
  103945. #ifndef SQLITE_OMIT_CHECK
  103946. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  103947. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  103948. }
  103949. #endif
  103950. #ifndef SQLITE_OMIT_FOREIGN_KEY
  103951. /* Disallow the transfer optimization if the destination table constains
  103952. ** any foreign key constraints. This is more restrictive than necessary.
  103953. ** But the main beneficiary of the transfer optimization is the VACUUM
  103954. ** command, and the VACUUM command disables foreign key constraints. So
  103955. ** the extra complication to make this rule less restrictive is probably
  103956. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  103957. */
  103958. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  103959. return 0;
  103960. }
  103961. #endif
  103962. if( (db->flags & SQLITE_CountRows)!=0 ){
  103963. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  103964. }
  103965. /* If we get this far, it means that the xfer optimization is at
  103966. ** least a possibility, though it might only work if the destination
  103967. ** table (tab1) is initially empty.
  103968. */
  103969. #ifdef SQLITE_TEST
  103970. sqlite3_xferopt_count++;
  103971. #endif
  103972. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  103973. v = sqlite3GetVdbe(pParse);
  103974. sqlite3CodeVerifySchema(pParse, iDbSrc);
  103975. iSrc = pParse->nTab++;
  103976. iDest = pParse->nTab++;
  103977. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  103978. regData = sqlite3GetTempReg(pParse);
  103979. regRowid = sqlite3GetTempReg(pParse);
  103980. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  103981. assert( HasRowid(pDest) || destHasUniqueIdx );
  103982. if( (db->flags & SQLITE_Vacuum)==0 && (
  103983. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  103984. || destHasUniqueIdx /* (2) */
  103985. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  103986. )){
  103987. /* In some circumstances, we are able to run the xfer optimization
  103988. ** only if the destination table is initially empty. Unless the
  103989. ** SQLITE_Vacuum flag is set, this block generates code to make
  103990. ** that determination. If SQLITE_Vacuum is set, then the destination
  103991. ** table is always empty.
  103992. **
  103993. ** Conditions under which the destination must be empty:
  103994. **
  103995. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  103996. ** (If the destination is not initially empty, the rowid fields
  103997. ** of index entries might need to change.)
  103998. **
  103999. ** (2) The destination has a unique index. (The xfer optimization
  104000. ** is unable to test uniqueness.)
  104001. **
  104002. ** (3) onError is something other than OE_Abort and OE_Rollback.
  104003. */
  104004. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  104005. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  104006. sqlite3VdbeJumpHere(v, addr1);
  104007. }
  104008. if( HasRowid(pSrc) ){
  104009. u8 insFlags;
  104010. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  104011. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  104012. if( pDest->iPKey>=0 ){
  104013. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  104014. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  104015. VdbeCoverage(v);
  104016. sqlite3RowidConstraint(pParse, onError, pDest);
  104017. sqlite3VdbeJumpHere(v, addr2);
  104018. autoIncStep(pParse, regAutoinc, regRowid);
  104019. }else if( pDest->pIndex==0 ){
  104020. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  104021. }else{
  104022. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  104023. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  104024. }
  104025. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  104026. if( db->flags & SQLITE_Vacuum ){
  104027. sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
  104028. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
  104029. OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
  104030. }else{
  104031. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
  104032. }
  104033. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  104034. (char*)pDest, P4_TABLE);
  104035. sqlite3VdbeChangeP5(v, insFlags);
  104036. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  104037. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  104038. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  104039. }else{
  104040. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  104041. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  104042. }
  104043. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  104044. u8 idxInsFlags = 0;
  104045. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  104046. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  104047. }
  104048. assert( pSrcIdx );
  104049. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  104050. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  104051. VdbeComment((v, "%s", pSrcIdx->zName));
  104052. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  104053. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  104054. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  104055. VdbeComment((v, "%s", pDestIdx->zName));
  104056. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  104057. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  104058. if( db->flags & SQLITE_Vacuum ){
  104059. /* This INSERT command is part of a VACUUM operation, which guarantees
  104060. ** that the destination table is empty. If all indexed columns use
  104061. ** collation sequence BINARY, then it can also be assumed that the
  104062. ** index will be populated by inserting keys in strictly sorted
  104063. ** order. In this case, instead of seeking within the b-tree as part
  104064. ** of every OP_IdxInsert opcode, an OP_Last is added before the
  104065. ** OP_IdxInsert to seek to the point within the b-tree where each key
  104066. ** should be inserted. This is faster.
  104067. **
  104068. ** If any of the indexed columns use a collation sequence other than
  104069. ** BINARY, this optimization is disabled. This is because the user
  104070. ** might change the definition of a collation sequence and then run
  104071. ** a VACUUM command. In that case keys may not be written in strictly
  104072. ** sorted order. */
  104073. for(i=0; i<pSrcIdx->nColumn; i++){
  104074. const char *zColl = pSrcIdx->azColl[i];
  104075. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  104076. }
  104077. if( i==pSrcIdx->nColumn ){
  104078. idxInsFlags = OPFLAG_USESEEKRESULT;
  104079. sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
  104080. }
  104081. }
  104082. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  104083. idxInsFlags |= OPFLAG_NCHANGE;
  104084. }
  104085. sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
  104086. sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
  104087. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  104088. sqlite3VdbeJumpHere(v, addr1);
  104089. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  104090. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  104091. }
  104092. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  104093. sqlite3ReleaseTempReg(pParse, regRowid);
  104094. sqlite3ReleaseTempReg(pParse, regData);
  104095. if( emptyDestTest ){
  104096. sqlite3AutoincrementEnd(pParse);
  104097. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  104098. sqlite3VdbeJumpHere(v, emptyDestTest);
  104099. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  104100. return 0;
  104101. }else{
  104102. return 1;
  104103. }
  104104. }
  104105. #endif /* SQLITE_OMIT_XFER_OPT */
  104106. /************** End of insert.c **********************************************/
  104107. /************** Begin file legacy.c ******************************************/
  104108. /*
  104109. ** 2001 September 15
  104110. **
  104111. ** The author disclaims copyright to this source code. In place of
  104112. ** a legal notice, here is a blessing:
  104113. **
  104114. ** May you do good and not evil.
  104115. ** May you find forgiveness for yourself and forgive others.
  104116. ** May you share freely, never taking more than you give.
  104117. **
  104118. *************************************************************************
  104119. ** Main file for the SQLite library. The routines in this file
  104120. ** implement the programmer interface to the library. Routines in
  104121. ** other files are for internal use by SQLite and should not be
  104122. ** accessed by users of the library.
  104123. */
  104124. /* #include "sqliteInt.h" */
  104125. /*
  104126. ** Execute SQL code. Return one of the SQLITE_ success/failure
  104127. ** codes. Also write an error message into memory obtained from
  104128. ** malloc() and make *pzErrMsg point to that message.
  104129. **
  104130. ** If the SQL is a query, then for each row in the query result
  104131. ** the xCallback() function is called. pArg becomes the first
  104132. ** argument to xCallback(). If xCallback=NULL then no callback
  104133. ** is invoked, even for queries.
  104134. */
  104135. SQLITE_API int sqlite3_exec(
  104136. sqlite3 *db, /* The database on which the SQL executes */
  104137. const char *zSql, /* The SQL to be executed */
  104138. sqlite3_callback xCallback, /* Invoke this callback routine */
  104139. void *pArg, /* First argument to xCallback() */
  104140. char **pzErrMsg /* Write error messages here */
  104141. ){
  104142. int rc = SQLITE_OK; /* Return code */
  104143. const char *zLeftover; /* Tail of unprocessed SQL */
  104144. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  104145. char **azCols = 0; /* Names of result columns */
  104146. int callbackIsInit; /* True if callback data is initialized */
  104147. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  104148. if( zSql==0 ) zSql = "";
  104149. sqlite3_mutex_enter(db->mutex);
  104150. sqlite3Error(db, SQLITE_OK);
  104151. while( rc==SQLITE_OK && zSql[0] ){
  104152. int nCol;
  104153. char **azVals = 0;
  104154. pStmt = 0;
  104155. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  104156. assert( rc==SQLITE_OK || pStmt==0 );
  104157. if( rc!=SQLITE_OK ){
  104158. continue;
  104159. }
  104160. if( !pStmt ){
  104161. /* this happens for a comment or white-space */
  104162. zSql = zLeftover;
  104163. continue;
  104164. }
  104165. callbackIsInit = 0;
  104166. nCol = sqlite3_column_count(pStmt);
  104167. while( 1 ){
  104168. int i;
  104169. rc = sqlite3_step(pStmt);
  104170. /* Invoke the callback function if required */
  104171. if( xCallback && (SQLITE_ROW==rc ||
  104172. (SQLITE_DONE==rc && !callbackIsInit
  104173. && db->flags&SQLITE_NullCallback)) ){
  104174. if( !callbackIsInit ){
  104175. azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
  104176. if( azCols==0 ){
  104177. goto exec_out;
  104178. }
  104179. for(i=0; i<nCol; i++){
  104180. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  104181. /* sqlite3VdbeSetColName() installs column names as UTF8
  104182. ** strings so there is no way for sqlite3_column_name() to fail. */
  104183. assert( azCols[i]!=0 );
  104184. }
  104185. callbackIsInit = 1;
  104186. }
  104187. if( rc==SQLITE_ROW ){
  104188. azVals = &azCols[nCol];
  104189. for(i=0; i<nCol; i++){
  104190. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  104191. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  104192. sqlite3OomFault(db);
  104193. goto exec_out;
  104194. }
  104195. }
  104196. azVals[i] = 0;
  104197. }
  104198. if( xCallback(pArg, nCol, azVals, azCols) ){
  104199. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  104200. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  104201. ** return SQLITE_ABORT. */
  104202. rc = SQLITE_ABORT;
  104203. sqlite3VdbeFinalize((Vdbe *)pStmt);
  104204. pStmt = 0;
  104205. sqlite3Error(db, SQLITE_ABORT);
  104206. goto exec_out;
  104207. }
  104208. }
  104209. if( rc!=SQLITE_ROW ){
  104210. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  104211. pStmt = 0;
  104212. zSql = zLeftover;
  104213. while( sqlite3Isspace(zSql[0]) ) zSql++;
  104214. break;
  104215. }
  104216. }
  104217. sqlite3DbFree(db, azCols);
  104218. azCols = 0;
  104219. }
  104220. exec_out:
  104221. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  104222. sqlite3DbFree(db, azCols);
  104223. rc = sqlite3ApiExit(db, rc);
  104224. if( rc!=SQLITE_OK && pzErrMsg ){
  104225. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  104226. *pzErrMsg = sqlite3Malloc(nErrMsg);
  104227. if( *pzErrMsg ){
  104228. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  104229. }else{
  104230. rc = SQLITE_NOMEM_BKPT;
  104231. sqlite3Error(db, SQLITE_NOMEM);
  104232. }
  104233. }else if( pzErrMsg ){
  104234. *pzErrMsg = 0;
  104235. }
  104236. assert( (rc&db->errMask)==rc );
  104237. sqlite3_mutex_leave(db->mutex);
  104238. return rc;
  104239. }
  104240. /************** End of legacy.c **********************************************/
  104241. /************** Begin file loadext.c *****************************************/
  104242. /*
  104243. ** 2006 June 7
  104244. **
  104245. ** The author disclaims copyright to this source code. In place of
  104246. ** a legal notice, here is a blessing:
  104247. **
  104248. ** May you do good and not evil.
  104249. ** May you find forgiveness for yourself and forgive others.
  104250. ** May you share freely, never taking more than you give.
  104251. **
  104252. *************************************************************************
  104253. ** This file contains code used to dynamically load extensions into
  104254. ** the SQLite library.
  104255. */
  104256. #ifndef SQLITE_CORE
  104257. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  104258. #endif
  104259. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  104260. /************** Begin file sqlite3ext.h **************************************/
  104261. /*
  104262. ** 2006 June 7
  104263. **
  104264. ** The author disclaims copyright to this source code. In place of
  104265. ** a legal notice, here is a blessing:
  104266. **
  104267. ** May you do good and not evil.
  104268. ** May you find forgiveness for yourself and forgive others.
  104269. ** May you share freely, never taking more than you give.
  104270. **
  104271. *************************************************************************
  104272. ** This header file defines the SQLite interface for use by
  104273. ** shared libraries that want to be imported as extensions into
  104274. ** an SQLite instance. Shared libraries that intend to be loaded
  104275. ** as extensions by SQLite should #include this file instead of
  104276. ** sqlite3.h.
  104277. */
  104278. #ifndef SQLITE3EXT_H
  104279. #define SQLITE3EXT_H
  104280. /* #include "sqlite3.h" */
  104281. /*
  104282. ** The following structure holds pointers to all of the SQLite API
  104283. ** routines.
  104284. **
  104285. ** WARNING: In order to maintain backwards compatibility, add new
  104286. ** interfaces to the end of this structure only. If you insert new
  104287. ** interfaces in the middle of this structure, then older different
  104288. ** versions of SQLite will not be able to load each other's shared
  104289. ** libraries!
  104290. */
  104291. struct sqlite3_api_routines {
  104292. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  104293. int (*aggregate_count)(sqlite3_context*);
  104294. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  104295. int (*bind_double)(sqlite3_stmt*,int,double);
  104296. int (*bind_int)(sqlite3_stmt*,int,int);
  104297. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  104298. int (*bind_null)(sqlite3_stmt*,int);
  104299. int (*bind_parameter_count)(sqlite3_stmt*);
  104300. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  104301. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  104302. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  104303. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  104304. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  104305. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  104306. int (*busy_timeout)(sqlite3*,int ms);
  104307. int (*changes)(sqlite3*);
  104308. int (*close)(sqlite3*);
  104309. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  104310. int eTextRep,const char*));
  104311. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  104312. int eTextRep,const void*));
  104313. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  104314. int (*column_bytes)(sqlite3_stmt*,int iCol);
  104315. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  104316. int (*column_count)(sqlite3_stmt*pStmt);
  104317. const char * (*column_database_name)(sqlite3_stmt*,int);
  104318. const void * (*column_database_name16)(sqlite3_stmt*,int);
  104319. const char * (*column_decltype)(sqlite3_stmt*,int i);
  104320. const void * (*column_decltype16)(sqlite3_stmt*,int);
  104321. double (*column_double)(sqlite3_stmt*,int iCol);
  104322. int (*column_int)(sqlite3_stmt*,int iCol);
  104323. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  104324. const char * (*column_name)(sqlite3_stmt*,int);
  104325. const void * (*column_name16)(sqlite3_stmt*,int);
  104326. const char * (*column_origin_name)(sqlite3_stmt*,int);
  104327. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  104328. const char * (*column_table_name)(sqlite3_stmt*,int);
  104329. const void * (*column_table_name16)(sqlite3_stmt*,int);
  104330. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  104331. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  104332. int (*column_type)(sqlite3_stmt*,int iCol);
  104333. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  104334. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  104335. int (*complete)(const char*sql);
  104336. int (*complete16)(const void*sql);
  104337. int (*create_collation)(sqlite3*,const char*,int,void*,
  104338. int(*)(void*,int,const void*,int,const void*));
  104339. int (*create_collation16)(sqlite3*,const void*,int,void*,
  104340. int(*)(void*,int,const void*,int,const void*));
  104341. int (*create_function)(sqlite3*,const char*,int,int,void*,
  104342. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  104343. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  104344. void (*xFinal)(sqlite3_context*));
  104345. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  104346. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  104347. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  104348. void (*xFinal)(sqlite3_context*));
  104349. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  104350. int (*data_count)(sqlite3_stmt*pStmt);
  104351. sqlite3 * (*db_handle)(sqlite3_stmt*);
  104352. int (*declare_vtab)(sqlite3*,const char*);
  104353. int (*enable_shared_cache)(int);
  104354. int (*errcode)(sqlite3*db);
  104355. const char * (*errmsg)(sqlite3*);
  104356. const void * (*errmsg16)(sqlite3*);
  104357. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  104358. int (*expired)(sqlite3_stmt*);
  104359. int (*finalize)(sqlite3_stmt*pStmt);
  104360. void (*free)(void*);
  104361. void (*free_table)(char**result);
  104362. int (*get_autocommit)(sqlite3*);
  104363. void * (*get_auxdata)(sqlite3_context*,int);
  104364. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  104365. int (*global_recover)(void);
  104366. void (*interruptx)(sqlite3*);
  104367. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  104368. const char * (*libversion)(void);
  104369. int (*libversion_number)(void);
  104370. void *(*malloc)(int);
  104371. char * (*mprintf)(const char*,...);
  104372. int (*open)(const char*,sqlite3**);
  104373. int (*open16)(const void*,sqlite3**);
  104374. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  104375. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  104376. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  104377. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  104378. void *(*realloc)(void*,int);
  104379. int (*reset)(sqlite3_stmt*pStmt);
  104380. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  104381. void (*result_double)(sqlite3_context*,double);
  104382. void (*result_error)(sqlite3_context*,const char*,int);
  104383. void (*result_error16)(sqlite3_context*,const void*,int);
  104384. void (*result_int)(sqlite3_context*,int);
  104385. void (*result_int64)(sqlite3_context*,sqlite_int64);
  104386. void (*result_null)(sqlite3_context*);
  104387. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  104388. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  104389. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  104390. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  104391. void (*result_value)(sqlite3_context*,sqlite3_value*);
  104392. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  104393. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  104394. const char*,const char*),void*);
  104395. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  104396. char * (*snprintf)(int,char*,const char*,...);
  104397. int (*step)(sqlite3_stmt*);
  104398. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  104399. char const**,char const**,int*,int*,int*);
  104400. void (*thread_cleanup)(void);
  104401. int (*total_changes)(sqlite3*);
  104402. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  104403. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  104404. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  104405. sqlite_int64),void*);
  104406. void * (*user_data)(sqlite3_context*);
  104407. const void * (*value_blob)(sqlite3_value*);
  104408. int (*value_bytes)(sqlite3_value*);
  104409. int (*value_bytes16)(sqlite3_value*);
  104410. double (*value_double)(sqlite3_value*);
  104411. int (*value_int)(sqlite3_value*);
  104412. sqlite_int64 (*value_int64)(sqlite3_value*);
  104413. int (*value_numeric_type)(sqlite3_value*);
  104414. const unsigned char * (*value_text)(sqlite3_value*);
  104415. const void * (*value_text16)(sqlite3_value*);
  104416. const void * (*value_text16be)(sqlite3_value*);
  104417. const void * (*value_text16le)(sqlite3_value*);
  104418. int (*value_type)(sqlite3_value*);
  104419. char *(*vmprintf)(const char*,va_list);
  104420. /* Added ??? */
  104421. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  104422. /* Added by 3.3.13 */
  104423. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  104424. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  104425. int (*clear_bindings)(sqlite3_stmt*);
  104426. /* Added by 3.4.1 */
  104427. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  104428. void (*xDestroy)(void *));
  104429. /* Added by 3.5.0 */
  104430. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  104431. int (*blob_bytes)(sqlite3_blob*);
  104432. int (*blob_close)(sqlite3_blob*);
  104433. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  104434. int,sqlite3_blob**);
  104435. int (*blob_read)(sqlite3_blob*,void*,int,int);
  104436. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  104437. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  104438. int(*)(void*,int,const void*,int,const void*),
  104439. void(*)(void*));
  104440. int (*file_control)(sqlite3*,const char*,int,void*);
  104441. sqlite3_int64 (*memory_highwater)(int);
  104442. sqlite3_int64 (*memory_used)(void);
  104443. sqlite3_mutex *(*mutex_alloc)(int);
  104444. void (*mutex_enter)(sqlite3_mutex*);
  104445. void (*mutex_free)(sqlite3_mutex*);
  104446. void (*mutex_leave)(sqlite3_mutex*);
  104447. int (*mutex_try)(sqlite3_mutex*);
  104448. int (*open_v2)(const char*,sqlite3**,int,const char*);
  104449. int (*release_memory)(int);
  104450. void (*result_error_nomem)(sqlite3_context*);
  104451. void (*result_error_toobig)(sqlite3_context*);
  104452. int (*sleep)(int);
  104453. void (*soft_heap_limit)(int);
  104454. sqlite3_vfs *(*vfs_find)(const char*);
  104455. int (*vfs_register)(sqlite3_vfs*,int);
  104456. int (*vfs_unregister)(sqlite3_vfs*);
  104457. int (*xthreadsafe)(void);
  104458. void (*result_zeroblob)(sqlite3_context*,int);
  104459. void (*result_error_code)(sqlite3_context*,int);
  104460. int (*test_control)(int, ...);
  104461. void (*randomness)(int,void*);
  104462. sqlite3 *(*context_db_handle)(sqlite3_context*);
  104463. int (*extended_result_codes)(sqlite3*,int);
  104464. int (*limit)(sqlite3*,int,int);
  104465. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  104466. const char *(*sql)(sqlite3_stmt*);
  104467. int (*status)(int,int*,int*,int);
  104468. int (*backup_finish)(sqlite3_backup*);
  104469. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  104470. int (*backup_pagecount)(sqlite3_backup*);
  104471. int (*backup_remaining)(sqlite3_backup*);
  104472. int (*backup_step)(sqlite3_backup*,int);
  104473. const char *(*compileoption_get)(int);
  104474. int (*compileoption_used)(const char*);
  104475. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  104476. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  104477. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  104478. void (*xFinal)(sqlite3_context*),
  104479. void(*xDestroy)(void*));
  104480. int (*db_config)(sqlite3*,int,...);
  104481. sqlite3_mutex *(*db_mutex)(sqlite3*);
  104482. int (*db_status)(sqlite3*,int,int*,int*,int);
  104483. int (*extended_errcode)(sqlite3*);
  104484. void (*log)(int,const char*,...);
  104485. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  104486. const char *(*sourceid)(void);
  104487. int (*stmt_status)(sqlite3_stmt*,int,int);
  104488. int (*strnicmp)(const char*,const char*,int);
  104489. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  104490. int (*wal_autocheckpoint)(sqlite3*,int);
  104491. int (*wal_checkpoint)(sqlite3*,const char*);
  104492. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  104493. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  104494. int (*vtab_config)(sqlite3*,int op,...);
  104495. int (*vtab_on_conflict)(sqlite3*);
  104496. /* Version 3.7.16 and later */
  104497. int (*close_v2)(sqlite3*);
  104498. const char *(*db_filename)(sqlite3*,const char*);
  104499. int (*db_readonly)(sqlite3*,const char*);
  104500. int (*db_release_memory)(sqlite3*);
  104501. const char *(*errstr)(int);
  104502. int (*stmt_busy)(sqlite3_stmt*);
  104503. int (*stmt_readonly)(sqlite3_stmt*);
  104504. int (*stricmp)(const char*,const char*);
  104505. int (*uri_boolean)(const char*,const char*,int);
  104506. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  104507. const char *(*uri_parameter)(const char*,const char*);
  104508. char *(*vsnprintf)(int,char*,const char*,va_list);
  104509. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  104510. /* Version 3.8.7 and later */
  104511. int (*auto_extension)(void(*)(void));
  104512. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  104513. void(*)(void*));
  104514. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  104515. void(*)(void*),unsigned char);
  104516. int (*cancel_auto_extension)(void(*)(void));
  104517. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  104518. void *(*malloc64)(sqlite3_uint64);
  104519. sqlite3_uint64 (*msize)(void*);
  104520. void *(*realloc64)(void*,sqlite3_uint64);
  104521. void (*reset_auto_extension)(void);
  104522. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  104523. void(*)(void*));
  104524. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  104525. void(*)(void*), unsigned char);
  104526. int (*strglob)(const char*,const char*);
  104527. /* Version 3.8.11 and later */
  104528. sqlite3_value *(*value_dup)(const sqlite3_value*);
  104529. void (*value_free)(sqlite3_value*);
  104530. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  104531. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  104532. /* Version 3.9.0 and later */
  104533. unsigned int (*value_subtype)(sqlite3_value*);
  104534. void (*result_subtype)(sqlite3_context*,unsigned int);
  104535. /* Version 3.10.0 and later */
  104536. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  104537. int (*strlike)(const char*,const char*,unsigned int);
  104538. int (*db_cacheflush)(sqlite3*);
  104539. /* Version 3.12.0 and later */
  104540. int (*system_errno)(sqlite3*);
  104541. /* Version 3.14.0 and later */
  104542. int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  104543. char *(*expanded_sql)(sqlite3_stmt*);
  104544. /* Version 3.18.0 and later */
  104545. void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  104546. };
  104547. /*
  104548. ** This is the function signature used for all extension entry points. It
  104549. ** is also defined in the file "loadext.c".
  104550. */
  104551. typedef int (*sqlite3_loadext_entry)(
  104552. sqlite3 *db, /* Handle to the database. */
  104553. char **pzErrMsg, /* Used to set error string on failure. */
  104554. const sqlite3_api_routines *pThunk /* Extension API function pointers. */
  104555. );
  104556. /*
  104557. ** The following macros redefine the API routines so that they are
  104558. ** redirected through the global sqlite3_api structure.
  104559. **
  104560. ** This header file is also used by the loadext.c source file
  104561. ** (part of the main SQLite library - not an extension) so that
  104562. ** it can get access to the sqlite3_api_routines structure
  104563. ** definition. But the main library does not want to redefine
  104564. ** the API. So the redefinition macros are only valid if the
  104565. ** SQLITE_CORE macros is undefined.
  104566. */
  104567. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  104568. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  104569. #ifndef SQLITE_OMIT_DEPRECATED
  104570. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  104571. #endif
  104572. #define sqlite3_bind_blob sqlite3_api->bind_blob
  104573. #define sqlite3_bind_double sqlite3_api->bind_double
  104574. #define sqlite3_bind_int sqlite3_api->bind_int
  104575. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  104576. #define sqlite3_bind_null sqlite3_api->bind_null
  104577. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  104578. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  104579. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  104580. #define sqlite3_bind_text sqlite3_api->bind_text
  104581. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  104582. #define sqlite3_bind_value sqlite3_api->bind_value
  104583. #define sqlite3_busy_handler sqlite3_api->busy_handler
  104584. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  104585. #define sqlite3_changes sqlite3_api->changes
  104586. #define sqlite3_close sqlite3_api->close
  104587. #define sqlite3_collation_needed sqlite3_api->collation_needed
  104588. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  104589. #define sqlite3_column_blob sqlite3_api->column_blob
  104590. #define sqlite3_column_bytes sqlite3_api->column_bytes
  104591. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  104592. #define sqlite3_column_count sqlite3_api->column_count
  104593. #define sqlite3_column_database_name sqlite3_api->column_database_name
  104594. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  104595. #define sqlite3_column_decltype sqlite3_api->column_decltype
  104596. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  104597. #define sqlite3_column_double sqlite3_api->column_double
  104598. #define sqlite3_column_int sqlite3_api->column_int
  104599. #define sqlite3_column_int64 sqlite3_api->column_int64
  104600. #define sqlite3_column_name sqlite3_api->column_name
  104601. #define sqlite3_column_name16 sqlite3_api->column_name16
  104602. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  104603. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  104604. #define sqlite3_column_table_name sqlite3_api->column_table_name
  104605. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  104606. #define sqlite3_column_text sqlite3_api->column_text
  104607. #define sqlite3_column_text16 sqlite3_api->column_text16
  104608. #define sqlite3_column_type sqlite3_api->column_type
  104609. #define sqlite3_column_value sqlite3_api->column_value
  104610. #define sqlite3_commit_hook sqlite3_api->commit_hook
  104611. #define sqlite3_complete sqlite3_api->complete
  104612. #define sqlite3_complete16 sqlite3_api->complete16
  104613. #define sqlite3_create_collation sqlite3_api->create_collation
  104614. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  104615. #define sqlite3_create_function sqlite3_api->create_function
  104616. #define sqlite3_create_function16 sqlite3_api->create_function16
  104617. #define sqlite3_create_module sqlite3_api->create_module
  104618. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  104619. #define sqlite3_data_count sqlite3_api->data_count
  104620. #define sqlite3_db_handle sqlite3_api->db_handle
  104621. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  104622. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  104623. #define sqlite3_errcode sqlite3_api->errcode
  104624. #define sqlite3_errmsg sqlite3_api->errmsg
  104625. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  104626. #define sqlite3_exec sqlite3_api->exec
  104627. #ifndef SQLITE_OMIT_DEPRECATED
  104628. #define sqlite3_expired sqlite3_api->expired
  104629. #endif
  104630. #define sqlite3_finalize sqlite3_api->finalize
  104631. #define sqlite3_free sqlite3_api->free
  104632. #define sqlite3_free_table sqlite3_api->free_table
  104633. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  104634. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  104635. #define sqlite3_get_table sqlite3_api->get_table
  104636. #ifndef SQLITE_OMIT_DEPRECATED
  104637. #define sqlite3_global_recover sqlite3_api->global_recover
  104638. #endif
  104639. #define sqlite3_interrupt sqlite3_api->interruptx
  104640. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  104641. #define sqlite3_libversion sqlite3_api->libversion
  104642. #define sqlite3_libversion_number sqlite3_api->libversion_number
  104643. #define sqlite3_malloc sqlite3_api->malloc
  104644. #define sqlite3_mprintf sqlite3_api->mprintf
  104645. #define sqlite3_open sqlite3_api->open
  104646. #define sqlite3_open16 sqlite3_api->open16
  104647. #define sqlite3_prepare sqlite3_api->prepare
  104648. #define sqlite3_prepare16 sqlite3_api->prepare16
  104649. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  104650. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  104651. #define sqlite3_profile sqlite3_api->profile
  104652. #define sqlite3_progress_handler sqlite3_api->progress_handler
  104653. #define sqlite3_realloc sqlite3_api->realloc
  104654. #define sqlite3_reset sqlite3_api->reset
  104655. #define sqlite3_result_blob sqlite3_api->result_blob
  104656. #define sqlite3_result_double sqlite3_api->result_double
  104657. #define sqlite3_result_error sqlite3_api->result_error
  104658. #define sqlite3_result_error16 sqlite3_api->result_error16
  104659. #define sqlite3_result_int sqlite3_api->result_int
  104660. #define sqlite3_result_int64 sqlite3_api->result_int64
  104661. #define sqlite3_result_null sqlite3_api->result_null
  104662. #define sqlite3_result_text sqlite3_api->result_text
  104663. #define sqlite3_result_text16 sqlite3_api->result_text16
  104664. #define sqlite3_result_text16be sqlite3_api->result_text16be
  104665. #define sqlite3_result_text16le sqlite3_api->result_text16le
  104666. #define sqlite3_result_value sqlite3_api->result_value
  104667. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  104668. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  104669. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  104670. #define sqlite3_snprintf sqlite3_api->snprintf
  104671. #define sqlite3_step sqlite3_api->step
  104672. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  104673. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  104674. #define sqlite3_total_changes sqlite3_api->total_changes
  104675. #define sqlite3_trace sqlite3_api->trace
  104676. #ifndef SQLITE_OMIT_DEPRECATED
  104677. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  104678. #endif
  104679. #define sqlite3_update_hook sqlite3_api->update_hook
  104680. #define sqlite3_user_data sqlite3_api->user_data
  104681. #define sqlite3_value_blob sqlite3_api->value_blob
  104682. #define sqlite3_value_bytes sqlite3_api->value_bytes
  104683. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  104684. #define sqlite3_value_double sqlite3_api->value_double
  104685. #define sqlite3_value_int sqlite3_api->value_int
  104686. #define sqlite3_value_int64 sqlite3_api->value_int64
  104687. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  104688. #define sqlite3_value_text sqlite3_api->value_text
  104689. #define sqlite3_value_text16 sqlite3_api->value_text16
  104690. #define sqlite3_value_text16be sqlite3_api->value_text16be
  104691. #define sqlite3_value_text16le sqlite3_api->value_text16le
  104692. #define sqlite3_value_type sqlite3_api->value_type
  104693. #define sqlite3_vmprintf sqlite3_api->vmprintf
  104694. #define sqlite3_vsnprintf sqlite3_api->vsnprintf
  104695. #define sqlite3_overload_function sqlite3_api->overload_function
  104696. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  104697. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  104698. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  104699. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  104700. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  104701. #define sqlite3_blob_close sqlite3_api->blob_close
  104702. #define sqlite3_blob_open sqlite3_api->blob_open
  104703. #define sqlite3_blob_read sqlite3_api->blob_read
  104704. #define sqlite3_blob_write sqlite3_api->blob_write
  104705. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  104706. #define sqlite3_file_control sqlite3_api->file_control
  104707. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  104708. #define sqlite3_memory_used sqlite3_api->memory_used
  104709. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  104710. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  104711. #define sqlite3_mutex_free sqlite3_api->mutex_free
  104712. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  104713. #define sqlite3_mutex_try sqlite3_api->mutex_try
  104714. #define sqlite3_open_v2 sqlite3_api->open_v2
  104715. #define sqlite3_release_memory sqlite3_api->release_memory
  104716. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  104717. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  104718. #define sqlite3_sleep sqlite3_api->sleep
  104719. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  104720. #define sqlite3_vfs_find sqlite3_api->vfs_find
  104721. #define sqlite3_vfs_register sqlite3_api->vfs_register
  104722. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  104723. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  104724. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  104725. #define sqlite3_result_error_code sqlite3_api->result_error_code
  104726. #define sqlite3_test_control sqlite3_api->test_control
  104727. #define sqlite3_randomness sqlite3_api->randomness
  104728. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  104729. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  104730. #define sqlite3_limit sqlite3_api->limit
  104731. #define sqlite3_next_stmt sqlite3_api->next_stmt
  104732. #define sqlite3_sql sqlite3_api->sql
  104733. #define sqlite3_status sqlite3_api->status
  104734. #define sqlite3_backup_finish sqlite3_api->backup_finish
  104735. #define sqlite3_backup_init sqlite3_api->backup_init
  104736. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  104737. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  104738. #define sqlite3_backup_step sqlite3_api->backup_step
  104739. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  104740. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  104741. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  104742. #define sqlite3_db_config sqlite3_api->db_config
  104743. #define sqlite3_db_mutex sqlite3_api->db_mutex
  104744. #define sqlite3_db_status sqlite3_api->db_status
  104745. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  104746. #define sqlite3_log sqlite3_api->log
  104747. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  104748. #define sqlite3_sourceid sqlite3_api->sourceid
  104749. #define sqlite3_stmt_status sqlite3_api->stmt_status
  104750. #define sqlite3_strnicmp sqlite3_api->strnicmp
  104751. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  104752. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  104753. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  104754. #define sqlite3_wal_hook sqlite3_api->wal_hook
  104755. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  104756. #define sqlite3_vtab_config sqlite3_api->vtab_config
  104757. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  104758. /* Version 3.7.16 and later */
  104759. #define sqlite3_close_v2 sqlite3_api->close_v2
  104760. #define sqlite3_db_filename sqlite3_api->db_filename
  104761. #define sqlite3_db_readonly sqlite3_api->db_readonly
  104762. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  104763. #define sqlite3_errstr sqlite3_api->errstr
  104764. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  104765. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  104766. #define sqlite3_stricmp sqlite3_api->stricmp
  104767. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  104768. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  104769. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  104770. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  104771. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  104772. /* Version 3.8.7 and later */
  104773. #define sqlite3_auto_extension sqlite3_api->auto_extension
  104774. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  104775. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  104776. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  104777. #define sqlite3_load_extension sqlite3_api->load_extension
  104778. #define sqlite3_malloc64 sqlite3_api->malloc64
  104779. #define sqlite3_msize sqlite3_api->msize
  104780. #define sqlite3_realloc64 sqlite3_api->realloc64
  104781. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  104782. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  104783. #define sqlite3_result_text64 sqlite3_api->result_text64
  104784. #define sqlite3_strglob sqlite3_api->strglob
  104785. /* Version 3.8.11 and later */
  104786. #define sqlite3_value_dup sqlite3_api->value_dup
  104787. #define sqlite3_value_free sqlite3_api->value_free
  104788. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  104789. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  104790. /* Version 3.9.0 and later */
  104791. #define sqlite3_value_subtype sqlite3_api->value_subtype
  104792. #define sqlite3_result_subtype sqlite3_api->result_subtype
  104793. /* Version 3.10.0 and later */
  104794. #define sqlite3_status64 sqlite3_api->status64
  104795. #define sqlite3_strlike sqlite3_api->strlike
  104796. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  104797. /* Version 3.12.0 and later */
  104798. #define sqlite3_system_errno sqlite3_api->system_errno
  104799. /* Version 3.14.0 and later */
  104800. #define sqlite3_trace_v2 sqlite3_api->trace_v2
  104801. #define sqlite3_expanded_sql sqlite3_api->expanded_sql
  104802. /* Version 3.18.0 and later */
  104803. #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
  104804. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  104805. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  104806. /* This case when the file really is being compiled as a loadable
  104807. ** extension */
  104808. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  104809. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  104810. # define SQLITE_EXTENSION_INIT3 \
  104811. extern const sqlite3_api_routines *sqlite3_api;
  104812. #else
  104813. /* This case when the file is being statically linked into the
  104814. ** application */
  104815. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  104816. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  104817. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  104818. #endif
  104819. #endif /* SQLITE3EXT_H */
  104820. /************** End of sqlite3ext.h ******************************************/
  104821. /************** Continuing where we left off in loadext.c ********************/
  104822. /* #include "sqliteInt.h" */
  104823. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  104824. /*
  104825. ** Some API routines are omitted when various features are
  104826. ** excluded from a build of SQLite. Substitute a NULL pointer
  104827. ** for any missing APIs.
  104828. */
  104829. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  104830. # define sqlite3_column_database_name 0
  104831. # define sqlite3_column_database_name16 0
  104832. # define sqlite3_column_table_name 0
  104833. # define sqlite3_column_table_name16 0
  104834. # define sqlite3_column_origin_name 0
  104835. # define sqlite3_column_origin_name16 0
  104836. #endif
  104837. #ifdef SQLITE_OMIT_AUTHORIZATION
  104838. # define sqlite3_set_authorizer 0
  104839. #endif
  104840. #ifdef SQLITE_OMIT_UTF16
  104841. # define sqlite3_bind_text16 0
  104842. # define sqlite3_collation_needed16 0
  104843. # define sqlite3_column_decltype16 0
  104844. # define sqlite3_column_name16 0
  104845. # define sqlite3_column_text16 0
  104846. # define sqlite3_complete16 0
  104847. # define sqlite3_create_collation16 0
  104848. # define sqlite3_create_function16 0
  104849. # define sqlite3_errmsg16 0
  104850. # define sqlite3_open16 0
  104851. # define sqlite3_prepare16 0
  104852. # define sqlite3_prepare16_v2 0
  104853. # define sqlite3_result_error16 0
  104854. # define sqlite3_result_text16 0
  104855. # define sqlite3_result_text16be 0
  104856. # define sqlite3_result_text16le 0
  104857. # define sqlite3_value_text16 0
  104858. # define sqlite3_value_text16be 0
  104859. # define sqlite3_value_text16le 0
  104860. # define sqlite3_column_database_name16 0
  104861. # define sqlite3_column_table_name16 0
  104862. # define sqlite3_column_origin_name16 0
  104863. #endif
  104864. #ifdef SQLITE_OMIT_COMPLETE
  104865. # define sqlite3_complete 0
  104866. # define sqlite3_complete16 0
  104867. #endif
  104868. #ifdef SQLITE_OMIT_DECLTYPE
  104869. # define sqlite3_column_decltype16 0
  104870. # define sqlite3_column_decltype 0
  104871. #endif
  104872. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  104873. # define sqlite3_progress_handler 0
  104874. #endif
  104875. #ifdef SQLITE_OMIT_VIRTUALTABLE
  104876. # define sqlite3_create_module 0
  104877. # define sqlite3_create_module_v2 0
  104878. # define sqlite3_declare_vtab 0
  104879. # define sqlite3_vtab_config 0
  104880. # define sqlite3_vtab_on_conflict 0
  104881. #endif
  104882. #ifdef SQLITE_OMIT_SHARED_CACHE
  104883. # define sqlite3_enable_shared_cache 0
  104884. #endif
  104885. #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
  104886. # define sqlite3_profile 0
  104887. # define sqlite3_trace 0
  104888. #endif
  104889. #ifdef SQLITE_OMIT_GET_TABLE
  104890. # define sqlite3_free_table 0
  104891. # define sqlite3_get_table 0
  104892. #endif
  104893. #ifdef SQLITE_OMIT_INCRBLOB
  104894. #define sqlite3_bind_zeroblob 0
  104895. #define sqlite3_blob_bytes 0
  104896. #define sqlite3_blob_close 0
  104897. #define sqlite3_blob_open 0
  104898. #define sqlite3_blob_read 0
  104899. #define sqlite3_blob_write 0
  104900. #define sqlite3_blob_reopen 0
  104901. #endif
  104902. #if defined(SQLITE_OMIT_TRACE)
  104903. # define sqlite3_trace_v2 0
  104904. #endif
  104905. /*
  104906. ** The following structure contains pointers to all SQLite API routines.
  104907. ** A pointer to this structure is passed into extensions when they are
  104908. ** loaded so that the extension can make calls back into the SQLite
  104909. ** library.
  104910. **
  104911. ** When adding new APIs, add them to the bottom of this structure
  104912. ** in order to preserve backwards compatibility.
  104913. **
  104914. ** Extensions that use newer APIs should first call the
  104915. ** sqlite3_libversion_number() to make sure that the API they
  104916. ** intend to use is supported by the library. Extensions should
  104917. ** also check to make sure that the pointer to the function is
  104918. ** not NULL before calling it.
  104919. */
  104920. static const sqlite3_api_routines sqlite3Apis = {
  104921. sqlite3_aggregate_context,
  104922. #ifndef SQLITE_OMIT_DEPRECATED
  104923. sqlite3_aggregate_count,
  104924. #else
  104925. 0,
  104926. #endif
  104927. sqlite3_bind_blob,
  104928. sqlite3_bind_double,
  104929. sqlite3_bind_int,
  104930. sqlite3_bind_int64,
  104931. sqlite3_bind_null,
  104932. sqlite3_bind_parameter_count,
  104933. sqlite3_bind_parameter_index,
  104934. sqlite3_bind_parameter_name,
  104935. sqlite3_bind_text,
  104936. sqlite3_bind_text16,
  104937. sqlite3_bind_value,
  104938. sqlite3_busy_handler,
  104939. sqlite3_busy_timeout,
  104940. sqlite3_changes,
  104941. sqlite3_close,
  104942. sqlite3_collation_needed,
  104943. sqlite3_collation_needed16,
  104944. sqlite3_column_blob,
  104945. sqlite3_column_bytes,
  104946. sqlite3_column_bytes16,
  104947. sqlite3_column_count,
  104948. sqlite3_column_database_name,
  104949. sqlite3_column_database_name16,
  104950. sqlite3_column_decltype,
  104951. sqlite3_column_decltype16,
  104952. sqlite3_column_double,
  104953. sqlite3_column_int,
  104954. sqlite3_column_int64,
  104955. sqlite3_column_name,
  104956. sqlite3_column_name16,
  104957. sqlite3_column_origin_name,
  104958. sqlite3_column_origin_name16,
  104959. sqlite3_column_table_name,
  104960. sqlite3_column_table_name16,
  104961. sqlite3_column_text,
  104962. sqlite3_column_text16,
  104963. sqlite3_column_type,
  104964. sqlite3_column_value,
  104965. sqlite3_commit_hook,
  104966. sqlite3_complete,
  104967. sqlite3_complete16,
  104968. sqlite3_create_collation,
  104969. sqlite3_create_collation16,
  104970. sqlite3_create_function,
  104971. sqlite3_create_function16,
  104972. sqlite3_create_module,
  104973. sqlite3_data_count,
  104974. sqlite3_db_handle,
  104975. sqlite3_declare_vtab,
  104976. sqlite3_enable_shared_cache,
  104977. sqlite3_errcode,
  104978. sqlite3_errmsg,
  104979. sqlite3_errmsg16,
  104980. sqlite3_exec,
  104981. #ifndef SQLITE_OMIT_DEPRECATED
  104982. sqlite3_expired,
  104983. #else
  104984. 0,
  104985. #endif
  104986. sqlite3_finalize,
  104987. sqlite3_free,
  104988. sqlite3_free_table,
  104989. sqlite3_get_autocommit,
  104990. sqlite3_get_auxdata,
  104991. sqlite3_get_table,
  104992. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  104993. sqlite3_interrupt,
  104994. sqlite3_last_insert_rowid,
  104995. sqlite3_libversion,
  104996. sqlite3_libversion_number,
  104997. sqlite3_malloc,
  104998. sqlite3_mprintf,
  104999. sqlite3_open,
  105000. sqlite3_open16,
  105001. sqlite3_prepare,
  105002. sqlite3_prepare16,
  105003. sqlite3_profile,
  105004. sqlite3_progress_handler,
  105005. sqlite3_realloc,
  105006. sqlite3_reset,
  105007. sqlite3_result_blob,
  105008. sqlite3_result_double,
  105009. sqlite3_result_error,
  105010. sqlite3_result_error16,
  105011. sqlite3_result_int,
  105012. sqlite3_result_int64,
  105013. sqlite3_result_null,
  105014. sqlite3_result_text,
  105015. sqlite3_result_text16,
  105016. sqlite3_result_text16be,
  105017. sqlite3_result_text16le,
  105018. sqlite3_result_value,
  105019. sqlite3_rollback_hook,
  105020. sqlite3_set_authorizer,
  105021. sqlite3_set_auxdata,
  105022. sqlite3_snprintf,
  105023. sqlite3_step,
  105024. sqlite3_table_column_metadata,
  105025. #ifndef SQLITE_OMIT_DEPRECATED
  105026. sqlite3_thread_cleanup,
  105027. #else
  105028. 0,
  105029. #endif
  105030. sqlite3_total_changes,
  105031. sqlite3_trace,
  105032. #ifndef SQLITE_OMIT_DEPRECATED
  105033. sqlite3_transfer_bindings,
  105034. #else
  105035. 0,
  105036. #endif
  105037. sqlite3_update_hook,
  105038. sqlite3_user_data,
  105039. sqlite3_value_blob,
  105040. sqlite3_value_bytes,
  105041. sqlite3_value_bytes16,
  105042. sqlite3_value_double,
  105043. sqlite3_value_int,
  105044. sqlite3_value_int64,
  105045. sqlite3_value_numeric_type,
  105046. sqlite3_value_text,
  105047. sqlite3_value_text16,
  105048. sqlite3_value_text16be,
  105049. sqlite3_value_text16le,
  105050. sqlite3_value_type,
  105051. sqlite3_vmprintf,
  105052. /*
  105053. ** The original API set ends here. All extensions can call any
  105054. ** of the APIs above provided that the pointer is not NULL. But
  105055. ** before calling APIs that follow, extension should check the
  105056. ** sqlite3_libversion_number() to make sure they are dealing with
  105057. ** a library that is new enough to support that API.
  105058. *************************************************************************
  105059. */
  105060. sqlite3_overload_function,
  105061. /*
  105062. ** Added after 3.3.13
  105063. */
  105064. sqlite3_prepare_v2,
  105065. sqlite3_prepare16_v2,
  105066. sqlite3_clear_bindings,
  105067. /*
  105068. ** Added for 3.4.1
  105069. */
  105070. sqlite3_create_module_v2,
  105071. /*
  105072. ** Added for 3.5.0
  105073. */
  105074. sqlite3_bind_zeroblob,
  105075. sqlite3_blob_bytes,
  105076. sqlite3_blob_close,
  105077. sqlite3_blob_open,
  105078. sqlite3_blob_read,
  105079. sqlite3_blob_write,
  105080. sqlite3_create_collation_v2,
  105081. sqlite3_file_control,
  105082. sqlite3_memory_highwater,
  105083. sqlite3_memory_used,
  105084. #ifdef SQLITE_MUTEX_OMIT
  105085. 0,
  105086. 0,
  105087. 0,
  105088. 0,
  105089. 0,
  105090. #else
  105091. sqlite3_mutex_alloc,
  105092. sqlite3_mutex_enter,
  105093. sqlite3_mutex_free,
  105094. sqlite3_mutex_leave,
  105095. sqlite3_mutex_try,
  105096. #endif
  105097. sqlite3_open_v2,
  105098. sqlite3_release_memory,
  105099. sqlite3_result_error_nomem,
  105100. sqlite3_result_error_toobig,
  105101. sqlite3_sleep,
  105102. sqlite3_soft_heap_limit,
  105103. sqlite3_vfs_find,
  105104. sqlite3_vfs_register,
  105105. sqlite3_vfs_unregister,
  105106. /*
  105107. ** Added for 3.5.8
  105108. */
  105109. sqlite3_threadsafe,
  105110. sqlite3_result_zeroblob,
  105111. sqlite3_result_error_code,
  105112. sqlite3_test_control,
  105113. sqlite3_randomness,
  105114. sqlite3_context_db_handle,
  105115. /*
  105116. ** Added for 3.6.0
  105117. */
  105118. sqlite3_extended_result_codes,
  105119. sqlite3_limit,
  105120. sqlite3_next_stmt,
  105121. sqlite3_sql,
  105122. sqlite3_status,
  105123. /*
  105124. ** Added for 3.7.4
  105125. */
  105126. sqlite3_backup_finish,
  105127. sqlite3_backup_init,
  105128. sqlite3_backup_pagecount,
  105129. sqlite3_backup_remaining,
  105130. sqlite3_backup_step,
  105131. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  105132. sqlite3_compileoption_get,
  105133. sqlite3_compileoption_used,
  105134. #else
  105135. 0,
  105136. 0,
  105137. #endif
  105138. sqlite3_create_function_v2,
  105139. sqlite3_db_config,
  105140. sqlite3_db_mutex,
  105141. sqlite3_db_status,
  105142. sqlite3_extended_errcode,
  105143. sqlite3_log,
  105144. sqlite3_soft_heap_limit64,
  105145. sqlite3_sourceid,
  105146. sqlite3_stmt_status,
  105147. sqlite3_strnicmp,
  105148. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  105149. sqlite3_unlock_notify,
  105150. #else
  105151. 0,
  105152. #endif
  105153. #ifndef SQLITE_OMIT_WAL
  105154. sqlite3_wal_autocheckpoint,
  105155. sqlite3_wal_checkpoint,
  105156. sqlite3_wal_hook,
  105157. #else
  105158. 0,
  105159. 0,
  105160. 0,
  105161. #endif
  105162. sqlite3_blob_reopen,
  105163. sqlite3_vtab_config,
  105164. sqlite3_vtab_on_conflict,
  105165. sqlite3_close_v2,
  105166. sqlite3_db_filename,
  105167. sqlite3_db_readonly,
  105168. sqlite3_db_release_memory,
  105169. sqlite3_errstr,
  105170. sqlite3_stmt_busy,
  105171. sqlite3_stmt_readonly,
  105172. sqlite3_stricmp,
  105173. sqlite3_uri_boolean,
  105174. sqlite3_uri_int64,
  105175. sqlite3_uri_parameter,
  105176. sqlite3_vsnprintf,
  105177. sqlite3_wal_checkpoint_v2,
  105178. /* Version 3.8.7 and later */
  105179. sqlite3_auto_extension,
  105180. sqlite3_bind_blob64,
  105181. sqlite3_bind_text64,
  105182. sqlite3_cancel_auto_extension,
  105183. sqlite3_load_extension,
  105184. sqlite3_malloc64,
  105185. sqlite3_msize,
  105186. sqlite3_realloc64,
  105187. sqlite3_reset_auto_extension,
  105188. sqlite3_result_blob64,
  105189. sqlite3_result_text64,
  105190. sqlite3_strglob,
  105191. /* Version 3.8.11 and later */
  105192. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  105193. sqlite3_value_free,
  105194. sqlite3_result_zeroblob64,
  105195. sqlite3_bind_zeroblob64,
  105196. /* Version 3.9.0 and later */
  105197. sqlite3_value_subtype,
  105198. sqlite3_result_subtype,
  105199. /* Version 3.10.0 and later */
  105200. sqlite3_status64,
  105201. sqlite3_strlike,
  105202. sqlite3_db_cacheflush,
  105203. /* Version 3.12.0 and later */
  105204. sqlite3_system_errno,
  105205. /* Version 3.14.0 and later */
  105206. sqlite3_trace_v2,
  105207. sqlite3_expanded_sql,
  105208. /* Version 3.18.0 and later */
  105209. sqlite3_set_last_insert_rowid
  105210. };
  105211. /*
  105212. ** Attempt to load an SQLite extension library contained in the file
  105213. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  105214. ** default entry point name (sqlite3_extension_init) is used. Use
  105215. ** of the default name is recommended.
  105216. **
  105217. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  105218. **
  105219. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  105220. ** error message text. The calling function should free this memory
  105221. ** by calling sqlite3DbFree(db, ).
  105222. */
  105223. static int sqlite3LoadExtension(
  105224. sqlite3 *db, /* Load the extension into this database connection */
  105225. const char *zFile, /* Name of the shared library containing extension */
  105226. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  105227. char **pzErrMsg /* Put error message here if not 0 */
  105228. ){
  105229. sqlite3_vfs *pVfs = db->pVfs;
  105230. void *handle;
  105231. sqlite3_loadext_entry xInit;
  105232. char *zErrmsg = 0;
  105233. const char *zEntry;
  105234. char *zAltEntry = 0;
  105235. void **aHandle;
  105236. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  105237. int ii;
  105238. int rc;
  105239. /* Shared library endings to try if zFile cannot be loaded as written */
  105240. static const char *azEndings[] = {
  105241. #if SQLITE_OS_WIN
  105242. "dll"
  105243. #elif defined(__APPLE__)
  105244. "dylib"
  105245. #else
  105246. "so"
  105247. #endif
  105248. };
  105249. if( pzErrMsg ) *pzErrMsg = 0;
  105250. /* Ticket #1863. To avoid a creating security problems for older
  105251. ** applications that relink against newer versions of SQLite, the
  105252. ** ability to run load_extension is turned off by default. One
  105253. ** must call either sqlite3_enable_load_extension(db) or
  105254. ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
  105255. ** to turn on extension loading.
  105256. */
  105257. if( (db->flags & SQLITE_LoadExtension)==0 ){
  105258. if( pzErrMsg ){
  105259. *pzErrMsg = sqlite3_mprintf("not authorized");
  105260. }
  105261. return SQLITE_ERROR;
  105262. }
  105263. zEntry = zProc ? zProc : "sqlite3_extension_init";
  105264. handle = sqlite3OsDlOpen(pVfs, zFile);
  105265. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  105266. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  105267. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  105268. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  105269. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  105270. sqlite3_free(zAltFile);
  105271. }
  105272. #endif
  105273. if( handle==0 ){
  105274. if( pzErrMsg ){
  105275. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  105276. if( zErrmsg ){
  105277. sqlite3_snprintf(nMsg, zErrmsg,
  105278. "unable to open shared library [%s]", zFile);
  105279. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  105280. }
  105281. }
  105282. return SQLITE_ERROR;
  105283. }
  105284. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  105285. /* If no entry point was specified and the default legacy
  105286. ** entry point name "sqlite3_extension_init" was not found, then
  105287. ** construct an entry point name "sqlite3_X_init" where the X is
  105288. ** replaced by the lowercase value of every ASCII alphabetic
  105289. ** character in the filename after the last "/" upto the first ".",
  105290. ** and eliding the first three characters if they are "lib".
  105291. ** Examples:
  105292. **
  105293. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  105294. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  105295. */
  105296. if( xInit==0 && zProc==0 ){
  105297. int iFile, iEntry, c;
  105298. int ncFile = sqlite3Strlen30(zFile);
  105299. zAltEntry = sqlite3_malloc64(ncFile+30);
  105300. if( zAltEntry==0 ){
  105301. sqlite3OsDlClose(pVfs, handle);
  105302. return SQLITE_NOMEM_BKPT;
  105303. }
  105304. memcpy(zAltEntry, "sqlite3_", 8);
  105305. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  105306. iFile++;
  105307. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  105308. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  105309. if( sqlite3Isalpha(c) ){
  105310. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  105311. }
  105312. }
  105313. memcpy(zAltEntry+iEntry, "_init", 6);
  105314. zEntry = zAltEntry;
  105315. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  105316. }
  105317. if( xInit==0 ){
  105318. if( pzErrMsg ){
  105319. nMsg += sqlite3Strlen30(zEntry);
  105320. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  105321. if( zErrmsg ){
  105322. sqlite3_snprintf(nMsg, zErrmsg,
  105323. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  105324. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  105325. }
  105326. }
  105327. sqlite3OsDlClose(pVfs, handle);
  105328. sqlite3_free(zAltEntry);
  105329. return SQLITE_ERROR;
  105330. }
  105331. sqlite3_free(zAltEntry);
  105332. rc = xInit(db, &zErrmsg, &sqlite3Apis);
  105333. if( rc ){
  105334. if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
  105335. if( pzErrMsg ){
  105336. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  105337. }
  105338. sqlite3_free(zErrmsg);
  105339. sqlite3OsDlClose(pVfs, handle);
  105340. return SQLITE_ERROR;
  105341. }
  105342. /* Append the new shared library handle to the db->aExtension array. */
  105343. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  105344. if( aHandle==0 ){
  105345. return SQLITE_NOMEM_BKPT;
  105346. }
  105347. if( db->nExtension>0 ){
  105348. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  105349. }
  105350. sqlite3DbFree(db, db->aExtension);
  105351. db->aExtension = aHandle;
  105352. db->aExtension[db->nExtension++] = handle;
  105353. return SQLITE_OK;
  105354. }
  105355. SQLITE_API int sqlite3_load_extension(
  105356. sqlite3 *db, /* Load the extension into this database connection */
  105357. const char *zFile, /* Name of the shared library containing extension */
  105358. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  105359. char **pzErrMsg /* Put error message here if not 0 */
  105360. ){
  105361. int rc;
  105362. sqlite3_mutex_enter(db->mutex);
  105363. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  105364. rc = sqlite3ApiExit(db, rc);
  105365. sqlite3_mutex_leave(db->mutex);
  105366. return rc;
  105367. }
  105368. /*
  105369. ** Call this routine when the database connection is closing in order
  105370. ** to clean up loaded extensions
  105371. */
  105372. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  105373. int i;
  105374. assert( sqlite3_mutex_held(db->mutex) );
  105375. for(i=0; i<db->nExtension; i++){
  105376. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  105377. }
  105378. sqlite3DbFree(db, db->aExtension);
  105379. }
  105380. /*
  105381. ** Enable or disable extension loading. Extension loading is disabled by
  105382. ** default so as not to open security holes in older applications.
  105383. */
  105384. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  105385. sqlite3_mutex_enter(db->mutex);
  105386. if( onoff ){
  105387. db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
  105388. }else{
  105389. db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
  105390. }
  105391. sqlite3_mutex_leave(db->mutex);
  105392. return SQLITE_OK;
  105393. }
  105394. #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  105395. /*
  105396. ** The following object holds the list of automatically loaded
  105397. ** extensions.
  105398. **
  105399. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  105400. ** mutex must be held while accessing this list.
  105401. */
  105402. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  105403. static SQLITE_WSD struct sqlite3AutoExtList {
  105404. u32 nExt; /* Number of entries in aExt[] */
  105405. void (**aExt)(void); /* Pointers to the extension init functions */
  105406. } sqlite3Autoext = { 0, 0 };
  105407. /* The "wsdAutoext" macro will resolve to the autoextension
  105408. ** state vector. If writable static data is unsupported on the target,
  105409. ** we have to locate the state vector at run-time. In the more common
  105410. ** case where writable static data is supported, wsdStat can refer directly
  105411. ** to the "sqlite3Autoext" state vector declared above.
  105412. */
  105413. #ifdef SQLITE_OMIT_WSD
  105414. # define wsdAutoextInit \
  105415. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  105416. # define wsdAutoext x[0]
  105417. #else
  105418. # define wsdAutoextInit
  105419. # define wsdAutoext sqlite3Autoext
  105420. #endif
  105421. /*
  105422. ** Register a statically linked extension that is automatically
  105423. ** loaded by every new database connection.
  105424. */
  105425. SQLITE_API int sqlite3_auto_extension(
  105426. void (*xInit)(void)
  105427. ){
  105428. int rc = SQLITE_OK;
  105429. #ifndef SQLITE_OMIT_AUTOINIT
  105430. rc = sqlite3_initialize();
  105431. if( rc ){
  105432. return rc;
  105433. }else
  105434. #endif
  105435. {
  105436. u32 i;
  105437. #if SQLITE_THREADSAFE
  105438. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  105439. #endif
  105440. wsdAutoextInit;
  105441. sqlite3_mutex_enter(mutex);
  105442. for(i=0; i<wsdAutoext.nExt; i++){
  105443. if( wsdAutoext.aExt[i]==xInit ) break;
  105444. }
  105445. if( i==wsdAutoext.nExt ){
  105446. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  105447. void (**aNew)(void);
  105448. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  105449. if( aNew==0 ){
  105450. rc = SQLITE_NOMEM_BKPT;
  105451. }else{
  105452. wsdAutoext.aExt = aNew;
  105453. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  105454. wsdAutoext.nExt++;
  105455. }
  105456. }
  105457. sqlite3_mutex_leave(mutex);
  105458. assert( (rc&0xff)==rc );
  105459. return rc;
  105460. }
  105461. }
  105462. /*
  105463. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  105464. ** set of routines that is invoked for each new database connection, if it
  105465. ** is currently on the list. If xInit is not on the list, then this
  105466. ** routine is a no-op.
  105467. **
  105468. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  105469. ** was not on the list.
  105470. */
  105471. SQLITE_API int sqlite3_cancel_auto_extension(
  105472. void (*xInit)(void)
  105473. ){
  105474. #if SQLITE_THREADSAFE
  105475. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  105476. #endif
  105477. int i;
  105478. int n = 0;
  105479. wsdAutoextInit;
  105480. sqlite3_mutex_enter(mutex);
  105481. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  105482. if( wsdAutoext.aExt[i]==xInit ){
  105483. wsdAutoext.nExt--;
  105484. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  105485. n++;
  105486. break;
  105487. }
  105488. }
  105489. sqlite3_mutex_leave(mutex);
  105490. return n;
  105491. }
  105492. /*
  105493. ** Reset the automatic extension loading mechanism.
  105494. */
  105495. SQLITE_API void sqlite3_reset_auto_extension(void){
  105496. #ifndef SQLITE_OMIT_AUTOINIT
  105497. if( sqlite3_initialize()==SQLITE_OK )
  105498. #endif
  105499. {
  105500. #if SQLITE_THREADSAFE
  105501. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  105502. #endif
  105503. wsdAutoextInit;
  105504. sqlite3_mutex_enter(mutex);
  105505. sqlite3_free(wsdAutoext.aExt);
  105506. wsdAutoext.aExt = 0;
  105507. wsdAutoext.nExt = 0;
  105508. sqlite3_mutex_leave(mutex);
  105509. }
  105510. }
  105511. /*
  105512. ** Load all automatic extensions.
  105513. **
  105514. ** If anything goes wrong, set an error in the database connection.
  105515. */
  105516. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  105517. u32 i;
  105518. int go = 1;
  105519. int rc;
  105520. sqlite3_loadext_entry xInit;
  105521. wsdAutoextInit;
  105522. if( wsdAutoext.nExt==0 ){
  105523. /* Common case: early out without every having to acquire a mutex */
  105524. return;
  105525. }
  105526. for(i=0; go; i++){
  105527. char *zErrmsg;
  105528. #if SQLITE_THREADSAFE
  105529. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  105530. #endif
  105531. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  105532. const sqlite3_api_routines *pThunk = 0;
  105533. #else
  105534. const sqlite3_api_routines *pThunk = &sqlite3Apis;
  105535. #endif
  105536. sqlite3_mutex_enter(mutex);
  105537. if( i>=wsdAutoext.nExt ){
  105538. xInit = 0;
  105539. go = 0;
  105540. }else{
  105541. xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
  105542. }
  105543. sqlite3_mutex_leave(mutex);
  105544. zErrmsg = 0;
  105545. if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
  105546. sqlite3ErrorWithMsg(db, rc,
  105547. "automatic extension loading failed: %s", zErrmsg);
  105548. go = 0;
  105549. }
  105550. sqlite3_free(zErrmsg);
  105551. }
  105552. }
  105553. /************** End of loadext.c *********************************************/
  105554. /************** Begin file pragma.c ******************************************/
  105555. /*
  105556. ** 2003 April 6
  105557. **
  105558. ** The author disclaims copyright to this source code. In place of
  105559. ** a legal notice, here is a blessing:
  105560. **
  105561. ** May you do good and not evil.
  105562. ** May you find forgiveness for yourself and forgive others.
  105563. ** May you share freely, never taking more than you give.
  105564. **
  105565. *************************************************************************
  105566. ** This file contains code used to implement the PRAGMA command.
  105567. */
  105568. /* #include "sqliteInt.h" */
  105569. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  105570. # if defined(__APPLE__)
  105571. # define SQLITE_ENABLE_LOCKING_STYLE 1
  105572. # else
  105573. # define SQLITE_ENABLE_LOCKING_STYLE 0
  105574. # endif
  105575. #endif
  105576. /***************************************************************************
  105577. ** The "pragma.h" include file is an automatically generated file that
  105578. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  105579. ** object. This ensures that the aPragmaName[] table is arranged in
  105580. ** lexicographical order to facility a binary search of the pragma name.
  105581. ** Do not edit pragma.h directly. Edit and rerun the script in at
  105582. ** ../tool/mkpragmatab.tcl. */
  105583. /************** Include pragma.h in the middle of pragma.c *******************/
  105584. /************** Begin file pragma.h ******************************************/
  105585. /* DO NOT EDIT!
  105586. ** This file is automatically generated by the script at
  105587. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  105588. ** that script and rerun it.
  105589. */
  105590. /* The various pragma types */
  105591. #define PragTyp_HEADER_VALUE 0
  105592. #define PragTyp_AUTO_VACUUM 1
  105593. #define PragTyp_FLAG 2
  105594. #define PragTyp_BUSY_TIMEOUT 3
  105595. #define PragTyp_CACHE_SIZE 4
  105596. #define PragTyp_CACHE_SPILL 5
  105597. #define PragTyp_CASE_SENSITIVE_LIKE 6
  105598. #define PragTyp_COLLATION_LIST 7
  105599. #define PragTyp_COMPILE_OPTIONS 8
  105600. #define PragTyp_DATA_STORE_DIRECTORY 9
  105601. #define PragTyp_DATABASE_LIST 10
  105602. #define PragTyp_DEFAULT_CACHE_SIZE 11
  105603. #define PragTyp_ENCODING 12
  105604. #define PragTyp_FOREIGN_KEY_CHECK 13
  105605. #define PragTyp_FOREIGN_KEY_LIST 14
  105606. #define PragTyp_INCREMENTAL_VACUUM 15
  105607. #define PragTyp_INDEX_INFO 16
  105608. #define PragTyp_INDEX_LIST 17
  105609. #define PragTyp_INTEGRITY_CHECK 18
  105610. #define PragTyp_JOURNAL_MODE 19
  105611. #define PragTyp_JOURNAL_SIZE_LIMIT 20
  105612. #define PragTyp_LOCK_PROXY_FILE 21
  105613. #define PragTyp_LOCKING_MODE 22
  105614. #define PragTyp_PAGE_COUNT 23
  105615. #define PragTyp_MMAP_SIZE 24
  105616. #define PragTyp_OPTIMIZE 25
  105617. #define PragTyp_PAGE_SIZE 26
  105618. #define PragTyp_SECURE_DELETE 27
  105619. #define PragTyp_SHRINK_MEMORY 28
  105620. #define PragTyp_SOFT_HEAP_LIMIT 29
  105621. #define PragTyp_SYNCHRONOUS 30
  105622. #define PragTyp_TABLE_INFO 31
  105623. #define PragTyp_TEMP_STORE 32
  105624. #define PragTyp_TEMP_STORE_DIRECTORY 33
  105625. #define PragTyp_THREADS 34
  105626. #define PragTyp_WAL_AUTOCHECKPOINT 35
  105627. #define PragTyp_WAL_CHECKPOINT 36
  105628. #define PragTyp_ACTIVATE_EXTENSIONS 37
  105629. #define PragTyp_HEXKEY 38
  105630. #define PragTyp_KEY 39
  105631. #define PragTyp_REKEY 40
  105632. #define PragTyp_LOCK_STATUS 41
  105633. #define PragTyp_PARSER_TRACE 42
  105634. #define PragTyp_STATS 43
  105635. /* Property flags associated with various pragma. */
  105636. #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
  105637. #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
  105638. #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
  105639. #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
  105640. #define PragFlg_Result0 0x10 /* Acts as query when no argument */
  105641. #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
  105642. #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
  105643. #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
  105644. /* Names of columns for pragmas that return multi-column result
  105645. ** or that return single-column results where the name of the
  105646. ** result column is different from the name of the pragma
  105647. */
  105648. static const char *const pragCName[] = {
  105649. /* 0 */ "cache_size", /* Used by: default_cache_size */
  105650. /* 1 */ "cid", /* Used by: table_info */
  105651. /* 2 */ "name",
  105652. /* 3 */ "type",
  105653. /* 4 */ "notnull",
  105654. /* 5 */ "dflt_value",
  105655. /* 6 */ "pk",
  105656. /* 7 */ "tbl", /* Used by: stats */
  105657. /* 8 */ "idx",
  105658. /* 9 */ "wdth",
  105659. /* 10 */ "hght",
  105660. /* 11 */ "flgs",
  105661. /* 12 */ "seqno", /* Used by: index_info */
  105662. /* 13 */ "cid",
  105663. /* 14 */ "name",
  105664. /* 15 */ "seqno", /* Used by: index_xinfo */
  105665. /* 16 */ "cid",
  105666. /* 17 */ "name",
  105667. /* 18 */ "desc",
  105668. /* 19 */ "coll",
  105669. /* 20 */ "key",
  105670. /* 21 */ "seq", /* Used by: index_list */
  105671. /* 22 */ "name",
  105672. /* 23 */ "unique",
  105673. /* 24 */ "origin",
  105674. /* 25 */ "partial",
  105675. /* 26 */ "seq", /* Used by: database_list */
  105676. /* 27 */ "name",
  105677. /* 28 */ "file",
  105678. /* 29 */ "seq", /* Used by: collation_list */
  105679. /* 30 */ "name",
  105680. /* 31 */ "id", /* Used by: foreign_key_list */
  105681. /* 32 */ "seq",
  105682. /* 33 */ "table",
  105683. /* 34 */ "from",
  105684. /* 35 */ "to",
  105685. /* 36 */ "on_update",
  105686. /* 37 */ "on_delete",
  105687. /* 38 */ "match",
  105688. /* 39 */ "table", /* Used by: foreign_key_check */
  105689. /* 40 */ "rowid",
  105690. /* 41 */ "parent",
  105691. /* 42 */ "fkid",
  105692. /* 43 */ "busy", /* Used by: wal_checkpoint */
  105693. /* 44 */ "log",
  105694. /* 45 */ "checkpointed",
  105695. /* 46 */ "timeout", /* Used by: busy_timeout */
  105696. /* 47 */ "database", /* Used by: lock_status */
  105697. /* 48 */ "status",
  105698. };
  105699. /* Definitions of all built-in pragmas */
  105700. typedef struct PragmaName {
  105701. const char *const zName; /* Name of pragma */
  105702. u8 ePragTyp; /* PragTyp_XXX value */
  105703. u8 mPragFlg; /* Zero or more PragFlg_XXX values */
  105704. u8 iPragCName; /* Start of column names in pragCName[] */
  105705. u8 nPragCName; /* Num of col names. 0 means use pragma name */
  105706. u32 iArg; /* Extra argument */
  105707. } PragmaName;
  105708. static const PragmaName aPragmaName[] = {
  105709. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  105710. {/* zName: */ "activate_extensions",
  105711. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  105712. /* ePragFlg: */ 0,
  105713. /* ColNames: */ 0, 0,
  105714. /* iArg: */ 0 },
  105715. #endif
  105716. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  105717. {/* zName: */ "application_id",
  105718. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  105719. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  105720. /* ColNames: */ 0, 0,
  105721. /* iArg: */ BTREE_APPLICATION_ID },
  105722. #endif
  105723. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  105724. {/* zName: */ "auto_vacuum",
  105725. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  105726. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  105727. /* ColNames: */ 0, 0,
  105728. /* iArg: */ 0 },
  105729. #endif
  105730. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105731. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  105732. {/* zName: */ "automatic_index",
  105733. /* ePragTyp: */ PragTyp_FLAG,
  105734. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105735. /* ColNames: */ 0, 0,
  105736. /* iArg: */ SQLITE_AutoIndex },
  105737. #endif
  105738. #endif
  105739. {/* zName: */ "busy_timeout",
  105740. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  105741. /* ePragFlg: */ PragFlg_Result0,
  105742. /* ColNames: */ 46, 1,
  105743. /* iArg: */ 0 },
  105744. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  105745. {/* zName: */ "cache_size",
  105746. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  105747. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  105748. /* ColNames: */ 0, 0,
  105749. /* iArg: */ 0 },
  105750. #endif
  105751. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105752. {/* zName: */ "cache_spill",
  105753. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  105754. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  105755. /* ColNames: */ 0, 0,
  105756. /* iArg: */ 0 },
  105757. #endif
  105758. {/* zName: */ "case_sensitive_like",
  105759. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  105760. /* ePragFlg: */ PragFlg_NoColumns,
  105761. /* ColNames: */ 0, 0,
  105762. /* iArg: */ 0 },
  105763. {/* zName: */ "cell_size_check",
  105764. /* ePragTyp: */ PragTyp_FLAG,
  105765. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105766. /* ColNames: */ 0, 0,
  105767. /* iArg: */ SQLITE_CellSizeCk },
  105768. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105769. {/* zName: */ "checkpoint_fullfsync",
  105770. /* ePragTyp: */ PragTyp_FLAG,
  105771. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105772. /* ColNames: */ 0, 0,
  105773. /* iArg: */ SQLITE_CkptFullFSync },
  105774. #endif
  105775. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  105776. {/* zName: */ "collation_list",
  105777. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  105778. /* ePragFlg: */ PragFlg_Result0,
  105779. /* ColNames: */ 29, 2,
  105780. /* iArg: */ 0 },
  105781. #endif
  105782. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  105783. {/* zName: */ "compile_options",
  105784. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  105785. /* ePragFlg: */ PragFlg_Result0,
  105786. /* ColNames: */ 0, 0,
  105787. /* iArg: */ 0 },
  105788. #endif
  105789. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105790. {/* zName: */ "count_changes",
  105791. /* ePragTyp: */ PragTyp_FLAG,
  105792. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105793. /* ColNames: */ 0, 0,
  105794. /* iArg: */ SQLITE_CountRows },
  105795. #endif
  105796. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  105797. {/* zName: */ "data_store_directory",
  105798. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  105799. /* ePragFlg: */ PragFlg_NoColumns1,
  105800. /* ColNames: */ 0, 0,
  105801. /* iArg: */ 0 },
  105802. #endif
  105803. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  105804. {/* zName: */ "data_version",
  105805. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  105806. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  105807. /* ColNames: */ 0, 0,
  105808. /* iArg: */ BTREE_DATA_VERSION },
  105809. #endif
  105810. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  105811. {/* zName: */ "database_list",
  105812. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  105813. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  105814. /* ColNames: */ 26, 3,
  105815. /* iArg: */ 0 },
  105816. #endif
  105817. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  105818. {/* zName: */ "default_cache_size",
  105819. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  105820. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  105821. /* ColNames: */ 0, 1,
  105822. /* iArg: */ 0 },
  105823. #endif
  105824. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105825. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  105826. {/* zName: */ "defer_foreign_keys",
  105827. /* ePragTyp: */ PragTyp_FLAG,
  105828. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105829. /* ColNames: */ 0, 0,
  105830. /* iArg: */ SQLITE_DeferFKs },
  105831. #endif
  105832. #endif
  105833. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105834. {/* zName: */ "empty_result_callbacks",
  105835. /* ePragTyp: */ PragTyp_FLAG,
  105836. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105837. /* ColNames: */ 0, 0,
  105838. /* iArg: */ SQLITE_NullCallback },
  105839. #endif
  105840. #if !defined(SQLITE_OMIT_UTF16)
  105841. {/* zName: */ "encoding",
  105842. /* ePragTyp: */ PragTyp_ENCODING,
  105843. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105844. /* ColNames: */ 0, 0,
  105845. /* iArg: */ 0 },
  105846. #endif
  105847. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  105848. {/* zName: */ "foreign_key_check",
  105849. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  105850. /* ePragFlg: */ PragFlg_NeedSchema,
  105851. /* ColNames: */ 39, 4,
  105852. /* iArg: */ 0 },
  105853. #endif
  105854. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  105855. {/* zName: */ "foreign_key_list",
  105856. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  105857. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  105858. /* ColNames: */ 31, 8,
  105859. /* iArg: */ 0 },
  105860. #endif
  105861. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105862. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  105863. {/* zName: */ "foreign_keys",
  105864. /* ePragTyp: */ PragTyp_FLAG,
  105865. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105866. /* ColNames: */ 0, 0,
  105867. /* iArg: */ SQLITE_ForeignKeys },
  105868. #endif
  105869. #endif
  105870. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  105871. {/* zName: */ "freelist_count",
  105872. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  105873. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  105874. /* ColNames: */ 0, 0,
  105875. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  105876. #endif
  105877. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105878. {/* zName: */ "full_column_names",
  105879. /* ePragTyp: */ PragTyp_FLAG,
  105880. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105881. /* ColNames: */ 0, 0,
  105882. /* iArg: */ SQLITE_FullColNames },
  105883. {/* zName: */ "fullfsync",
  105884. /* ePragTyp: */ PragTyp_FLAG,
  105885. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105886. /* ColNames: */ 0, 0,
  105887. /* iArg: */ SQLITE_FullFSync },
  105888. #endif
  105889. #if defined(SQLITE_HAS_CODEC)
  105890. {/* zName: */ "hexkey",
  105891. /* ePragTyp: */ PragTyp_HEXKEY,
  105892. /* ePragFlg: */ 0,
  105893. /* ColNames: */ 0, 0,
  105894. /* iArg: */ 0 },
  105895. {/* zName: */ "hexrekey",
  105896. /* ePragTyp: */ PragTyp_HEXKEY,
  105897. /* ePragFlg: */ 0,
  105898. /* ColNames: */ 0, 0,
  105899. /* iArg: */ 0 },
  105900. #endif
  105901. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105902. #if !defined(SQLITE_OMIT_CHECK)
  105903. {/* zName: */ "ignore_check_constraints",
  105904. /* ePragTyp: */ PragTyp_FLAG,
  105905. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105906. /* ColNames: */ 0, 0,
  105907. /* iArg: */ SQLITE_IgnoreChecks },
  105908. #endif
  105909. #endif
  105910. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  105911. {/* zName: */ "incremental_vacuum",
  105912. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  105913. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
  105914. /* ColNames: */ 0, 0,
  105915. /* iArg: */ 0 },
  105916. #endif
  105917. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  105918. {/* zName: */ "index_info",
  105919. /* ePragTyp: */ PragTyp_INDEX_INFO,
  105920. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  105921. /* ColNames: */ 12, 3,
  105922. /* iArg: */ 0 },
  105923. {/* zName: */ "index_list",
  105924. /* ePragTyp: */ PragTyp_INDEX_LIST,
  105925. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  105926. /* ColNames: */ 21, 5,
  105927. /* iArg: */ 0 },
  105928. {/* zName: */ "index_xinfo",
  105929. /* ePragTyp: */ PragTyp_INDEX_INFO,
  105930. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  105931. /* ColNames: */ 15, 6,
  105932. /* iArg: */ 1 },
  105933. #endif
  105934. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  105935. {/* zName: */ "integrity_check",
  105936. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  105937. /* ePragFlg: */ PragFlg_NeedSchema,
  105938. /* ColNames: */ 0, 0,
  105939. /* iArg: */ 0 },
  105940. #endif
  105941. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  105942. {/* zName: */ "journal_mode",
  105943. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  105944. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  105945. /* ColNames: */ 0, 0,
  105946. /* iArg: */ 0 },
  105947. {/* zName: */ "journal_size_limit",
  105948. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  105949. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  105950. /* ColNames: */ 0, 0,
  105951. /* iArg: */ 0 },
  105952. #endif
  105953. #if defined(SQLITE_HAS_CODEC)
  105954. {/* zName: */ "key",
  105955. /* ePragTyp: */ PragTyp_KEY,
  105956. /* ePragFlg: */ 0,
  105957. /* ColNames: */ 0, 0,
  105958. /* iArg: */ 0 },
  105959. #endif
  105960. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105961. {/* zName: */ "legacy_file_format",
  105962. /* ePragTyp: */ PragTyp_FLAG,
  105963. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105964. /* ColNames: */ 0, 0,
  105965. /* iArg: */ SQLITE_LegacyFileFmt },
  105966. #endif
  105967. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  105968. {/* zName: */ "lock_proxy_file",
  105969. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  105970. /* ePragFlg: */ PragFlg_NoColumns1,
  105971. /* ColNames: */ 0, 0,
  105972. /* iArg: */ 0 },
  105973. #endif
  105974. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  105975. {/* zName: */ "lock_status",
  105976. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  105977. /* ePragFlg: */ PragFlg_Result0,
  105978. /* ColNames: */ 47, 2,
  105979. /* iArg: */ 0 },
  105980. #endif
  105981. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  105982. {/* zName: */ "locking_mode",
  105983. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  105984. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  105985. /* ColNames: */ 0, 0,
  105986. /* iArg: */ 0 },
  105987. {/* zName: */ "max_page_count",
  105988. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  105989. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  105990. /* ColNames: */ 0, 0,
  105991. /* iArg: */ 0 },
  105992. {/* zName: */ "mmap_size",
  105993. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  105994. /* ePragFlg: */ 0,
  105995. /* ColNames: */ 0, 0,
  105996. /* iArg: */ 0 },
  105997. #endif
  105998. {/* zName: */ "optimize",
  105999. /* ePragTyp: */ PragTyp_OPTIMIZE,
  106000. /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
  106001. /* ColNames: */ 0, 0,
  106002. /* iArg: */ 0 },
  106003. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106004. {/* zName: */ "page_count",
  106005. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  106006. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  106007. /* ColNames: */ 0, 0,
  106008. /* iArg: */ 0 },
  106009. {/* zName: */ "page_size",
  106010. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  106011. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  106012. /* ColNames: */ 0, 0,
  106013. /* iArg: */ 0 },
  106014. #endif
  106015. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
  106016. {/* zName: */ "parser_trace",
  106017. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  106018. /* ePragFlg: */ 0,
  106019. /* ColNames: */ 0, 0,
  106020. /* iArg: */ 0 },
  106021. #endif
  106022. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106023. {/* zName: */ "query_only",
  106024. /* ePragTyp: */ PragTyp_FLAG,
  106025. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106026. /* ColNames: */ 0, 0,
  106027. /* iArg: */ SQLITE_QueryOnly },
  106028. #endif
  106029. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  106030. {/* zName: */ "quick_check",
  106031. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  106032. /* ePragFlg: */ PragFlg_NeedSchema,
  106033. /* ColNames: */ 0, 0,
  106034. /* iArg: */ 0 },
  106035. #endif
  106036. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106037. {/* zName: */ "read_uncommitted",
  106038. /* ePragTyp: */ PragTyp_FLAG,
  106039. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106040. /* ColNames: */ 0, 0,
  106041. /* iArg: */ SQLITE_ReadUncommitted },
  106042. {/* zName: */ "recursive_triggers",
  106043. /* ePragTyp: */ PragTyp_FLAG,
  106044. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106045. /* ColNames: */ 0, 0,
  106046. /* iArg: */ SQLITE_RecTriggers },
  106047. #endif
  106048. #if defined(SQLITE_HAS_CODEC)
  106049. {/* zName: */ "rekey",
  106050. /* ePragTyp: */ PragTyp_REKEY,
  106051. /* ePragFlg: */ 0,
  106052. /* ColNames: */ 0, 0,
  106053. /* iArg: */ 0 },
  106054. #endif
  106055. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106056. {/* zName: */ "reverse_unordered_selects",
  106057. /* ePragTyp: */ PragTyp_FLAG,
  106058. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106059. /* ColNames: */ 0, 0,
  106060. /* iArg: */ SQLITE_ReverseOrder },
  106061. #endif
  106062. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  106063. {/* zName: */ "schema_version",
  106064. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  106065. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  106066. /* ColNames: */ 0, 0,
  106067. /* iArg: */ BTREE_SCHEMA_VERSION },
  106068. #endif
  106069. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106070. {/* zName: */ "secure_delete",
  106071. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  106072. /* ePragFlg: */ PragFlg_Result0,
  106073. /* ColNames: */ 0, 0,
  106074. /* iArg: */ 0 },
  106075. #endif
  106076. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106077. {/* zName: */ "short_column_names",
  106078. /* ePragTyp: */ PragTyp_FLAG,
  106079. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106080. /* ColNames: */ 0, 0,
  106081. /* iArg: */ SQLITE_ShortColNames },
  106082. #endif
  106083. {/* zName: */ "shrink_memory",
  106084. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  106085. /* ePragFlg: */ PragFlg_NoColumns,
  106086. /* ColNames: */ 0, 0,
  106087. /* iArg: */ 0 },
  106088. {/* zName: */ "soft_heap_limit",
  106089. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  106090. /* ePragFlg: */ PragFlg_Result0,
  106091. /* ColNames: */ 0, 0,
  106092. /* iArg: */ 0 },
  106093. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106094. #if defined(SQLITE_DEBUG)
  106095. {/* zName: */ "sql_trace",
  106096. /* ePragTyp: */ PragTyp_FLAG,
  106097. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106098. /* ColNames: */ 0, 0,
  106099. /* iArg: */ SQLITE_SqlTrace },
  106100. #endif
  106101. #endif
  106102. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
  106103. {/* zName: */ "stats",
  106104. /* ePragTyp: */ PragTyp_STATS,
  106105. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  106106. /* ColNames: */ 7, 5,
  106107. /* iArg: */ 0 },
  106108. #endif
  106109. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106110. {/* zName: */ "synchronous",
  106111. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  106112. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  106113. /* ColNames: */ 0, 0,
  106114. /* iArg: */ 0 },
  106115. #endif
  106116. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  106117. {/* zName: */ "table_info",
  106118. /* ePragTyp: */ PragTyp_TABLE_INFO,
  106119. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  106120. /* ColNames: */ 1, 6,
  106121. /* iArg: */ 0 },
  106122. #endif
  106123. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106124. {/* zName: */ "temp_store",
  106125. /* ePragTyp: */ PragTyp_TEMP_STORE,
  106126. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106127. /* ColNames: */ 0, 0,
  106128. /* iArg: */ 0 },
  106129. {/* zName: */ "temp_store_directory",
  106130. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  106131. /* ePragFlg: */ PragFlg_NoColumns1,
  106132. /* ColNames: */ 0, 0,
  106133. /* iArg: */ 0 },
  106134. #endif
  106135. {/* zName: */ "threads",
  106136. /* ePragTyp: */ PragTyp_THREADS,
  106137. /* ePragFlg: */ PragFlg_Result0,
  106138. /* ColNames: */ 0, 0,
  106139. /* iArg: */ 0 },
  106140. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  106141. {/* zName: */ "user_version",
  106142. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  106143. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  106144. /* ColNames: */ 0, 0,
  106145. /* iArg: */ BTREE_USER_VERSION },
  106146. #endif
  106147. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106148. #if defined(SQLITE_DEBUG)
  106149. {/* zName: */ "vdbe_addoptrace",
  106150. /* ePragTyp: */ PragTyp_FLAG,
  106151. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106152. /* ColNames: */ 0, 0,
  106153. /* iArg: */ SQLITE_VdbeAddopTrace },
  106154. {/* zName: */ "vdbe_debug",
  106155. /* ePragTyp: */ PragTyp_FLAG,
  106156. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106157. /* ColNames: */ 0, 0,
  106158. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  106159. {/* zName: */ "vdbe_eqp",
  106160. /* ePragTyp: */ PragTyp_FLAG,
  106161. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106162. /* ColNames: */ 0, 0,
  106163. /* iArg: */ SQLITE_VdbeEQP },
  106164. {/* zName: */ "vdbe_listing",
  106165. /* ePragTyp: */ PragTyp_FLAG,
  106166. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106167. /* ColNames: */ 0, 0,
  106168. /* iArg: */ SQLITE_VdbeListing },
  106169. {/* zName: */ "vdbe_trace",
  106170. /* ePragTyp: */ PragTyp_FLAG,
  106171. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106172. /* ColNames: */ 0, 0,
  106173. /* iArg: */ SQLITE_VdbeTrace },
  106174. #endif
  106175. #endif
  106176. #if !defined(SQLITE_OMIT_WAL)
  106177. {/* zName: */ "wal_autocheckpoint",
  106178. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  106179. /* ePragFlg: */ 0,
  106180. /* ColNames: */ 0, 0,
  106181. /* iArg: */ 0 },
  106182. {/* zName: */ "wal_checkpoint",
  106183. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  106184. /* ePragFlg: */ PragFlg_NeedSchema,
  106185. /* ColNames: */ 43, 3,
  106186. /* iArg: */ 0 },
  106187. #endif
  106188. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106189. {/* zName: */ "writable_schema",
  106190. /* ePragTyp: */ PragTyp_FLAG,
  106191. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106192. /* ColNames: */ 0, 0,
  106193. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  106194. #endif
  106195. };
  106196. /* Number of pragmas: 60 on by default, 74 total. */
  106197. /************** End of pragma.h **********************************************/
  106198. /************** Continuing where we left off in pragma.c *********************/
  106199. /*
  106200. ** Interpret the given string as a safety level. Return 0 for OFF,
  106201. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  106202. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  106203. ** if the omitFull parameter it 1.
  106204. **
  106205. ** Note that the values returned are one less that the values that
  106206. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  106207. ** to support legacy SQL code. The safety level used to be boolean
  106208. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  106209. */
  106210. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  106211. /* 123456789 123456789 123 */
  106212. static const char zText[] = "onoffalseyestruextrafull";
  106213. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  106214. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  106215. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  106216. /* on no off false yes true extra full */
  106217. int i, n;
  106218. if( sqlite3Isdigit(*z) ){
  106219. return (u8)sqlite3Atoi(z);
  106220. }
  106221. n = sqlite3Strlen30(z);
  106222. for(i=0; i<ArraySize(iLength); i++){
  106223. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  106224. && (!omitFull || iValue[i]<=1)
  106225. ){
  106226. return iValue[i];
  106227. }
  106228. }
  106229. return dflt;
  106230. }
  106231. /*
  106232. ** Interpret the given string as a boolean value.
  106233. */
  106234. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  106235. return getSafetyLevel(z,1,dflt)!=0;
  106236. }
  106237. /* The sqlite3GetBoolean() function is used by other modules but the
  106238. ** remainder of this file is specific to PRAGMA processing. So omit
  106239. ** the rest of the file if PRAGMAs are omitted from the build.
  106240. */
  106241. #if !defined(SQLITE_OMIT_PRAGMA)
  106242. /*
  106243. ** Interpret the given string as a locking mode value.
  106244. */
  106245. static int getLockingMode(const char *z){
  106246. if( z ){
  106247. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  106248. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  106249. }
  106250. return PAGER_LOCKINGMODE_QUERY;
  106251. }
  106252. #ifndef SQLITE_OMIT_AUTOVACUUM
  106253. /*
  106254. ** Interpret the given string as an auto-vacuum mode value.
  106255. **
  106256. ** The following strings, "none", "full" and "incremental" are
  106257. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  106258. */
  106259. static int getAutoVacuum(const char *z){
  106260. int i;
  106261. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  106262. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  106263. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  106264. i = sqlite3Atoi(z);
  106265. return (u8)((i>=0&&i<=2)?i:0);
  106266. }
  106267. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  106268. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106269. /*
  106270. ** Interpret the given string as a temp db location. Return 1 for file
  106271. ** backed temporary databases, 2 for the Red-Black tree in memory database
  106272. ** and 0 to use the compile-time default.
  106273. */
  106274. static int getTempStore(const char *z){
  106275. if( z[0]>='0' && z[0]<='2' ){
  106276. return z[0] - '0';
  106277. }else if( sqlite3StrICmp(z, "file")==0 ){
  106278. return 1;
  106279. }else if( sqlite3StrICmp(z, "memory")==0 ){
  106280. return 2;
  106281. }else{
  106282. return 0;
  106283. }
  106284. }
  106285. #endif /* SQLITE_PAGER_PRAGMAS */
  106286. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106287. /*
  106288. ** Invalidate temp storage, either when the temp storage is changed
  106289. ** from default, or when 'file' and the temp_store_directory has changed
  106290. */
  106291. static int invalidateTempStorage(Parse *pParse){
  106292. sqlite3 *db = pParse->db;
  106293. if( db->aDb[1].pBt!=0 ){
  106294. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  106295. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  106296. "from within a transaction");
  106297. return SQLITE_ERROR;
  106298. }
  106299. sqlite3BtreeClose(db->aDb[1].pBt);
  106300. db->aDb[1].pBt = 0;
  106301. sqlite3ResetAllSchemasOfConnection(db);
  106302. }
  106303. return SQLITE_OK;
  106304. }
  106305. #endif /* SQLITE_PAGER_PRAGMAS */
  106306. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106307. /*
  106308. ** If the TEMP database is open, close it and mark the database schema
  106309. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  106310. ** or DEFAULT_TEMP_STORE pragmas.
  106311. */
  106312. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  106313. int ts = getTempStore(zStorageType);
  106314. sqlite3 *db = pParse->db;
  106315. if( db->temp_store==ts ) return SQLITE_OK;
  106316. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  106317. return SQLITE_ERROR;
  106318. }
  106319. db->temp_store = (u8)ts;
  106320. return SQLITE_OK;
  106321. }
  106322. #endif /* SQLITE_PAGER_PRAGMAS */
  106323. /*
  106324. ** Set result column names for a pragma.
  106325. */
  106326. static void setPragmaResultColumnNames(
  106327. Vdbe *v, /* The query under construction */
  106328. const PragmaName *pPragma /* The pragma */
  106329. ){
  106330. u8 n = pPragma->nPragCName;
  106331. sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
  106332. if( n==0 ){
  106333. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
  106334. }else{
  106335. int i, j;
  106336. for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
  106337. sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
  106338. }
  106339. }
  106340. }
  106341. /*
  106342. ** Generate code to return a single integer value.
  106343. */
  106344. static void returnSingleInt(Vdbe *v, i64 value){
  106345. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  106346. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  106347. }
  106348. /*
  106349. ** Generate code to return a single text value.
  106350. */
  106351. static void returnSingleText(
  106352. Vdbe *v, /* Prepared statement under construction */
  106353. const char *zValue /* Value to be returned */
  106354. ){
  106355. if( zValue ){
  106356. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  106357. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  106358. }
  106359. }
  106360. /*
  106361. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  106362. ** set these values for all pagers.
  106363. */
  106364. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106365. static void setAllPagerFlags(sqlite3 *db){
  106366. if( db->autoCommit ){
  106367. Db *pDb = db->aDb;
  106368. int n = db->nDb;
  106369. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  106370. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  106371. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  106372. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  106373. == PAGER_FLAGS_MASK );
  106374. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  106375. while( (n--) > 0 ){
  106376. if( pDb->pBt ){
  106377. sqlite3BtreeSetPagerFlags(pDb->pBt,
  106378. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  106379. }
  106380. pDb++;
  106381. }
  106382. }
  106383. }
  106384. #else
  106385. # define setAllPagerFlags(X) /* no-op */
  106386. #endif
  106387. /*
  106388. ** Return a human-readable name for a constraint resolution action.
  106389. */
  106390. #ifndef SQLITE_OMIT_FOREIGN_KEY
  106391. static const char *actionName(u8 action){
  106392. const char *zName;
  106393. switch( action ){
  106394. case OE_SetNull: zName = "SET NULL"; break;
  106395. case OE_SetDflt: zName = "SET DEFAULT"; break;
  106396. case OE_Cascade: zName = "CASCADE"; break;
  106397. case OE_Restrict: zName = "RESTRICT"; break;
  106398. default: zName = "NO ACTION";
  106399. assert( action==OE_None ); break;
  106400. }
  106401. return zName;
  106402. }
  106403. #endif
  106404. /*
  106405. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  106406. ** defined in pager.h. This function returns the associated lowercase
  106407. ** journal-mode name.
  106408. */
  106409. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  106410. static char * const azModeName[] = {
  106411. "delete", "persist", "off", "truncate", "memory"
  106412. #ifndef SQLITE_OMIT_WAL
  106413. , "wal"
  106414. #endif
  106415. };
  106416. assert( PAGER_JOURNALMODE_DELETE==0 );
  106417. assert( PAGER_JOURNALMODE_PERSIST==1 );
  106418. assert( PAGER_JOURNALMODE_OFF==2 );
  106419. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  106420. assert( PAGER_JOURNALMODE_MEMORY==4 );
  106421. assert( PAGER_JOURNALMODE_WAL==5 );
  106422. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  106423. if( eMode==ArraySize(azModeName) ) return 0;
  106424. return azModeName[eMode];
  106425. }
  106426. /*
  106427. ** Locate a pragma in the aPragmaName[] array.
  106428. */
  106429. static const PragmaName *pragmaLocate(const char *zName){
  106430. int upr, lwr, mid = 0, rc;
  106431. lwr = 0;
  106432. upr = ArraySize(aPragmaName)-1;
  106433. while( lwr<=upr ){
  106434. mid = (lwr+upr)/2;
  106435. rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
  106436. if( rc==0 ) break;
  106437. if( rc<0 ){
  106438. upr = mid - 1;
  106439. }else{
  106440. lwr = mid + 1;
  106441. }
  106442. }
  106443. return lwr>upr ? 0 : &aPragmaName[mid];
  106444. }
  106445. /*
  106446. ** Helper subroutine for PRAGMA integrity_check:
  106447. **
  106448. ** Generate code to output a single-column result row with the result
  106449. ** held in register regResult. Decrement the result count and halt if
  106450. ** the maximum number of result rows have been issued.
  106451. */
  106452. static int integrityCheckResultRow(Vdbe *v, int regResult){
  106453. int addr;
  106454. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 1);
  106455. addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
  106456. VdbeCoverage(v);
  106457. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  106458. return addr;
  106459. }
  106460. /*
  106461. ** Process a pragma statement.
  106462. **
  106463. ** Pragmas are of this form:
  106464. **
  106465. ** PRAGMA [schema.]id [= value]
  106466. **
  106467. ** The identifier might also be a string. The value is a string, and
  106468. ** identifier, or a number. If minusFlag is true, then the value is
  106469. ** a number that was preceded by a minus sign.
  106470. **
  106471. ** If the left side is "database.id" then pId1 is the database name
  106472. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  106473. ** id and pId2 is any empty string.
  106474. */
  106475. SQLITE_PRIVATE void sqlite3Pragma(
  106476. Parse *pParse,
  106477. Token *pId1, /* First part of [schema.]id field */
  106478. Token *pId2, /* Second part of [schema.]id field, or NULL */
  106479. Token *pValue, /* Token for <value>, or NULL */
  106480. int minusFlag /* True if a '-' sign preceded <value> */
  106481. ){
  106482. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  106483. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  106484. const char *zDb = 0; /* The database name */
  106485. Token *pId; /* Pointer to <id> token */
  106486. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  106487. int iDb; /* Database index for <database> */
  106488. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  106489. sqlite3 *db = pParse->db; /* The database connection */
  106490. Db *pDb; /* The specific database being pragmaed */
  106491. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  106492. const PragmaName *pPragma; /* The pragma */
  106493. if( v==0 ) return;
  106494. sqlite3VdbeRunOnlyOnce(v);
  106495. pParse->nMem = 2;
  106496. /* Interpret the [schema.] part of the pragma statement. iDb is the
  106497. ** index of the database this pragma is being applied to in db.aDb[]. */
  106498. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  106499. if( iDb<0 ) return;
  106500. pDb = &db->aDb[iDb];
  106501. /* If the temp database has been explicitly named as part of the
  106502. ** pragma, make sure it is open.
  106503. */
  106504. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  106505. return;
  106506. }
  106507. zLeft = sqlite3NameFromToken(db, pId);
  106508. if( !zLeft ) return;
  106509. if( minusFlag ){
  106510. zRight = sqlite3MPrintf(db, "-%T", pValue);
  106511. }else{
  106512. zRight = sqlite3NameFromToken(db, pValue);
  106513. }
  106514. assert( pId2 );
  106515. zDb = pId2->n>0 ? pDb->zDbSName : 0;
  106516. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  106517. goto pragma_out;
  106518. }
  106519. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  106520. ** connection. If it returns SQLITE_OK, then assume that the VFS
  106521. ** handled the pragma and generate a no-op prepared statement.
  106522. **
  106523. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  106524. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  106525. ** object corresponding to the database file to which the pragma
  106526. ** statement refers.
  106527. **
  106528. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  106529. ** file control is an array of pointers to strings (char**) in which the
  106530. ** second element of the array is the name of the pragma and the third
  106531. ** element is the argument to the pragma or NULL if the pragma has no
  106532. ** argument.
  106533. */
  106534. aFcntl[0] = 0;
  106535. aFcntl[1] = zLeft;
  106536. aFcntl[2] = zRight;
  106537. aFcntl[3] = 0;
  106538. db->busyHandler.nBusy = 0;
  106539. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  106540. if( rc==SQLITE_OK ){
  106541. sqlite3VdbeSetNumCols(v, 1);
  106542. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
  106543. returnSingleText(v, aFcntl[0]);
  106544. sqlite3_free(aFcntl[0]);
  106545. goto pragma_out;
  106546. }
  106547. if( rc!=SQLITE_NOTFOUND ){
  106548. if( aFcntl[0] ){
  106549. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  106550. sqlite3_free(aFcntl[0]);
  106551. }
  106552. pParse->nErr++;
  106553. pParse->rc = rc;
  106554. goto pragma_out;
  106555. }
  106556. /* Locate the pragma in the lookup table */
  106557. pPragma = pragmaLocate(zLeft);
  106558. if( pPragma==0 ) goto pragma_out;
  106559. /* Make sure the database schema is loaded if the pragma requires that */
  106560. if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
  106561. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  106562. }
  106563. /* Register the result column names for pragmas that return results */
  106564. if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
  106565. && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
  106566. ){
  106567. setPragmaResultColumnNames(v, pPragma);
  106568. }
  106569. /* Jump to the appropriate pragma handler */
  106570. switch( pPragma->ePragTyp ){
  106571. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  106572. /*
  106573. ** PRAGMA [schema.]default_cache_size
  106574. ** PRAGMA [schema.]default_cache_size=N
  106575. **
  106576. ** The first form reports the current persistent setting for the
  106577. ** page cache size. The value returned is the maximum number of
  106578. ** pages in the page cache. The second form sets both the current
  106579. ** page cache size value and the persistent page cache size value
  106580. ** stored in the database file.
  106581. **
  106582. ** Older versions of SQLite would set the default cache size to a
  106583. ** negative number to indicate synchronous=OFF. These days, synchronous
  106584. ** is always on by default regardless of the sign of the default cache
  106585. ** size. But continue to take the absolute value of the default cache
  106586. ** size of historical compatibility.
  106587. */
  106588. case PragTyp_DEFAULT_CACHE_SIZE: {
  106589. static const int iLn = VDBE_OFFSET_LINENO(2);
  106590. static const VdbeOpList getCacheSize[] = {
  106591. { OP_Transaction, 0, 0, 0}, /* 0 */
  106592. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  106593. { OP_IfPos, 1, 8, 0},
  106594. { OP_Integer, 0, 2, 0},
  106595. { OP_Subtract, 1, 2, 1},
  106596. { OP_IfPos, 1, 8, 0},
  106597. { OP_Integer, 0, 1, 0}, /* 6 */
  106598. { OP_Noop, 0, 0, 0},
  106599. { OP_ResultRow, 1, 1, 0},
  106600. };
  106601. VdbeOp *aOp;
  106602. sqlite3VdbeUsesBtree(v, iDb);
  106603. if( !zRight ){
  106604. pParse->nMem += 2;
  106605. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  106606. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  106607. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  106608. aOp[0].p1 = iDb;
  106609. aOp[1].p1 = iDb;
  106610. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  106611. }else{
  106612. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  106613. sqlite3BeginWriteOperation(pParse, 0, iDb);
  106614. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  106615. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106616. pDb->pSchema->cache_size = size;
  106617. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  106618. }
  106619. break;
  106620. }
  106621. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  106622. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106623. /*
  106624. ** PRAGMA [schema.]page_size
  106625. ** PRAGMA [schema.]page_size=N
  106626. **
  106627. ** The first form reports the current setting for the
  106628. ** database page size in bytes. The second form sets the
  106629. ** database page size value. The value can only be set if
  106630. ** the database has not yet been created.
  106631. */
  106632. case PragTyp_PAGE_SIZE: {
  106633. Btree *pBt = pDb->pBt;
  106634. assert( pBt!=0 );
  106635. if( !zRight ){
  106636. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  106637. returnSingleInt(v, size);
  106638. }else{
  106639. /* Malloc may fail when setting the page-size, as there is an internal
  106640. ** buffer that the pager module resizes using sqlite3_realloc().
  106641. */
  106642. db->nextPagesize = sqlite3Atoi(zRight);
  106643. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  106644. sqlite3OomFault(db);
  106645. }
  106646. }
  106647. break;
  106648. }
  106649. /*
  106650. ** PRAGMA [schema.]secure_delete
  106651. ** PRAGMA [schema.]secure_delete=ON/OFF
  106652. **
  106653. ** The first form reports the current setting for the
  106654. ** secure_delete flag. The second form changes the secure_delete
  106655. ** flag setting and reports thenew value.
  106656. */
  106657. case PragTyp_SECURE_DELETE: {
  106658. Btree *pBt = pDb->pBt;
  106659. int b = -1;
  106660. assert( pBt!=0 );
  106661. if( zRight ){
  106662. b = sqlite3GetBoolean(zRight, 0);
  106663. }
  106664. if( pId2->n==0 && b>=0 ){
  106665. int ii;
  106666. for(ii=0; ii<db->nDb; ii++){
  106667. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  106668. }
  106669. }
  106670. b = sqlite3BtreeSecureDelete(pBt, b);
  106671. returnSingleInt(v, b);
  106672. break;
  106673. }
  106674. /*
  106675. ** PRAGMA [schema.]max_page_count
  106676. ** PRAGMA [schema.]max_page_count=N
  106677. **
  106678. ** The first form reports the current setting for the
  106679. ** maximum number of pages in the database file. The
  106680. ** second form attempts to change this setting. Both
  106681. ** forms return the current setting.
  106682. **
  106683. ** The absolute value of N is used. This is undocumented and might
  106684. ** change. The only purpose is to provide an easy way to test
  106685. ** the sqlite3AbsInt32() function.
  106686. **
  106687. ** PRAGMA [schema.]page_count
  106688. **
  106689. ** Return the number of pages in the specified database.
  106690. */
  106691. case PragTyp_PAGE_COUNT: {
  106692. int iReg;
  106693. sqlite3CodeVerifySchema(pParse, iDb);
  106694. iReg = ++pParse->nMem;
  106695. if( sqlite3Tolower(zLeft[0])=='p' ){
  106696. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  106697. }else{
  106698. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  106699. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  106700. }
  106701. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  106702. break;
  106703. }
  106704. /*
  106705. ** PRAGMA [schema.]locking_mode
  106706. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  106707. */
  106708. case PragTyp_LOCKING_MODE: {
  106709. const char *zRet = "normal";
  106710. int eMode = getLockingMode(zRight);
  106711. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  106712. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  106713. ** the current default locking mode (which may be different to
  106714. ** the locking-mode of the main database).
  106715. */
  106716. eMode = db->dfltLockMode;
  106717. }else{
  106718. Pager *pPager;
  106719. if( pId2->n==0 ){
  106720. /* This indicates that no database name was specified as part
  106721. ** of the PRAGMA command. In this case the locking-mode must be
  106722. ** set on all attached databases, as well as the main db file.
  106723. **
  106724. ** Also, the sqlite3.dfltLockMode variable is set so that
  106725. ** any subsequently attached databases also use the specified
  106726. ** locking mode.
  106727. */
  106728. int ii;
  106729. assert(pDb==&db->aDb[0]);
  106730. for(ii=2; ii<db->nDb; ii++){
  106731. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  106732. sqlite3PagerLockingMode(pPager, eMode);
  106733. }
  106734. db->dfltLockMode = (u8)eMode;
  106735. }
  106736. pPager = sqlite3BtreePager(pDb->pBt);
  106737. eMode = sqlite3PagerLockingMode(pPager, eMode);
  106738. }
  106739. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  106740. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  106741. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  106742. zRet = "exclusive";
  106743. }
  106744. returnSingleText(v, zRet);
  106745. break;
  106746. }
  106747. /*
  106748. ** PRAGMA [schema.]journal_mode
  106749. ** PRAGMA [schema.]journal_mode =
  106750. ** (delete|persist|off|truncate|memory|wal|off)
  106751. */
  106752. case PragTyp_JOURNAL_MODE: {
  106753. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  106754. int ii; /* Loop counter */
  106755. if( zRight==0 ){
  106756. /* If there is no "=MODE" part of the pragma, do a query for the
  106757. ** current mode */
  106758. eMode = PAGER_JOURNALMODE_QUERY;
  106759. }else{
  106760. const char *zMode;
  106761. int n = sqlite3Strlen30(zRight);
  106762. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  106763. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  106764. }
  106765. if( !zMode ){
  106766. /* If the "=MODE" part does not match any known journal mode,
  106767. ** then do a query */
  106768. eMode = PAGER_JOURNALMODE_QUERY;
  106769. }
  106770. }
  106771. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  106772. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  106773. iDb = 0;
  106774. pId2->n = 1;
  106775. }
  106776. for(ii=db->nDb-1; ii>=0; ii--){
  106777. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  106778. sqlite3VdbeUsesBtree(v, ii);
  106779. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  106780. }
  106781. }
  106782. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  106783. break;
  106784. }
  106785. /*
  106786. ** PRAGMA [schema.]journal_size_limit
  106787. ** PRAGMA [schema.]journal_size_limit=N
  106788. **
  106789. ** Get or set the size limit on rollback journal files.
  106790. */
  106791. case PragTyp_JOURNAL_SIZE_LIMIT: {
  106792. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  106793. i64 iLimit = -2;
  106794. if( zRight ){
  106795. sqlite3DecOrHexToI64(zRight, &iLimit);
  106796. if( iLimit<-1 ) iLimit = -1;
  106797. }
  106798. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  106799. returnSingleInt(v, iLimit);
  106800. break;
  106801. }
  106802. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  106803. /*
  106804. ** PRAGMA [schema.]auto_vacuum
  106805. ** PRAGMA [schema.]auto_vacuum=N
  106806. **
  106807. ** Get or set the value of the database 'auto-vacuum' parameter.
  106808. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  106809. */
  106810. #ifndef SQLITE_OMIT_AUTOVACUUM
  106811. case PragTyp_AUTO_VACUUM: {
  106812. Btree *pBt = pDb->pBt;
  106813. assert( pBt!=0 );
  106814. if( !zRight ){
  106815. returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
  106816. }else{
  106817. int eAuto = getAutoVacuum(zRight);
  106818. assert( eAuto>=0 && eAuto<=2 );
  106819. db->nextAutovac = (u8)eAuto;
  106820. /* Call SetAutoVacuum() to set initialize the internal auto and
  106821. ** incr-vacuum flags. This is required in case this connection
  106822. ** creates the database file. It is important that it is created
  106823. ** as an auto-vacuum capable db.
  106824. */
  106825. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  106826. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  106827. /* When setting the auto_vacuum mode to either "full" or
  106828. ** "incremental", write the value of meta[6] in the database
  106829. ** file. Before writing to meta[6], check that meta[3] indicates
  106830. ** that this really is an auto-vacuum capable database.
  106831. */
  106832. static const int iLn = VDBE_OFFSET_LINENO(2);
  106833. static const VdbeOpList setMeta6[] = {
  106834. { OP_Transaction, 0, 1, 0}, /* 0 */
  106835. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  106836. { OP_If, 1, 0, 0}, /* 2 */
  106837. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  106838. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  106839. };
  106840. VdbeOp *aOp;
  106841. int iAddr = sqlite3VdbeCurrentAddr(v);
  106842. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  106843. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  106844. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  106845. aOp[0].p1 = iDb;
  106846. aOp[1].p1 = iDb;
  106847. aOp[2].p2 = iAddr+4;
  106848. aOp[4].p1 = iDb;
  106849. aOp[4].p3 = eAuto - 1;
  106850. sqlite3VdbeUsesBtree(v, iDb);
  106851. }
  106852. }
  106853. break;
  106854. }
  106855. #endif
  106856. /*
  106857. ** PRAGMA [schema.]incremental_vacuum(N)
  106858. **
  106859. ** Do N steps of incremental vacuuming on a database.
  106860. */
  106861. #ifndef SQLITE_OMIT_AUTOVACUUM
  106862. case PragTyp_INCREMENTAL_VACUUM: {
  106863. int iLimit, addr;
  106864. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  106865. iLimit = 0x7fffffff;
  106866. }
  106867. sqlite3BeginWriteOperation(pParse, 0, iDb);
  106868. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  106869. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  106870. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  106871. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  106872. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  106873. sqlite3VdbeJumpHere(v, addr);
  106874. break;
  106875. }
  106876. #endif
  106877. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106878. /*
  106879. ** PRAGMA [schema.]cache_size
  106880. ** PRAGMA [schema.]cache_size=N
  106881. **
  106882. ** The first form reports the current local setting for the
  106883. ** page cache size. The second form sets the local
  106884. ** page cache size value. If N is positive then that is the
  106885. ** number of pages in the cache. If N is negative, then the
  106886. ** number of pages is adjusted so that the cache uses -N kibibytes
  106887. ** of memory.
  106888. */
  106889. case PragTyp_CACHE_SIZE: {
  106890. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106891. if( !zRight ){
  106892. returnSingleInt(v, pDb->pSchema->cache_size);
  106893. }else{
  106894. int size = sqlite3Atoi(zRight);
  106895. pDb->pSchema->cache_size = size;
  106896. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  106897. }
  106898. break;
  106899. }
  106900. /*
  106901. ** PRAGMA [schema.]cache_spill
  106902. ** PRAGMA cache_spill=BOOLEAN
  106903. ** PRAGMA [schema.]cache_spill=N
  106904. **
  106905. ** The first form reports the current local setting for the
  106906. ** page cache spill size. The second form turns cache spill on
  106907. ** or off. When turnning cache spill on, the size is set to the
  106908. ** current cache_size. The third form sets a spill size that
  106909. ** may be different form the cache size.
  106910. ** If N is positive then that is the
  106911. ** number of pages in the cache. If N is negative, then the
  106912. ** number of pages is adjusted so that the cache uses -N kibibytes
  106913. ** of memory.
  106914. **
  106915. ** If the number of cache_spill pages is less then the number of
  106916. ** cache_size pages, no spilling occurs until the page count exceeds
  106917. ** the number of cache_size pages.
  106918. **
  106919. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  106920. ** not just the schema specified.
  106921. */
  106922. case PragTyp_CACHE_SPILL: {
  106923. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106924. if( !zRight ){
  106925. returnSingleInt(v,
  106926. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  106927. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  106928. }else{
  106929. int size = 1;
  106930. if( sqlite3GetInt32(zRight, &size) ){
  106931. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  106932. }
  106933. if( sqlite3GetBoolean(zRight, size!=0) ){
  106934. db->flags |= SQLITE_CacheSpill;
  106935. }else{
  106936. db->flags &= ~SQLITE_CacheSpill;
  106937. }
  106938. setAllPagerFlags(db);
  106939. }
  106940. break;
  106941. }
  106942. /*
  106943. ** PRAGMA [schema.]mmap_size(N)
  106944. **
  106945. ** Used to set mapping size limit. The mapping size limit is
  106946. ** used to limit the aggregate size of all memory mapped regions of the
  106947. ** database file. If this parameter is set to zero, then memory mapping
  106948. ** is not used at all. If N is negative, then the default memory map
  106949. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  106950. ** The parameter N is measured in bytes.
  106951. **
  106952. ** This value is advisory. The underlying VFS is free to memory map
  106953. ** as little or as much as it wants. Except, if N is set to 0 then the
  106954. ** upper layers will never invoke the xFetch interfaces to the VFS.
  106955. */
  106956. case PragTyp_MMAP_SIZE: {
  106957. sqlite3_int64 sz;
  106958. #if SQLITE_MAX_MMAP_SIZE>0
  106959. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106960. if( zRight ){
  106961. int ii;
  106962. sqlite3DecOrHexToI64(zRight, &sz);
  106963. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  106964. if( pId2->n==0 ) db->szMmap = sz;
  106965. for(ii=db->nDb-1; ii>=0; ii--){
  106966. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  106967. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  106968. }
  106969. }
  106970. }
  106971. sz = -1;
  106972. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  106973. #else
  106974. sz = 0;
  106975. rc = SQLITE_OK;
  106976. #endif
  106977. if( rc==SQLITE_OK ){
  106978. returnSingleInt(v, sz);
  106979. }else if( rc!=SQLITE_NOTFOUND ){
  106980. pParse->nErr++;
  106981. pParse->rc = rc;
  106982. }
  106983. break;
  106984. }
  106985. /*
  106986. ** PRAGMA temp_store
  106987. ** PRAGMA temp_store = "default"|"memory"|"file"
  106988. **
  106989. ** Return or set the local value of the temp_store flag. Changing
  106990. ** the local value does not make changes to the disk file and the default
  106991. ** value will be restored the next time the database is opened.
  106992. **
  106993. ** Note that it is possible for the library compile-time options to
  106994. ** override this setting
  106995. */
  106996. case PragTyp_TEMP_STORE: {
  106997. if( !zRight ){
  106998. returnSingleInt(v, db->temp_store);
  106999. }else{
  107000. changeTempStorage(pParse, zRight);
  107001. }
  107002. break;
  107003. }
  107004. /*
  107005. ** PRAGMA temp_store_directory
  107006. ** PRAGMA temp_store_directory = ""|"directory_name"
  107007. **
  107008. ** Return or set the local value of the temp_store_directory flag. Changing
  107009. ** the value sets a specific directory to be used for temporary files.
  107010. ** Setting to a null string reverts to the default temporary directory search.
  107011. ** If temporary directory is changed, then invalidateTempStorage.
  107012. **
  107013. */
  107014. case PragTyp_TEMP_STORE_DIRECTORY: {
  107015. if( !zRight ){
  107016. returnSingleText(v, sqlite3_temp_directory);
  107017. }else{
  107018. #ifndef SQLITE_OMIT_WSD
  107019. if( zRight[0] ){
  107020. int res;
  107021. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  107022. if( rc!=SQLITE_OK || res==0 ){
  107023. sqlite3ErrorMsg(pParse, "not a writable directory");
  107024. goto pragma_out;
  107025. }
  107026. }
  107027. if( SQLITE_TEMP_STORE==0
  107028. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  107029. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  107030. ){
  107031. invalidateTempStorage(pParse);
  107032. }
  107033. sqlite3_free(sqlite3_temp_directory);
  107034. if( zRight[0] ){
  107035. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  107036. }else{
  107037. sqlite3_temp_directory = 0;
  107038. }
  107039. #endif /* SQLITE_OMIT_WSD */
  107040. }
  107041. break;
  107042. }
  107043. #if SQLITE_OS_WIN
  107044. /*
  107045. ** PRAGMA data_store_directory
  107046. ** PRAGMA data_store_directory = ""|"directory_name"
  107047. **
  107048. ** Return or set the local value of the data_store_directory flag. Changing
  107049. ** the value sets a specific directory to be used for database files that
  107050. ** were specified with a relative pathname. Setting to a null string reverts
  107051. ** to the default database directory, which for database files specified with
  107052. ** a relative path will probably be based on the current directory for the
  107053. ** process. Database file specified with an absolute path are not impacted
  107054. ** by this setting, regardless of its value.
  107055. **
  107056. */
  107057. case PragTyp_DATA_STORE_DIRECTORY: {
  107058. if( !zRight ){
  107059. returnSingleText(v, sqlite3_data_directory);
  107060. }else{
  107061. #ifndef SQLITE_OMIT_WSD
  107062. if( zRight[0] ){
  107063. int res;
  107064. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  107065. if( rc!=SQLITE_OK || res==0 ){
  107066. sqlite3ErrorMsg(pParse, "not a writable directory");
  107067. goto pragma_out;
  107068. }
  107069. }
  107070. sqlite3_free(sqlite3_data_directory);
  107071. if( zRight[0] ){
  107072. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  107073. }else{
  107074. sqlite3_data_directory = 0;
  107075. }
  107076. #endif /* SQLITE_OMIT_WSD */
  107077. }
  107078. break;
  107079. }
  107080. #endif
  107081. #if SQLITE_ENABLE_LOCKING_STYLE
  107082. /*
  107083. ** PRAGMA [schema.]lock_proxy_file
  107084. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  107085. **
  107086. ** Return or set the value of the lock_proxy_file flag. Changing
  107087. ** the value sets a specific file to be used for database access locks.
  107088. **
  107089. */
  107090. case PragTyp_LOCK_PROXY_FILE: {
  107091. if( !zRight ){
  107092. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  107093. char *proxy_file_path = NULL;
  107094. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  107095. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  107096. &proxy_file_path);
  107097. returnSingleText(v, proxy_file_path);
  107098. }else{
  107099. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  107100. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  107101. int res;
  107102. if( zRight[0] ){
  107103. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  107104. zRight);
  107105. } else {
  107106. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  107107. NULL);
  107108. }
  107109. if( res!=SQLITE_OK ){
  107110. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  107111. goto pragma_out;
  107112. }
  107113. }
  107114. break;
  107115. }
  107116. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  107117. /*
  107118. ** PRAGMA [schema.]synchronous
  107119. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  107120. **
  107121. ** Return or set the local value of the synchronous flag. Changing
  107122. ** the local value does not make changes to the disk file and the
  107123. ** default value will be restored the next time the database is
  107124. ** opened.
  107125. */
  107126. case PragTyp_SYNCHRONOUS: {
  107127. if( !zRight ){
  107128. returnSingleInt(v, pDb->safety_level-1);
  107129. }else{
  107130. if( !db->autoCommit ){
  107131. sqlite3ErrorMsg(pParse,
  107132. "Safety level may not be changed inside a transaction");
  107133. }else if( iDb!=1 ){
  107134. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  107135. if( iLevel==0 ) iLevel = 1;
  107136. pDb->safety_level = iLevel;
  107137. pDb->bSyncSet = 1;
  107138. setAllPagerFlags(db);
  107139. }
  107140. }
  107141. break;
  107142. }
  107143. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  107144. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  107145. case PragTyp_FLAG: {
  107146. if( zRight==0 ){
  107147. setPragmaResultColumnNames(v, pPragma);
  107148. returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
  107149. }else{
  107150. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  107151. if( db->autoCommit==0 ){
  107152. /* Foreign key support may not be enabled or disabled while not
  107153. ** in auto-commit mode. */
  107154. mask &= ~(SQLITE_ForeignKeys);
  107155. }
  107156. #if SQLITE_USER_AUTHENTICATION
  107157. if( db->auth.authLevel==UAUTH_User ){
  107158. /* Do not allow non-admin users to modify the schema arbitrarily */
  107159. mask &= ~(SQLITE_WriteSchema);
  107160. }
  107161. #endif
  107162. if( sqlite3GetBoolean(zRight, 0) ){
  107163. db->flags |= mask;
  107164. }else{
  107165. db->flags &= ~mask;
  107166. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  107167. }
  107168. /* Many of the flag-pragmas modify the code generated by the SQL
  107169. ** compiler (eg. count_changes). So add an opcode to expire all
  107170. ** compiled SQL statements after modifying a pragma value.
  107171. */
  107172. sqlite3VdbeAddOp0(v, OP_Expire);
  107173. setAllPagerFlags(db);
  107174. }
  107175. break;
  107176. }
  107177. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  107178. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  107179. /*
  107180. ** PRAGMA table_info(<table>)
  107181. **
  107182. ** Return a single row for each column of the named table. The columns of
  107183. ** the returned data set are:
  107184. **
  107185. ** cid: Column id (numbered from left to right, starting at 0)
  107186. ** name: Column name
  107187. ** type: Column declaration type.
  107188. ** notnull: True if 'NOT NULL' is part of column declaration
  107189. ** dflt_value: The default value for the column, if any.
  107190. */
  107191. case PragTyp_TABLE_INFO: if( zRight ){
  107192. Table *pTab;
  107193. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  107194. if( pTab ){
  107195. int i, k;
  107196. int nHidden = 0;
  107197. Column *pCol;
  107198. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  107199. pParse->nMem = 6;
  107200. sqlite3CodeVerifySchema(pParse, iDb);
  107201. sqlite3ViewGetColumnNames(pParse, pTab);
  107202. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  107203. if( IsHiddenColumn(pCol) ){
  107204. nHidden++;
  107205. continue;
  107206. }
  107207. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  107208. k = 0;
  107209. }else if( pPk==0 ){
  107210. k = 1;
  107211. }else{
  107212. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  107213. }
  107214. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
  107215. sqlite3VdbeMultiLoad(v, 1, "issisi",
  107216. i-nHidden,
  107217. pCol->zName,
  107218. sqlite3ColumnType(pCol,""),
  107219. pCol->notNull ? 1 : 0,
  107220. pCol->pDflt ? pCol->pDflt->u.zToken : 0,
  107221. k);
  107222. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  107223. }
  107224. }
  107225. }
  107226. break;
  107227. #ifdef SQLITE_DEBUG
  107228. case PragTyp_STATS: {
  107229. Index *pIdx;
  107230. HashElem *i;
  107231. pParse->nMem = 5;
  107232. sqlite3CodeVerifySchema(pParse, iDb);
  107233. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  107234. Table *pTab = sqliteHashData(i);
  107235. sqlite3VdbeMultiLoad(v, 1, "ssiii",
  107236. pTab->zName,
  107237. 0,
  107238. pTab->szTabRow,
  107239. pTab->nRowLogEst,
  107240. pTab->tabFlags);
  107241. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  107242. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107243. sqlite3VdbeMultiLoad(v, 2, "siii",
  107244. pIdx->zName,
  107245. pIdx->szIdxRow,
  107246. pIdx->aiRowLogEst[0],
  107247. pIdx->hasStat1);
  107248. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  107249. }
  107250. }
  107251. }
  107252. break;
  107253. #endif
  107254. case PragTyp_INDEX_INFO: if( zRight ){
  107255. Index *pIdx;
  107256. Table *pTab;
  107257. pIdx = sqlite3FindIndex(db, zRight, zDb);
  107258. if( pIdx ){
  107259. int i;
  107260. int mx;
  107261. if( pPragma->iArg ){
  107262. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  107263. mx = pIdx->nColumn;
  107264. pParse->nMem = 6;
  107265. }else{
  107266. /* PRAGMA index_info (legacy version) */
  107267. mx = pIdx->nKeyCol;
  107268. pParse->nMem = 3;
  107269. }
  107270. pTab = pIdx->pTable;
  107271. sqlite3CodeVerifySchema(pParse, iDb);
  107272. assert( pParse->nMem<=pPragma->nPragCName );
  107273. for(i=0; i<mx; i++){
  107274. i16 cnum = pIdx->aiColumn[i];
  107275. sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
  107276. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  107277. if( pPragma->iArg ){
  107278. sqlite3VdbeMultiLoad(v, 4, "isi",
  107279. pIdx->aSortOrder[i],
  107280. pIdx->azColl[i],
  107281. i<pIdx->nKeyCol);
  107282. }
  107283. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  107284. }
  107285. }
  107286. }
  107287. break;
  107288. case PragTyp_INDEX_LIST: if( zRight ){
  107289. Index *pIdx;
  107290. Table *pTab;
  107291. int i;
  107292. pTab = sqlite3FindTable(db, zRight, zDb);
  107293. if( pTab ){
  107294. pParse->nMem = 5;
  107295. sqlite3CodeVerifySchema(pParse, iDb);
  107296. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  107297. const char *azOrigin[] = { "c", "u", "pk" };
  107298. sqlite3VdbeMultiLoad(v, 1, "isisi",
  107299. i,
  107300. pIdx->zName,
  107301. IsUniqueIndex(pIdx),
  107302. azOrigin[pIdx->idxType],
  107303. pIdx->pPartIdxWhere!=0);
  107304. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  107305. }
  107306. }
  107307. }
  107308. break;
  107309. case PragTyp_DATABASE_LIST: {
  107310. int i;
  107311. pParse->nMem = 3;
  107312. for(i=0; i<db->nDb; i++){
  107313. if( db->aDb[i].pBt==0 ) continue;
  107314. assert( db->aDb[i].zDbSName!=0 );
  107315. sqlite3VdbeMultiLoad(v, 1, "iss",
  107316. i,
  107317. db->aDb[i].zDbSName,
  107318. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  107319. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  107320. }
  107321. }
  107322. break;
  107323. case PragTyp_COLLATION_LIST: {
  107324. int i = 0;
  107325. HashElem *p;
  107326. pParse->nMem = 2;
  107327. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  107328. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  107329. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  107330. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  107331. }
  107332. }
  107333. break;
  107334. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  107335. #ifndef SQLITE_OMIT_FOREIGN_KEY
  107336. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  107337. FKey *pFK;
  107338. Table *pTab;
  107339. pTab = sqlite3FindTable(db, zRight, zDb);
  107340. if( pTab ){
  107341. pFK = pTab->pFKey;
  107342. if( pFK ){
  107343. int i = 0;
  107344. pParse->nMem = 8;
  107345. sqlite3CodeVerifySchema(pParse, iDb);
  107346. while(pFK){
  107347. int j;
  107348. for(j=0; j<pFK->nCol; j++){
  107349. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  107350. i,
  107351. j,
  107352. pFK->zTo,
  107353. pTab->aCol[pFK->aCol[j].iFrom].zName,
  107354. pFK->aCol[j].zCol,
  107355. actionName(pFK->aAction[1]), /* ON UPDATE */
  107356. actionName(pFK->aAction[0]), /* ON DELETE */
  107357. "NONE");
  107358. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  107359. }
  107360. ++i;
  107361. pFK = pFK->pNextFrom;
  107362. }
  107363. }
  107364. }
  107365. }
  107366. break;
  107367. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  107368. #ifndef SQLITE_OMIT_FOREIGN_KEY
  107369. #ifndef SQLITE_OMIT_TRIGGER
  107370. case PragTyp_FOREIGN_KEY_CHECK: {
  107371. FKey *pFK; /* A foreign key constraint */
  107372. Table *pTab; /* Child table contain "REFERENCES" keyword */
  107373. Table *pParent; /* Parent table that child points to */
  107374. Index *pIdx; /* Index in the parent table */
  107375. int i; /* Loop counter: Foreign key number for pTab */
  107376. int j; /* Loop counter: Field of the foreign key */
  107377. HashElem *k; /* Loop counter: Next table in schema */
  107378. int x; /* result variable */
  107379. int regResult; /* 3 registers to hold a result row */
  107380. int regKey; /* Register to hold key for checking the FK */
  107381. int regRow; /* Registers to hold a row from pTab */
  107382. int addrTop; /* Top of a loop checking foreign keys */
  107383. int addrOk; /* Jump here if the key is OK */
  107384. int *aiCols; /* child to parent column mapping */
  107385. regResult = pParse->nMem+1;
  107386. pParse->nMem += 4;
  107387. regKey = ++pParse->nMem;
  107388. regRow = ++pParse->nMem;
  107389. sqlite3CodeVerifySchema(pParse, iDb);
  107390. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  107391. while( k ){
  107392. if( zRight ){
  107393. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  107394. k = 0;
  107395. }else{
  107396. pTab = (Table*)sqliteHashData(k);
  107397. k = sqliteHashNext(k);
  107398. }
  107399. if( pTab==0 || pTab->pFKey==0 ) continue;
  107400. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  107401. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  107402. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  107403. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  107404. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  107405. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  107406. if( pParent==0 ) continue;
  107407. pIdx = 0;
  107408. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  107409. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  107410. if( x==0 ){
  107411. if( pIdx==0 ){
  107412. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  107413. }else{
  107414. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  107415. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  107416. }
  107417. }else{
  107418. k = 0;
  107419. break;
  107420. }
  107421. }
  107422. assert( pParse->nErr>0 || pFK==0 );
  107423. if( pFK ) break;
  107424. if( pParse->nTab<i ) pParse->nTab = i;
  107425. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  107426. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  107427. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  107428. pIdx = 0;
  107429. aiCols = 0;
  107430. if( pParent ){
  107431. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  107432. assert( x==0 );
  107433. }
  107434. addrOk = sqlite3VdbeMakeLabel(v);
  107435. /* Generate code to read the child key values into registers
  107436. ** regRow..regRow+n. If any of the child key values are NULL, this
  107437. ** row cannot cause an FK violation. Jump directly to addrOk in
  107438. ** this case. */
  107439. for(j=0; j<pFK->nCol; j++){
  107440. int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
  107441. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
  107442. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  107443. }
  107444. /* Generate code to query the parent index for a matching parent
  107445. ** key. If a match is found, jump to addrOk. */
  107446. if( pIdx ){
  107447. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  107448. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  107449. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  107450. VdbeCoverage(v);
  107451. }else if( pParent ){
  107452. int jmp = sqlite3VdbeCurrentAddr(v)+2;
  107453. sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
  107454. sqlite3VdbeGoto(v, addrOk);
  107455. assert( pFK->nCol==1 );
  107456. }
  107457. /* Generate code to report an FK violation to the caller. */
  107458. if( HasRowid(pTab) ){
  107459. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  107460. }else{
  107461. sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
  107462. }
  107463. sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
  107464. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  107465. sqlite3VdbeResolveLabel(v, addrOk);
  107466. sqlite3DbFree(db, aiCols);
  107467. }
  107468. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  107469. sqlite3VdbeJumpHere(v, addrTop);
  107470. }
  107471. }
  107472. break;
  107473. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  107474. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  107475. #ifndef NDEBUG
  107476. case PragTyp_PARSER_TRACE: {
  107477. if( zRight ){
  107478. if( sqlite3GetBoolean(zRight, 0) ){
  107479. sqlite3ParserTrace(stdout, "parser: ");
  107480. }else{
  107481. sqlite3ParserTrace(0, 0);
  107482. }
  107483. }
  107484. }
  107485. break;
  107486. #endif
  107487. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  107488. ** used will be case sensitive or not depending on the RHS.
  107489. */
  107490. case PragTyp_CASE_SENSITIVE_LIKE: {
  107491. if( zRight ){
  107492. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  107493. }
  107494. }
  107495. break;
  107496. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  107497. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  107498. #endif
  107499. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  107500. /* PRAGMA integrity_check
  107501. ** PRAGMA integrity_check(N)
  107502. ** PRAGMA quick_check
  107503. ** PRAGMA quick_check(N)
  107504. **
  107505. ** Verify the integrity of the database.
  107506. **
  107507. ** The "quick_check" is reduced version of
  107508. ** integrity_check designed to detect most database corruption
  107509. ** without the overhead of cross-checking indexes. Quick_check
  107510. ** is linear time wherease integrity_check is O(NlogN).
  107511. */
  107512. case PragTyp_INTEGRITY_CHECK: {
  107513. int i, j, addr, mxErr;
  107514. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  107515. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  107516. ** then iDb is set to the index of the database identified by <db>.
  107517. ** In this case, the integrity of database iDb only is verified by
  107518. ** the VDBE created below.
  107519. **
  107520. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  107521. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  107522. ** to -1 here, to indicate that the VDBE should verify the integrity
  107523. ** of all attached databases. */
  107524. assert( iDb>=0 );
  107525. assert( iDb==0 || pId2->z );
  107526. if( pId2->z==0 ) iDb = -1;
  107527. /* Initialize the VDBE program */
  107528. pParse->nMem = 6;
  107529. /* Set the maximum error count */
  107530. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  107531. if( zRight ){
  107532. sqlite3GetInt32(zRight, &mxErr);
  107533. if( mxErr<=0 ){
  107534. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  107535. }
  107536. }
  107537. sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
  107538. /* Do an integrity check on each database file */
  107539. for(i=0; i<db->nDb; i++){
  107540. HashElem *x;
  107541. Hash *pTbls;
  107542. int *aRoot;
  107543. int cnt = 0;
  107544. int mxIdx = 0;
  107545. int nIdx;
  107546. if( OMIT_TEMPDB && i==1 ) continue;
  107547. if( iDb>=0 && i!=iDb ) continue;
  107548. sqlite3CodeVerifySchema(pParse, i);
  107549. /* Do an integrity check of the B-Tree
  107550. **
  107551. ** Begin by finding the root pages numbers
  107552. ** for all tables and indices in the database.
  107553. */
  107554. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  107555. pTbls = &db->aDb[i].pSchema->tblHash;
  107556. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  107557. Table *pTab = sqliteHashData(x);
  107558. Index *pIdx;
  107559. if( HasRowid(pTab) ) cnt++;
  107560. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  107561. if( nIdx>mxIdx ) mxIdx = nIdx;
  107562. }
  107563. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  107564. if( aRoot==0 ) break;
  107565. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  107566. Table *pTab = sqliteHashData(x);
  107567. Index *pIdx;
  107568. if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
  107569. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107570. aRoot[cnt++] = pIdx->tnum;
  107571. }
  107572. }
  107573. aRoot[cnt] = 0;
  107574. /* Make sure sufficient number of registers have been allocated */
  107575. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  107576. /* Do the b-tree integrity checks */
  107577. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  107578. sqlite3VdbeChangeP5(v, (u8)i);
  107579. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  107580. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  107581. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  107582. P4_DYNAMIC);
  107583. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  107584. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  107585. integrityCheckResultRow(v, 2);
  107586. sqlite3VdbeJumpHere(v, addr);
  107587. /* Make sure all the indices are constructed correctly.
  107588. */
  107589. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  107590. Table *pTab = sqliteHashData(x);
  107591. Index *pIdx, *pPk;
  107592. Index *pPrior = 0;
  107593. int loopTop;
  107594. int iDataCur, iIdxCur;
  107595. int r1 = -1;
  107596. if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
  107597. if( pTab->pCheck==0
  107598. && (pTab->tabFlags & TF_HasNotNull)==0
  107599. && (pTab->pIndex==0 || isQuick)
  107600. ){
  107601. continue; /* No additional checks needed for this table */
  107602. }
  107603. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  107604. sqlite3ExprCacheClear(pParse);
  107605. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  107606. 1, 0, &iDataCur, &iIdxCur);
  107607. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  107608. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  107609. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  107610. }
  107611. assert( pParse->nMem>=8+j );
  107612. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  107613. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  107614. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  107615. /* Verify that all NOT NULL columns really are NOT NULL */
  107616. for(j=0; j<pTab->nCol; j++){
  107617. char *zErr;
  107618. int jmp2;
  107619. if( j==pTab->iPKey ) continue;
  107620. if( pTab->aCol[j].notNull==0 ) continue;
  107621. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  107622. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  107623. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  107624. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  107625. pTab->aCol[j].zName);
  107626. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  107627. integrityCheckResultRow(v, 3);
  107628. sqlite3VdbeJumpHere(v, jmp2);
  107629. }
  107630. /* Verify CHECK constraints */
  107631. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  107632. ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
  107633. if( db->mallocFailed==0 ){
  107634. int addrCkFault = sqlite3VdbeMakeLabel(v);
  107635. int addrCkOk = sqlite3VdbeMakeLabel(v);
  107636. char *zErr;
  107637. int k;
  107638. pParse->iSelfTab = iDataCur;
  107639. sqlite3ExprCachePush(pParse);
  107640. for(k=pCheck->nExpr-1; k>0; k--){
  107641. sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
  107642. }
  107643. sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
  107644. SQLITE_JUMPIFNULL);
  107645. sqlite3VdbeResolveLabel(v, addrCkFault);
  107646. zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
  107647. pTab->zName);
  107648. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  107649. integrityCheckResultRow(v, 3);
  107650. sqlite3VdbeResolveLabel(v, addrCkOk);
  107651. sqlite3ExprCachePop(pParse);
  107652. }
  107653. sqlite3ExprListDelete(db, pCheck);
  107654. }
  107655. /* Validate index entries for the current row */
  107656. for(j=0, pIdx=pTab->pIndex; pIdx && !isQuick; pIdx=pIdx->pNext, j++){
  107657. int jmp2, jmp3, jmp4, jmp5;
  107658. int ckUniq = sqlite3VdbeMakeLabel(v);
  107659. if( pPk==pIdx ) continue;
  107660. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  107661. pPrior, r1);
  107662. pPrior = pIdx;
  107663. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
  107664. /* Verify that an index entry exists for the current table row */
  107665. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  107666. pIdx->nColumn); VdbeCoverage(v);
  107667. sqlite3VdbeLoadString(v, 3, "row ");
  107668. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  107669. sqlite3VdbeLoadString(v, 4, " missing from index ");
  107670. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  107671. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  107672. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  107673. jmp4 = integrityCheckResultRow(v, 3);
  107674. sqlite3VdbeJumpHere(v, jmp2);
  107675. /* For UNIQUE indexes, verify that only one entry exists with the
  107676. ** current key. The entry is unique if (1) any column is NULL
  107677. ** or (2) the next entry has a different key */
  107678. if( IsUniqueIndex(pIdx) ){
  107679. int uniqOk = sqlite3VdbeMakeLabel(v);
  107680. int jmp6;
  107681. int kk;
  107682. for(kk=0; kk<pIdx->nKeyCol; kk++){
  107683. int iCol = pIdx->aiColumn[kk];
  107684. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  107685. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  107686. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  107687. VdbeCoverage(v);
  107688. }
  107689. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  107690. sqlite3VdbeGoto(v, uniqOk);
  107691. sqlite3VdbeJumpHere(v, jmp6);
  107692. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  107693. pIdx->nKeyCol); VdbeCoverage(v);
  107694. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  107695. sqlite3VdbeGoto(v, jmp5);
  107696. sqlite3VdbeResolveLabel(v, uniqOk);
  107697. }
  107698. sqlite3VdbeJumpHere(v, jmp4);
  107699. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  107700. }
  107701. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  107702. sqlite3VdbeJumpHere(v, loopTop-1);
  107703. #ifndef SQLITE_OMIT_BTREECOUNT
  107704. if( !isQuick ){
  107705. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  107706. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  107707. if( pPk==pIdx ) continue;
  107708. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  107709. addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
  107710. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  107711. sqlite3VdbeLoadString(v, 3, pIdx->zName);
  107712. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  107713. integrityCheckResultRow(v, 7);
  107714. sqlite3VdbeJumpHere(v, addr);
  107715. }
  107716. }
  107717. #endif /* SQLITE_OMIT_BTREECOUNT */
  107718. }
  107719. }
  107720. {
  107721. static const int iLn = VDBE_OFFSET_LINENO(2);
  107722. static const VdbeOpList endCode[] = {
  107723. { OP_AddImm, 1, 0, 0}, /* 0 */
  107724. { OP_IfNotZero, 1, 4, 0}, /* 1 */
  107725. { OP_String8, 0, 3, 0}, /* 2 */
  107726. { OP_ResultRow, 3, 1, 0}, /* 3 */
  107727. };
  107728. VdbeOp *aOp;
  107729. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  107730. if( aOp ){
  107731. aOp[0].p2 = 1-mxErr;
  107732. aOp[2].p4type = P4_STATIC;
  107733. aOp[2].p4.z = "ok";
  107734. }
  107735. }
  107736. }
  107737. break;
  107738. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  107739. #ifndef SQLITE_OMIT_UTF16
  107740. /*
  107741. ** PRAGMA encoding
  107742. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  107743. **
  107744. ** In its first form, this pragma returns the encoding of the main
  107745. ** database. If the database is not initialized, it is initialized now.
  107746. **
  107747. ** The second form of this pragma is a no-op if the main database file
  107748. ** has not already been initialized. In this case it sets the default
  107749. ** encoding that will be used for the main database file if a new file
  107750. ** is created. If an existing main database file is opened, then the
  107751. ** default text encoding for the existing database is used.
  107752. **
  107753. ** In all cases new databases created using the ATTACH command are
  107754. ** created to use the same default text encoding as the main database. If
  107755. ** the main database has not been initialized and/or created when ATTACH
  107756. ** is executed, this is done before the ATTACH operation.
  107757. **
  107758. ** In the second form this pragma sets the text encoding to be used in
  107759. ** new database files created using this database handle. It is only
  107760. ** useful if invoked immediately after the main database i
  107761. */
  107762. case PragTyp_ENCODING: {
  107763. static const struct EncName {
  107764. char *zName;
  107765. u8 enc;
  107766. } encnames[] = {
  107767. { "UTF8", SQLITE_UTF8 },
  107768. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  107769. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  107770. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  107771. { "UTF16le", SQLITE_UTF16LE },
  107772. { "UTF16be", SQLITE_UTF16BE },
  107773. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  107774. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  107775. { 0, 0 }
  107776. };
  107777. const struct EncName *pEnc;
  107778. if( !zRight ){ /* "PRAGMA encoding" */
  107779. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  107780. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  107781. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  107782. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  107783. returnSingleText(v, encnames[ENC(pParse->db)].zName);
  107784. }else{ /* "PRAGMA encoding = XXX" */
  107785. /* Only change the value of sqlite.enc if the database handle is not
  107786. ** initialized. If the main database exists, the new sqlite.enc value
  107787. ** will be overwritten when the schema is next loaded. If it does not
  107788. ** already exists, it will be created to use the new encoding value.
  107789. */
  107790. if(
  107791. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  107792. DbHasProperty(db, 0, DB_Empty)
  107793. ){
  107794. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  107795. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  107796. SCHEMA_ENC(db) = ENC(db) =
  107797. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  107798. break;
  107799. }
  107800. }
  107801. if( !pEnc->zName ){
  107802. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  107803. }
  107804. }
  107805. }
  107806. }
  107807. break;
  107808. #endif /* SQLITE_OMIT_UTF16 */
  107809. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  107810. /*
  107811. ** PRAGMA [schema.]schema_version
  107812. ** PRAGMA [schema.]schema_version = <integer>
  107813. **
  107814. ** PRAGMA [schema.]user_version
  107815. ** PRAGMA [schema.]user_version = <integer>
  107816. **
  107817. ** PRAGMA [schema.]freelist_count
  107818. **
  107819. ** PRAGMA [schema.]data_version
  107820. **
  107821. ** PRAGMA [schema.]application_id
  107822. ** PRAGMA [schema.]application_id = <integer>
  107823. **
  107824. ** The pragma's schema_version and user_version are used to set or get
  107825. ** the value of the schema-version and user-version, respectively. Both
  107826. ** the schema-version and the user-version are 32-bit signed integers
  107827. ** stored in the database header.
  107828. **
  107829. ** The schema-cookie is usually only manipulated internally by SQLite. It
  107830. ** is incremented by SQLite whenever the database schema is modified (by
  107831. ** creating or dropping a table or index). The schema version is used by
  107832. ** SQLite each time a query is executed to ensure that the internal cache
  107833. ** of the schema used when compiling the SQL query matches the schema of
  107834. ** the database against which the compiled query is actually executed.
  107835. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  107836. ** the schema-version is potentially dangerous and may lead to program
  107837. ** crashes or database corruption. Use with caution!
  107838. **
  107839. ** The user-version is not used internally by SQLite. It may be used by
  107840. ** applications for any purpose.
  107841. */
  107842. case PragTyp_HEADER_VALUE: {
  107843. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  107844. sqlite3VdbeUsesBtree(v, iDb);
  107845. if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
  107846. /* Write the specified cookie value */
  107847. static const VdbeOpList setCookie[] = {
  107848. { OP_Transaction, 0, 1, 0}, /* 0 */
  107849. { OP_SetCookie, 0, 0, 0}, /* 1 */
  107850. };
  107851. VdbeOp *aOp;
  107852. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  107853. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  107854. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  107855. aOp[0].p1 = iDb;
  107856. aOp[1].p1 = iDb;
  107857. aOp[1].p2 = iCookie;
  107858. aOp[1].p3 = sqlite3Atoi(zRight);
  107859. }else{
  107860. /* Read the specified cookie value */
  107861. static const VdbeOpList readCookie[] = {
  107862. { OP_Transaction, 0, 0, 0}, /* 0 */
  107863. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  107864. { OP_ResultRow, 1, 1, 0}
  107865. };
  107866. VdbeOp *aOp;
  107867. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  107868. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  107869. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  107870. aOp[0].p1 = iDb;
  107871. aOp[1].p1 = iDb;
  107872. aOp[1].p3 = iCookie;
  107873. sqlite3VdbeReusable(v);
  107874. }
  107875. }
  107876. break;
  107877. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  107878. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  107879. /*
  107880. ** PRAGMA compile_options
  107881. **
  107882. ** Return the names of all compile-time options used in this build,
  107883. ** one option per row.
  107884. */
  107885. case PragTyp_COMPILE_OPTIONS: {
  107886. int i = 0;
  107887. const char *zOpt;
  107888. pParse->nMem = 1;
  107889. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  107890. sqlite3VdbeLoadString(v, 1, zOpt);
  107891. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  107892. }
  107893. sqlite3VdbeReusable(v);
  107894. }
  107895. break;
  107896. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  107897. #ifndef SQLITE_OMIT_WAL
  107898. /*
  107899. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  107900. **
  107901. ** Checkpoint the database.
  107902. */
  107903. case PragTyp_WAL_CHECKPOINT: {
  107904. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  107905. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  107906. if( zRight ){
  107907. if( sqlite3StrICmp(zRight, "full")==0 ){
  107908. eMode = SQLITE_CHECKPOINT_FULL;
  107909. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  107910. eMode = SQLITE_CHECKPOINT_RESTART;
  107911. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  107912. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  107913. }
  107914. }
  107915. pParse->nMem = 3;
  107916. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  107917. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  107918. }
  107919. break;
  107920. /*
  107921. ** PRAGMA wal_autocheckpoint
  107922. ** PRAGMA wal_autocheckpoint = N
  107923. **
  107924. ** Configure a database connection to automatically checkpoint a database
  107925. ** after accumulating N frames in the log. Or query for the current value
  107926. ** of N.
  107927. */
  107928. case PragTyp_WAL_AUTOCHECKPOINT: {
  107929. if( zRight ){
  107930. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  107931. }
  107932. returnSingleInt(v,
  107933. db->xWalCallback==sqlite3WalDefaultHook ?
  107934. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  107935. }
  107936. break;
  107937. #endif
  107938. /*
  107939. ** PRAGMA shrink_memory
  107940. **
  107941. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  107942. ** connection on which it is invoked to free up as much memory as it
  107943. ** can, by calling sqlite3_db_release_memory().
  107944. */
  107945. case PragTyp_SHRINK_MEMORY: {
  107946. sqlite3_db_release_memory(db);
  107947. break;
  107948. }
  107949. /*
  107950. ** PRAGMA optimize
  107951. ** PRAGMA optimize(MASK)
  107952. ** PRAGMA schema.optimize
  107953. ** PRAGMA schema.optimize(MASK)
  107954. **
  107955. ** Attempt to optimize the database. All schemas are optimized in the first
  107956. ** two forms, and only the specified schema is optimized in the latter two.
  107957. **
  107958. ** The details of optimizations performed by this pragma are expected
  107959. ** to change and improve over time. Applications should anticipate that
  107960. ** this pragma will perform new optimizations in future releases.
  107961. **
  107962. ** The optional argument is a bitmask of optimizations to perform:
  107963. **
  107964. ** 0x0001 Debugging mode. Do not actually perform any optimizations
  107965. ** but instead return one line of text for each optimization
  107966. ** that would have been done. Off by default.
  107967. **
  107968. ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
  107969. ** See below for additional information.
  107970. **
  107971. ** 0x0004 (Not yet implemented) Record usage and performance
  107972. ** information from the current session in the
  107973. ** database file so that it will be available to "optimize"
  107974. ** pragmas run by future database connections.
  107975. **
  107976. ** 0x0008 (Not yet implemented) Create indexes that might have
  107977. ** been helpful to recent queries
  107978. **
  107979. ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all ** of the optimizations listed above except Debug Mode, including new
  107980. ** optimizations that have not yet been invented. If new optimizations are
  107981. ** ever added that should be off by default, those off-by-default
  107982. ** optimizations will have bitmasks of 0x10000 or larger.
  107983. **
  107984. ** DETERMINATION OF WHEN TO RUN ANALYZE
  107985. **
  107986. ** In the current implementation, a table is analyzed if only if all of
  107987. ** the following are true:
  107988. **
  107989. ** (1) MASK bit 0x02 is set.
  107990. **
  107991. ** (2) The query planner used sqlite_stat1-style statistics for one or
  107992. ** more indexes of the table at some point during the lifetime of
  107993. ** the current connection.
  107994. **
  107995. ** (3) One or more indexes of the table are currently unanalyzed OR
  107996. ** the number of rows in the table has increased by 25 times or more
  107997. ** since the last time ANALYZE was run.
  107998. **
  107999. ** The rules for when tables are analyzed are likely to change in
  108000. ** future releases.
  108001. */
  108002. case PragTyp_OPTIMIZE: {
  108003. int iDbLast; /* Loop termination point for the schema loop */
  108004. int iTabCur; /* Cursor for a table whose size needs checking */
  108005. HashElem *k; /* Loop over tables of a schema */
  108006. Schema *pSchema; /* The current schema */
  108007. Table *pTab; /* A table in the schema */
  108008. Index *pIdx; /* An index of the table */
  108009. LogEst szThreshold; /* Size threshold above which reanalysis is needd */
  108010. char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
  108011. u32 opMask; /* Mask of operations to perform */
  108012. if( zRight ){
  108013. opMask = (u32)sqlite3Atoi(zRight);
  108014. if( (opMask & 0x02)==0 ) break;
  108015. }else{
  108016. opMask = 0xfffe;
  108017. }
  108018. iTabCur = pParse->nTab++;
  108019. for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
  108020. if( iDb==1 ) continue;
  108021. sqlite3CodeVerifySchema(pParse, iDb);
  108022. pSchema = db->aDb[iDb].pSchema;
  108023. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  108024. pTab = (Table*)sqliteHashData(k);
  108025. /* If table pTab has not been used in a way that would benefit from
  108026. ** having analysis statistics during the current session, then skip it.
  108027. ** This also has the effect of skipping virtual tables and views */
  108028. if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
  108029. /* Reanalyze if the table is 25 times larger than the last analysis */
  108030. szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
  108031. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  108032. if( !pIdx->hasStat1 ){
  108033. szThreshold = 0; /* Always analyze if any index lacks statistics */
  108034. break;
  108035. }
  108036. }
  108037. if( szThreshold ){
  108038. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  108039. sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
  108040. sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
  108041. VdbeCoverage(v);
  108042. }
  108043. zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
  108044. db->aDb[iDb].zDbSName, pTab->zName);
  108045. if( opMask & 0x01 ){
  108046. int r1 = sqlite3GetTempReg(pParse);
  108047. sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
  108048. sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
  108049. }else{
  108050. sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
  108051. }
  108052. }
  108053. }
  108054. sqlite3VdbeAddOp0(v, OP_Expire);
  108055. break;
  108056. }
  108057. /*
  108058. ** PRAGMA busy_timeout
  108059. ** PRAGMA busy_timeout = N
  108060. **
  108061. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  108062. ** if one is set. If no busy handler or a different busy handler is set
  108063. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  108064. ** disables the timeout.
  108065. */
  108066. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  108067. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  108068. if( zRight ){
  108069. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  108070. }
  108071. returnSingleInt(v, db->busyTimeout);
  108072. break;
  108073. }
  108074. /*
  108075. ** PRAGMA soft_heap_limit
  108076. ** PRAGMA soft_heap_limit = N
  108077. **
  108078. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  108079. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  108080. ** specified and is a non-negative integer.
  108081. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  108082. ** returns the same integer that would be returned by the
  108083. ** sqlite3_soft_heap_limit64(-1) C-language function.
  108084. */
  108085. case PragTyp_SOFT_HEAP_LIMIT: {
  108086. sqlite3_int64 N;
  108087. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  108088. sqlite3_soft_heap_limit64(N);
  108089. }
  108090. returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
  108091. break;
  108092. }
  108093. /*
  108094. ** PRAGMA threads
  108095. ** PRAGMA threads = N
  108096. **
  108097. ** Configure the maximum number of worker threads. Return the new
  108098. ** maximum, which might be less than requested.
  108099. */
  108100. case PragTyp_THREADS: {
  108101. sqlite3_int64 N;
  108102. if( zRight
  108103. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  108104. && N>=0
  108105. ){
  108106. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  108107. }
  108108. returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  108109. break;
  108110. }
  108111. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  108112. /*
  108113. ** Report the current state of file logs for all databases
  108114. */
  108115. case PragTyp_LOCK_STATUS: {
  108116. static const char *const azLockName[] = {
  108117. "unlocked", "shared", "reserved", "pending", "exclusive"
  108118. };
  108119. int i;
  108120. pParse->nMem = 2;
  108121. for(i=0; i<db->nDb; i++){
  108122. Btree *pBt;
  108123. const char *zState = "unknown";
  108124. int j;
  108125. if( db->aDb[i].zDbSName==0 ) continue;
  108126. pBt = db->aDb[i].pBt;
  108127. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  108128. zState = "closed";
  108129. }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
  108130. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  108131. zState = azLockName[j];
  108132. }
  108133. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  108134. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  108135. }
  108136. break;
  108137. }
  108138. #endif
  108139. #ifdef SQLITE_HAS_CODEC
  108140. case PragTyp_KEY: {
  108141. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  108142. break;
  108143. }
  108144. case PragTyp_REKEY: {
  108145. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  108146. break;
  108147. }
  108148. case PragTyp_HEXKEY: {
  108149. if( zRight ){
  108150. u8 iByte;
  108151. int i;
  108152. char zKey[40];
  108153. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  108154. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  108155. if( (i&1)!=0 ) zKey[i/2] = iByte;
  108156. }
  108157. if( (zLeft[3] & 0xf)==0xb ){
  108158. sqlite3_key_v2(db, zDb, zKey, i/2);
  108159. }else{
  108160. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  108161. }
  108162. }
  108163. break;
  108164. }
  108165. #endif
  108166. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  108167. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  108168. #ifdef SQLITE_HAS_CODEC
  108169. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  108170. sqlite3_activate_see(&zRight[4]);
  108171. }
  108172. #endif
  108173. #ifdef SQLITE_ENABLE_CEROD
  108174. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  108175. sqlite3_activate_cerod(&zRight[6]);
  108176. }
  108177. #endif
  108178. }
  108179. break;
  108180. #endif
  108181. } /* End of the PRAGMA switch */
  108182. /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
  108183. ** purpose is to execute assert() statements to verify that if the
  108184. ** PragFlg_NoColumns1 flag is set and the caller specified an argument
  108185. ** to the PRAGMA, the implementation has not added any OP_ResultRow
  108186. ** instructions to the VM. */
  108187. if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
  108188. sqlite3VdbeVerifyNoResultRow(v);
  108189. }
  108190. pragma_out:
  108191. sqlite3DbFree(db, zLeft);
  108192. sqlite3DbFree(db, zRight);
  108193. }
  108194. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108195. /*****************************************************************************
  108196. ** Implementation of an eponymous virtual table that runs a pragma.
  108197. **
  108198. */
  108199. typedef struct PragmaVtab PragmaVtab;
  108200. typedef struct PragmaVtabCursor PragmaVtabCursor;
  108201. struct PragmaVtab {
  108202. sqlite3_vtab base; /* Base class. Must be first */
  108203. sqlite3 *db; /* The database connection to which it belongs */
  108204. const PragmaName *pName; /* Name of the pragma */
  108205. u8 nHidden; /* Number of hidden columns */
  108206. u8 iHidden; /* Index of the first hidden column */
  108207. };
  108208. struct PragmaVtabCursor {
  108209. sqlite3_vtab_cursor base; /* Base class. Must be first */
  108210. sqlite3_stmt *pPragma; /* The pragma statement to run */
  108211. sqlite_int64 iRowid; /* Current rowid */
  108212. char *azArg[2]; /* Value of the argument and schema */
  108213. };
  108214. /*
  108215. ** Pragma virtual table module xConnect method.
  108216. */
  108217. static int pragmaVtabConnect(
  108218. sqlite3 *db,
  108219. void *pAux,
  108220. int argc, const char *const*argv,
  108221. sqlite3_vtab **ppVtab,
  108222. char **pzErr
  108223. ){
  108224. const PragmaName *pPragma = (const PragmaName*)pAux;
  108225. PragmaVtab *pTab = 0;
  108226. int rc;
  108227. int i, j;
  108228. char cSep = '(';
  108229. StrAccum acc;
  108230. char zBuf[200];
  108231. UNUSED_PARAMETER(argc);
  108232. UNUSED_PARAMETER(argv);
  108233. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  108234. sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
  108235. for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
  108236. sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
  108237. cSep = ',';
  108238. }
  108239. if( i==0 ){
  108240. sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
  108241. cSep = ',';
  108242. i++;
  108243. }
  108244. j = 0;
  108245. if( pPragma->mPragFlg & PragFlg_Result1 ){
  108246. sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
  108247. j++;
  108248. }
  108249. if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
  108250. sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
  108251. j++;
  108252. }
  108253. sqlite3StrAccumAppend(&acc, ")", 1);
  108254. sqlite3StrAccumFinish(&acc);
  108255. assert( strlen(zBuf) < sizeof(zBuf)-1 );
  108256. rc = sqlite3_declare_vtab(db, zBuf);
  108257. if( rc==SQLITE_OK ){
  108258. pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
  108259. if( pTab==0 ){
  108260. rc = SQLITE_NOMEM;
  108261. }else{
  108262. memset(pTab, 0, sizeof(PragmaVtab));
  108263. pTab->pName = pPragma;
  108264. pTab->db = db;
  108265. pTab->iHidden = i;
  108266. pTab->nHidden = j;
  108267. }
  108268. }else{
  108269. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  108270. }
  108271. *ppVtab = (sqlite3_vtab*)pTab;
  108272. return rc;
  108273. }
  108274. /*
  108275. ** Pragma virtual table module xDisconnect method.
  108276. */
  108277. static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
  108278. PragmaVtab *pTab = (PragmaVtab*)pVtab;
  108279. sqlite3_free(pTab);
  108280. return SQLITE_OK;
  108281. }
  108282. /* Figure out the best index to use to search a pragma virtual table.
  108283. **
  108284. ** There are not really any index choices. But we want to encourage the
  108285. ** query planner to give == constraints on as many hidden parameters as
  108286. ** possible, and especially on the first hidden parameter. So return a
  108287. ** high cost if hidden parameters are unconstrained.
  108288. */
  108289. static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  108290. PragmaVtab *pTab = (PragmaVtab*)tab;
  108291. const struct sqlite3_index_constraint *pConstraint;
  108292. int i, j;
  108293. int seen[2];
  108294. pIdxInfo->estimatedCost = (double)1;
  108295. if( pTab->nHidden==0 ){ return SQLITE_OK; }
  108296. pConstraint = pIdxInfo->aConstraint;
  108297. seen[0] = 0;
  108298. seen[1] = 0;
  108299. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  108300. if( pConstraint->usable==0 ) continue;
  108301. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  108302. if( pConstraint->iColumn < pTab->iHidden ) continue;
  108303. j = pConstraint->iColumn - pTab->iHidden;
  108304. assert( j < 2 );
  108305. seen[j] = i+1;
  108306. }
  108307. if( seen[0]==0 ){
  108308. pIdxInfo->estimatedCost = (double)2147483647;
  108309. pIdxInfo->estimatedRows = 2147483647;
  108310. return SQLITE_OK;
  108311. }
  108312. j = seen[0]-1;
  108313. pIdxInfo->aConstraintUsage[j].argvIndex = 1;
  108314. pIdxInfo->aConstraintUsage[j].omit = 1;
  108315. if( seen[1]==0 ) return SQLITE_OK;
  108316. pIdxInfo->estimatedCost = (double)20;
  108317. pIdxInfo->estimatedRows = 20;
  108318. j = seen[1]-1;
  108319. pIdxInfo->aConstraintUsage[j].argvIndex = 2;
  108320. pIdxInfo->aConstraintUsage[j].omit = 1;
  108321. return SQLITE_OK;
  108322. }
  108323. /* Create a new cursor for the pragma virtual table */
  108324. static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
  108325. PragmaVtabCursor *pCsr;
  108326. pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
  108327. if( pCsr==0 ) return SQLITE_NOMEM;
  108328. memset(pCsr, 0, sizeof(PragmaVtabCursor));
  108329. pCsr->base.pVtab = pVtab;
  108330. *ppCursor = &pCsr->base;
  108331. return SQLITE_OK;
  108332. }
  108333. /* Clear all content from pragma virtual table cursor. */
  108334. static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  108335. int i;
  108336. sqlite3_finalize(pCsr->pPragma);
  108337. pCsr->pPragma = 0;
  108338. for(i=0; i<ArraySize(pCsr->azArg); i++){
  108339. sqlite3_free(pCsr->azArg[i]);
  108340. pCsr->azArg[i] = 0;
  108341. }
  108342. }
  108343. /* Close a pragma virtual table cursor */
  108344. static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
  108345. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
  108346. pragmaVtabCursorClear(pCsr);
  108347. sqlite3_free(pCsr);
  108348. return SQLITE_OK;
  108349. }
  108350. /* Advance the pragma virtual table cursor to the next row */
  108351. static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
  108352. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108353. int rc = SQLITE_OK;
  108354. /* Increment the xRowid value */
  108355. pCsr->iRowid++;
  108356. assert( pCsr->pPragma );
  108357. if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
  108358. rc = sqlite3_finalize(pCsr->pPragma);
  108359. pCsr->pPragma = 0;
  108360. pragmaVtabCursorClear(pCsr);
  108361. }
  108362. return rc;
  108363. }
  108364. /*
  108365. ** Pragma virtual table module xFilter method.
  108366. */
  108367. static int pragmaVtabFilter(
  108368. sqlite3_vtab_cursor *pVtabCursor,
  108369. int idxNum, const char *idxStr,
  108370. int argc, sqlite3_value **argv
  108371. ){
  108372. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108373. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  108374. int rc;
  108375. int i, j;
  108376. StrAccum acc;
  108377. char *zSql;
  108378. UNUSED_PARAMETER(idxNum);
  108379. UNUSED_PARAMETER(idxStr);
  108380. pragmaVtabCursorClear(pCsr);
  108381. j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
  108382. for(i=0; i<argc; i++, j++){
  108383. assert( j<ArraySize(pCsr->azArg) );
  108384. pCsr->azArg[j] = sqlite3_mprintf("%s", sqlite3_value_text(argv[i]));
  108385. if( pCsr->azArg[j]==0 ){
  108386. return SQLITE_NOMEM;
  108387. }
  108388. }
  108389. sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
  108390. sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
  108391. if( pCsr->azArg[1] ){
  108392. sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
  108393. }
  108394. sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
  108395. if( pCsr->azArg[0] ){
  108396. sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
  108397. }
  108398. zSql = sqlite3StrAccumFinish(&acc);
  108399. if( zSql==0 ) return SQLITE_NOMEM;
  108400. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
  108401. sqlite3_free(zSql);
  108402. if( rc!=SQLITE_OK ){
  108403. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  108404. return rc;
  108405. }
  108406. return pragmaVtabNext(pVtabCursor);
  108407. }
  108408. /*
  108409. ** Pragma virtual table module xEof method.
  108410. */
  108411. static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
  108412. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108413. return (pCsr->pPragma==0);
  108414. }
  108415. /* The xColumn method simply returns the corresponding column from
  108416. ** the PRAGMA.
  108417. */
  108418. static int pragmaVtabColumn(
  108419. sqlite3_vtab_cursor *pVtabCursor,
  108420. sqlite3_context *ctx,
  108421. int i
  108422. ){
  108423. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108424. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  108425. if( i<pTab->iHidden ){
  108426. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
  108427. }else{
  108428. sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
  108429. }
  108430. return SQLITE_OK;
  108431. }
  108432. /*
  108433. ** Pragma virtual table module xRowid method.
  108434. */
  108435. static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
  108436. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108437. *p = pCsr->iRowid;
  108438. return SQLITE_OK;
  108439. }
  108440. /* The pragma virtual table object */
  108441. static const sqlite3_module pragmaVtabModule = {
  108442. 0, /* iVersion */
  108443. 0, /* xCreate - create a table */
  108444. pragmaVtabConnect, /* xConnect - connect to an existing table */
  108445. pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
  108446. pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
  108447. 0, /* xDestroy - Drop a table */
  108448. pragmaVtabOpen, /* xOpen - open a cursor */
  108449. pragmaVtabClose, /* xClose - close a cursor */
  108450. pragmaVtabFilter, /* xFilter - configure scan constraints */
  108451. pragmaVtabNext, /* xNext - advance a cursor */
  108452. pragmaVtabEof, /* xEof */
  108453. pragmaVtabColumn, /* xColumn - read data */
  108454. pragmaVtabRowid, /* xRowid - read data */
  108455. 0, /* xUpdate - write data */
  108456. 0, /* xBegin - begin transaction */
  108457. 0, /* xSync - sync transaction */
  108458. 0, /* xCommit - commit transaction */
  108459. 0, /* xRollback - rollback transaction */
  108460. 0, /* xFindFunction - function overloading */
  108461. 0, /* xRename - rename the table */
  108462. 0, /* xSavepoint */
  108463. 0, /* xRelease */
  108464. 0 /* xRollbackTo */
  108465. };
  108466. /*
  108467. ** Check to see if zTabName is really the name of a pragma. If it is,
  108468. ** then register an eponymous virtual table for that pragma and return
  108469. ** a pointer to the Module object for the new virtual table.
  108470. */
  108471. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
  108472. const PragmaName *pName;
  108473. assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
  108474. pName = pragmaLocate(zName+7);
  108475. if( pName==0 ) return 0;
  108476. if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
  108477. assert( sqlite3HashFind(&db->aModule, zName)==0 );
  108478. return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
  108479. }
  108480. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  108481. #endif /* SQLITE_OMIT_PRAGMA */
  108482. /************** End of pragma.c **********************************************/
  108483. /************** Begin file prepare.c *****************************************/
  108484. /*
  108485. ** 2005 May 25
  108486. **
  108487. ** The author disclaims copyright to this source code. In place of
  108488. ** a legal notice, here is a blessing:
  108489. **
  108490. ** May you do good and not evil.
  108491. ** May you find forgiveness for yourself and forgive others.
  108492. ** May you share freely, never taking more than you give.
  108493. **
  108494. *************************************************************************
  108495. ** This file contains the implementation of the sqlite3_prepare()
  108496. ** interface, and routines that contribute to loading the database schema
  108497. ** from disk.
  108498. */
  108499. /* #include "sqliteInt.h" */
  108500. /*
  108501. ** Fill the InitData structure with an error message that indicates
  108502. ** that the database is corrupt.
  108503. */
  108504. static void corruptSchema(
  108505. InitData *pData, /* Initialization context */
  108506. const char *zObj, /* Object being parsed at the point of error */
  108507. const char *zExtra /* Error information */
  108508. ){
  108509. sqlite3 *db = pData->db;
  108510. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  108511. char *z;
  108512. if( zObj==0 ) zObj = "?";
  108513. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  108514. if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  108515. sqlite3DbFree(db, *pData->pzErrMsg);
  108516. *pData->pzErrMsg = z;
  108517. }
  108518. pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
  108519. }
  108520. /*
  108521. ** This is the callback routine for the code that initializes the
  108522. ** database. See sqlite3Init() below for additional information.
  108523. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  108524. **
  108525. ** Each callback contains the following information:
  108526. **
  108527. ** argv[0] = name of thing being created
  108528. ** argv[1] = root page number for table or index. 0 for trigger or view.
  108529. ** argv[2] = SQL text for the CREATE statement.
  108530. **
  108531. */
  108532. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  108533. InitData *pData = (InitData*)pInit;
  108534. sqlite3 *db = pData->db;
  108535. int iDb = pData->iDb;
  108536. assert( argc==3 );
  108537. UNUSED_PARAMETER2(NotUsed, argc);
  108538. assert( sqlite3_mutex_held(db->mutex) );
  108539. DbClearProperty(db, iDb, DB_Empty);
  108540. if( db->mallocFailed ){
  108541. corruptSchema(pData, argv[0], 0);
  108542. return 1;
  108543. }
  108544. assert( iDb>=0 && iDb<db->nDb );
  108545. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  108546. if( argv[1]==0 ){
  108547. corruptSchema(pData, argv[0], 0);
  108548. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  108549. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  108550. ** But because db->init.busy is set to 1, no VDBE code is generated
  108551. ** or executed. All the parser does is build the internal data
  108552. ** structures that describe the table, index, or view.
  108553. */
  108554. int rc;
  108555. u8 saved_iDb = db->init.iDb;
  108556. sqlite3_stmt *pStmt;
  108557. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  108558. assert( db->init.busy );
  108559. db->init.iDb = iDb;
  108560. db->init.newTnum = sqlite3Atoi(argv[1]);
  108561. db->init.orphanTrigger = 0;
  108562. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  108563. rc = db->errCode;
  108564. assert( (rc&0xFF)==(rcp&0xFF) );
  108565. db->init.iDb = saved_iDb;
  108566. assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 );
  108567. if( SQLITE_OK!=rc ){
  108568. if( db->init.orphanTrigger ){
  108569. assert( iDb==1 );
  108570. }else{
  108571. pData->rc = rc;
  108572. if( rc==SQLITE_NOMEM ){
  108573. sqlite3OomFault(db);
  108574. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  108575. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  108576. }
  108577. }
  108578. }
  108579. sqlite3_finalize(pStmt);
  108580. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  108581. corruptSchema(pData, argv[0], 0);
  108582. }else{
  108583. /* If the SQL column is blank it means this is an index that
  108584. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  108585. ** constraint for a CREATE TABLE. The index should have already
  108586. ** been created when we processed the CREATE TABLE. All we have
  108587. ** to do here is record the root page number for that index.
  108588. */
  108589. Index *pIndex;
  108590. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
  108591. if( pIndex==0 ){
  108592. /* This can occur if there exists an index on a TEMP table which
  108593. ** has the same name as another index on a permanent index. Since
  108594. ** the permanent table is hidden by the TEMP table, we can also
  108595. ** safely ignore the index on the permanent table.
  108596. */
  108597. /* Do Nothing */;
  108598. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  108599. corruptSchema(pData, argv[0], "invalid rootpage");
  108600. }
  108601. }
  108602. return 0;
  108603. }
  108604. /*
  108605. ** Attempt to read the database schema and initialize internal
  108606. ** data structures for a single database file. The index of the
  108607. ** database file is given by iDb. iDb==0 is used for the main
  108608. ** database. iDb==1 should never be used. iDb>=2 is used for
  108609. ** auxiliary databases. Return one of the SQLITE_ error codes to
  108610. ** indicate success or failure.
  108611. */
  108612. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  108613. int rc;
  108614. int i;
  108615. #ifndef SQLITE_OMIT_DEPRECATED
  108616. int size;
  108617. #endif
  108618. Db *pDb;
  108619. char const *azArg[4];
  108620. int meta[5];
  108621. InitData initData;
  108622. const char *zMasterName;
  108623. int openedTransaction = 0;
  108624. assert( iDb>=0 && iDb<db->nDb );
  108625. assert( db->aDb[iDb].pSchema );
  108626. assert( sqlite3_mutex_held(db->mutex) );
  108627. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  108628. /* Construct the in-memory representation schema tables (sqlite_master or
  108629. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  108630. ** table name will be inserted automatically by the parser so we can just
  108631. ** use the abbreviation "x" here. The parser will also automatically tag
  108632. ** the schema table as read-only. */
  108633. azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
  108634. azArg[1] = "1";
  108635. azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
  108636. "rootpage integer,sql text)";
  108637. azArg[3] = 0;
  108638. initData.db = db;
  108639. initData.iDb = iDb;
  108640. initData.rc = SQLITE_OK;
  108641. initData.pzErrMsg = pzErrMsg;
  108642. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  108643. if( initData.rc ){
  108644. rc = initData.rc;
  108645. goto error_out;
  108646. }
  108647. /* Create a cursor to hold the database open
  108648. */
  108649. pDb = &db->aDb[iDb];
  108650. if( pDb->pBt==0 ){
  108651. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  108652. DbSetProperty(db, 1, DB_SchemaLoaded);
  108653. }
  108654. return SQLITE_OK;
  108655. }
  108656. /* If there is not already a read-only (or read-write) transaction opened
  108657. ** on the b-tree database, open one now. If a transaction is opened, it
  108658. ** will be closed before this function returns. */
  108659. sqlite3BtreeEnter(pDb->pBt);
  108660. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  108661. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  108662. if( rc!=SQLITE_OK ){
  108663. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  108664. goto initone_error_out;
  108665. }
  108666. openedTransaction = 1;
  108667. }
  108668. /* Get the database meta information.
  108669. **
  108670. ** Meta values are as follows:
  108671. ** meta[0] Schema cookie. Changes with each schema change.
  108672. ** meta[1] File format of schema layer.
  108673. ** meta[2] Size of the page cache.
  108674. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  108675. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  108676. ** meta[5] User version
  108677. ** meta[6] Incremental vacuum mode
  108678. ** meta[7] unused
  108679. ** meta[8] unused
  108680. ** meta[9] unused
  108681. **
  108682. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  108683. ** the possible values of meta[4].
  108684. */
  108685. for(i=0; i<ArraySize(meta); i++){
  108686. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  108687. }
  108688. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  108689. /* If opening a non-empty database, check the text encoding. For the
  108690. ** main database, set sqlite3.enc to the encoding of the main database.
  108691. ** For an attached db, it is an error if the encoding is not the same
  108692. ** as sqlite3.enc.
  108693. */
  108694. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  108695. if( iDb==0 ){
  108696. #ifndef SQLITE_OMIT_UTF16
  108697. u8 encoding;
  108698. /* If opening the main database, set ENC(db). */
  108699. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  108700. if( encoding==0 ) encoding = SQLITE_UTF8;
  108701. ENC(db) = encoding;
  108702. #else
  108703. ENC(db) = SQLITE_UTF8;
  108704. #endif
  108705. }else{
  108706. /* If opening an attached database, the encoding much match ENC(db) */
  108707. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  108708. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  108709. " text encoding as main database");
  108710. rc = SQLITE_ERROR;
  108711. goto initone_error_out;
  108712. }
  108713. }
  108714. }else{
  108715. DbSetProperty(db, iDb, DB_Empty);
  108716. }
  108717. pDb->pSchema->enc = ENC(db);
  108718. if( pDb->pSchema->cache_size==0 ){
  108719. #ifndef SQLITE_OMIT_DEPRECATED
  108720. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  108721. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  108722. pDb->pSchema->cache_size = size;
  108723. #else
  108724. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  108725. #endif
  108726. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  108727. }
  108728. /*
  108729. ** file_format==1 Version 3.0.0.
  108730. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  108731. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  108732. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  108733. */
  108734. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  108735. if( pDb->pSchema->file_format==0 ){
  108736. pDb->pSchema->file_format = 1;
  108737. }
  108738. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  108739. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  108740. rc = SQLITE_ERROR;
  108741. goto initone_error_out;
  108742. }
  108743. /* Ticket #2804: When we open a database in the newer file format,
  108744. ** clear the legacy_file_format pragma flag so that a VACUUM will
  108745. ** not downgrade the database and thus invalidate any descending
  108746. ** indices that the user might have created.
  108747. */
  108748. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  108749. db->flags &= ~SQLITE_LegacyFileFmt;
  108750. }
  108751. /* Read the schema information out of the schema tables
  108752. */
  108753. assert( db->init.busy );
  108754. {
  108755. char *zSql;
  108756. zSql = sqlite3MPrintf(db,
  108757. "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
  108758. db->aDb[iDb].zDbSName, zMasterName);
  108759. #ifndef SQLITE_OMIT_AUTHORIZATION
  108760. {
  108761. sqlite3_xauth xAuth;
  108762. xAuth = db->xAuth;
  108763. db->xAuth = 0;
  108764. #endif
  108765. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  108766. #ifndef SQLITE_OMIT_AUTHORIZATION
  108767. db->xAuth = xAuth;
  108768. }
  108769. #endif
  108770. if( rc==SQLITE_OK ) rc = initData.rc;
  108771. sqlite3DbFree(db, zSql);
  108772. #ifndef SQLITE_OMIT_ANALYZE
  108773. if( rc==SQLITE_OK ){
  108774. sqlite3AnalysisLoad(db, iDb);
  108775. }
  108776. #endif
  108777. }
  108778. if( db->mallocFailed ){
  108779. rc = SQLITE_NOMEM_BKPT;
  108780. sqlite3ResetAllSchemasOfConnection(db);
  108781. }
  108782. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  108783. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  108784. ** the schema loaded, even if errors occurred. In this situation the
  108785. ** current sqlite3_prepare() operation will fail, but the following one
  108786. ** will attempt to compile the supplied statement against whatever subset
  108787. ** of the schema was loaded before the error occurred. The primary
  108788. ** purpose of this is to allow access to the sqlite_master table
  108789. ** even when its contents have been corrupted.
  108790. */
  108791. DbSetProperty(db, iDb, DB_SchemaLoaded);
  108792. rc = SQLITE_OK;
  108793. }
  108794. /* Jump here for an error that occurs after successfully allocating
  108795. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  108796. ** before that point, jump to error_out.
  108797. */
  108798. initone_error_out:
  108799. if( openedTransaction ){
  108800. sqlite3BtreeCommit(pDb->pBt);
  108801. }
  108802. sqlite3BtreeLeave(pDb->pBt);
  108803. error_out:
  108804. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  108805. sqlite3OomFault(db);
  108806. }
  108807. return rc;
  108808. }
  108809. /*
  108810. ** Initialize all database files - the main database file, the file
  108811. ** used to store temporary tables, and any additional database files
  108812. ** created using ATTACH statements. Return a success code. If an
  108813. ** error occurs, write an error message into *pzErrMsg.
  108814. **
  108815. ** After a database is initialized, the DB_SchemaLoaded bit is set
  108816. ** bit is set in the flags field of the Db structure. If the database
  108817. ** file was of zero-length, then the DB_Empty flag is also set.
  108818. */
  108819. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  108820. int i, rc;
  108821. int commit_internal = !(db->flags&SQLITE_InternChanges);
  108822. assert( sqlite3_mutex_held(db->mutex) );
  108823. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  108824. assert( db->init.busy==0 );
  108825. rc = SQLITE_OK;
  108826. db->init.busy = 1;
  108827. ENC(db) = SCHEMA_ENC(db);
  108828. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  108829. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  108830. rc = sqlite3InitOne(db, i, pzErrMsg);
  108831. if( rc ){
  108832. sqlite3ResetOneSchema(db, i);
  108833. }
  108834. }
  108835. /* Once all the other databases have been initialized, load the schema
  108836. ** for the TEMP database. This is loaded last, as the TEMP database
  108837. ** schema may contain references to objects in other databases.
  108838. */
  108839. #ifndef SQLITE_OMIT_TEMPDB
  108840. assert( db->nDb>1 );
  108841. if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  108842. rc = sqlite3InitOne(db, 1, pzErrMsg);
  108843. if( rc ){
  108844. sqlite3ResetOneSchema(db, 1);
  108845. }
  108846. }
  108847. #endif
  108848. db->init.busy = 0;
  108849. if( rc==SQLITE_OK && commit_internal ){
  108850. sqlite3CommitInternalChanges(db);
  108851. }
  108852. return rc;
  108853. }
  108854. /*
  108855. ** This routine is a no-op if the database schema is already initialized.
  108856. ** Otherwise, the schema is loaded. An error code is returned.
  108857. */
  108858. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  108859. int rc = SQLITE_OK;
  108860. sqlite3 *db = pParse->db;
  108861. assert( sqlite3_mutex_held(db->mutex) );
  108862. if( !db->init.busy ){
  108863. rc = sqlite3Init(db, &pParse->zErrMsg);
  108864. }
  108865. if( rc!=SQLITE_OK ){
  108866. pParse->rc = rc;
  108867. pParse->nErr++;
  108868. }
  108869. return rc;
  108870. }
  108871. /*
  108872. ** Check schema cookies in all databases. If any cookie is out
  108873. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  108874. ** make no changes to pParse->rc.
  108875. */
  108876. static void schemaIsValid(Parse *pParse){
  108877. sqlite3 *db = pParse->db;
  108878. int iDb;
  108879. int rc;
  108880. int cookie;
  108881. assert( pParse->checkSchema );
  108882. assert( sqlite3_mutex_held(db->mutex) );
  108883. for(iDb=0; iDb<db->nDb; iDb++){
  108884. int openedTransaction = 0; /* True if a transaction is opened */
  108885. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  108886. if( pBt==0 ) continue;
  108887. /* If there is not already a read-only (or read-write) transaction opened
  108888. ** on the b-tree database, open one now. If a transaction is opened, it
  108889. ** will be closed immediately after reading the meta-value. */
  108890. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  108891. rc = sqlite3BtreeBeginTrans(pBt, 0);
  108892. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  108893. sqlite3OomFault(db);
  108894. }
  108895. if( rc!=SQLITE_OK ) return;
  108896. openedTransaction = 1;
  108897. }
  108898. /* Read the schema cookie from the database. If it does not match the
  108899. ** value stored as part of the in-memory schema representation,
  108900. ** set Parse.rc to SQLITE_SCHEMA. */
  108901. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  108902. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  108903. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  108904. sqlite3ResetOneSchema(db, iDb);
  108905. pParse->rc = SQLITE_SCHEMA;
  108906. }
  108907. /* Close the transaction, if one was opened. */
  108908. if( openedTransaction ){
  108909. sqlite3BtreeCommit(pBt);
  108910. }
  108911. }
  108912. }
  108913. /*
  108914. ** Convert a schema pointer into the iDb index that indicates
  108915. ** which database file in db->aDb[] the schema refers to.
  108916. **
  108917. ** If the same database is attached more than once, the first
  108918. ** attached database is returned.
  108919. */
  108920. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  108921. int i = -1000000;
  108922. /* If pSchema is NULL, then return -1000000. This happens when code in
  108923. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  108924. ** created by a sub-select). In this case the return value of this
  108925. ** function should never be used.
  108926. **
  108927. ** We return -1000000 instead of the more usual -1 simply because using
  108928. ** -1000000 as the incorrect index into db->aDb[] is much
  108929. ** more likely to cause a segfault than -1 (of course there are assert()
  108930. ** statements too, but it never hurts to play the odds).
  108931. */
  108932. assert( sqlite3_mutex_held(db->mutex) );
  108933. if( pSchema ){
  108934. for(i=0; ALWAYS(i<db->nDb); i++){
  108935. if( db->aDb[i].pSchema==pSchema ){
  108936. break;
  108937. }
  108938. }
  108939. assert( i>=0 && i<db->nDb );
  108940. }
  108941. return i;
  108942. }
  108943. /*
  108944. ** Free all memory allocations in the pParse object
  108945. */
  108946. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  108947. if( pParse ){
  108948. sqlite3 *db = pParse->db;
  108949. sqlite3DbFree(db, pParse->aLabel);
  108950. sqlite3ExprListDelete(db, pParse->pConstExpr);
  108951. if( db ){
  108952. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  108953. db->lookaside.bDisable -= pParse->disableLookaside;
  108954. }
  108955. pParse->disableLookaside = 0;
  108956. }
  108957. }
  108958. /*
  108959. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  108960. */
  108961. static int sqlite3Prepare(
  108962. sqlite3 *db, /* Database handle. */
  108963. const char *zSql, /* UTF-8 encoded SQL statement. */
  108964. int nBytes, /* Length of zSql in bytes. */
  108965. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  108966. Vdbe *pReprepare, /* VM being reprepared */
  108967. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  108968. const char **pzTail /* OUT: End of parsed string */
  108969. ){
  108970. char *zErrMsg = 0; /* Error message */
  108971. int rc = SQLITE_OK; /* Result code */
  108972. int i; /* Loop counter */
  108973. Parse sParse; /* Parsing context */
  108974. memset(&sParse, 0, PARSE_HDR_SZ);
  108975. memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  108976. sParse.pReprepare = pReprepare;
  108977. assert( ppStmt && *ppStmt==0 );
  108978. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  108979. assert( sqlite3_mutex_held(db->mutex) );
  108980. /* Check to verify that it is possible to get a read lock on all
  108981. ** database schemas. The inability to get a read lock indicates that
  108982. ** some other database connection is holding a write-lock, which in
  108983. ** turn means that the other connection has made uncommitted changes
  108984. ** to the schema.
  108985. **
  108986. ** Were we to proceed and prepare the statement against the uncommitted
  108987. ** schema changes and if those schema changes are subsequently rolled
  108988. ** back and different changes are made in their place, then when this
  108989. ** prepared statement goes to run the schema cookie would fail to detect
  108990. ** the schema change. Disaster would follow.
  108991. **
  108992. ** This thread is currently holding mutexes on all Btrees (because
  108993. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  108994. ** is not possible for another thread to start a new schema change
  108995. ** while this routine is running. Hence, we do not need to hold
  108996. ** locks on the schema, we just need to make sure nobody else is
  108997. ** holding them.
  108998. **
  108999. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  109000. ** but it does *not* override schema lock detection, so this all still
  109001. ** works even if READ_UNCOMMITTED is set.
  109002. */
  109003. for(i=0; i<db->nDb; i++) {
  109004. Btree *pBt = db->aDb[i].pBt;
  109005. if( pBt ){
  109006. assert( sqlite3BtreeHoldsMutex(pBt) );
  109007. rc = sqlite3BtreeSchemaLocked(pBt);
  109008. if( rc ){
  109009. const char *zDb = db->aDb[i].zDbSName;
  109010. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  109011. testcase( db->flags & SQLITE_ReadUncommitted );
  109012. goto end_prepare;
  109013. }
  109014. }
  109015. }
  109016. sqlite3VtabUnlockList(db);
  109017. sParse.db = db;
  109018. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  109019. char *zSqlCopy;
  109020. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  109021. testcase( nBytes==mxLen );
  109022. testcase( nBytes==mxLen+1 );
  109023. if( nBytes>mxLen ){
  109024. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  109025. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  109026. goto end_prepare;
  109027. }
  109028. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  109029. if( zSqlCopy ){
  109030. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  109031. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  109032. sqlite3DbFree(db, zSqlCopy);
  109033. }else{
  109034. sParse.zTail = &zSql[nBytes];
  109035. }
  109036. }else{
  109037. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  109038. }
  109039. assert( 0==sParse.nQueryLoop );
  109040. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  109041. if( sParse.checkSchema ){
  109042. schemaIsValid(&sParse);
  109043. }
  109044. if( db->mallocFailed ){
  109045. sParse.rc = SQLITE_NOMEM_BKPT;
  109046. }
  109047. if( pzTail ){
  109048. *pzTail = sParse.zTail;
  109049. }
  109050. rc = sParse.rc;
  109051. #ifndef SQLITE_OMIT_EXPLAIN
  109052. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  109053. static const char * const azColName[] = {
  109054. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  109055. "selectid", "order", "from", "detail"
  109056. };
  109057. int iFirst, mx;
  109058. if( sParse.explain==2 ){
  109059. sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
  109060. iFirst = 8;
  109061. mx = 12;
  109062. }else{
  109063. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  109064. iFirst = 0;
  109065. mx = 8;
  109066. }
  109067. for(i=iFirst; i<mx; i++){
  109068. sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
  109069. azColName[i], SQLITE_STATIC);
  109070. }
  109071. }
  109072. #endif
  109073. if( db->init.busy==0 ){
  109074. Vdbe *pVdbe = sParse.pVdbe;
  109075. sqlite3VdbeSetSql(pVdbe, zSql, (int)(sParse.zTail-zSql), saveSqlFlag);
  109076. }
  109077. if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  109078. sqlite3VdbeFinalize(sParse.pVdbe);
  109079. assert(!(*ppStmt));
  109080. }else{
  109081. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  109082. }
  109083. if( zErrMsg ){
  109084. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  109085. sqlite3DbFree(db, zErrMsg);
  109086. }else{
  109087. sqlite3Error(db, rc);
  109088. }
  109089. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  109090. while( sParse.pTriggerPrg ){
  109091. TriggerPrg *pT = sParse.pTriggerPrg;
  109092. sParse.pTriggerPrg = pT->pNext;
  109093. sqlite3DbFree(db, pT);
  109094. }
  109095. end_prepare:
  109096. sqlite3ParserReset(&sParse);
  109097. rc = sqlite3ApiExit(db, rc);
  109098. assert( (rc&db->errMask)==rc );
  109099. return rc;
  109100. }
  109101. static int sqlite3LockAndPrepare(
  109102. sqlite3 *db, /* Database handle. */
  109103. const char *zSql, /* UTF-8 encoded SQL statement. */
  109104. int nBytes, /* Length of zSql in bytes. */
  109105. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  109106. Vdbe *pOld, /* VM being reprepared */
  109107. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109108. const char **pzTail /* OUT: End of parsed string */
  109109. ){
  109110. int rc;
  109111. #ifdef SQLITE_ENABLE_API_ARMOR
  109112. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  109113. #endif
  109114. *ppStmt = 0;
  109115. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  109116. return SQLITE_MISUSE_BKPT;
  109117. }
  109118. sqlite3_mutex_enter(db->mutex);
  109119. sqlite3BtreeEnterAll(db);
  109120. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  109121. if( rc==SQLITE_SCHEMA ){
  109122. sqlite3_finalize(*ppStmt);
  109123. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  109124. }
  109125. sqlite3BtreeLeaveAll(db);
  109126. sqlite3_mutex_leave(db->mutex);
  109127. assert( rc==SQLITE_OK || *ppStmt==0 );
  109128. return rc;
  109129. }
  109130. /*
  109131. ** Rerun the compilation of a statement after a schema change.
  109132. **
  109133. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  109134. ** if the statement cannot be recompiled because another connection has
  109135. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  109136. ** occurs, return SQLITE_SCHEMA.
  109137. */
  109138. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  109139. int rc;
  109140. sqlite3_stmt *pNew;
  109141. const char *zSql;
  109142. sqlite3 *db;
  109143. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  109144. zSql = sqlite3_sql((sqlite3_stmt *)p);
  109145. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  109146. db = sqlite3VdbeDb(p);
  109147. assert( sqlite3_mutex_held(db->mutex) );
  109148. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  109149. if( rc ){
  109150. if( rc==SQLITE_NOMEM ){
  109151. sqlite3OomFault(db);
  109152. }
  109153. assert( pNew==0 );
  109154. return rc;
  109155. }else{
  109156. assert( pNew!=0 );
  109157. }
  109158. sqlite3VdbeSwap((Vdbe*)pNew, p);
  109159. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  109160. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  109161. sqlite3VdbeFinalize((Vdbe*)pNew);
  109162. return SQLITE_OK;
  109163. }
  109164. /*
  109165. ** Two versions of the official API. Legacy and new use. In the legacy
  109166. ** version, the original SQL text is not saved in the prepared statement
  109167. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  109168. ** sqlite3_step(). In the new version, the original SQL text is retained
  109169. ** and the statement is automatically recompiled if an schema change
  109170. ** occurs.
  109171. */
  109172. SQLITE_API int sqlite3_prepare(
  109173. sqlite3 *db, /* Database handle. */
  109174. const char *zSql, /* UTF-8 encoded SQL statement. */
  109175. int nBytes, /* Length of zSql in bytes. */
  109176. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109177. const char **pzTail /* OUT: End of parsed string */
  109178. ){
  109179. int rc;
  109180. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  109181. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  109182. return rc;
  109183. }
  109184. SQLITE_API int sqlite3_prepare_v2(
  109185. sqlite3 *db, /* Database handle. */
  109186. const char *zSql, /* UTF-8 encoded SQL statement. */
  109187. int nBytes, /* Length of zSql in bytes. */
  109188. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109189. const char **pzTail /* OUT: End of parsed string */
  109190. ){
  109191. int rc;
  109192. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  109193. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  109194. return rc;
  109195. }
  109196. #ifndef SQLITE_OMIT_UTF16
  109197. /*
  109198. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  109199. */
  109200. static int sqlite3Prepare16(
  109201. sqlite3 *db, /* Database handle. */
  109202. const void *zSql, /* UTF-16 encoded SQL statement. */
  109203. int nBytes, /* Length of zSql in bytes. */
  109204. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  109205. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109206. const void **pzTail /* OUT: End of parsed string */
  109207. ){
  109208. /* This function currently works by first transforming the UTF-16
  109209. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  109210. ** tricky bit is figuring out the pointer to return in *pzTail.
  109211. */
  109212. char *zSql8;
  109213. const char *zTail8 = 0;
  109214. int rc = SQLITE_OK;
  109215. #ifdef SQLITE_ENABLE_API_ARMOR
  109216. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  109217. #endif
  109218. *ppStmt = 0;
  109219. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  109220. return SQLITE_MISUSE_BKPT;
  109221. }
  109222. if( nBytes>=0 ){
  109223. int sz;
  109224. const char *z = (const char*)zSql;
  109225. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  109226. nBytes = sz;
  109227. }
  109228. sqlite3_mutex_enter(db->mutex);
  109229. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  109230. if( zSql8 ){
  109231. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  109232. }
  109233. if( zTail8 && pzTail ){
  109234. /* If sqlite3_prepare returns a tail pointer, we calculate the
  109235. ** equivalent pointer into the UTF-16 string by counting the unicode
  109236. ** characters between zSql8 and zTail8, and then returning a pointer
  109237. ** the same number of characters into the UTF-16 string.
  109238. */
  109239. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  109240. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  109241. }
  109242. sqlite3DbFree(db, zSql8);
  109243. rc = sqlite3ApiExit(db, rc);
  109244. sqlite3_mutex_leave(db->mutex);
  109245. return rc;
  109246. }
  109247. /*
  109248. ** Two versions of the official API. Legacy and new use. In the legacy
  109249. ** version, the original SQL text is not saved in the prepared statement
  109250. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  109251. ** sqlite3_step(). In the new version, the original SQL text is retained
  109252. ** and the statement is automatically recompiled if an schema change
  109253. ** occurs.
  109254. */
  109255. SQLITE_API int sqlite3_prepare16(
  109256. sqlite3 *db, /* Database handle. */
  109257. const void *zSql, /* UTF-16 encoded SQL statement. */
  109258. int nBytes, /* Length of zSql in bytes. */
  109259. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109260. const void **pzTail /* OUT: End of parsed string */
  109261. ){
  109262. int rc;
  109263. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  109264. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  109265. return rc;
  109266. }
  109267. SQLITE_API int sqlite3_prepare16_v2(
  109268. sqlite3 *db, /* Database handle. */
  109269. const void *zSql, /* UTF-16 encoded SQL statement. */
  109270. int nBytes, /* Length of zSql in bytes. */
  109271. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109272. const void **pzTail /* OUT: End of parsed string */
  109273. ){
  109274. int rc;
  109275. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  109276. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  109277. return rc;
  109278. }
  109279. #endif /* SQLITE_OMIT_UTF16 */
  109280. /************** End of prepare.c *********************************************/
  109281. /************** Begin file select.c ******************************************/
  109282. /*
  109283. ** 2001 September 15
  109284. **
  109285. ** The author disclaims copyright to this source code. In place of
  109286. ** a legal notice, here is a blessing:
  109287. **
  109288. ** May you do good and not evil.
  109289. ** May you find forgiveness for yourself and forgive others.
  109290. ** May you share freely, never taking more than you give.
  109291. **
  109292. *************************************************************************
  109293. ** This file contains C code routines that are called by the parser
  109294. ** to handle SELECT statements in SQLite.
  109295. */
  109296. /* #include "sqliteInt.h" */
  109297. /*
  109298. ** Trace output macros
  109299. */
  109300. #if SELECTTRACE_ENABLED
  109301. /***/ int sqlite3SelectTrace = 0;
  109302. # define SELECTTRACE(K,P,S,X) \
  109303. if(sqlite3SelectTrace&(K)) \
  109304. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
  109305. (S)->zSelName,(S)),\
  109306. sqlite3DebugPrintf X
  109307. #else
  109308. # define SELECTTRACE(K,P,S,X)
  109309. #endif
  109310. /*
  109311. ** An instance of the following object is used to record information about
  109312. ** how to process the DISTINCT keyword, to simplify passing that information
  109313. ** into the selectInnerLoop() routine.
  109314. */
  109315. typedef struct DistinctCtx DistinctCtx;
  109316. struct DistinctCtx {
  109317. u8 isTnct; /* True if the DISTINCT keyword is present */
  109318. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  109319. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  109320. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  109321. };
  109322. /*
  109323. ** An instance of the following object is used to record information about
  109324. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  109325. */
  109326. typedef struct SortCtx SortCtx;
  109327. struct SortCtx {
  109328. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  109329. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  109330. int iECursor; /* Cursor number for the sorter */
  109331. int regReturn; /* Register holding block-output return address */
  109332. int labelBkOut; /* Start label for the block-output subroutine */
  109333. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  109334. int labelDone; /* Jump here when done, ex: LIMIT reached */
  109335. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  109336. u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
  109337. };
  109338. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  109339. /*
  109340. ** Delete all the content of a Select structure. Deallocate the structure
  109341. ** itself only if bFree is true.
  109342. */
  109343. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  109344. while( p ){
  109345. Select *pPrior = p->pPrior;
  109346. sqlite3ExprListDelete(db, p->pEList);
  109347. sqlite3SrcListDelete(db, p->pSrc);
  109348. sqlite3ExprDelete(db, p->pWhere);
  109349. sqlite3ExprListDelete(db, p->pGroupBy);
  109350. sqlite3ExprDelete(db, p->pHaving);
  109351. sqlite3ExprListDelete(db, p->pOrderBy);
  109352. sqlite3ExprDelete(db, p->pLimit);
  109353. sqlite3ExprDelete(db, p->pOffset);
  109354. if( p->pWith ) sqlite3WithDelete(db, p->pWith);
  109355. if( bFree ) sqlite3DbFreeNN(db, p);
  109356. p = pPrior;
  109357. bFree = 1;
  109358. }
  109359. }
  109360. /*
  109361. ** Initialize a SelectDest structure.
  109362. */
  109363. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  109364. pDest->eDest = (u8)eDest;
  109365. pDest->iSDParm = iParm;
  109366. pDest->zAffSdst = 0;
  109367. pDest->iSdst = 0;
  109368. pDest->nSdst = 0;
  109369. }
  109370. /*
  109371. ** Allocate a new Select structure and return a pointer to that
  109372. ** structure.
  109373. */
  109374. SQLITE_PRIVATE Select *sqlite3SelectNew(
  109375. Parse *pParse, /* Parsing context */
  109376. ExprList *pEList, /* which columns to include in the result */
  109377. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  109378. Expr *pWhere, /* the WHERE clause */
  109379. ExprList *pGroupBy, /* the GROUP BY clause */
  109380. Expr *pHaving, /* the HAVING clause */
  109381. ExprList *pOrderBy, /* the ORDER BY clause */
  109382. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  109383. Expr *pLimit, /* LIMIT value. NULL means not used */
  109384. Expr *pOffset /* OFFSET value. NULL means no offset */
  109385. ){
  109386. Select *pNew;
  109387. Select standin;
  109388. pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
  109389. if( pNew==0 ){
  109390. assert( pParse->db->mallocFailed );
  109391. pNew = &standin;
  109392. }
  109393. if( pEList==0 ){
  109394. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(pParse->db,TK_ASTERISK,0));
  109395. }
  109396. pNew->pEList = pEList;
  109397. pNew->op = TK_SELECT;
  109398. pNew->selFlags = selFlags;
  109399. pNew->iLimit = 0;
  109400. pNew->iOffset = 0;
  109401. #if SELECTTRACE_ENABLED
  109402. pNew->zSelName[0] = 0;
  109403. #endif
  109404. pNew->addrOpenEphm[0] = -1;
  109405. pNew->addrOpenEphm[1] = -1;
  109406. pNew->nSelectRow = 0;
  109407. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
  109408. pNew->pSrc = pSrc;
  109409. pNew->pWhere = pWhere;
  109410. pNew->pGroupBy = pGroupBy;
  109411. pNew->pHaving = pHaving;
  109412. pNew->pOrderBy = pOrderBy;
  109413. pNew->pPrior = 0;
  109414. pNew->pNext = 0;
  109415. pNew->pLimit = pLimit;
  109416. pNew->pOffset = pOffset;
  109417. pNew->pWith = 0;
  109418. assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || pParse->db->mallocFailed!=0 );
  109419. if( pParse->db->mallocFailed ) {
  109420. clearSelect(pParse->db, pNew, pNew!=&standin);
  109421. pNew = 0;
  109422. }else{
  109423. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  109424. }
  109425. assert( pNew!=&standin );
  109426. return pNew;
  109427. }
  109428. #if SELECTTRACE_ENABLED
  109429. /*
  109430. ** Set the name of a Select object
  109431. */
  109432. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  109433. if( p && zName ){
  109434. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  109435. }
  109436. }
  109437. #endif
  109438. /*
  109439. ** Delete the given Select structure and all of its substructures.
  109440. */
  109441. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  109442. if( p ) clearSelect(db, p, 1);
  109443. }
  109444. /*
  109445. ** Return a pointer to the right-most SELECT statement in a compound.
  109446. */
  109447. static Select *findRightmost(Select *p){
  109448. while( p->pNext ) p = p->pNext;
  109449. return p;
  109450. }
  109451. /*
  109452. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  109453. ** type of join. Return an integer constant that expresses that type
  109454. ** in terms of the following bit values:
  109455. **
  109456. ** JT_INNER
  109457. ** JT_CROSS
  109458. ** JT_OUTER
  109459. ** JT_NATURAL
  109460. ** JT_LEFT
  109461. ** JT_RIGHT
  109462. **
  109463. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  109464. **
  109465. ** If an illegal or unsupported join type is seen, then still return
  109466. ** a join type, but put an error in the pParse structure.
  109467. */
  109468. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  109469. int jointype = 0;
  109470. Token *apAll[3];
  109471. Token *p;
  109472. /* 0123456789 123456789 123456789 123 */
  109473. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  109474. static const struct {
  109475. u8 i; /* Beginning of keyword text in zKeyText[] */
  109476. u8 nChar; /* Length of the keyword in characters */
  109477. u8 code; /* Join type mask */
  109478. } aKeyword[] = {
  109479. /* natural */ { 0, 7, JT_NATURAL },
  109480. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  109481. /* outer */ { 10, 5, JT_OUTER },
  109482. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  109483. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  109484. /* inner */ { 23, 5, JT_INNER },
  109485. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  109486. };
  109487. int i, j;
  109488. apAll[0] = pA;
  109489. apAll[1] = pB;
  109490. apAll[2] = pC;
  109491. for(i=0; i<3 && apAll[i]; i++){
  109492. p = apAll[i];
  109493. for(j=0; j<ArraySize(aKeyword); j++){
  109494. if( p->n==aKeyword[j].nChar
  109495. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  109496. jointype |= aKeyword[j].code;
  109497. break;
  109498. }
  109499. }
  109500. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  109501. if( j>=ArraySize(aKeyword) ){
  109502. jointype |= JT_ERROR;
  109503. break;
  109504. }
  109505. }
  109506. if(
  109507. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  109508. (jointype & JT_ERROR)!=0
  109509. ){
  109510. const char *zSp = " ";
  109511. assert( pB!=0 );
  109512. if( pC==0 ){ zSp++; }
  109513. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  109514. "%T %T%s%T", pA, pB, zSp, pC);
  109515. jointype = JT_INNER;
  109516. }else if( (jointype & JT_OUTER)!=0
  109517. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  109518. sqlite3ErrorMsg(pParse,
  109519. "RIGHT and FULL OUTER JOINs are not currently supported");
  109520. jointype = JT_INNER;
  109521. }
  109522. return jointype;
  109523. }
  109524. /*
  109525. ** Return the index of a column in a table. Return -1 if the column
  109526. ** is not contained in the table.
  109527. */
  109528. static int columnIndex(Table *pTab, const char *zCol){
  109529. int i;
  109530. for(i=0; i<pTab->nCol; i++){
  109531. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  109532. }
  109533. return -1;
  109534. }
  109535. /*
  109536. ** Search the first N tables in pSrc, from left to right, looking for a
  109537. ** table that has a column named zCol.
  109538. **
  109539. ** When found, set *piTab and *piCol to the table index and column index
  109540. ** of the matching column and return TRUE.
  109541. **
  109542. ** If not found, return FALSE.
  109543. */
  109544. static int tableAndColumnIndex(
  109545. SrcList *pSrc, /* Array of tables to search */
  109546. int N, /* Number of tables in pSrc->a[] to search */
  109547. const char *zCol, /* Name of the column we are looking for */
  109548. int *piTab, /* Write index of pSrc->a[] here */
  109549. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  109550. ){
  109551. int i; /* For looping over tables in pSrc */
  109552. int iCol; /* Index of column matching zCol */
  109553. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  109554. for(i=0; i<N; i++){
  109555. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  109556. if( iCol>=0 ){
  109557. if( piTab ){
  109558. *piTab = i;
  109559. *piCol = iCol;
  109560. }
  109561. return 1;
  109562. }
  109563. }
  109564. return 0;
  109565. }
  109566. /*
  109567. ** This function is used to add terms implied by JOIN syntax to the
  109568. ** WHERE clause expression of a SELECT statement. The new term, which
  109569. ** is ANDed with the existing WHERE clause, is of the form:
  109570. **
  109571. ** (tab1.col1 = tab2.col2)
  109572. **
  109573. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  109574. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  109575. ** column iColRight of tab2.
  109576. */
  109577. static void addWhereTerm(
  109578. Parse *pParse, /* Parsing context */
  109579. SrcList *pSrc, /* List of tables in FROM clause */
  109580. int iLeft, /* Index of first table to join in pSrc */
  109581. int iColLeft, /* Index of column in first table */
  109582. int iRight, /* Index of second table in pSrc */
  109583. int iColRight, /* Index of column in second table */
  109584. int isOuterJoin, /* True if this is an OUTER join */
  109585. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  109586. ){
  109587. sqlite3 *db = pParse->db;
  109588. Expr *pE1;
  109589. Expr *pE2;
  109590. Expr *pEq;
  109591. assert( iLeft<iRight );
  109592. assert( pSrc->nSrc>iRight );
  109593. assert( pSrc->a[iLeft].pTab );
  109594. assert( pSrc->a[iRight].pTab );
  109595. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  109596. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  109597. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  109598. if( pEq && isOuterJoin ){
  109599. ExprSetProperty(pEq, EP_FromJoin);
  109600. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  109601. ExprSetVVAProperty(pEq, EP_NoReduce);
  109602. pEq->iRightJoinTable = (i16)pE2->iTable;
  109603. }
  109604. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  109605. }
  109606. /*
  109607. ** Set the EP_FromJoin property on all terms of the given expression.
  109608. ** And set the Expr.iRightJoinTable to iTable for every term in the
  109609. ** expression.
  109610. **
  109611. ** The EP_FromJoin property is used on terms of an expression to tell
  109612. ** the LEFT OUTER JOIN processing logic that this term is part of the
  109613. ** join restriction specified in the ON or USING clause and not a part
  109614. ** of the more general WHERE clause. These terms are moved over to the
  109615. ** WHERE clause during join processing but we need to remember that they
  109616. ** originated in the ON or USING clause.
  109617. **
  109618. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  109619. ** expression depends on table iRightJoinTable even if that table is not
  109620. ** explicitly mentioned in the expression. That information is needed
  109621. ** for cases like this:
  109622. **
  109623. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  109624. **
  109625. ** The where clause needs to defer the handling of the t1.x=5
  109626. ** term until after the t2 loop of the join. In that way, a
  109627. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  109628. ** defer the handling of t1.x=5, it will be processed immediately
  109629. ** after the t1 loop and rows with t1.x!=5 will never appear in
  109630. ** the output, which is incorrect.
  109631. */
  109632. static void setJoinExpr(Expr *p, int iTable){
  109633. while( p ){
  109634. ExprSetProperty(p, EP_FromJoin);
  109635. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  109636. ExprSetVVAProperty(p, EP_NoReduce);
  109637. p->iRightJoinTable = (i16)iTable;
  109638. if( p->op==TK_FUNCTION && p->x.pList ){
  109639. int i;
  109640. for(i=0; i<p->x.pList->nExpr; i++){
  109641. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  109642. }
  109643. }
  109644. setJoinExpr(p->pLeft, iTable);
  109645. p = p->pRight;
  109646. }
  109647. }
  109648. /*
  109649. ** This routine processes the join information for a SELECT statement.
  109650. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  109651. ** NATURAL joins also create extra WHERE clause terms.
  109652. **
  109653. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  109654. ** The left most table is the first entry in Select.pSrc. The right-most
  109655. ** table is the last entry. The join operator is held in the entry to
  109656. ** the left. Thus entry 0 contains the join operator for the join between
  109657. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  109658. ** also attached to the left entry.
  109659. **
  109660. ** This routine returns the number of errors encountered.
  109661. */
  109662. static int sqliteProcessJoin(Parse *pParse, Select *p){
  109663. SrcList *pSrc; /* All tables in the FROM clause */
  109664. int i, j; /* Loop counters */
  109665. struct SrcList_item *pLeft; /* Left table being joined */
  109666. struct SrcList_item *pRight; /* Right table being joined */
  109667. pSrc = p->pSrc;
  109668. pLeft = &pSrc->a[0];
  109669. pRight = &pLeft[1];
  109670. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  109671. Table *pLeftTab = pLeft->pTab;
  109672. Table *pRightTab = pRight->pTab;
  109673. int isOuter;
  109674. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  109675. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  109676. /* When the NATURAL keyword is present, add WHERE clause terms for
  109677. ** every column that the two tables have in common.
  109678. */
  109679. if( pRight->fg.jointype & JT_NATURAL ){
  109680. if( pRight->pOn || pRight->pUsing ){
  109681. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  109682. "an ON or USING clause", 0);
  109683. return 1;
  109684. }
  109685. for(j=0; j<pRightTab->nCol; j++){
  109686. char *zName; /* Name of column in the right table */
  109687. int iLeft; /* Matching left table */
  109688. int iLeftCol; /* Matching column in the left table */
  109689. zName = pRightTab->aCol[j].zName;
  109690. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  109691. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  109692. isOuter, &p->pWhere);
  109693. }
  109694. }
  109695. }
  109696. /* Disallow both ON and USING clauses in the same join
  109697. */
  109698. if( pRight->pOn && pRight->pUsing ){
  109699. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  109700. "clauses in the same join");
  109701. return 1;
  109702. }
  109703. /* Add the ON clause to the end of the WHERE clause, connected by
  109704. ** an AND operator.
  109705. */
  109706. if( pRight->pOn ){
  109707. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  109708. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  109709. pRight->pOn = 0;
  109710. }
  109711. /* Create extra terms on the WHERE clause for each column named
  109712. ** in the USING clause. Example: If the two tables to be joined are
  109713. ** A and B and the USING clause names X, Y, and Z, then add this
  109714. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  109715. ** Report an error if any column mentioned in the USING clause is
  109716. ** not contained in both tables to be joined.
  109717. */
  109718. if( pRight->pUsing ){
  109719. IdList *pList = pRight->pUsing;
  109720. for(j=0; j<pList->nId; j++){
  109721. char *zName; /* Name of the term in the USING clause */
  109722. int iLeft; /* Table on the left with matching column name */
  109723. int iLeftCol; /* Column number of matching column on the left */
  109724. int iRightCol; /* Column number of matching column on the right */
  109725. zName = pList->a[j].zName;
  109726. iRightCol = columnIndex(pRightTab, zName);
  109727. if( iRightCol<0
  109728. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  109729. ){
  109730. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  109731. "not present in both tables", zName);
  109732. return 1;
  109733. }
  109734. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  109735. isOuter, &p->pWhere);
  109736. }
  109737. }
  109738. }
  109739. return 0;
  109740. }
  109741. /* Forward reference */
  109742. static KeyInfo *keyInfoFromExprList(
  109743. Parse *pParse, /* Parsing context */
  109744. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  109745. int iStart, /* Begin with this column of pList */
  109746. int nExtra /* Add this many extra columns to the end */
  109747. );
  109748. /*
  109749. ** Generate code that will push the record in registers regData
  109750. ** through regData+nData-1 onto the sorter.
  109751. */
  109752. static void pushOntoSorter(
  109753. Parse *pParse, /* Parser context */
  109754. SortCtx *pSort, /* Information about the ORDER BY clause */
  109755. Select *pSelect, /* The whole SELECT statement */
  109756. int regData, /* First register holding data to be sorted */
  109757. int regOrigData, /* First register holding data before packing */
  109758. int nData, /* Number of elements in the data array */
  109759. int nPrefixReg /* No. of reg prior to regData available for use */
  109760. ){
  109761. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  109762. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  109763. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  109764. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  109765. int regBase; /* Regs for sorter record */
  109766. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  109767. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  109768. int op; /* Opcode to add sorter record to sorter */
  109769. int iLimit; /* LIMIT counter */
  109770. assert( bSeq==0 || bSeq==1 );
  109771. assert( nData==1 || regData==regOrigData || regOrigData==0 );
  109772. if( nPrefixReg ){
  109773. assert( nPrefixReg==nExpr+bSeq );
  109774. regBase = regData - nExpr - bSeq;
  109775. }else{
  109776. regBase = pParse->nMem + 1;
  109777. pParse->nMem += nBase;
  109778. }
  109779. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  109780. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  109781. pSort->labelDone = sqlite3VdbeMakeLabel(v);
  109782. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  109783. SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
  109784. if( bSeq ){
  109785. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  109786. }
  109787. if( nPrefixReg==0 && nData>0 ){
  109788. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  109789. }
  109790. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  109791. if( nOBSat>0 ){
  109792. int regPrevKey; /* The first nOBSat columns of the previous row */
  109793. int addrFirst; /* Address of the OP_IfNot opcode */
  109794. int addrJmp; /* Address of the OP_Jump opcode */
  109795. VdbeOp *pOp; /* Opcode that opens the sorter */
  109796. int nKey; /* Number of sorting key columns, including OP_Sequence */
  109797. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  109798. regPrevKey = pParse->nMem+1;
  109799. pParse->nMem += pSort->nOBSat;
  109800. nKey = nExpr - pSort->nOBSat + bSeq;
  109801. if( bSeq ){
  109802. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  109803. }else{
  109804. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  109805. }
  109806. VdbeCoverage(v);
  109807. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  109808. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  109809. if( pParse->db->mallocFailed ) return;
  109810. pOp->p2 = nKey + nData;
  109811. pKI = pOp->p4.pKeyInfo;
  109812. memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
  109813. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  109814. testcase( pKI->nXField>2 );
  109815. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  109816. pKI->nXField-1);
  109817. addrJmp = sqlite3VdbeCurrentAddr(v);
  109818. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  109819. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  109820. pSort->regReturn = ++pParse->nMem;
  109821. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  109822. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  109823. if( iLimit ){
  109824. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  109825. VdbeCoverage(v);
  109826. }
  109827. sqlite3VdbeJumpHere(v, addrFirst);
  109828. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  109829. sqlite3VdbeJumpHere(v, addrJmp);
  109830. }
  109831. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  109832. op = OP_SorterInsert;
  109833. }else{
  109834. op = OP_IdxInsert;
  109835. }
  109836. sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
  109837. regBase+nOBSat, nBase-nOBSat);
  109838. if( iLimit ){
  109839. int addr;
  109840. int r1 = 0;
  109841. /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit
  109842. ** register is initialized with value of LIMIT+OFFSET.) After the sorter
  109843. ** fills up, delete the least entry in the sorter after each insert.
  109844. ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
  109845. addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
  109846. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  109847. if( pSort->bOrderedInnerLoop ){
  109848. r1 = ++pParse->nMem;
  109849. sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
  109850. VdbeComment((v, "seq"));
  109851. }
  109852. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  109853. if( pSort->bOrderedInnerLoop ){
  109854. /* If the inner loop is driven by an index such that values from
  109855. ** the same iteration of the inner loop are in sorted order, then
  109856. ** immediately jump to the next iteration of an inner loop if the
  109857. ** entry from the current iteration does not fit into the top
  109858. ** LIMIT+OFFSET entries of the sorter. */
  109859. int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
  109860. sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
  109861. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  109862. VdbeCoverage(v);
  109863. }
  109864. sqlite3VdbeJumpHere(v, addr);
  109865. }
  109866. }
  109867. /*
  109868. ** Add code to implement the OFFSET
  109869. */
  109870. static void codeOffset(
  109871. Vdbe *v, /* Generate code into this VM */
  109872. int iOffset, /* Register holding the offset counter */
  109873. int iContinue /* Jump here to skip the current record */
  109874. ){
  109875. if( iOffset>0 ){
  109876. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  109877. VdbeComment((v, "OFFSET"));
  109878. }
  109879. }
  109880. /*
  109881. ** Add code that will check to make sure the N registers starting at iMem
  109882. ** form a distinct entry. iTab is a sorting index that holds previously
  109883. ** seen combinations of the N values. A new entry is made in iTab
  109884. ** if the current N values are new.
  109885. **
  109886. ** A jump to addrRepeat is made and the N+1 values are popped from the
  109887. ** stack if the top N elements are not distinct.
  109888. */
  109889. static void codeDistinct(
  109890. Parse *pParse, /* Parsing and code generating context */
  109891. int iTab, /* A sorting index used to test for distinctness */
  109892. int addrRepeat, /* Jump to here if not distinct */
  109893. int N, /* Number of elements */
  109894. int iMem /* First element */
  109895. ){
  109896. Vdbe *v;
  109897. int r1;
  109898. v = pParse->pVdbe;
  109899. r1 = sqlite3GetTempReg(pParse);
  109900. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  109901. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  109902. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
  109903. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  109904. sqlite3ReleaseTempReg(pParse, r1);
  109905. }
  109906. /*
  109907. ** This routine generates the code for the inside of the inner loop
  109908. ** of a SELECT.
  109909. **
  109910. ** If srcTab is negative, then the pEList expressions
  109911. ** are evaluated in order to get the data for this row. If srcTab is
  109912. ** zero or more, then data is pulled from srcTab and pEList is used only
  109913. ** to get the number of columns and the collation sequence for each column.
  109914. */
  109915. static void selectInnerLoop(
  109916. Parse *pParse, /* The parser context */
  109917. Select *p, /* The complete select statement being coded */
  109918. ExprList *pEList, /* List of values being extracted */
  109919. int srcTab, /* Pull data from this table */
  109920. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  109921. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  109922. SelectDest *pDest, /* How to dispose of the results */
  109923. int iContinue, /* Jump here to continue with next row */
  109924. int iBreak /* Jump here to break out of the inner loop */
  109925. ){
  109926. Vdbe *v = pParse->pVdbe;
  109927. int i;
  109928. int hasDistinct; /* True if the DISTINCT keyword is present */
  109929. int eDest = pDest->eDest; /* How to dispose of results */
  109930. int iParm = pDest->iSDParm; /* First argument to disposal method */
  109931. int nResultCol; /* Number of result columns */
  109932. int nPrefixReg = 0; /* Number of extra registers before regResult */
  109933. /* Usually, regResult is the first cell in an array of memory cells
  109934. ** containing the current result row. In this case regOrig is set to the
  109935. ** same value. However, if the results are being sent to the sorter, the
  109936. ** values for any expressions that are also part of the sort-key are omitted
  109937. ** from this array. In this case regOrig is set to zero. */
  109938. int regResult; /* Start of memory holding current results */
  109939. int regOrig; /* Start of memory holding full result (or 0) */
  109940. assert( v );
  109941. assert( pEList!=0 );
  109942. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  109943. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  109944. if( pSort==0 && !hasDistinct ){
  109945. assert( iContinue!=0 );
  109946. codeOffset(v, p->iOffset, iContinue);
  109947. }
  109948. /* Pull the requested columns.
  109949. */
  109950. nResultCol = pEList->nExpr;
  109951. if( pDest->iSdst==0 ){
  109952. if( pSort ){
  109953. nPrefixReg = pSort->pOrderBy->nExpr;
  109954. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  109955. pParse->nMem += nPrefixReg;
  109956. }
  109957. pDest->iSdst = pParse->nMem+1;
  109958. pParse->nMem += nResultCol;
  109959. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  109960. /* This is an error condition that can result, for example, when a SELECT
  109961. ** on the right-hand side of an INSERT contains more result columns than
  109962. ** there are columns in the table on the left. The error will be caught
  109963. ** and reported later. But we need to make sure enough memory is allocated
  109964. ** to avoid other spurious errors in the meantime. */
  109965. pParse->nMem += nResultCol;
  109966. }
  109967. pDest->nSdst = nResultCol;
  109968. regOrig = regResult = pDest->iSdst;
  109969. if( srcTab>=0 ){
  109970. for(i=0; i<nResultCol; i++){
  109971. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  109972. VdbeComment((v, "%s", pEList->a[i].zName));
  109973. }
  109974. }else if( eDest!=SRT_Exists ){
  109975. /* If the destination is an EXISTS(...) expression, the actual
  109976. ** values returned by the SELECT are not required.
  109977. */
  109978. u8 ecelFlags;
  109979. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  109980. ecelFlags = SQLITE_ECEL_DUP;
  109981. }else{
  109982. ecelFlags = 0;
  109983. }
  109984. if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
  109985. /* For each expression in pEList that is a copy of an expression in
  109986. ** the ORDER BY clause (pSort->pOrderBy), set the associated
  109987. ** iOrderByCol value to one more than the index of the ORDER BY
  109988. ** expression within the sort-key that pushOntoSorter() will generate.
  109989. ** This allows the pEList field to be omitted from the sorted record,
  109990. ** saving space and CPU cycles. */
  109991. ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
  109992. for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
  109993. int j;
  109994. if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
  109995. pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
  109996. }
  109997. }
  109998. regOrig = 0;
  109999. assert( eDest==SRT_Set || eDest==SRT_Mem
  110000. || eDest==SRT_Coroutine || eDest==SRT_Output );
  110001. }
  110002. nResultCol = sqlite3ExprCodeExprList(pParse,pEList,regResult,0,ecelFlags);
  110003. }
  110004. /* If the DISTINCT keyword was present on the SELECT statement
  110005. ** and this row has been seen before, then do not make this row
  110006. ** part of the result.
  110007. */
  110008. if( hasDistinct ){
  110009. switch( pDistinct->eTnctType ){
  110010. case WHERE_DISTINCT_ORDERED: {
  110011. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  110012. int iJump; /* Jump destination */
  110013. int regPrev; /* Previous row content */
  110014. /* Allocate space for the previous row */
  110015. regPrev = pParse->nMem+1;
  110016. pParse->nMem += nResultCol;
  110017. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  110018. ** sets the MEM_Cleared bit on the first register of the
  110019. ** previous value. This will cause the OP_Ne below to always
  110020. ** fail on the first iteration of the loop even if the first
  110021. ** row is all NULLs.
  110022. */
  110023. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  110024. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  110025. pOp->opcode = OP_Null;
  110026. pOp->p1 = 1;
  110027. pOp->p2 = regPrev;
  110028. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  110029. for(i=0; i<nResultCol; i++){
  110030. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  110031. if( i<nResultCol-1 ){
  110032. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  110033. VdbeCoverage(v);
  110034. }else{
  110035. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  110036. VdbeCoverage(v);
  110037. }
  110038. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  110039. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  110040. }
  110041. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  110042. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  110043. break;
  110044. }
  110045. case WHERE_DISTINCT_UNIQUE: {
  110046. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  110047. break;
  110048. }
  110049. default: {
  110050. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  110051. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  110052. regResult);
  110053. break;
  110054. }
  110055. }
  110056. if( pSort==0 ){
  110057. codeOffset(v, p->iOffset, iContinue);
  110058. }
  110059. }
  110060. switch( eDest ){
  110061. /* In this mode, write each query result to the key of the temporary
  110062. ** table iParm.
  110063. */
  110064. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  110065. case SRT_Union: {
  110066. int r1;
  110067. r1 = sqlite3GetTempReg(pParse);
  110068. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  110069. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  110070. sqlite3ReleaseTempReg(pParse, r1);
  110071. break;
  110072. }
  110073. /* Construct a record from the query result, but instead of
  110074. ** saving that record, use it as a key to delete elements from
  110075. ** the temporary table iParm.
  110076. */
  110077. case SRT_Except: {
  110078. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  110079. break;
  110080. }
  110081. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  110082. /* Store the result as data using a unique key.
  110083. */
  110084. case SRT_Fifo:
  110085. case SRT_DistFifo:
  110086. case SRT_Table:
  110087. case SRT_EphemTab: {
  110088. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  110089. testcase( eDest==SRT_Table );
  110090. testcase( eDest==SRT_EphemTab );
  110091. testcase( eDest==SRT_Fifo );
  110092. testcase( eDest==SRT_DistFifo );
  110093. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  110094. #ifndef SQLITE_OMIT_CTE
  110095. if( eDest==SRT_DistFifo ){
  110096. /* If the destination is DistFifo, then cursor (iParm+1) is open
  110097. ** on an ephemeral index. If the current row is already present
  110098. ** in the index, do not write it to the output. If not, add the
  110099. ** current row to the index and proceed with writing it to the
  110100. ** output table as well. */
  110101. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  110102. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  110103. VdbeCoverage(v);
  110104. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
  110105. assert( pSort==0 );
  110106. }
  110107. #endif
  110108. if( pSort ){
  110109. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
  110110. }else{
  110111. int r2 = sqlite3GetTempReg(pParse);
  110112. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  110113. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  110114. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  110115. sqlite3ReleaseTempReg(pParse, r2);
  110116. }
  110117. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  110118. break;
  110119. }
  110120. #ifndef SQLITE_OMIT_SUBQUERY
  110121. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  110122. ** then there should be a single item on the stack. Write this
  110123. ** item into the set table with bogus data.
  110124. */
  110125. case SRT_Set: {
  110126. if( pSort ){
  110127. /* At first glance you would think we could optimize out the
  110128. ** ORDER BY in this case since the order of entries in the set
  110129. ** does not matter. But there might be a LIMIT clause, in which
  110130. ** case the order does matter */
  110131. pushOntoSorter(
  110132. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  110133. }else{
  110134. int r1 = sqlite3GetTempReg(pParse);
  110135. assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
  110136. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
  110137. r1, pDest->zAffSdst, nResultCol);
  110138. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  110139. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  110140. sqlite3ReleaseTempReg(pParse, r1);
  110141. }
  110142. break;
  110143. }
  110144. /* If any row exist in the result set, record that fact and abort.
  110145. */
  110146. case SRT_Exists: {
  110147. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  110148. /* The LIMIT clause will terminate the loop for us */
  110149. break;
  110150. }
  110151. /* If this is a scalar select that is part of an expression, then
  110152. ** store the results in the appropriate memory cell or array of
  110153. ** memory cells and break out of the scan loop.
  110154. */
  110155. case SRT_Mem: {
  110156. if( pSort ){
  110157. assert( nResultCol<=pDest->nSdst );
  110158. pushOntoSorter(
  110159. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  110160. }else{
  110161. assert( nResultCol==pDest->nSdst );
  110162. assert( regResult==iParm );
  110163. /* The LIMIT clause will jump out of the loop for us */
  110164. }
  110165. break;
  110166. }
  110167. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  110168. case SRT_Coroutine: /* Send data to a co-routine */
  110169. case SRT_Output: { /* Return the results */
  110170. testcase( eDest==SRT_Coroutine );
  110171. testcase( eDest==SRT_Output );
  110172. if( pSort ){
  110173. pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
  110174. nPrefixReg);
  110175. }else if( eDest==SRT_Coroutine ){
  110176. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  110177. }else{
  110178. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  110179. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  110180. }
  110181. break;
  110182. }
  110183. #ifndef SQLITE_OMIT_CTE
  110184. /* Write the results into a priority queue that is order according to
  110185. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  110186. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  110187. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  110188. ** final OP_Sequence column. The last column is the record as a blob.
  110189. */
  110190. case SRT_DistQueue:
  110191. case SRT_Queue: {
  110192. int nKey;
  110193. int r1, r2, r3;
  110194. int addrTest = 0;
  110195. ExprList *pSO;
  110196. pSO = pDest->pOrderBy;
  110197. assert( pSO );
  110198. nKey = pSO->nExpr;
  110199. r1 = sqlite3GetTempReg(pParse);
  110200. r2 = sqlite3GetTempRange(pParse, nKey+2);
  110201. r3 = r2+nKey+1;
  110202. if( eDest==SRT_DistQueue ){
  110203. /* If the destination is DistQueue, then cursor (iParm+1) is open
  110204. ** on a second ephemeral index that holds all values every previously
  110205. ** added to the queue. */
  110206. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  110207. regResult, nResultCol);
  110208. VdbeCoverage(v);
  110209. }
  110210. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  110211. if( eDest==SRT_DistQueue ){
  110212. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  110213. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  110214. }
  110215. for(i=0; i<nKey; i++){
  110216. sqlite3VdbeAddOp2(v, OP_SCopy,
  110217. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  110218. r2+i);
  110219. }
  110220. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  110221. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  110222. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
  110223. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  110224. sqlite3ReleaseTempReg(pParse, r1);
  110225. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  110226. break;
  110227. }
  110228. #endif /* SQLITE_OMIT_CTE */
  110229. #if !defined(SQLITE_OMIT_TRIGGER)
  110230. /* Discard the results. This is used for SELECT statements inside
  110231. ** the body of a TRIGGER. The purpose of such selects is to call
  110232. ** user-defined functions that have side effects. We do not care
  110233. ** about the actual results of the select.
  110234. */
  110235. default: {
  110236. assert( eDest==SRT_Discard );
  110237. break;
  110238. }
  110239. #endif
  110240. }
  110241. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  110242. ** there is a sorter, in which case the sorter has already limited
  110243. ** the output for us.
  110244. */
  110245. if( pSort==0 && p->iLimit ){
  110246. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  110247. }
  110248. }
  110249. /*
  110250. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  110251. ** X extra columns.
  110252. */
  110253. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  110254. int nExtra = (N+X)*(sizeof(CollSeq*)+1);
  110255. KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
  110256. if( p ){
  110257. p->aSortOrder = (u8*)&p->aColl[N+X];
  110258. p->nField = (u16)N;
  110259. p->nXField = (u16)X;
  110260. p->enc = ENC(db);
  110261. p->db = db;
  110262. p->nRef = 1;
  110263. memset(&p[1], 0, nExtra);
  110264. }else{
  110265. sqlite3OomFault(db);
  110266. }
  110267. return p;
  110268. }
  110269. /*
  110270. ** Deallocate a KeyInfo object
  110271. */
  110272. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  110273. if( p ){
  110274. assert( p->nRef>0 );
  110275. p->nRef--;
  110276. if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
  110277. }
  110278. }
  110279. /*
  110280. ** Make a new pointer to a KeyInfo object
  110281. */
  110282. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  110283. if( p ){
  110284. assert( p->nRef>0 );
  110285. p->nRef++;
  110286. }
  110287. return p;
  110288. }
  110289. #ifdef SQLITE_DEBUG
  110290. /*
  110291. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  110292. ** can only be changed if this is just a single reference to the object.
  110293. **
  110294. ** This routine is used only inside of assert() statements.
  110295. */
  110296. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  110297. #endif /* SQLITE_DEBUG */
  110298. /*
  110299. ** Given an expression list, generate a KeyInfo structure that records
  110300. ** the collating sequence for each expression in that expression list.
  110301. **
  110302. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  110303. ** KeyInfo structure is appropriate for initializing a virtual index to
  110304. ** implement that clause. If the ExprList is the result set of a SELECT
  110305. ** then the KeyInfo structure is appropriate for initializing a virtual
  110306. ** index to implement a DISTINCT test.
  110307. **
  110308. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  110309. ** function is responsible for seeing that this structure is eventually
  110310. ** freed.
  110311. */
  110312. static KeyInfo *keyInfoFromExprList(
  110313. Parse *pParse, /* Parsing context */
  110314. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  110315. int iStart, /* Begin with this column of pList */
  110316. int nExtra /* Add this many extra columns to the end */
  110317. ){
  110318. int nExpr;
  110319. KeyInfo *pInfo;
  110320. struct ExprList_item *pItem;
  110321. sqlite3 *db = pParse->db;
  110322. int i;
  110323. nExpr = pList->nExpr;
  110324. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  110325. if( pInfo ){
  110326. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  110327. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  110328. CollSeq *pColl;
  110329. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  110330. if( !pColl ) pColl = db->pDfltColl;
  110331. pInfo->aColl[i-iStart] = pColl;
  110332. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  110333. }
  110334. }
  110335. return pInfo;
  110336. }
  110337. /*
  110338. ** Name of the connection operator, used for error messages.
  110339. */
  110340. static const char *selectOpName(int id){
  110341. char *z;
  110342. switch( id ){
  110343. case TK_ALL: z = "UNION ALL"; break;
  110344. case TK_INTERSECT: z = "INTERSECT"; break;
  110345. case TK_EXCEPT: z = "EXCEPT"; break;
  110346. default: z = "UNION"; break;
  110347. }
  110348. return z;
  110349. }
  110350. #ifndef SQLITE_OMIT_EXPLAIN
  110351. /*
  110352. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  110353. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  110354. ** where the caption is of the form:
  110355. **
  110356. ** "USE TEMP B-TREE FOR xxx"
  110357. **
  110358. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  110359. ** is determined by the zUsage argument.
  110360. */
  110361. static void explainTempTable(Parse *pParse, const char *zUsage){
  110362. if( pParse->explain==2 ){
  110363. Vdbe *v = pParse->pVdbe;
  110364. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  110365. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  110366. }
  110367. }
  110368. /*
  110369. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  110370. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  110371. ** in sqlite3Select() to assign values to structure member variables that
  110372. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  110373. ** code with #ifndef directives.
  110374. */
  110375. # define explainSetInteger(a, b) a = b
  110376. #else
  110377. /* No-op versions of the explainXXX() functions and macros. */
  110378. # define explainTempTable(y,z)
  110379. # define explainSetInteger(y,z)
  110380. #endif
  110381. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  110382. /*
  110383. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  110384. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  110385. ** where the caption is of one of the two forms:
  110386. **
  110387. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  110388. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  110389. **
  110390. ** where iSub1 and iSub2 are the integers passed as the corresponding
  110391. ** function parameters, and op is the text representation of the parameter
  110392. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  110393. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  110394. ** false, or the second form if it is true.
  110395. */
  110396. static void explainComposite(
  110397. Parse *pParse, /* Parse context */
  110398. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  110399. int iSub1, /* Subquery id 1 */
  110400. int iSub2, /* Subquery id 2 */
  110401. int bUseTmp /* True if a temp table was used */
  110402. ){
  110403. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  110404. if( pParse->explain==2 ){
  110405. Vdbe *v = pParse->pVdbe;
  110406. char *zMsg = sqlite3MPrintf(
  110407. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  110408. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  110409. );
  110410. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  110411. }
  110412. }
  110413. #else
  110414. /* No-op versions of the explainXXX() functions and macros. */
  110415. # define explainComposite(v,w,x,y,z)
  110416. #endif
  110417. /*
  110418. ** If the inner loop was generated using a non-null pOrderBy argument,
  110419. ** then the results were placed in a sorter. After the loop is terminated
  110420. ** we need to run the sorter and output the results. The following
  110421. ** routine generates the code needed to do that.
  110422. */
  110423. static void generateSortTail(
  110424. Parse *pParse, /* Parsing context */
  110425. Select *p, /* The SELECT statement */
  110426. SortCtx *pSort, /* Information on the ORDER BY clause */
  110427. int nColumn, /* Number of columns of data */
  110428. SelectDest *pDest /* Write the sorted results here */
  110429. ){
  110430. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  110431. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  110432. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  110433. int addr;
  110434. int addrOnce = 0;
  110435. int iTab;
  110436. ExprList *pOrderBy = pSort->pOrderBy;
  110437. int eDest = pDest->eDest;
  110438. int iParm = pDest->iSDParm;
  110439. int regRow;
  110440. int regRowid;
  110441. int iCol;
  110442. int nKey;
  110443. int iSortTab; /* Sorter cursor to read from */
  110444. int nSortData; /* Trailing values to read from sorter */
  110445. int i;
  110446. int bSeq; /* True if sorter record includes seq. no. */
  110447. struct ExprList_item *aOutEx = p->pEList->a;
  110448. assert( addrBreak<0 );
  110449. if( pSort->labelBkOut ){
  110450. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  110451. sqlite3VdbeGoto(v, addrBreak);
  110452. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  110453. }
  110454. iTab = pSort->iECursor;
  110455. if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
  110456. regRowid = 0;
  110457. regRow = pDest->iSdst;
  110458. nSortData = nColumn;
  110459. }else{
  110460. regRowid = sqlite3GetTempReg(pParse);
  110461. regRow = sqlite3GetTempRange(pParse, nColumn);
  110462. nSortData = nColumn;
  110463. }
  110464. nKey = pOrderBy->nExpr - pSort->nOBSat;
  110465. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  110466. int regSortOut = ++pParse->nMem;
  110467. iSortTab = pParse->nTab++;
  110468. if( pSort->labelBkOut ){
  110469. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  110470. }
  110471. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  110472. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  110473. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  110474. VdbeCoverage(v);
  110475. codeOffset(v, p->iOffset, addrContinue);
  110476. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  110477. bSeq = 0;
  110478. }else{
  110479. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  110480. codeOffset(v, p->iOffset, addrContinue);
  110481. iSortTab = iTab;
  110482. bSeq = 1;
  110483. }
  110484. for(i=0, iCol=nKey+bSeq; i<nSortData; i++){
  110485. int iRead;
  110486. if( aOutEx[i].u.x.iOrderByCol ){
  110487. iRead = aOutEx[i].u.x.iOrderByCol-1;
  110488. }else{
  110489. iRead = iCol++;
  110490. }
  110491. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
  110492. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  110493. }
  110494. switch( eDest ){
  110495. case SRT_Table:
  110496. case SRT_EphemTab: {
  110497. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  110498. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  110499. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  110500. break;
  110501. }
  110502. #ifndef SQLITE_OMIT_SUBQUERY
  110503. case SRT_Set: {
  110504. assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
  110505. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
  110506. pDest->zAffSdst, nColumn);
  110507. sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
  110508. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
  110509. break;
  110510. }
  110511. case SRT_Mem: {
  110512. /* The LIMIT clause will terminate the loop for us */
  110513. break;
  110514. }
  110515. #endif
  110516. default: {
  110517. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  110518. testcase( eDest==SRT_Output );
  110519. testcase( eDest==SRT_Coroutine );
  110520. if( eDest==SRT_Output ){
  110521. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  110522. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  110523. }else{
  110524. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  110525. }
  110526. break;
  110527. }
  110528. }
  110529. if( regRowid ){
  110530. if( eDest==SRT_Set ){
  110531. sqlite3ReleaseTempRange(pParse, regRow, nColumn);
  110532. }else{
  110533. sqlite3ReleaseTempReg(pParse, regRow);
  110534. }
  110535. sqlite3ReleaseTempReg(pParse, regRowid);
  110536. }
  110537. /* The bottom of the loop
  110538. */
  110539. sqlite3VdbeResolveLabel(v, addrContinue);
  110540. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  110541. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  110542. }else{
  110543. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  110544. }
  110545. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  110546. sqlite3VdbeResolveLabel(v, addrBreak);
  110547. }
  110548. /*
  110549. ** Return a pointer to a string containing the 'declaration type' of the
  110550. ** expression pExpr. The string may be treated as static by the caller.
  110551. **
  110552. ** Also try to estimate the size of the returned value and return that
  110553. ** result in *pEstWidth.
  110554. **
  110555. ** The declaration type is the exact datatype definition extracted from the
  110556. ** original CREATE TABLE statement if the expression is a column. The
  110557. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  110558. ** is considered a column can be complex in the presence of subqueries. The
  110559. ** result-set expression in all of the following SELECT statements is
  110560. ** considered a column by this function.
  110561. **
  110562. ** SELECT col FROM tbl;
  110563. ** SELECT (SELECT col FROM tbl;
  110564. ** SELECT (SELECT col FROM tbl);
  110565. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  110566. **
  110567. ** The declaration type for any expression other than a column is NULL.
  110568. **
  110569. ** This routine has either 3 or 6 parameters depending on whether or not
  110570. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  110571. */
  110572. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110573. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  110574. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  110575. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  110576. #endif
  110577. static const char *columnTypeImpl(
  110578. NameContext *pNC,
  110579. Expr *pExpr,
  110580. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110581. const char **pzOrigDb,
  110582. const char **pzOrigTab,
  110583. const char **pzOrigCol,
  110584. #endif
  110585. u8 *pEstWidth
  110586. ){
  110587. char const *zType = 0;
  110588. int j;
  110589. u8 estWidth = 1;
  110590. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110591. char const *zOrigDb = 0;
  110592. char const *zOrigTab = 0;
  110593. char const *zOrigCol = 0;
  110594. #endif
  110595. assert( pExpr!=0 );
  110596. assert( pNC->pSrcList!=0 );
  110597. switch( pExpr->op ){
  110598. case TK_AGG_COLUMN:
  110599. case TK_COLUMN: {
  110600. /* The expression is a column. Locate the table the column is being
  110601. ** extracted from in NameContext.pSrcList. This table may be real
  110602. ** database table or a subquery.
  110603. */
  110604. Table *pTab = 0; /* Table structure column is extracted from */
  110605. Select *pS = 0; /* Select the column is extracted from */
  110606. int iCol = pExpr->iColumn; /* Index of column in pTab */
  110607. testcase( pExpr->op==TK_AGG_COLUMN );
  110608. testcase( pExpr->op==TK_COLUMN );
  110609. while( pNC && !pTab ){
  110610. SrcList *pTabList = pNC->pSrcList;
  110611. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  110612. if( j<pTabList->nSrc ){
  110613. pTab = pTabList->a[j].pTab;
  110614. pS = pTabList->a[j].pSelect;
  110615. }else{
  110616. pNC = pNC->pNext;
  110617. }
  110618. }
  110619. if( pTab==0 ){
  110620. /* At one time, code such as "SELECT new.x" within a trigger would
  110621. ** cause this condition to run. Since then, we have restructured how
  110622. ** trigger code is generated and so this condition is no longer
  110623. ** possible. However, it can still be true for statements like
  110624. ** the following:
  110625. **
  110626. ** CREATE TABLE t1(col INTEGER);
  110627. ** SELECT (SELECT t1.col) FROM FROM t1;
  110628. **
  110629. ** when columnType() is called on the expression "t1.col" in the
  110630. ** sub-select. In this case, set the column type to NULL, even
  110631. ** though it should really be "INTEGER".
  110632. **
  110633. ** This is not a problem, as the column type of "t1.col" is never
  110634. ** used. When columnType() is called on the expression
  110635. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  110636. ** branch below. */
  110637. break;
  110638. }
  110639. assert( pTab && pExpr->pTab==pTab );
  110640. if( pS ){
  110641. /* The "table" is actually a sub-select or a view in the FROM clause
  110642. ** of the SELECT statement. Return the declaration type and origin
  110643. ** data for the result-set column of the sub-select.
  110644. */
  110645. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  110646. /* If iCol is less than zero, then the expression requests the
  110647. ** rowid of the sub-select or view. This expression is legal (see
  110648. ** test case misc2.2.2) - it always evaluates to NULL.
  110649. **
  110650. ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
  110651. ** caught already by name resolution.
  110652. */
  110653. NameContext sNC;
  110654. Expr *p = pS->pEList->a[iCol].pExpr;
  110655. sNC.pSrcList = pS->pSrc;
  110656. sNC.pNext = pNC;
  110657. sNC.pParse = pNC->pParse;
  110658. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  110659. }
  110660. }else if( pTab->pSchema ){
  110661. /* A real table */
  110662. assert( !pS );
  110663. if( iCol<0 ) iCol = pTab->iPKey;
  110664. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  110665. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110666. if( iCol<0 ){
  110667. zType = "INTEGER";
  110668. zOrigCol = "rowid";
  110669. }else{
  110670. zOrigCol = pTab->aCol[iCol].zName;
  110671. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  110672. estWidth = pTab->aCol[iCol].szEst;
  110673. }
  110674. zOrigTab = pTab->zName;
  110675. if( pNC->pParse ){
  110676. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  110677. zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  110678. }
  110679. #else
  110680. if( iCol<0 ){
  110681. zType = "INTEGER";
  110682. }else{
  110683. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  110684. estWidth = pTab->aCol[iCol].szEst;
  110685. }
  110686. #endif
  110687. }
  110688. break;
  110689. }
  110690. #ifndef SQLITE_OMIT_SUBQUERY
  110691. case TK_SELECT: {
  110692. /* The expression is a sub-select. Return the declaration type and
  110693. ** origin info for the single column in the result set of the SELECT
  110694. ** statement.
  110695. */
  110696. NameContext sNC;
  110697. Select *pS = pExpr->x.pSelect;
  110698. Expr *p = pS->pEList->a[0].pExpr;
  110699. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  110700. sNC.pSrcList = pS->pSrc;
  110701. sNC.pNext = pNC;
  110702. sNC.pParse = pNC->pParse;
  110703. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  110704. break;
  110705. }
  110706. #endif
  110707. }
  110708. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110709. if( pzOrigDb ){
  110710. assert( pzOrigTab && pzOrigCol );
  110711. *pzOrigDb = zOrigDb;
  110712. *pzOrigTab = zOrigTab;
  110713. *pzOrigCol = zOrigCol;
  110714. }
  110715. #endif
  110716. if( pEstWidth ) *pEstWidth = estWidth;
  110717. return zType;
  110718. }
  110719. /*
  110720. ** Generate code that will tell the VDBE the declaration types of columns
  110721. ** in the result set.
  110722. */
  110723. static void generateColumnTypes(
  110724. Parse *pParse, /* Parser context */
  110725. SrcList *pTabList, /* List of tables */
  110726. ExprList *pEList /* Expressions defining the result set */
  110727. ){
  110728. #ifndef SQLITE_OMIT_DECLTYPE
  110729. Vdbe *v = pParse->pVdbe;
  110730. int i;
  110731. NameContext sNC;
  110732. sNC.pSrcList = pTabList;
  110733. sNC.pParse = pParse;
  110734. sNC.pNext = 0;
  110735. for(i=0; i<pEList->nExpr; i++){
  110736. Expr *p = pEList->a[i].pExpr;
  110737. const char *zType;
  110738. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110739. const char *zOrigDb = 0;
  110740. const char *zOrigTab = 0;
  110741. const char *zOrigCol = 0;
  110742. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  110743. /* The vdbe must make its own copy of the column-type and other
  110744. ** column specific strings, in case the schema is reset before this
  110745. ** virtual machine is deleted.
  110746. */
  110747. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  110748. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  110749. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  110750. #else
  110751. zType = columnType(&sNC, p, 0, 0, 0, 0);
  110752. #endif
  110753. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  110754. }
  110755. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  110756. }
  110757. /*
  110758. ** Return the Table objecct in the SrcList that has cursor iCursor.
  110759. ** Or return NULL if no such Table object exists in the SrcList.
  110760. */
  110761. static Table *tableWithCursor(SrcList *pList, int iCursor){
  110762. int j;
  110763. for(j=0; j<pList->nSrc; j++){
  110764. if( pList->a[j].iCursor==iCursor ) return pList->a[j].pTab;
  110765. }
  110766. return 0;
  110767. }
  110768. /*
  110769. ** Generate code that will tell the VDBE the names of columns
  110770. ** in the result set. This information is used to provide the
  110771. ** azCol[] values in the callback.
  110772. */
  110773. static void generateColumnNames(
  110774. Parse *pParse, /* Parser context */
  110775. SrcList *pTabList, /* List of tables */
  110776. ExprList *pEList /* Expressions defining the result set */
  110777. ){
  110778. Vdbe *v = pParse->pVdbe;
  110779. int i;
  110780. Table *pTab;
  110781. sqlite3 *db = pParse->db;
  110782. int fullNames, shortNames;
  110783. #ifndef SQLITE_OMIT_EXPLAIN
  110784. /* If this is an EXPLAIN, skip this step */
  110785. if( pParse->explain ){
  110786. return;
  110787. }
  110788. #endif
  110789. if( pParse->colNamesSet || db->mallocFailed ) return;
  110790. assert( v!=0 );
  110791. assert( pTabList!=0 );
  110792. pParse->colNamesSet = 1;
  110793. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  110794. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  110795. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  110796. for(i=0; i<pEList->nExpr; i++){
  110797. Expr *p;
  110798. p = pEList->a[i].pExpr;
  110799. if( NEVER(p==0) ) continue;
  110800. if( pEList->a[i].zName ){
  110801. char *zName = pEList->a[i].zName;
  110802. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  110803. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN)
  110804. && (pTab = tableWithCursor(pTabList, p->iTable))!=0
  110805. ){
  110806. char *zCol;
  110807. int iCol = p->iColumn;
  110808. if( iCol<0 ) iCol = pTab->iPKey;
  110809. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  110810. if( iCol<0 ){
  110811. zCol = "rowid";
  110812. }else{
  110813. zCol = pTab->aCol[iCol].zName;
  110814. }
  110815. if( !shortNames && !fullNames ){
  110816. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  110817. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  110818. }else if( fullNames ){
  110819. char *zName = 0;
  110820. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  110821. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  110822. }else{
  110823. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  110824. }
  110825. }else{
  110826. const char *z = pEList->a[i].zSpan;
  110827. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  110828. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  110829. }
  110830. }
  110831. generateColumnTypes(pParse, pTabList, pEList);
  110832. }
  110833. /*
  110834. ** Given an expression list (which is really the list of expressions
  110835. ** that form the result set of a SELECT statement) compute appropriate
  110836. ** column names for a table that would hold the expression list.
  110837. **
  110838. ** All column names will be unique.
  110839. **
  110840. ** Only the column names are computed. Column.zType, Column.zColl,
  110841. ** and other fields of Column are zeroed.
  110842. **
  110843. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  110844. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  110845. */
  110846. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  110847. Parse *pParse, /* Parsing context */
  110848. ExprList *pEList, /* Expr list from which to derive column names */
  110849. i16 *pnCol, /* Write the number of columns here */
  110850. Column **paCol /* Write the new column list here */
  110851. ){
  110852. sqlite3 *db = pParse->db; /* Database connection */
  110853. int i, j; /* Loop counters */
  110854. u32 cnt; /* Index added to make the name unique */
  110855. Column *aCol, *pCol; /* For looping over result columns */
  110856. int nCol; /* Number of columns in the result set */
  110857. Expr *p; /* Expression for a single result column */
  110858. char *zName; /* Column name */
  110859. int nName; /* Size of name in zName[] */
  110860. Hash ht; /* Hash table of column names */
  110861. sqlite3HashInit(&ht);
  110862. if( pEList ){
  110863. nCol = pEList->nExpr;
  110864. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  110865. testcase( aCol==0 );
  110866. }else{
  110867. nCol = 0;
  110868. aCol = 0;
  110869. }
  110870. assert( nCol==(i16)nCol );
  110871. *pnCol = nCol;
  110872. *paCol = aCol;
  110873. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  110874. /* Get an appropriate name for the column
  110875. */
  110876. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  110877. if( (zName = pEList->a[i].zName)!=0 ){
  110878. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  110879. }else{
  110880. Expr *pColExpr = p; /* The expression that is the result column name */
  110881. Table *pTab; /* Table associated with this expression */
  110882. while( pColExpr->op==TK_DOT ){
  110883. pColExpr = pColExpr->pRight;
  110884. assert( pColExpr!=0 );
  110885. }
  110886. if( pColExpr->op==TK_COLUMN && pColExpr->pTab!=0 ){
  110887. /* For columns use the column name name */
  110888. int iCol = pColExpr->iColumn;
  110889. pTab = pColExpr->pTab;
  110890. if( iCol<0 ) iCol = pTab->iPKey;
  110891. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  110892. }else if( pColExpr->op==TK_ID ){
  110893. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  110894. zName = pColExpr->u.zToken;
  110895. }else{
  110896. /* Use the original text of the column expression as its name */
  110897. zName = pEList->a[i].zSpan;
  110898. }
  110899. }
  110900. zName = sqlite3MPrintf(db, "%s", zName);
  110901. /* Make sure the column name is unique. If the name is not unique,
  110902. ** append an integer to the name so that it becomes unique.
  110903. */
  110904. cnt = 0;
  110905. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  110906. nName = sqlite3Strlen30(zName);
  110907. if( nName>0 ){
  110908. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  110909. if( zName[j]==':' ) nName = j;
  110910. }
  110911. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  110912. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  110913. }
  110914. pCol->zName = zName;
  110915. sqlite3ColumnPropertiesFromName(0, pCol);
  110916. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  110917. sqlite3OomFault(db);
  110918. }
  110919. }
  110920. sqlite3HashClear(&ht);
  110921. if( db->mallocFailed ){
  110922. for(j=0; j<i; j++){
  110923. sqlite3DbFree(db, aCol[j].zName);
  110924. }
  110925. sqlite3DbFree(db, aCol);
  110926. *paCol = 0;
  110927. *pnCol = 0;
  110928. return SQLITE_NOMEM_BKPT;
  110929. }
  110930. return SQLITE_OK;
  110931. }
  110932. /*
  110933. ** Add type and collation information to a column list based on
  110934. ** a SELECT statement.
  110935. **
  110936. ** The column list presumably came from selectColumnNamesFromExprList().
  110937. ** The column list has only names, not types or collations. This
  110938. ** routine goes through and adds the types and collations.
  110939. **
  110940. ** This routine requires that all identifiers in the SELECT
  110941. ** statement be resolved.
  110942. */
  110943. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  110944. Parse *pParse, /* Parsing contexts */
  110945. Table *pTab, /* Add column type information to this table */
  110946. Select *pSelect /* SELECT used to determine types and collations */
  110947. ){
  110948. sqlite3 *db = pParse->db;
  110949. NameContext sNC;
  110950. Column *pCol;
  110951. CollSeq *pColl;
  110952. int i;
  110953. Expr *p;
  110954. struct ExprList_item *a;
  110955. u64 szAll = 0;
  110956. assert( pSelect!=0 );
  110957. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  110958. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  110959. if( db->mallocFailed ) return;
  110960. memset(&sNC, 0, sizeof(sNC));
  110961. sNC.pSrcList = pSelect->pSrc;
  110962. a = pSelect->pEList->a;
  110963. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  110964. const char *zType;
  110965. int n, m;
  110966. p = a[i].pExpr;
  110967. zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
  110968. szAll += pCol->szEst;
  110969. pCol->affinity = sqlite3ExprAffinity(p);
  110970. if( zType && (m = sqlite3Strlen30(zType))>0 ){
  110971. n = sqlite3Strlen30(pCol->zName);
  110972. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  110973. if( pCol->zName ){
  110974. memcpy(&pCol->zName[n+1], zType, m+1);
  110975. pCol->colFlags |= COLFLAG_HASTYPE;
  110976. }
  110977. }
  110978. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  110979. pColl = sqlite3ExprCollSeq(pParse, p);
  110980. if( pColl && pCol->zColl==0 ){
  110981. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  110982. }
  110983. }
  110984. pTab->szTabRow = sqlite3LogEst(szAll*4);
  110985. }
  110986. /*
  110987. ** Given a SELECT statement, generate a Table structure that describes
  110988. ** the result set of that SELECT.
  110989. */
  110990. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  110991. Table *pTab;
  110992. sqlite3 *db = pParse->db;
  110993. int savedFlags;
  110994. savedFlags = db->flags;
  110995. db->flags &= ~SQLITE_FullColNames;
  110996. db->flags |= SQLITE_ShortColNames;
  110997. sqlite3SelectPrep(pParse, pSelect, 0);
  110998. if( pParse->nErr ) return 0;
  110999. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  111000. db->flags = savedFlags;
  111001. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  111002. if( pTab==0 ){
  111003. return 0;
  111004. }
  111005. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  111006. ** is disabled */
  111007. assert( db->lookaside.bDisable );
  111008. pTab->nTabRef = 1;
  111009. pTab->zName = 0;
  111010. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  111011. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  111012. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  111013. pTab->iPKey = -1;
  111014. if( db->mallocFailed ){
  111015. sqlite3DeleteTable(db, pTab);
  111016. return 0;
  111017. }
  111018. return pTab;
  111019. }
  111020. /*
  111021. ** Get a VDBE for the given parser context. Create a new one if necessary.
  111022. ** If an error occurs, return NULL and leave a message in pParse.
  111023. */
  111024. static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
  111025. Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
  111026. if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1);
  111027. if( pParse->pToplevel==0
  111028. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  111029. ){
  111030. pParse->okConstFactor = 1;
  111031. }
  111032. return v;
  111033. }
  111034. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  111035. Vdbe *v = pParse->pVdbe;
  111036. return v ? v : allocVdbe(pParse);
  111037. }
  111038. /*
  111039. ** Compute the iLimit and iOffset fields of the SELECT based on the
  111040. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  111041. ** that appear in the original SQL statement after the LIMIT and OFFSET
  111042. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  111043. ** are the integer memory register numbers for counters used to compute
  111044. ** the limit and offset. If there is no limit and/or offset, then
  111045. ** iLimit and iOffset are negative.
  111046. **
  111047. ** This routine changes the values of iLimit and iOffset only if
  111048. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  111049. ** iOffset should have been preset to appropriate default values (zero)
  111050. ** prior to calling this routine.
  111051. **
  111052. ** The iOffset register (if it exists) is initialized to the value
  111053. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  111054. ** iOffset+1 is initialized to LIMIT+OFFSET.
  111055. **
  111056. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  111057. ** redefined. The UNION ALL operator uses this property to force
  111058. ** the reuse of the same limit and offset registers across multiple
  111059. ** SELECT statements.
  111060. */
  111061. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  111062. Vdbe *v = 0;
  111063. int iLimit = 0;
  111064. int iOffset;
  111065. int n;
  111066. if( p->iLimit ) return;
  111067. /*
  111068. ** "LIMIT -1" always shows all rows. There is some
  111069. ** controversy about what the correct behavior should be.
  111070. ** The current implementation interprets "LIMIT 0" to mean
  111071. ** no rows.
  111072. */
  111073. sqlite3ExprCacheClear(pParse);
  111074. assert( p->pOffset==0 || p->pLimit!=0 );
  111075. if( p->pLimit ){
  111076. p->iLimit = iLimit = ++pParse->nMem;
  111077. v = sqlite3GetVdbe(pParse);
  111078. assert( v!=0 );
  111079. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  111080. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  111081. VdbeComment((v, "LIMIT counter"));
  111082. if( n==0 ){
  111083. sqlite3VdbeGoto(v, iBreak);
  111084. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  111085. p->nSelectRow = sqlite3LogEst((u64)n);
  111086. p->selFlags |= SF_FixedLimit;
  111087. }
  111088. }else{
  111089. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  111090. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  111091. VdbeComment((v, "LIMIT counter"));
  111092. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  111093. }
  111094. if( p->pOffset ){
  111095. p->iOffset = iOffset = ++pParse->nMem;
  111096. pParse->nMem++; /* Allocate an extra register for limit+offset */
  111097. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  111098. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  111099. VdbeComment((v, "OFFSET counter"));
  111100. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  111101. VdbeComment((v, "LIMIT+OFFSET"));
  111102. }
  111103. }
  111104. }
  111105. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  111106. /*
  111107. ** Return the appropriate collating sequence for the iCol-th column of
  111108. ** the result set for the compound-select statement "p". Return NULL if
  111109. ** the column has no default collating sequence.
  111110. **
  111111. ** The collating sequence for the compound select is taken from the
  111112. ** left-most term of the select that has a collating sequence.
  111113. */
  111114. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  111115. CollSeq *pRet;
  111116. if( p->pPrior ){
  111117. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  111118. }else{
  111119. pRet = 0;
  111120. }
  111121. assert( iCol>=0 );
  111122. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  111123. ** have been thrown during name resolution and we would not have gotten
  111124. ** this far */
  111125. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  111126. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  111127. }
  111128. return pRet;
  111129. }
  111130. /*
  111131. ** The select statement passed as the second parameter is a compound SELECT
  111132. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  111133. ** structure suitable for implementing the ORDER BY.
  111134. **
  111135. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  111136. ** function is responsible for ensuring that this structure is eventually
  111137. ** freed.
  111138. */
  111139. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  111140. ExprList *pOrderBy = p->pOrderBy;
  111141. int nOrderBy = p->pOrderBy->nExpr;
  111142. sqlite3 *db = pParse->db;
  111143. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  111144. if( pRet ){
  111145. int i;
  111146. for(i=0; i<nOrderBy; i++){
  111147. struct ExprList_item *pItem = &pOrderBy->a[i];
  111148. Expr *pTerm = pItem->pExpr;
  111149. CollSeq *pColl;
  111150. if( pTerm->flags & EP_Collate ){
  111151. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  111152. }else{
  111153. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  111154. if( pColl==0 ) pColl = db->pDfltColl;
  111155. pOrderBy->a[i].pExpr =
  111156. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  111157. }
  111158. assert( sqlite3KeyInfoIsWriteable(pRet) );
  111159. pRet->aColl[i] = pColl;
  111160. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  111161. }
  111162. }
  111163. return pRet;
  111164. }
  111165. #ifndef SQLITE_OMIT_CTE
  111166. /*
  111167. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  111168. ** query of the form:
  111169. **
  111170. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  111171. ** \___________/ \_______________/
  111172. ** p->pPrior p
  111173. **
  111174. **
  111175. ** There is exactly one reference to the recursive-table in the FROM clause
  111176. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  111177. **
  111178. ** The setup-query runs once to generate an initial set of rows that go
  111179. ** into a Queue table. Rows are extracted from the Queue table one by
  111180. ** one. Each row extracted from Queue is output to pDest. Then the single
  111181. ** extracted row (now in the iCurrent table) becomes the content of the
  111182. ** recursive-table for a recursive-query run. The output of the recursive-query
  111183. ** is added back into the Queue table. Then another row is extracted from Queue
  111184. ** and the iteration continues until the Queue table is empty.
  111185. **
  111186. ** If the compound query operator is UNION then no duplicate rows are ever
  111187. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  111188. ** that have ever been inserted into Queue and causes duplicates to be
  111189. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  111190. **
  111191. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  111192. ** ORDER BY order and the first entry is extracted for each cycle. Without
  111193. ** an ORDER BY, the Queue table is just a FIFO.
  111194. **
  111195. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  111196. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  111197. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  111198. ** with a positive value, then the first OFFSET outputs are discarded rather
  111199. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  111200. ** rows have been skipped.
  111201. */
  111202. static void generateWithRecursiveQuery(
  111203. Parse *pParse, /* Parsing context */
  111204. Select *p, /* The recursive SELECT to be coded */
  111205. SelectDest *pDest /* What to do with query results */
  111206. ){
  111207. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  111208. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  111209. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  111210. Select *pSetup = p->pPrior; /* The setup query */
  111211. int addrTop; /* Top of the loop */
  111212. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  111213. int iCurrent = 0; /* The Current table */
  111214. int regCurrent; /* Register holding Current table */
  111215. int iQueue; /* The Queue table */
  111216. int iDistinct = 0; /* To ensure unique results if UNION */
  111217. int eDest = SRT_Fifo; /* How to write to Queue */
  111218. SelectDest destQueue; /* SelectDest targetting the Queue table */
  111219. int i; /* Loop counter */
  111220. int rc; /* Result code */
  111221. ExprList *pOrderBy; /* The ORDER BY clause */
  111222. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  111223. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  111224. /* Obtain authorization to do a recursive query */
  111225. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  111226. /* Process the LIMIT and OFFSET clauses, if they exist */
  111227. addrBreak = sqlite3VdbeMakeLabel(v);
  111228. p->nSelectRow = 320; /* 4 billion rows */
  111229. computeLimitRegisters(pParse, p, addrBreak);
  111230. pLimit = p->pLimit;
  111231. pOffset = p->pOffset;
  111232. regLimit = p->iLimit;
  111233. regOffset = p->iOffset;
  111234. p->pLimit = p->pOffset = 0;
  111235. p->iLimit = p->iOffset = 0;
  111236. pOrderBy = p->pOrderBy;
  111237. /* Locate the cursor number of the Current table */
  111238. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  111239. if( pSrc->a[i].fg.isRecursive ){
  111240. iCurrent = pSrc->a[i].iCursor;
  111241. break;
  111242. }
  111243. }
  111244. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  111245. ** the Distinct table must be exactly one greater than Queue in order
  111246. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  111247. iQueue = pParse->nTab++;
  111248. if( p->op==TK_UNION ){
  111249. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  111250. iDistinct = pParse->nTab++;
  111251. }else{
  111252. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  111253. }
  111254. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  111255. /* Allocate cursors for Current, Queue, and Distinct. */
  111256. regCurrent = ++pParse->nMem;
  111257. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  111258. if( pOrderBy ){
  111259. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  111260. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  111261. (char*)pKeyInfo, P4_KEYINFO);
  111262. destQueue.pOrderBy = pOrderBy;
  111263. }else{
  111264. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  111265. }
  111266. VdbeComment((v, "Queue table"));
  111267. if( iDistinct ){
  111268. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  111269. p->selFlags |= SF_UsesEphemeral;
  111270. }
  111271. /* Detach the ORDER BY clause from the compound SELECT */
  111272. p->pOrderBy = 0;
  111273. /* Store the results of the setup-query in Queue. */
  111274. pSetup->pNext = 0;
  111275. rc = sqlite3Select(pParse, pSetup, &destQueue);
  111276. pSetup->pNext = p;
  111277. if( rc ) goto end_of_recursive_query;
  111278. /* Find the next row in the Queue and output that row */
  111279. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  111280. /* Transfer the next row in Queue over to Current */
  111281. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  111282. if( pOrderBy ){
  111283. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  111284. }else{
  111285. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  111286. }
  111287. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  111288. /* Output the single row in Current */
  111289. addrCont = sqlite3VdbeMakeLabel(v);
  111290. codeOffset(v, regOffset, addrCont);
  111291. selectInnerLoop(pParse, p, p->pEList, iCurrent,
  111292. 0, 0, pDest, addrCont, addrBreak);
  111293. if( regLimit ){
  111294. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  111295. VdbeCoverage(v);
  111296. }
  111297. sqlite3VdbeResolveLabel(v, addrCont);
  111298. /* Execute the recursive SELECT taking the single row in Current as
  111299. ** the value for the recursive-table. Store the results in the Queue.
  111300. */
  111301. if( p->selFlags & SF_Aggregate ){
  111302. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  111303. }else{
  111304. p->pPrior = 0;
  111305. sqlite3Select(pParse, p, &destQueue);
  111306. assert( p->pPrior==0 );
  111307. p->pPrior = pSetup;
  111308. }
  111309. /* Keep running the loop until the Queue is empty */
  111310. sqlite3VdbeGoto(v, addrTop);
  111311. sqlite3VdbeResolveLabel(v, addrBreak);
  111312. end_of_recursive_query:
  111313. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  111314. p->pOrderBy = pOrderBy;
  111315. p->pLimit = pLimit;
  111316. p->pOffset = pOffset;
  111317. return;
  111318. }
  111319. #endif /* SQLITE_OMIT_CTE */
  111320. /* Forward references */
  111321. static int multiSelectOrderBy(
  111322. Parse *pParse, /* Parsing context */
  111323. Select *p, /* The right-most of SELECTs to be coded */
  111324. SelectDest *pDest /* What to do with query results */
  111325. );
  111326. /*
  111327. ** Handle the special case of a compound-select that originates from a
  111328. ** VALUES clause. By handling this as a special case, we avoid deep
  111329. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  111330. ** on a VALUES clause.
  111331. **
  111332. ** Because the Select object originates from a VALUES clause:
  111333. ** (1) It has no LIMIT or OFFSET
  111334. ** (2) All terms are UNION ALL
  111335. ** (3) There is no ORDER BY clause
  111336. */
  111337. static int multiSelectValues(
  111338. Parse *pParse, /* Parsing context */
  111339. Select *p, /* The right-most of SELECTs to be coded */
  111340. SelectDest *pDest /* What to do with query results */
  111341. ){
  111342. Select *pPrior;
  111343. int nRow = 1;
  111344. int rc = 0;
  111345. assert( p->selFlags & SF_MultiValue );
  111346. do{
  111347. assert( p->selFlags & SF_Values );
  111348. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  111349. assert( p->pLimit==0 );
  111350. assert( p->pOffset==0 );
  111351. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  111352. if( p->pPrior==0 ) break;
  111353. assert( p->pPrior->pNext==p );
  111354. p = p->pPrior;
  111355. nRow++;
  111356. }while(1);
  111357. while( p ){
  111358. pPrior = p->pPrior;
  111359. p->pPrior = 0;
  111360. rc = sqlite3Select(pParse, p, pDest);
  111361. p->pPrior = pPrior;
  111362. if( rc ) break;
  111363. p->nSelectRow = nRow;
  111364. p = p->pNext;
  111365. }
  111366. return rc;
  111367. }
  111368. /*
  111369. ** This routine is called to process a compound query form from
  111370. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  111371. ** INTERSECT
  111372. **
  111373. ** "p" points to the right-most of the two queries. the query on the
  111374. ** left is p->pPrior. The left query could also be a compound query
  111375. ** in which case this routine will be called recursively.
  111376. **
  111377. ** The results of the total query are to be written into a destination
  111378. ** of type eDest with parameter iParm.
  111379. **
  111380. ** Example 1: Consider a three-way compound SQL statement.
  111381. **
  111382. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  111383. **
  111384. ** This statement is parsed up as follows:
  111385. **
  111386. ** SELECT c FROM t3
  111387. ** |
  111388. ** `-----> SELECT b FROM t2
  111389. ** |
  111390. ** `------> SELECT a FROM t1
  111391. **
  111392. ** The arrows in the diagram above represent the Select.pPrior pointer.
  111393. ** So if this routine is called with p equal to the t3 query, then
  111394. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  111395. **
  111396. ** Notice that because of the way SQLite parses compound SELECTs, the
  111397. ** individual selects always group from left to right.
  111398. */
  111399. static int multiSelect(
  111400. Parse *pParse, /* Parsing context */
  111401. Select *p, /* The right-most of SELECTs to be coded */
  111402. SelectDest *pDest /* What to do with query results */
  111403. ){
  111404. int rc = SQLITE_OK; /* Success code from a subroutine */
  111405. Select *pPrior; /* Another SELECT immediately to our left */
  111406. Vdbe *v; /* Generate code to this VDBE */
  111407. SelectDest dest; /* Alternative data destination */
  111408. Select *pDelete = 0; /* Chain of simple selects to delete */
  111409. sqlite3 *db; /* Database connection */
  111410. #ifndef SQLITE_OMIT_EXPLAIN
  111411. int iSub1 = 0; /* EQP id of left-hand query */
  111412. int iSub2 = 0; /* EQP id of right-hand query */
  111413. #endif
  111414. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  111415. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  111416. */
  111417. assert( p && p->pPrior ); /* Calling function guarantees this much */
  111418. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  111419. db = pParse->db;
  111420. pPrior = p->pPrior;
  111421. dest = *pDest;
  111422. if( pPrior->pOrderBy ){
  111423. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  111424. selectOpName(p->op));
  111425. rc = 1;
  111426. goto multi_select_end;
  111427. }
  111428. if( pPrior->pLimit ){
  111429. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  111430. selectOpName(p->op));
  111431. rc = 1;
  111432. goto multi_select_end;
  111433. }
  111434. v = sqlite3GetVdbe(pParse);
  111435. assert( v!=0 ); /* The VDBE already created by calling function */
  111436. /* Create the destination temporary table if necessary
  111437. */
  111438. if( dest.eDest==SRT_EphemTab ){
  111439. assert( p->pEList );
  111440. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  111441. dest.eDest = SRT_Table;
  111442. }
  111443. /* Special handling for a compound-select that originates as a VALUES clause.
  111444. */
  111445. if( p->selFlags & SF_MultiValue ){
  111446. rc = multiSelectValues(pParse, p, &dest);
  111447. goto multi_select_end;
  111448. }
  111449. /* Make sure all SELECTs in the statement have the same number of elements
  111450. ** in their result sets.
  111451. */
  111452. assert( p->pEList && pPrior->pEList );
  111453. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  111454. #ifndef SQLITE_OMIT_CTE
  111455. if( p->selFlags & SF_Recursive ){
  111456. generateWithRecursiveQuery(pParse, p, &dest);
  111457. }else
  111458. #endif
  111459. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  111460. */
  111461. if( p->pOrderBy ){
  111462. return multiSelectOrderBy(pParse, p, pDest);
  111463. }else
  111464. /* Generate code for the left and right SELECT statements.
  111465. */
  111466. switch( p->op ){
  111467. case TK_ALL: {
  111468. int addr = 0;
  111469. int nLimit;
  111470. assert( !pPrior->pLimit );
  111471. pPrior->iLimit = p->iLimit;
  111472. pPrior->iOffset = p->iOffset;
  111473. pPrior->pLimit = p->pLimit;
  111474. pPrior->pOffset = p->pOffset;
  111475. explainSetInteger(iSub1, pParse->iNextSelectId);
  111476. rc = sqlite3Select(pParse, pPrior, &dest);
  111477. p->pLimit = 0;
  111478. p->pOffset = 0;
  111479. if( rc ){
  111480. goto multi_select_end;
  111481. }
  111482. p->pPrior = 0;
  111483. p->iLimit = pPrior->iLimit;
  111484. p->iOffset = pPrior->iOffset;
  111485. if( p->iLimit ){
  111486. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  111487. VdbeComment((v, "Jump ahead if LIMIT reached"));
  111488. if( p->iOffset ){
  111489. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  111490. p->iLimit, p->iOffset+1, p->iOffset);
  111491. }
  111492. }
  111493. explainSetInteger(iSub2, pParse->iNextSelectId);
  111494. rc = sqlite3Select(pParse, p, &dest);
  111495. testcase( rc!=SQLITE_OK );
  111496. pDelete = p->pPrior;
  111497. p->pPrior = pPrior;
  111498. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  111499. if( pPrior->pLimit
  111500. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  111501. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  111502. ){
  111503. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  111504. }
  111505. if( addr ){
  111506. sqlite3VdbeJumpHere(v, addr);
  111507. }
  111508. break;
  111509. }
  111510. case TK_EXCEPT:
  111511. case TK_UNION: {
  111512. int unionTab; /* Cursor number of the temporary table holding result */
  111513. u8 op = 0; /* One of the SRT_ operations to apply to self */
  111514. int priorOp; /* The SRT_ operation to apply to prior selects */
  111515. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  111516. int addr;
  111517. SelectDest uniondest;
  111518. testcase( p->op==TK_EXCEPT );
  111519. testcase( p->op==TK_UNION );
  111520. priorOp = SRT_Union;
  111521. if( dest.eDest==priorOp ){
  111522. /* We can reuse a temporary table generated by a SELECT to our
  111523. ** right.
  111524. */
  111525. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  111526. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  111527. unionTab = dest.iSDParm;
  111528. }else{
  111529. /* We will need to create our own temporary table to hold the
  111530. ** intermediate results.
  111531. */
  111532. unionTab = pParse->nTab++;
  111533. assert( p->pOrderBy==0 );
  111534. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  111535. assert( p->addrOpenEphm[0] == -1 );
  111536. p->addrOpenEphm[0] = addr;
  111537. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  111538. assert( p->pEList );
  111539. }
  111540. /* Code the SELECT statements to our left
  111541. */
  111542. assert( !pPrior->pOrderBy );
  111543. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  111544. explainSetInteger(iSub1, pParse->iNextSelectId);
  111545. rc = sqlite3Select(pParse, pPrior, &uniondest);
  111546. if( rc ){
  111547. goto multi_select_end;
  111548. }
  111549. /* Code the current SELECT statement
  111550. */
  111551. if( p->op==TK_EXCEPT ){
  111552. op = SRT_Except;
  111553. }else{
  111554. assert( p->op==TK_UNION );
  111555. op = SRT_Union;
  111556. }
  111557. p->pPrior = 0;
  111558. pLimit = p->pLimit;
  111559. p->pLimit = 0;
  111560. pOffset = p->pOffset;
  111561. p->pOffset = 0;
  111562. uniondest.eDest = op;
  111563. explainSetInteger(iSub2, pParse->iNextSelectId);
  111564. rc = sqlite3Select(pParse, p, &uniondest);
  111565. testcase( rc!=SQLITE_OK );
  111566. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  111567. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  111568. sqlite3ExprListDelete(db, p->pOrderBy);
  111569. pDelete = p->pPrior;
  111570. p->pPrior = pPrior;
  111571. p->pOrderBy = 0;
  111572. if( p->op==TK_UNION ){
  111573. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  111574. }
  111575. sqlite3ExprDelete(db, p->pLimit);
  111576. p->pLimit = pLimit;
  111577. p->pOffset = pOffset;
  111578. p->iLimit = 0;
  111579. p->iOffset = 0;
  111580. /* Convert the data in the temporary table into whatever form
  111581. ** it is that we currently need.
  111582. */
  111583. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  111584. if( dest.eDest!=priorOp ){
  111585. int iCont, iBreak, iStart;
  111586. assert( p->pEList );
  111587. if( dest.eDest==SRT_Output ){
  111588. Select *pFirst = p;
  111589. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  111590. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  111591. }
  111592. iBreak = sqlite3VdbeMakeLabel(v);
  111593. iCont = sqlite3VdbeMakeLabel(v);
  111594. computeLimitRegisters(pParse, p, iBreak);
  111595. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  111596. iStart = sqlite3VdbeCurrentAddr(v);
  111597. selectInnerLoop(pParse, p, p->pEList, unionTab,
  111598. 0, 0, &dest, iCont, iBreak);
  111599. sqlite3VdbeResolveLabel(v, iCont);
  111600. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  111601. sqlite3VdbeResolveLabel(v, iBreak);
  111602. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  111603. }
  111604. break;
  111605. }
  111606. default: assert( p->op==TK_INTERSECT ); {
  111607. int tab1, tab2;
  111608. int iCont, iBreak, iStart;
  111609. Expr *pLimit, *pOffset;
  111610. int addr;
  111611. SelectDest intersectdest;
  111612. int r1;
  111613. /* INTERSECT is different from the others since it requires
  111614. ** two temporary tables. Hence it has its own case. Begin
  111615. ** by allocating the tables we will need.
  111616. */
  111617. tab1 = pParse->nTab++;
  111618. tab2 = pParse->nTab++;
  111619. assert( p->pOrderBy==0 );
  111620. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  111621. assert( p->addrOpenEphm[0] == -1 );
  111622. p->addrOpenEphm[0] = addr;
  111623. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  111624. assert( p->pEList );
  111625. /* Code the SELECTs to our left into temporary table "tab1".
  111626. */
  111627. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  111628. explainSetInteger(iSub1, pParse->iNextSelectId);
  111629. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  111630. if( rc ){
  111631. goto multi_select_end;
  111632. }
  111633. /* Code the current SELECT into temporary table "tab2"
  111634. */
  111635. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  111636. assert( p->addrOpenEphm[1] == -1 );
  111637. p->addrOpenEphm[1] = addr;
  111638. p->pPrior = 0;
  111639. pLimit = p->pLimit;
  111640. p->pLimit = 0;
  111641. pOffset = p->pOffset;
  111642. p->pOffset = 0;
  111643. intersectdest.iSDParm = tab2;
  111644. explainSetInteger(iSub2, pParse->iNextSelectId);
  111645. rc = sqlite3Select(pParse, p, &intersectdest);
  111646. testcase( rc!=SQLITE_OK );
  111647. pDelete = p->pPrior;
  111648. p->pPrior = pPrior;
  111649. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  111650. sqlite3ExprDelete(db, p->pLimit);
  111651. p->pLimit = pLimit;
  111652. p->pOffset = pOffset;
  111653. /* Generate code to take the intersection of the two temporary
  111654. ** tables.
  111655. */
  111656. assert( p->pEList );
  111657. if( dest.eDest==SRT_Output ){
  111658. Select *pFirst = p;
  111659. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  111660. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  111661. }
  111662. iBreak = sqlite3VdbeMakeLabel(v);
  111663. iCont = sqlite3VdbeMakeLabel(v);
  111664. computeLimitRegisters(pParse, p, iBreak);
  111665. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  111666. r1 = sqlite3GetTempReg(pParse);
  111667. iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
  111668. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  111669. sqlite3ReleaseTempReg(pParse, r1);
  111670. selectInnerLoop(pParse, p, p->pEList, tab1,
  111671. 0, 0, &dest, iCont, iBreak);
  111672. sqlite3VdbeResolveLabel(v, iCont);
  111673. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  111674. sqlite3VdbeResolveLabel(v, iBreak);
  111675. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  111676. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  111677. break;
  111678. }
  111679. }
  111680. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  111681. /* Compute collating sequences used by
  111682. ** temporary tables needed to implement the compound select.
  111683. ** Attach the KeyInfo structure to all temporary tables.
  111684. **
  111685. ** This section is run by the right-most SELECT statement only.
  111686. ** SELECT statements to the left always skip this part. The right-most
  111687. ** SELECT might also skip this part if it has no ORDER BY clause and
  111688. ** no temp tables are required.
  111689. */
  111690. if( p->selFlags & SF_UsesEphemeral ){
  111691. int i; /* Loop counter */
  111692. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  111693. Select *pLoop; /* For looping through SELECT statements */
  111694. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  111695. int nCol; /* Number of columns in result set */
  111696. assert( p->pNext==0 );
  111697. nCol = p->pEList->nExpr;
  111698. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  111699. if( !pKeyInfo ){
  111700. rc = SQLITE_NOMEM_BKPT;
  111701. goto multi_select_end;
  111702. }
  111703. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  111704. *apColl = multiSelectCollSeq(pParse, p, i);
  111705. if( 0==*apColl ){
  111706. *apColl = db->pDfltColl;
  111707. }
  111708. }
  111709. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  111710. for(i=0; i<2; i++){
  111711. int addr = pLoop->addrOpenEphm[i];
  111712. if( addr<0 ){
  111713. /* If [0] is unused then [1] is also unused. So we can
  111714. ** always safely abort as soon as the first unused slot is found */
  111715. assert( pLoop->addrOpenEphm[1]<0 );
  111716. break;
  111717. }
  111718. sqlite3VdbeChangeP2(v, addr, nCol);
  111719. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  111720. P4_KEYINFO);
  111721. pLoop->addrOpenEphm[i] = -1;
  111722. }
  111723. }
  111724. sqlite3KeyInfoUnref(pKeyInfo);
  111725. }
  111726. multi_select_end:
  111727. pDest->iSdst = dest.iSdst;
  111728. pDest->nSdst = dest.nSdst;
  111729. sqlite3SelectDelete(db, pDelete);
  111730. return rc;
  111731. }
  111732. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  111733. /*
  111734. ** Error message for when two or more terms of a compound select have different
  111735. ** size result sets.
  111736. */
  111737. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  111738. if( p->selFlags & SF_Values ){
  111739. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  111740. }else{
  111741. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  111742. " do not have the same number of result columns", selectOpName(p->op));
  111743. }
  111744. }
  111745. /*
  111746. ** Code an output subroutine for a coroutine implementation of a
  111747. ** SELECT statment.
  111748. **
  111749. ** The data to be output is contained in pIn->iSdst. There are
  111750. ** pIn->nSdst columns to be output. pDest is where the output should
  111751. ** be sent.
  111752. **
  111753. ** regReturn is the number of the register holding the subroutine
  111754. ** return address.
  111755. **
  111756. ** If regPrev>0 then it is the first register in a vector that
  111757. ** records the previous output. mem[regPrev] is a flag that is false
  111758. ** if there has been no previous output. If regPrev>0 then code is
  111759. ** generated to suppress duplicates. pKeyInfo is used for comparing
  111760. ** keys.
  111761. **
  111762. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  111763. ** iBreak.
  111764. */
  111765. static int generateOutputSubroutine(
  111766. Parse *pParse, /* Parsing context */
  111767. Select *p, /* The SELECT statement */
  111768. SelectDest *pIn, /* Coroutine supplying data */
  111769. SelectDest *pDest, /* Where to send the data */
  111770. int regReturn, /* The return address register */
  111771. int regPrev, /* Previous result register. No uniqueness if 0 */
  111772. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  111773. int iBreak /* Jump here if we hit the LIMIT */
  111774. ){
  111775. Vdbe *v = pParse->pVdbe;
  111776. int iContinue;
  111777. int addr;
  111778. addr = sqlite3VdbeCurrentAddr(v);
  111779. iContinue = sqlite3VdbeMakeLabel(v);
  111780. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  111781. */
  111782. if( regPrev ){
  111783. int addr1, addr2;
  111784. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  111785. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  111786. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  111787. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  111788. sqlite3VdbeJumpHere(v, addr1);
  111789. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  111790. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  111791. }
  111792. if( pParse->db->mallocFailed ) return 0;
  111793. /* Suppress the first OFFSET entries if there is an OFFSET clause
  111794. */
  111795. codeOffset(v, p->iOffset, iContinue);
  111796. assert( pDest->eDest!=SRT_Exists );
  111797. assert( pDest->eDest!=SRT_Table );
  111798. switch( pDest->eDest ){
  111799. /* Store the result as data using a unique key.
  111800. */
  111801. case SRT_EphemTab: {
  111802. int r1 = sqlite3GetTempReg(pParse);
  111803. int r2 = sqlite3GetTempReg(pParse);
  111804. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  111805. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  111806. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  111807. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  111808. sqlite3ReleaseTempReg(pParse, r2);
  111809. sqlite3ReleaseTempReg(pParse, r1);
  111810. break;
  111811. }
  111812. #ifndef SQLITE_OMIT_SUBQUERY
  111813. /* If we are creating a set for an "expr IN (SELECT ...)".
  111814. */
  111815. case SRT_Set: {
  111816. int r1;
  111817. testcase( pIn->nSdst>1 );
  111818. r1 = sqlite3GetTempReg(pParse);
  111819. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
  111820. r1, pDest->zAffSdst, pIn->nSdst);
  111821. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  111822. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
  111823. pIn->iSdst, pIn->nSdst);
  111824. sqlite3ReleaseTempReg(pParse, r1);
  111825. break;
  111826. }
  111827. /* If this is a scalar select that is part of an expression, then
  111828. ** store the results in the appropriate memory cell and break out
  111829. ** of the scan loop.
  111830. */
  111831. case SRT_Mem: {
  111832. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  111833. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  111834. /* The LIMIT clause will jump out of the loop for us */
  111835. break;
  111836. }
  111837. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  111838. /* The results are stored in a sequence of registers
  111839. ** starting at pDest->iSdst. Then the co-routine yields.
  111840. */
  111841. case SRT_Coroutine: {
  111842. if( pDest->iSdst==0 ){
  111843. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  111844. pDest->nSdst = pIn->nSdst;
  111845. }
  111846. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  111847. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  111848. break;
  111849. }
  111850. /* If none of the above, then the result destination must be
  111851. ** SRT_Output. This routine is never called with any other
  111852. ** destination other than the ones handled above or SRT_Output.
  111853. **
  111854. ** For SRT_Output, results are stored in a sequence of registers.
  111855. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  111856. ** return the next row of result.
  111857. */
  111858. default: {
  111859. assert( pDest->eDest==SRT_Output );
  111860. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  111861. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  111862. break;
  111863. }
  111864. }
  111865. /* Jump to the end of the loop if the LIMIT is reached.
  111866. */
  111867. if( p->iLimit ){
  111868. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  111869. }
  111870. /* Generate the subroutine return
  111871. */
  111872. sqlite3VdbeResolveLabel(v, iContinue);
  111873. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  111874. return addr;
  111875. }
  111876. /*
  111877. ** Alternative compound select code generator for cases when there
  111878. ** is an ORDER BY clause.
  111879. **
  111880. ** We assume a query of the following form:
  111881. **
  111882. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  111883. **
  111884. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  111885. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  111886. ** co-routines. Then run the co-routines in parallel and merge the results
  111887. ** into the output. In addition to the two coroutines (called selectA and
  111888. ** selectB) there are 7 subroutines:
  111889. **
  111890. ** outA: Move the output of the selectA coroutine into the output
  111891. ** of the compound query.
  111892. **
  111893. ** outB: Move the output of the selectB coroutine into the output
  111894. ** of the compound query. (Only generated for UNION and
  111895. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  111896. ** appears only in B.)
  111897. **
  111898. ** AltB: Called when there is data from both coroutines and A<B.
  111899. **
  111900. ** AeqB: Called when there is data from both coroutines and A==B.
  111901. **
  111902. ** AgtB: Called when there is data from both coroutines and A>B.
  111903. **
  111904. ** EofA: Called when data is exhausted from selectA.
  111905. **
  111906. ** EofB: Called when data is exhausted from selectB.
  111907. **
  111908. ** The implementation of the latter five subroutines depend on which
  111909. ** <operator> is used:
  111910. **
  111911. **
  111912. ** UNION ALL UNION EXCEPT INTERSECT
  111913. ** ------------- ----------------- -------------- -----------------
  111914. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  111915. **
  111916. ** AeqB: outA, nextA nextA nextA outA, nextA
  111917. **
  111918. ** AgtB: outB, nextB outB, nextB nextB nextB
  111919. **
  111920. ** EofA: outB, nextB outB, nextB halt halt
  111921. **
  111922. ** EofB: outA, nextA outA, nextA outA, nextA halt
  111923. **
  111924. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  111925. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  111926. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  111927. ** following nextX causes a jump to the end of the select processing.
  111928. **
  111929. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  111930. ** within the output subroutine. The regPrev register set holds the previously
  111931. ** output value. A comparison is made against this value and the output
  111932. ** is skipped if the next results would be the same as the previous.
  111933. **
  111934. ** The implementation plan is to implement the two coroutines and seven
  111935. ** subroutines first, then put the control logic at the bottom. Like this:
  111936. **
  111937. ** goto Init
  111938. ** coA: coroutine for left query (A)
  111939. ** coB: coroutine for right query (B)
  111940. ** outA: output one row of A
  111941. ** outB: output one row of B (UNION and UNION ALL only)
  111942. ** EofA: ...
  111943. ** EofB: ...
  111944. ** AltB: ...
  111945. ** AeqB: ...
  111946. ** AgtB: ...
  111947. ** Init: initialize coroutine registers
  111948. ** yield coA
  111949. ** if eof(A) goto EofA
  111950. ** yield coB
  111951. ** if eof(B) goto EofB
  111952. ** Cmpr: Compare A, B
  111953. ** Jump AltB, AeqB, AgtB
  111954. ** End: ...
  111955. **
  111956. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  111957. ** actually called using Gosub and they do not Return. EofA and EofB loop
  111958. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  111959. ** and AgtB jump to either L2 or to one of EofA or EofB.
  111960. */
  111961. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  111962. static int multiSelectOrderBy(
  111963. Parse *pParse, /* Parsing context */
  111964. Select *p, /* The right-most of SELECTs to be coded */
  111965. SelectDest *pDest /* What to do with query results */
  111966. ){
  111967. int i, j; /* Loop counters */
  111968. Select *pPrior; /* Another SELECT immediately to our left */
  111969. Vdbe *v; /* Generate code to this VDBE */
  111970. SelectDest destA; /* Destination for coroutine A */
  111971. SelectDest destB; /* Destination for coroutine B */
  111972. int regAddrA; /* Address register for select-A coroutine */
  111973. int regAddrB; /* Address register for select-B coroutine */
  111974. int addrSelectA; /* Address of the select-A coroutine */
  111975. int addrSelectB; /* Address of the select-B coroutine */
  111976. int regOutA; /* Address register for the output-A subroutine */
  111977. int regOutB; /* Address register for the output-B subroutine */
  111978. int addrOutA; /* Address of the output-A subroutine */
  111979. int addrOutB = 0; /* Address of the output-B subroutine */
  111980. int addrEofA; /* Address of the select-A-exhausted subroutine */
  111981. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  111982. int addrEofB; /* Address of the select-B-exhausted subroutine */
  111983. int addrAltB; /* Address of the A<B subroutine */
  111984. int addrAeqB; /* Address of the A==B subroutine */
  111985. int addrAgtB; /* Address of the A>B subroutine */
  111986. int regLimitA; /* Limit register for select-A */
  111987. int regLimitB; /* Limit register for select-A */
  111988. int regPrev; /* A range of registers to hold previous output */
  111989. int savedLimit; /* Saved value of p->iLimit */
  111990. int savedOffset; /* Saved value of p->iOffset */
  111991. int labelCmpr; /* Label for the start of the merge algorithm */
  111992. int labelEnd; /* Label for the end of the overall SELECT stmt */
  111993. int addr1; /* Jump instructions that get retargetted */
  111994. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  111995. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  111996. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  111997. sqlite3 *db; /* Database connection */
  111998. ExprList *pOrderBy; /* The ORDER BY clause */
  111999. int nOrderBy; /* Number of terms in the ORDER BY clause */
  112000. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  112001. #ifndef SQLITE_OMIT_EXPLAIN
  112002. int iSub1; /* EQP id of left-hand query */
  112003. int iSub2; /* EQP id of right-hand query */
  112004. #endif
  112005. assert( p->pOrderBy!=0 );
  112006. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  112007. db = pParse->db;
  112008. v = pParse->pVdbe;
  112009. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  112010. labelEnd = sqlite3VdbeMakeLabel(v);
  112011. labelCmpr = sqlite3VdbeMakeLabel(v);
  112012. /* Patch up the ORDER BY clause
  112013. */
  112014. op = p->op;
  112015. pPrior = p->pPrior;
  112016. assert( pPrior->pOrderBy==0 );
  112017. pOrderBy = p->pOrderBy;
  112018. assert( pOrderBy );
  112019. nOrderBy = pOrderBy->nExpr;
  112020. /* For operators other than UNION ALL we have to make sure that
  112021. ** the ORDER BY clause covers every term of the result set. Add
  112022. ** terms to the ORDER BY clause as necessary.
  112023. */
  112024. if( op!=TK_ALL ){
  112025. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  112026. struct ExprList_item *pItem;
  112027. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  112028. assert( pItem->u.x.iOrderByCol>0 );
  112029. if( pItem->u.x.iOrderByCol==i ) break;
  112030. }
  112031. if( j==nOrderBy ){
  112032. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  112033. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  112034. pNew->flags |= EP_IntValue;
  112035. pNew->u.iValue = i;
  112036. p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  112037. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  112038. }
  112039. }
  112040. }
  112041. /* Compute the comparison permutation and keyinfo that is used with
  112042. ** the permutation used to determine if the next
  112043. ** row of results comes from selectA or selectB. Also add explicit
  112044. ** collations to the ORDER BY clause terms so that when the subqueries
  112045. ** to the right and the left are evaluated, they use the correct
  112046. ** collation.
  112047. */
  112048. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  112049. if( aPermute ){
  112050. struct ExprList_item *pItem;
  112051. aPermute[0] = nOrderBy;
  112052. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  112053. assert( pItem->u.x.iOrderByCol>0 );
  112054. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  112055. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  112056. }
  112057. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  112058. }else{
  112059. pKeyMerge = 0;
  112060. }
  112061. /* Reattach the ORDER BY clause to the query.
  112062. */
  112063. p->pOrderBy = pOrderBy;
  112064. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  112065. /* Allocate a range of temporary registers and the KeyInfo needed
  112066. ** for the logic that removes duplicate result rows when the
  112067. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  112068. */
  112069. if( op==TK_ALL ){
  112070. regPrev = 0;
  112071. }else{
  112072. int nExpr = p->pEList->nExpr;
  112073. assert( nOrderBy>=nExpr || db->mallocFailed );
  112074. regPrev = pParse->nMem+1;
  112075. pParse->nMem += nExpr+1;
  112076. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  112077. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  112078. if( pKeyDup ){
  112079. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  112080. for(i=0; i<nExpr; i++){
  112081. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  112082. pKeyDup->aSortOrder[i] = 0;
  112083. }
  112084. }
  112085. }
  112086. /* Separate the left and the right query from one another
  112087. */
  112088. p->pPrior = 0;
  112089. pPrior->pNext = 0;
  112090. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  112091. if( pPrior->pPrior==0 ){
  112092. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  112093. }
  112094. /* Compute the limit registers */
  112095. computeLimitRegisters(pParse, p, labelEnd);
  112096. if( p->iLimit && op==TK_ALL ){
  112097. regLimitA = ++pParse->nMem;
  112098. regLimitB = ++pParse->nMem;
  112099. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  112100. regLimitA);
  112101. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  112102. }else{
  112103. regLimitA = regLimitB = 0;
  112104. }
  112105. sqlite3ExprDelete(db, p->pLimit);
  112106. p->pLimit = 0;
  112107. sqlite3ExprDelete(db, p->pOffset);
  112108. p->pOffset = 0;
  112109. regAddrA = ++pParse->nMem;
  112110. regAddrB = ++pParse->nMem;
  112111. regOutA = ++pParse->nMem;
  112112. regOutB = ++pParse->nMem;
  112113. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  112114. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  112115. /* Generate a coroutine to evaluate the SELECT statement to the
  112116. ** left of the compound operator - the "A" select.
  112117. */
  112118. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  112119. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  112120. VdbeComment((v, "left SELECT"));
  112121. pPrior->iLimit = regLimitA;
  112122. explainSetInteger(iSub1, pParse->iNextSelectId);
  112123. sqlite3Select(pParse, pPrior, &destA);
  112124. sqlite3VdbeEndCoroutine(v, regAddrA);
  112125. sqlite3VdbeJumpHere(v, addr1);
  112126. /* Generate a coroutine to evaluate the SELECT statement on
  112127. ** the right - the "B" select
  112128. */
  112129. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  112130. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  112131. VdbeComment((v, "right SELECT"));
  112132. savedLimit = p->iLimit;
  112133. savedOffset = p->iOffset;
  112134. p->iLimit = regLimitB;
  112135. p->iOffset = 0;
  112136. explainSetInteger(iSub2, pParse->iNextSelectId);
  112137. sqlite3Select(pParse, p, &destB);
  112138. p->iLimit = savedLimit;
  112139. p->iOffset = savedOffset;
  112140. sqlite3VdbeEndCoroutine(v, regAddrB);
  112141. /* Generate a subroutine that outputs the current row of the A
  112142. ** select as the next output row of the compound select.
  112143. */
  112144. VdbeNoopComment((v, "Output routine for A"));
  112145. addrOutA = generateOutputSubroutine(pParse,
  112146. p, &destA, pDest, regOutA,
  112147. regPrev, pKeyDup, labelEnd);
  112148. /* Generate a subroutine that outputs the current row of the B
  112149. ** select as the next output row of the compound select.
  112150. */
  112151. if( op==TK_ALL || op==TK_UNION ){
  112152. VdbeNoopComment((v, "Output routine for B"));
  112153. addrOutB = generateOutputSubroutine(pParse,
  112154. p, &destB, pDest, regOutB,
  112155. regPrev, pKeyDup, labelEnd);
  112156. }
  112157. sqlite3KeyInfoUnref(pKeyDup);
  112158. /* Generate a subroutine to run when the results from select A
  112159. ** are exhausted and only data in select B remains.
  112160. */
  112161. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  112162. addrEofA_noB = addrEofA = labelEnd;
  112163. }else{
  112164. VdbeNoopComment((v, "eof-A subroutine"));
  112165. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  112166. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  112167. VdbeCoverage(v);
  112168. sqlite3VdbeGoto(v, addrEofA);
  112169. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  112170. }
  112171. /* Generate a subroutine to run when the results from select B
  112172. ** are exhausted and only data in select A remains.
  112173. */
  112174. if( op==TK_INTERSECT ){
  112175. addrEofB = addrEofA;
  112176. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  112177. }else{
  112178. VdbeNoopComment((v, "eof-B subroutine"));
  112179. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  112180. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  112181. sqlite3VdbeGoto(v, addrEofB);
  112182. }
  112183. /* Generate code to handle the case of A<B
  112184. */
  112185. VdbeNoopComment((v, "A-lt-B subroutine"));
  112186. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  112187. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  112188. sqlite3VdbeGoto(v, labelCmpr);
  112189. /* Generate code to handle the case of A==B
  112190. */
  112191. if( op==TK_ALL ){
  112192. addrAeqB = addrAltB;
  112193. }else if( op==TK_INTERSECT ){
  112194. addrAeqB = addrAltB;
  112195. addrAltB++;
  112196. }else{
  112197. VdbeNoopComment((v, "A-eq-B subroutine"));
  112198. addrAeqB =
  112199. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  112200. sqlite3VdbeGoto(v, labelCmpr);
  112201. }
  112202. /* Generate code to handle the case of A>B
  112203. */
  112204. VdbeNoopComment((v, "A-gt-B subroutine"));
  112205. addrAgtB = sqlite3VdbeCurrentAddr(v);
  112206. if( op==TK_ALL || op==TK_UNION ){
  112207. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  112208. }
  112209. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  112210. sqlite3VdbeGoto(v, labelCmpr);
  112211. /* This code runs once to initialize everything.
  112212. */
  112213. sqlite3VdbeJumpHere(v, addr1);
  112214. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  112215. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  112216. /* Implement the main merge loop
  112217. */
  112218. sqlite3VdbeResolveLabel(v, labelCmpr);
  112219. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  112220. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  112221. (char*)pKeyMerge, P4_KEYINFO);
  112222. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  112223. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  112224. /* Jump to the this point in order to terminate the query.
  112225. */
  112226. sqlite3VdbeResolveLabel(v, labelEnd);
  112227. /* Set the number of output columns
  112228. */
  112229. if( pDest->eDest==SRT_Output ){
  112230. Select *pFirst = pPrior;
  112231. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  112232. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  112233. }
  112234. /* Reassembly the compound query so that it will be freed correctly
  112235. ** by the calling function */
  112236. if( p->pPrior ){
  112237. sqlite3SelectDelete(db, p->pPrior);
  112238. }
  112239. p->pPrior = pPrior;
  112240. pPrior->pNext = p;
  112241. /*** TBD: Insert subroutine calls to close cursors on incomplete
  112242. **** subqueries ****/
  112243. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  112244. return pParse->nErr!=0;
  112245. }
  112246. #endif
  112247. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  112248. /* An instance of the SubstContext object describes an substitution edit
  112249. ** to be performed on a parse tree.
  112250. **
  112251. ** All references to columns in table iTable are to be replaced by corresponding
  112252. ** expressions in pEList.
  112253. */
  112254. typedef struct SubstContext {
  112255. Parse *pParse; /* The parsing context */
  112256. int iTable; /* Replace references to this table */
  112257. int iNewTable; /* New table number */
  112258. int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
  112259. ExprList *pEList; /* Replacement expressions */
  112260. } SubstContext;
  112261. /* Forward Declarations */
  112262. static void substExprList(SubstContext*, ExprList*);
  112263. static void substSelect(SubstContext*, Select*, int);
  112264. /*
  112265. ** Scan through the expression pExpr. Replace every reference to
  112266. ** a column in table number iTable with a copy of the iColumn-th
  112267. ** entry in pEList. (But leave references to the ROWID column
  112268. ** unchanged.)
  112269. **
  112270. ** This routine is part of the flattening procedure. A subquery
  112271. ** whose result set is defined by pEList appears as entry in the
  112272. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  112273. ** FORM clause entry is iTable. This routine makes the necessary
  112274. ** changes to pExpr so that it refers directly to the source table
  112275. ** of the subquery rather the result set of the subquery.
  112276. */
  112277. static Expr *substExpr(
  112278. SubstContext *pSubst, /* Description of the substitution */
  112279. Expr *pExpr /* Expr in which substitution occurs */
  112280. ){
  112281. if( pExpr==0 ) return 0;
  112282. if( ExprHasProperty(pExpr, EP_FromJoin) && pExpr->iRightJoinTable==pSubst->iTable ){
  112283. pExpr->iRightJoinTable = pSubst->iNewTable;
  112284. }
  112285. if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
  112286. if( pExpr->iColumn<0 ){
  112287. pExpr->op = TK_NULL;
  112288. }else{
  112289. Expr *pNew;
  112290. Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
  112291. Expr ifNullRow;
  112292. assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
  112293. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  112294. if( sqlite3ExprIsVector(pCopy) ){
  112295. sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
  112296. }else{
  112297. sqlite3 *db = pSubst->pParse->db;
  112298. if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
  112299. memset(&ifNullRow, 0, sizeof(ifNullRow));
  112300. ifNullRow.op = TK_IF_NULL_ROW;
  112301. ifNullRow.pLeft = pCopy;
  112302. ifNullRow.iTable = pSubst->iNewTable;
  112303. pCopy = &ifNullRow;
  112304. }
  112305. pNew = sqlite3ExprDup(db, pCopy, 0);
  112306. if( pNew && (pExpr->flags & EP_FromJoin) ){
  112307. pNew->iRightJoinTable = pExpr->iRightJoinTable;
  112308. pNew->flags |= EP_FromJoin;
  112309. }
  112310. sqlite3ExprDelete(db, pExpr);
  112311. pExpr = pNew;
  112312. }
  112313. }
  112314. }else{
  112315. if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
  112316. pExpr->iTable = pSubst->iNewTable;
  112317. }
  112318. pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
  112319. pExpr->pRight = substExpr(pSubst, pExpr->pRight);
  112320. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  112321. substSelect(pSubst, pExpr->x.pSelect, 1);
  112322. }else{
  112323. substExprList(pSubst, pExpr->x.pList);
  112324. }
  112325. }
  112326. return pExpr;
  112327. }
  112328. static void substExprList(
  112329. SubstContext *pSubst, /* Description of the substitution */
  112330. ExprList *pList /* List to scan and in which to make substitutes */
  112331. ){
  112332. int i;
  112333. if( pList==0 ) return;
  112334. for(i=0; i<pList->nExpr; i++){
  112335. pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
  112336. }
  112337. }
  112338. static void substSelect(
  112339. SubstContext *pSubst, /* Description of the substitution */
  112340. Select *p, /* SELECT statement in which to make substitutions */
  112341. int doPrior /* Do substitutes on p->pPrior too */
  112342. ){
  112343. SrcList *pSrc;
  112344. struct SrcList_item *pItem;
  112345. int i;
  112346. if( !p ) return;
  112347. do{
  112348. substExprList(pSubst, p->pEList);
  112349. substExprList(pSubst, p->pGroupBy);
  112350. substExprList(pSubst, p->pOrderBy);
  112351. p->pHaving = substExpr(pSubst, p->pHaving);
  112352. p->pWhere = substExpr(pSubst, p->pWhere);
  112353. pSrc = p->pSrc;
  112354. assert( pSrc!=0 );
  112355. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  112356. substSelect(pSubst, pItem->pSelect, 1);
  112357. if( pItem->fg.isTabFunc ){
  112358. substExprList(pSubst, pItem->u1.pFuncArg);
  112359. }
  112360. }
  112361. }while( doPrior && (p = p->pPrior)!=0 );
  112362. }
  112363. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  112364. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  112365. /*
  112366. ** This routine attempts to flatten subqueries as a performance optimization.
  112367. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  112368. **
  112369. ** To understand the concept of flattening, consider the following
  112370. ** query:
  112371. **
  112372. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  112373. **
  112374. ** The default way of implementing this query is to execute the
  112375. ** subquery first and store the results in a temporary table, then
  112376. ** run the outer query on that temporary table. This requires two
  112377. ** passes over the data. Furthermore, because the temporary table
  112378. ** has no indices, the WHERE clause on the outer query cannot be
  112379. ** optimized.
  112380. **
  112381. ** This routine attempts to rewrite queries such as the above into
  112382. ** a single flat select, like this:
  112383. **
  112384. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  112385. **
  112386. ** The code generated for this simplification gives the same result
  112387. ** but only has to scan the data once. And because indices might
  112388. ** exist on the table t1, a complete scan of the data might be
  112389. ** avoided.
  112390. **
  112391. ** Flattening is only attempted if all of the following are true:
  112392. **
  112393. ** (1) The subquery and the outer query do not both use aggregates.
  112394. **
  112395. ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
  112396. ** and (2b) the outer query does not use subqueries other than the one
  112397. ** FROM-clause subquery that is a candidate for flattening. (2b is
  112398. ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
  112399. **
  112400. ** (3) The subquery is not the right operand of a LEFT JOIN
  112401. ** or the subquery is not itself a join and the outer query is not
  112402. ** an aggregate.
  112403. **
  112404. ** (4) The subquery is not DISTINCT.
  112405. **
  112406. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  112407. ** sub-queries that were excluded from this optimization. Restriction
  112408. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  112409. **
  112410. ** (6) The subquery does not use aggregates or the outer query is not
  112411. ** DISTINCT.
  112412. **
  112413. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  112414. ** A FROM clause, consider adding a FROM clause with the special
  112415. ** table sqlite_once that consists of a single row containing a
  112416. ** single NULL.
  112417. **
  112418. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  112419. **
  112420. ** (9) The subquery does not use LIMIT or the outer query does not use
  112421. ** aggregates.
  112422. **
  112423. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  112424. ** accidently carried the comment forward until 2014-09-15. Original
  112425. ** text: "The subquery does not use aggregates or the outer query
  112426. ** does not use LIMIT."
  112427. **
  112428. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  112429. **
  112430. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  112431. ** a separate restriction deriving from ticket #350.
  112432. **
  112433. ** (13) The subquery and outer query do not both use LIMIT.
  112434. **
  112435. ** (14) The subquery does not use OFFSET.
  112436. **
  112437. ** (15) The outer query is not part of a compound select or the
  112438. ** subquery does not have a LIMIT clause.
  112439. ** (See ticket #2339 and ticket [02a8e81d44]).
  112440. **
  112441. ** (16) The outer query is not an aggregate or the subquery does
  112442. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  112443. ** until we introduced the group_concat() function.
  112444. **
  112445. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  112446. ** compound clause made up entirely of non-aggregate queries, and
  112447. ** the parent query:
  112448. **
  112449. ** * is not itself part of a compound select,
  112450. ** * is not an aggregate or DISTINCT query, and
  112451. ** * is not a join
  112452. **
  112453. ** The parent and sub-query may contain WHERE clauses. Subject to
  112454. ** rules (11), (13) and (14), they may also contain ORDER BY,
  112455. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  112456. ** operator other than UNION ALL because all the other compound
  112457. ** operators have an implied DISTINCT which is disallowed by
  112458. ** restriction (4).
  112459. **
  112460. ** Also, each component of the sub-query must return the same number
  112461. ** of result columns. This is actually a requirement for any compound
  112462. ** SELECT statement, but all the code here does is make sure that no
  112463. ** such (illegal) sub-query is flattened. The caller will detect the
  112464. ** syntax error and return a detailed message.
  112465. **
  112466. ** (18) If the sub-query is a compound select, then all terms of the
  112467. ** ORDER by clause of the parent must be simple references to
  112468. ** columns of the sub-query.
  112469. **
  112470. ** (19) The subquery does not use LIMIT or the outer query does not
  112471. ** have a WHERE clause.
  112472. **
  112473. ** (20) If the sub-query is a compound select, then it must not use
  112474. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  112475. ** somewhat by saying that the terms of the ORDER BY clause must
  112476. ** appear as unmodified result columns in the outer query. But we
  112477. ** have other optimizations in mind to deal with that case.
  112478. **
  112479. ** (21) The subquery does not use LIMIT or the outer query is not
  112480. ** DISTINCT. (See ticket [752e1646fc]).
  112481. **
  112482. ** (22) The subquery is not a recursive CTE.
  112483. **
  112484. ** (23) The parent is not a recursive CTE, or the sub-query is not a
  112485. ** compound query. This restriction is because transforming the
  112486. ** parent to a compound query confuses the code that handles
  112487. ** recursive queries in multiSelect().
  112488. **
  112489. ** (24) The subquery is not an aggregate that uses the built-in min() or
  112490. ** or max() functions. (Without this restriction, a query like:
  112491. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  112492. ** return the value X for which Y was maximal.)
  112493. **
  112494. **
  112495. ** In this routine, the "p" parameter is a pointer to the outer query.
  112496. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  112497. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  112498. **
  112499. ** If flattening is not attempted, this routine is a no-op and returns 0.
  112500. ** If flattening is attempted this routine returns 1.
  112501. **
  112502. ** All of the expression analysis must occur on both the outer query and
  112503. ** the subquery before this routine runs.
  112504. */
  112505. static int flattenSubquery(
  112506. Parse *pParse, /* Parsing context */
  112507. Select *p, /* The parent or outer SELECT statement */
  112508. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  112509. int isAgg, /* True if outer SELECT uses aggregate functions */
  112510. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  112511. ){
  112512. const char *zSavedAuthContext = pParse->zAuthContext;
  112513. Select *pParent; /* Current UNION ALL term of the other query */
  112514. Select *pSub; /* The inner query or "subquery" */
  112515. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  112516. SrcList *pSrc; /* The FROM clause of the outer query */
  112517. SrcList *pSubSrc; /* The FROM clause of the subquery */
  112518. ExprList *pList; /* The result set of the outer query */
  112519. int iParent; /* VDBE cursor number of the pSub result set temp table */
  112520. int iNewParent = -1;/* Replacement table for iParent */
  112521. int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
  112522. int i; /* Loop counter */
  112523. Expr *pWhere; /* The WHERE clause */
  112524. struct SrcList_item *pSubitem; /* The subquery */
  112525. sqlite3 *db = pParse->db;
  112526. /* Check to see if flattening is permitted. Return 0 if not.
  112527. */
  112528. assert( p!=0 );
  112529. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  112530. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  112531. pSrc = p->pSrc;
  112532. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  112533. pSubitem = &pSrc->a[iFrom];
  112534. iParent = pSubitem->iCursor;
  112535. pSub = pSubitem->pSelect;
  112536. assert( pSub!=0 );
  112537. if( subqueryIsAgg ){
  112538. if( isAgg ) return 0; /* Restriction (1) */
  112539. if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
  112540. if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
  112541. || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
  112542. || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
  112543. ){
  112544. return 0; /* Restriction (2b) */
  112545. }
  112546. }
  112547. pSubSrc = pSub->pSrc;
  112548. assert( pSubSrc );
  112549. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  112550. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  112551. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  112552. ** became arbitrary expressions, we were forced to add restrictions (13)
  112553. ** and (14). */
  112554. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  112555. if( pSub->pOffset ) return 0; /* Restriction (14) */
  112556. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  112557. return 0; /* Restriction (15) */
  112558. }
  112559. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  112560. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  112561. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  112562. return 0; /* Restrictions (8)(9) */
  112563. }
  112564. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  112565. return 0; /* Restriction (6) */
  112566. }
  112567. if( p->pOrderBy && pSub->pOrderBy ){
  112568. return 0; /* Restriction (11) */
  112569. }
  112570. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  112571. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  112572. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  112573. return 0; /* Restriction (21) */
  112574. }
  112575. testcase( pSub->selFlags & SF_Recursive );
  112576. testcase( pSub->selFlags & SF_MinMaxAgg );
  112577. if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
  112578. return 0; /* Restrictions (22) and (24) */
  112579. }
  112580. if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
  112581. return 0; /* Restriction (23) */
  112582. }
  112583. /*
  112584. ** If the subquery is the right operand of a LEFT JOIN, then the
  112585. ** subquery may not be a join itself. Example of why this is not allowed:
  112586. **
  112587. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  112588. **
  112589. ** If we flatten the above, we would get
  112590. **
  112591. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  112592. **
  112593. ** which is not at all the same thing.
  112594. **
  112595. ** If the subquery is the right operand of a LEFT JOIN, then the outer
  112596. ** query cannot be an aggregate. This is an artifact of the way aggregates
  112597. ** are processed - there is not mechanism to determine if the LEFT JOIN
  112598. ** table should be all-NULL.
  112599. **
  112600. ** See also tickets #306, #350, and #3300.
  112601. */
  112602. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  112603. isLeftJoin = 1;
  112604. if( pSubSrc->nSrc>1 || isAgg ){
  112605. return 0; /* Restriction (3) */
  112606. }
  112607. }
  112608. #ifdef SQLITE_EXTRA_IFNULLROW
  112609. else if( iFrom>0 && !isAgg ){
  112610. /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
  112611. ** every reference to any result column from subquery in a join, even though
  112612. ** they are not necessary. This will stress-test the OP_IfNullRow opcode. */
  112613. isLeftJoin = -1;
  112614. }
  112615. #endif
  112616. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  112617. ** use only the UNION ALL operator. And none of the simple select queries
  112618. ** that make up the compound SELECT are allowed to be aggregate or distinct
  112619. ** queries.
  112620. */
  112621. if( pSub->pPrior ){
  112622. if( pSub->pOrderBy ){
  112623. return 0; /* Restriction 20 */
  112624. }
  112625. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  112626. return 0;
  112627. }
  112628. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  112629. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  112630. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  112631. assert( pSub->pSrc!=0 );
  112632. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  112633. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  112634. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  112635. || pSub1->pSrc->nSrc<1
  112636. ){
  112637. return 0;
  112638. }
  112639. testcase( pSub1->pSrc->nSrc>1 );
  112640. }
  112641. /* Restriction 18. */
  112642. if( p->pOrderBy ){
  112643. int ii;
  112644. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  112645. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  112646. }
  112647. }
  112648. }
  112649. /***** If we reach this point, flattening is permitted. *****/
  112650. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  112651. pSub->zSelName, pSub, iFrom));
  112652. /* Authorize the subquery */
  112653. pParse->zAuthContext = pSubitem->zName;
  112654. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  112655. testcase( i==SQLITE_DENY );
  112656. pParse->zAuthContext = zSavedAuthContext;
  112657. /* If the sub-query is a compound SELECT statement, then (by restrictions
  112658. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  112659. ** be of the form:
  112660. **
  112661. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  112662. **
  112663. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  112664. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  112665. ** OFFSET clauses and joins them to the left-hand-side of the original
  112666. ** using UNION ALL operators. In this case N is the number of simple
  112667. ** select statements in the compound sub-query.
  112668. **
  112669. ** Example:
  112670. **
  112671. ** SELECT a+1 FROM (
  112672. ** SELECT x FROM tab
  112673. ** UNION ALL
  112674. ** SELECT y FROM tab
  112675. ** UNION ALL
  112676. ** SELECT abs(z*2) FROM tab2
  112677. ** ) WHERE a!=5 ORDER BY 1
  112678. **
  112679. ** Transformed into:
  112680. **
  112681. ** SELECT x+1 FROM tab WHERE x+1!=5
  112682. ** UNION ALL
  112683. ** SELECT y+1 FROM tab WHERE y+1!=5
  112684. ** UNION ALL
  112685. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  112686. ** ORDER BY 1
  112687. **
  112688. ** We call this the "compound-subquery flattening".
  112689. */
  112690. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  112691. Select *pNew;
  112692. ExprList *pOrderBy = p->pOrderBy;
  112693. Expr *pLimit = p->pLimit;
  112694. Expr *pOffset = p->pOffset;
  112695. Select *pPrior = p->pPrior;
  112696. p->pOrderBy = 0;
  112697. p->pSrc = 0;
  112698. p->pPrior = 0;
  112699. p->pLimit = 0;
  112700. p->pOffset = 0;
  112701. pNew = sqlite3SelectDup(db, p, 0);
  112702. sqlite3SelectSetName(pNew, pSub->zSelName);
  112703. p->pOffset = pOffset;
  112704. p->pLimit = pLimit;
  112705. p->pOrderBy = pOrderBy;
  112706. p->pSrc = pSrc;
  112707. p->op = TK_ALL;
  112708. if( pNew==0 ){
  112709. p->pPrior = pPrior;
  112710. }else{
  112711. pNew->pPrior = pPrior;
  112712. if( pPrior ) pPrior->pNext = pNew;
  112713. pNew->pNext = p;
  112714. p->pPrior = pNew;
  112715. SELECTTRACE(2,pParse,p,
  112716. ("compound-subquery flattener creates %s.%p as peer\n",
  112717. pNew->zSelName, pNew));
  112718. }
  112719. if( db->mallocFailed ) return 1;
  112720. }
  112721. /* Begin flattening the iFrom-th entry of the FROM clause
  112722. ** in the outer query.
  112723. */
  112724. pSub = pSub1 = pSubitem->pSelect;
  112725. /* Delete the transient table structure associated with the
  112726. ** subquery
  112727. */
  112728. sqlite3DbFree(db, pSubitem->zDatabase);
  112729. sqlite3DbFree(db, pSubitem->zName);
  112730. sqlite3DbFree(db, pSubitem->zAlias);
  112731. pSubitem->zDatabase = 0;
  112732. pSubitem->zName = 0;
  112733. pSubitem->zAlias = 0;
  112734. pSubitem->pSelect = 0;
  112735. /* Defer deleting the Table object associated with the
  112736. ** subquery until code generation is
  112737. ** complete, since there may still exist Expr.pTab entries that
  112738. ** refer to the subquery even after flattening. Ticket #3346.
  112739. **
  112740. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  112741. */
  112742. if( ALWAYS(pSubitem->pTab!=0) ){
  112743. Table *pTabToDel = pSubitem->pTab;
  112744. if( pTabToDel->nTabRef==1 ){
  112745. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  112746. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  112747. pToplevel->pZombieTab = pTabToDel;
  112748. }else{
  112749. pTabToDel->nTabRef--;
  112750. }
  112751. pSubitem->pTab = 0;
  112752. }
  112753. /* The following loop runs once for each term in a compound-subquery
  112754. ** flattening (as described above). If we are doing a different kind
  112755. ** of flattening - a flattening other than a compound-subquery flattening -
  112756. ** then this loop only runs once.
  112757. **
  112758. ** This loop moves all of the FROM elements of the subquery into the
  112759. ** the FROM clause of the outer query. Before doing this, remember
  112760. ** the cursor number for the original outer query FROM element in
  112761. ** iParent. The iParent cursor will never be used. Subsequent code
  112762. ** will scan expressions looking for iParent references and replace
  112763. ** those references with expressions that resolve to the subquery FROM
  112764. ** elements we are now copying in.
  112765. */
  112766. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  112767. int nSubSrc;
  112768. u8 jointype = 0;
  112769. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  112770. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  112771. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  112772. if( pSrc ){
  112773. assert( pParent==p ); /* First time through the loop */
  112774. jointype = pSubitem->fg.jointype;
  112775. }else{
  112776. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  112777. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  112778. if( pSrc==0 ){
  112779. assert( db->mallocFailed );
  112780. break;
  112781. }
  112782. }
  112783. /* The subquery uses a single slot of the FROM clause of the outer
  112784. ** query. If the subquery has more than one element in its FROM clause,
  112785. ** then expand the outer query to make space for it to hold all elements
  112786. ** of the subquery.
  112787. **
  112788. ** Example:
  112789. **
  112790. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  112791. **
  112792. ** The outer query has 3 slots in its FROM clause. One slot of the
  112793. ** outer query (the middle slot) is used by the subquery. The next
  112794. ** block of code will expand the outer query FROM clause to 4 slots.
  112795. ** The middle slot is expanded to two slots in order to make space
  112796. ** for the two elements in the FROM clause of the subquery.
  112797. */
  112798. if( nSubSrc>1 ){
  112799. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  112800. if( db->mallocFailed ){
  112801. break;
  112802. }
  112803. }
  112804. /* Transfer the FROM clause terms from the subquery into the
  112805. ** outer query.
  112806. */
  112807. for(i=0; i<nSubSrc; i++){
  112808. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  112809. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  112810. pSrc->a[i+iFrom] = pSubSrc->a[i];
  112811. iNewParent = pSubSrc->a[i].iCursor;
  112812. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  112813. }
  112814. pSrc->a[iFrom].fg.jointype = jointype;
  112815. /* Now begin substituting subquery result set expressions for
  112816. ** references to the iParent in the outer query.
  112817. **
  112818. ** Example:
  112819. **
  112820. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  112821. ** \ \_____________ subquery __________/ /
  112822. ** \_____________________ outer query ______________________________/
  112823. **
  112824. ** We look at every expression in the outer query and every place we see
  112825. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  112826. */
  112827. pList = pParent->pEList;
  112828. for(i=0; i<pList->nExpr; i++){
  112829. if( pList->a[i].zName==0 ){
  112830. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  112831. sqlite3Dequote(zName);
  112832. pList->a[i].zName = zName;
  112833. }
  112834. }
  112835. if( pSub->pOrderBy ){
  112836. /* At this point, any non-zero iOrderByCol values indicate that the
  112837. ** ORDER BY column expression is identical to the iOrderByCol'th
  112838. ** expression returned by SELECT statement pSub. Since these values
  112839. ** do not necessarily correspond to columns in SELECT statement pParent,
  112840. ** zero them before transfering the ORDER BY clause.
  112841. **
  112842. ** Not doing this may cause an error if a subsequent call to this
  112843. ** function attempts to flatten a compound sub-query into pParent
  112844. ** (the only way this can happen is if the compound sub-query is
  112845. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  112846. ExprList *pOrderBy = pSub->pOrderBy;
  112847. for(i=0; i<pOrderBy->nExpr; i++){
  112848. pOrderBy->a[i].u.x.iOrderByCol = 0;
  112849. }
  112850. assert( pParent->pOrderBy==0 );
  112851. assert( pSub->pPrior==0 );
  112852. pParent->pOrderBy = pOrderBy;
  112853. pSub->pOrderBy = 0;
  112854. }
  112855. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  112856. if( isLeftJoin>0 ){
  112857. setJoinExpr(pWhere, iNewParent);
  112858. }
  112859. if( subqueryIsAgg ){
  112860. assert( pParent->pHaving==0 );
  112861. pParent->pHaving = pParent->pWhere;
  112862. pParent->pWhere = pWhere;
  112863. pParent->pHaving = sqlite3ExprAnd(db,
  112864. sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving
  112865. );
  112866. assert( pParent->pGroupBy==0 );
  112867. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  112868. }else{
  112869. pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
  112870. }
  112871. if( db->mallocFailed==0 ){
  112872. SubstContext x;
  112873. x.pParse = pParse;
  112874. x.iTable = iParent;
  112875. x.iNewTable = iNewParent;
  112876. x.isLeftJoin = isLeftJoin;
  112877. x.pEList = pSub->pEList;
  112878. substSelect(&x, pParent, 0);
  112879. }
  112880. /* The flattened query is distinct if either the inner or the
  112881. ** outer query is distinct.
  112882. */
  112883. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  112884. /*
  112885. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  112886. **
  112887. ** One is tempted to try to add a and b to combine the limits. But this
  112888. ** does not work if either limit is negative.
  112889. */
  112890. if( pSub->pLimit ){
  112891. pParent->pLimit = pSub->pLimit;
  112892. pSub->pLimit = 0;
  112893. }
  112894. }
  112895. /* Finially, delete what is left of the subquery and return
  112896. ** success.
  112897. */
  112898. sqlite3SelectDelete(db, pSub1);
  112899. #if SELECTTRACE_ENABLED
  112900. if( sqlite3SelectTrace & 0x100 ){
  112901. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  112902. sqlite3TreeViewSelect(0, p, 0);
  112903. }
  112904. #endif
  112905. return 1;
  112906. }
  112907. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  112908. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  112909. /*
  112910. ** Make copies of relevant WHERE clause terms of the outer query into
  112911. ** the WHERE clause of subquery. Example:
  112912. **
  112913. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  112914. **
  112915. ** Transformed into:
  112916. **
  112917. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  112918. ** WHERE x=5 AND y=10;
  112919. **
  112920. ** The hope is that the terms added to the inner query will make it more
  112921. ** efficient.
  112922. **
  112923. ** Do not attempt this optimization if:
  112924. **
  112925. ** (1) The inner query is an aggregate. (In that case, we'd really want
  112926. ** to copy the outer WHERE-clause terms onto the HAVING clause of the
  112927. ** inner query. But they probably won't help there so do not bother.)
  112928. **
  112929. ** (2) The inner query is the recursive part of a common table expression.
  112930. **
  112931. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  112932. ** close would change the meaning of the LIMIT).
  112933. **
  112934. ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
  112935. ** enforces this restriction since this routine does not have enough
  112936. ** information to know.)
  112937. **
  112938. ** (5) The WHERE clause expression originates in the ON or USING clause
  112939. ** of a LEFT JOIN.
  112940. **
  112941. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  112942. ** terms are duplicated into the subquery.
  112943. */
  112944. static int pushDownWhereTerms(
  112945. Parse *pParse, /* Parse context (for malloc() and error reporting) */
  112946. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  112947. Expr *pWhere, /* The WHERE clause of the outer query */
  112948. int iCursor /* Cursor number of the subquery */
  112949. ){
  112950. Expr *pNew;
  112951. int nChng = 0;
  112952. Select *pX; /* For looping over compound SELECTs in pSubq */
  112953. if( pWhere==0 ) return 0;
  112954. for(pX=pSubq; pX; pX=pX->pPrior){
  112955. if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
  112956. testcase( pX->selFlags & SF_Aggregate );
  112957. testcase( pX->selFlags & SF_Recursive );
  112958. testcase( pX!=pSubq );
  112959. return 0; /* restrictions (1) and (2) */
  112960. }
  112961. }
  112962. if( pSubq->pLimit!=0 ){
  112963. return 0; /* restriction (3) */
  112964. }
  112965. while( pWhere->op==TK_AND ){
  112966. nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor);
  112967. pWhere = pWhere->pLeft;
  112968. }
  112969. if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
  112970. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  112971. nChng++;
  112972. while( pSubq ){
  112973. SubstContext x;
  112974. pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
  112975. x.pParse = pParse;
  112976. x.iTable = iCursor;
  112977. x.iNewTable = iCursor;
  112978. x.isLeftJoin = 0;
  112979. x.pEList = pSubq->pEList;
  112980. pNew = substExpr(&x, pNew);
  112981. pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
  112982. pSubq = pSubq->pPrior;
  112983. }
  112984. }
  112985. return nChng;
  112986. }
  112987. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  112988. /*
  112989. ** Based on the contents of the AggInfo structure indicated by the first
  112990. ** argument, this function checks if the following are true:
  112991. **
  112992. ** * the query contains just a single aggregate function,
  112993. ** * the aggregate function is either min() or max(), and
  112994. ** * the argument to the aggregate function is a column value.
  112995. **
  112996. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  112997. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  112998. ** list of arguments passed to the aggregate before returning.
  112999. **
  113000. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  113001. ** WHERE_ORDERBY_NORMAL is returned.
  113002. */
  113003. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  113004. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  113005. *ppMinMax = 0;
  113006. if( pAggInfo->nFunc==1 ){
  113007. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  113008. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  113009. assert( pExpr->op==TK_AGG_FUNCTION );
  113010. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  113011. const char *zFunc = pExpr->u.zToken;
  113012. if( sqlite3StrICmp(zFunc, "min")==0 ){
  113013. eRet = WHERE_ORDERBY_MIN;
  113014. *ppMinMax = pEList;
  113015. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  113016. eRet = WHERE_ORDERBY_MAX;
  113017. *ppMinMax = pEList;
  113018. }
  113019. }
  113020. }
  113021. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  113022. return eRet;
  113023. }
  113024. /*
  113025. ** The select statement passed as the first argument is an aggregate query.
  113026. ** The second argument is the associated aggregate-info object. This
  113027. ** function tests if the SELECT is of the form:
  113028. **
  113029. ** SELECT count(*) FROM <tbl>
  113030. **
  113031. ** where table is a database table, not a sub-select or view. If the query
  113032. ** does match this pattern, then a pointer to the Table object representing
  113033. ** <tbl> is returned. Otherwise, 0 is returned.
  113034. */
  113035. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  113036. Table *pTab;
  113037. Expr *pExpr;
  113038. assert( !p->pGroupBy );
  113039. if( p->pWhere || p->pEList->nExpr!=1
  113040. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  113041. ){
  113042. return 0;
  113043. }
  113044. pTab = p->pSrc->a[0].pTab;
  113045. pExpr = p->pEList->a[0].pExpr;
  113046. assert( pTab && !pTab->pSelect && pExpr );
  113047. if( IsVirtual(pTab) ) return 0;
  113048. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  113049. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  113050. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  113051. if( pExpr->flags&EP_Distinct ) return 0;
  113052. return pTab;
  113053. }
  113054. /*
  113055. ** If the source-list item passed as an argument was augmented with an
  113056. ** INDEXED BY clause, then try to locate the specified index. If there
  113057. ** was such a clause and the named index cannot be found, return
  113058. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  113059. ** pFrom->pIndex and return SQLITE_OK.
  113060. */
  113061. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  113062. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  113063. Table *pTab = pFrom->pTab;
  113064. char *zIndexedBy = pFrom->u1.zIndexedBy;
  113065. Index *pIdx;
  113066. for(pIdx=pTab->pIndex;
  113067. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  113068. pIdx=pIdx->pNext
  113069. );
  113070. if( !pIdx ){
  113071. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  113072. pParse->checkSchema = 1;
  113073. return SQLITE_ERROR;
  113074. }
  113075. pFrom->pIBIndex = pIdx;
  113076. }
  113077. return SQLITE_OK;
  113078. }
  113079. /*
  113080. ** Detect compound SELECT statements that use an ORDER BY clause with
  113081. ** an alternative collating sequence.
  113082. **
  113083. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  113084. **
  113085. ** These are rewritten as a subquery:
  113086. **
  113087. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  113088. ** ORDER BY ... COLLATE ...
  113089. **
  113090. ** This transformation is necessary because the multiSelectOrderBy() routine
  113091. ** above that generates the code for a compound SELECT with an ORDER BY clause
  113092. ** uses a merge algorithm that requires the same collating sequence on the
  113093. ** result columns as on the ORDER BY clause. See ticket
  113094. ** http://www.sqlite.org/src/info/6709574d2a
  113095. **
  113096. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  113097. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  113098. ** there are COLLATE terms in the ORDER BY.
  113099. */
  113100. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  113101. int i;
  113102. Select *pNew;
  113103. Select *pX;
  113104. sqlite3 *db;
  113105. struct ExprList_item *a;
  113106. SrcList *pNewSrc;
  113107. Parse *pParse;
  113108. Token dummy;
  113109. if( p->pPrior==0 ) return WRC_Continue;
  113110. if( p->pOrderBy==0 ) return WRC_Continue;
  113111. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  113112. if( pX==0 ) return WRC_Continue;
  113113. a = p->pOrderBy->a;
  113114. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  113115. if( a[i].pExpr->flags & EP_Collate ) break;
  113116. }
  113117. if( i<0 ) return WRC_Continue;
  113118. /* If we reach this point, that means the transformation is required. */
  113119. pParse = pWalker->pParse;
  113120. db = pParse->db;
  113121. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  113122. if( pNew==0 ) return WRC_Abort;
  113123. memset(&dummy, 0, sizeof(dummy));
  113124. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  113125. if( pNewSrc==0 ) return WRC_Abort;
  113126. *pNew = *p;
  113127. p->pSrc = pNewSrc;
  113128. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  113129. p->op = TK_SELECT;
  113130. p->pWhere = 0;
  113131. pNew->pGroupBy = 0;
  113132. pNew->pHaving = 0;
  113133. pNew->pOrderBy = 0;
  113134. p->pPrior = 0;
  113135. p->pNext = 0;
  113136. p->pWith = 0;
  113137. p->selFlags &= ~SF_Compound;
  113138. assert( (p->selFlags & SF_Converted)==0 );
  113139. p->selFlags |= SF_Converted;
  113140. assert( pNew->pPrior!=0 );
  113141. pNew->pPrior->pNext = pNew;
  113142. pNew->pLimit = 0;
  113143. pNew->pOffset = 0;
  113144. return WRC_Continue;
  113145. }
  113146. /*
  113147. ** Check to see if the FROM clause term pFrom has table-valued function
  113148. ** arguments. If it does, leave an error message in pParse and return
  113149. ** non-zero, since pFrom is not allowed to be a table-valued function.
  113150. */
  113151. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  113152. if( pFrom->fg.isTabFunc ){
  113153. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  113154. return 1;
  113155. }
  113156. return 0;
  113157. }
  113158. #ifndef SQLITE_OMIT_CTE
  113159. /*
  113160. ** Argument pWith (which may be NULL) points to a linked list of nested
  113161. ** WITH contexts, from inner to outermost. If the table identified by
  113162. ** FROM clause element pItem is really a common-table-expression (CTE)
  113163. ** then return a pointer to the CTE definition for that table. Otherwise
  113164. ** return NULL.
  113165. **
  113166. ** If a non-NULL value is returned, set *ppContext to point to the With
  113167. ** object that the returned CTE belongs to.
  113168. */
  113169. static struct Cte *searchWith(
  113170. With *pWith, /* Current innermost WITH clause */
  113171. struct SrcList_item *pItem, /* FROM clause element to resolve */
  113172. With **ppContext /* OUT: WITH clause return value belongs to */
  113173. ){
  113174. const char *zName;
  113175. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  113176. With *p;
  113177. for(p=pWith; p; p=p->pOuter){
  113178. int i;
  113179. for(i=0; i<p->nCte; i++){
  113180. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  113181. *ppContext = p;
  113182. return &p->a[i];
  113183. }
  113184. }
  113185. }
  113186. }
  113187. return 0;
  113188. }
  113189. /* The code generator maintains a stack of active WITH clauses
  113190. ** with the inner-most WITH clause being at the top of the stack.
  113191. **
  113192. ** This routine pushes the WITH clause passed as the second argument
  113193. ** onto the top of the stack. If argument bFree is true, then this
  113194. ** WITH clause will never be popped from the stack. In this case it
  113195. ** should be freed along with the Parse object. In other cases, when
  113196. ** bFree==0, the With object will be freed along with the SELECT
  113197. ** statement with which it is associated.
  113198. */
  113199. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  113200. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  113201. if( pWith ){
  113202. assert( pParse->pWith!=pWith );
  113203. pWith->pOuter = pParse->pWith;
  113204. pParse->pWith = pWith;
  113205. if( bFree ) pParse->pWithToFree = pWith;
  113206. }
  113207. }
  113208. /*
  113209. ** This function checks if argument pFrom refers to a CTE declared by
  113210. ** a WITH clause on the stack currently maintained by the parser. And,
  113211. ** if currently processing a CTE expression, if it is a recursive
  113212. ** reference to the current CTE.
  113213. **
  113214. ** If pFrom falls into either of the two categories above, pFrom->pTab
  113215. ** and other fields are populated accordingly. The caller should check
  113216. ** (pFrom->pTab!=0) to determine whether or not a successful match
  113217. ** was found.
  113218. **
  113219. ** Whether or not a match is found, SQLITE_OK is returned if no error
  113220. ** occurs. If an error does occur, an error message is stored in the
  113221. ** parser and some error code other than SQLITE_OK returned.
  113222. */
  113223. static int withExpand(
  113224. Walker *pWalker,
  113225. struct SrcList_item *pFrom
  113226. ){
  113227. Parse *pParse = pWalker->pParse;
  113228. sqlite3 *db = pParse->db;
  113229. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  113230. With *pWith; /* WITH clause that pCte belongs to */
  113231. assert( pFrom->pTab==0 );
  113232. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  113233. if( pCte ){
  113234. Table *pTab;
  113235. ExprList *pEList;
  113236. Select *pSel;
  113237. Select *pLeft; /* Left-most SELECT statement */
  113238. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  113239. With *pSavedWith; /* Initial value of pParse->pWith */
  113240. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  113241. ** recursive reference to CTE pCte. Leave an error in pParse and return
  113242. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  113243. ** In this case, proceed. */
  113244. if( pCte->zCteErr ){
  113245. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  113246. return SQLITE_ERROR;
  113247. }
  113248. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  113249. assert( pFrom->pTab==0 );
  113250. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  113251. if( pTab==0 ) return WRC_Abort;
  113252. pTab->nTabRef = 1;
  113253. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  113254. pTab->iPKey = -1;
  113255. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  113256. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  113257. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  113258. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  113259. assert( pFrom->pSelect );
  113260. /* Check if this is a recursive CTE. */
  113261. pSel = pFrom->pSelect;
  113262. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  113263. if( bMayRecursive ){
  113264. int i;
  113265. SrcList *pSrc = pFrom->pSelect->pSrc;
  113266. for(i=0; i<pSrc->nSrc; i++){
  113267. struct SrcList_item *pItem = &pSrc->a[i];
  113268. if( pItem->zDatabase==0
  113269. && pItem->zName!=0
  113270. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  113271. ){
  113272. pItem->pTab = pTab;
  113273. pItem->fg.isRecursive = 1;
  113274. pTab->nTabRef++;
  113275. pSel->selFlags |= SF_Recursive;
  113276. }
  113277. }
  113278. }
  113279. /* Only one recursive reference is permitted. */
  113280. if( pTab->nTabRef>2 ){
  113281. sqlite3ErrorMsg(
  113282. pParse, "multiple references to recursive table: %s", pCte->zName
  113283. );
  113284. return SQLITE_ERROR;
  113285. }
  113286. assert( pTab->nTabRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
  113287. pCte->zCteErr = "circular reference: %s";
  113288. pSavedWith = pParse->pWith;
  113289. pParse->pWith = pWith;
  113290. if( bMayRecursive ){
  113291. Select *pPrior = pSel->pPrior;
  113292. assert( pPrior->pWith==0 );
  113293. pPrior->pWith = pSel->pWith;
  113294. sqlite3WalkSelect(pWalker, pPrior);
  113295. pPrior->pWith = 0;
  113296. }else{
  113297. sqlite3WalkSelect(pWalker, pSel);
  113298. }
  113299. pParse->pWith = pWith;
  113300. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  113301. pEList = pLeft->pEList;
  113302. if( pCte->pCols ){
  113303. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  113304. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  113305. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  113306. );
  113307. pParse->pWith = pSavedWith;
  113308. return SQLITE_ERROR;
  113309. }
  113310. pEList = pCte->pCols;
  113311. }
  113312. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  113313. if( bMayRecursive ){
  113314. if( pSel->selFlags & SF_Recursive ){
  113315. pCte->zCteErr = "multiple recursive references: %s";
  113316. }else{
  113317. pCte->zCteErr = "recursive reference in a subquery: %s";
  113318. }
  113319. sqlite3WalkSelect(pWalker, pSel);
  113320. }
  113321. pCte->zCteErr = 0;
  113322. pParse->pWith = pSavedWith;
  113323. }
  113324. return SQLITE_OK;
  113325. }
  113326. #endif
  113327. #ifndef SQLITE_OMIT_CTE
  113328. /*
  113329. ** If the SELECT passed as the second argument has an associated WITH
  113330. ** clause, pop it from the stack stored as part of the Parse object.
  113331. **
  113332. ** This function is used as the xSelectCallback2() callback by
  113333. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  113334. ** names and other FROM clause elements.
  113335. */
  113336. static void selectPopWith(Walker *pWalker, Select *p){
  113337. Parse *pParse = pWalker->pParse;
  113338. if( pParse->pWith && p->pPrior==0 ){
  113339. With *pWith = findRightmost(p)->pWith;
  113340. if( pWith!=0 ){
  113341. assert( pParse->pWith==pWith );
  113342. pParse->pWith = pWith->pOuter;
  113343. }
  113344. }
  113345. }
  113346. #else
  113347. #define selectPopWith 0
  113348. #endif
  113349. /*
  113350. ** This routine is a Walker callback for "expanding" a SELECT statement.
  113351. ** "Expanding" means to do the following:
  113352. **
  113353. ** (1) Make sure VDBE cursor numbers have been assigned to every
  113354. ** element of the FROM clause.
  113355. **
  113356. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  113357. ** defines FROM clause. When views appear in the FROM clause,
  113358. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  113359. ** that implements the view. A copy is made of the view's SELECT
  113360. ** statement so that we can freely modify or delete that statement
  113361. ** without worrying about messing up the persistent representation
  113362. ** of the view.
  113363. **
  113364. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  113365. ** on joins and the ON and USING clause of joins.
  113366. **
  113367. ** (4) Scan the list of columns in the result set (pEList) looking
  113368. ** for instances of the "*" operator or the TABLE.* operator.
  113369. ** If found, expand each "*" to be every column in every table
  113370. ** and TABLE.* to be every column in TABLE.
  113371. **
  113372. */
  113373. static int selectExpander(Walker *pWalker, Select *p){
  113374. Parse *pParse = pWalker->pParse;
  113375. int i, j, k;
  113376. SrcList *pTabList;
  113377. ExprList *pEList;
  113378. struct SrcList_item *pFrom;
  113379. sqlite3 *db = pParse->db;
  113380. Expr *pE, *pRight, *pExpr;
  113381. u16 selFlags = p->selFlags;
  113382. p->selFlags |= SF_Expanded;
  113383. if( db->mallocFailed ){
  113384. return WRC_Abort;
  113385. }
  113386. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  113387. return WRC_Prune;
  113388. }
  113389. pTabList = p->pSrc;
  113390. pEList = p->pEList;
  113391. if( p->pWith ){
  113392. sqlite3WithPush(pParse, p->pWith, 0);
  113393. }
  113394. /* Make sure cursor numbers have been assigned to all entries in
  113395. ** the FROM clause of the SELECT statement.
  113396. */
  113397. sqlite3SrcListAssignCursors(pParse, pTabList);
  113398. /* Look up every table named in the FROM clause of the select. If
  113399. ** an entry of the FROM clause is a subquery instead of a table or view,
  113400. ** then create a transient table structure to describe the subquery.
  113401. */
  113402. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  113403. Table *pTab;
  113404. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  113405. if( pFrom->fg.isRecursive ) continue;
  113406. assert( pFrom->pTab==0 );
  113407. #ifndef SQLITE_OMIT_CTE
  113408. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  113409. if( pFrom->pTab ) {} else
  113410. #endif
  113411. if( pFrom->zName==0 ){
  113412. #ifndef SQLITE_OMIT_SUBQUERY
  113413. Select *pSel = pFrom->pSelect;
  113414. /* A sub-query in the FROM clause of a SELECT */
  113415. assert( pSel!=0 );
  113416. assert( pFrom->pTab==0 );
  113417. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  113418. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  113419. if( pTab==0 ) return WRC_Abort;
  113420. pTab->nTabRef = 1;
  113421. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  113422. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  113423. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  113424. pTab->iPKey = -1;
  113425. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  113426. pTab->tabFlags |= TF_Ephemeral;
  113427. #endif
  113428. }else{
  113429. /* An ordinary table or view name in the FROM clause */
  113430. assert( pFrom->pTab==0 );
  113431. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  113432. if( pTab==0 ) return WRC_Abort;
  113433. if( pTab->nTabRef>=0xffff ){
  113434. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  113435. pTab->zName);
  113436. pFrom->pTab = 0;
  113437. return WRC_Abort;
  113438. }
  113439. pTab->nTabRef++;
  113440. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  113441. return WRC_Abort;
  113442. }
  113443. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  113444. if( IsVirtual(pTab) || pTab->pSelect ){
  113445. i16 nCol;
  113446. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  113447. assert( pFrom->pSelect==0 );
  113448. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  113449. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  113450. nCol = pTab->nCol;
  113451. pTab->nCol = -1;
  113452. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  113453. pTab->nCol = nCol;
  113454. }
  113455. #endif
  113456. }
  113457. /* Locate the index named by the INDEXED BY clause, if any. */
  113458. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  113459. return WRC_Abort;
  113460. }
  113461. }
  113462. /* Process NATURAL keywords, and ON and USING clauses of joins.
  113463. */
  113464. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  113465. return WRC_Abort;
  113466. }
  113467. /* For every "*" that occurs in the column list, insert the names of
  113468. ** all columns in all tables. And for every TABLE.* insert the names
  113469. ** of all columns in TABLE. The parser inserted a special expression
  113470. ** with the TK_ASTERISK operator for each "*" that it found in the column
  113471. ** list. The following code just has to locate the TK_ASTERISK
  113472. ** expressions and expand each one to the list of all columns in
  113473. ** all tables.
  113474. **
  113475. ** The first loop just checks to see if there are any "*" operators
  113476. ** that need expanding.
  113477. */
  113478. for(k=0; k<pEList->nExpr; k++){
  113479. pE = pEList->a[k].pExpr;
  113480. if( pE->op==TK_ASTERISK ) break;
  113481. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  113482. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  113483. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  113484. }
  113485. if( k<pEList->nExpr ){
  113486. /*
  113487. ** If we get here it means the result set contains one or more "*"
  113488. ** operators that need to be expanded. Loop through each expression
  113489. ** in the result set and expand them one by one.
  113490. */
  113491. struct ExprList_item *a = pEList->a;
  113492. ExprList *pNew = 0;
  113493. int flags = pParse->db->flags;
  113494. int longNames = (flags & SQLITE_FullColNames)!=0
  113495. && (flags & SQLITE_ShortColNames)==0;
  113496. for(k=0; k<pEList->nExpr; k++){
  113497. pE = a[k].pExpr;
  113498. pRight = pE->pRight;
  113499. assert( pE->op!=TK_DOT || pRight!=0 );
  113500. if( pE->op!=TK_ASTERISK
  113501. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  113502. ){
  113503. /* This particular expression does not need to be expanded.
  113504. */
  113505. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  113506. if( pNew ){
  113507. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  113508. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  113509. a[k].zName = 0;
  113510. a[k].zSpan = 0;
  113511. }
  113512. a[k].pExpr = 0;
  113513. }else{
  113514. /* This expression is a "*" or a "TABLE.*" and needs to be
  113515. ** expanded. */
  113516. int tableSeen = 0; /* Set to 1 when TABLE matches */
  113517. char *zTName = 0; /* text of name of TABLE */
  113518. if( pE->op==TK_DOT ){
  113519. assert( pE->pLeft!=0 );
  113520. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  113521. zTName = pE->pLeft->u.zToken;
  113522. }
  113523. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  113524. Table *pTab = pFrom->pTab;
  113525. Select *pSub = pFrom->pSelect;
  113526. char *zTabName = pFrom->zAlias;
  113527. const char *zSchemaName = 0;
  113528. int iDb;
  113529. if( zTabName==0 ){
  113530. zTabName = pTab->zName;
  113531. }
  113532. if( db->mallocFailed ) break;
  113533. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  113534. pSub = 0;
  113535. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  113536. continue;
  113537. }
  113538. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  113539. zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  113540. }
  113541. for(j=0; j<pTab->nCol; j++){
  113542. char *zName = pTab->aCol[j].zName;
  113543. char *zColname; /* The computed column name */
  113544. char *zToFree; /* Malloced string that needs to be freed */
  113545. Token sColname; /* Computed column name as a token */
  113546. assert( zName );
  113547. if( zTName && pSub
  113548. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  113549. ){
  113550. continue;
  113551. }
  113552. /* If a column is marked as 'hidden', omit it from the expanded
  113553. ** result-set list unless the SELECT has the SF_IncludeHidden
  113554. ** bit set.
  113555. */
  113556. if( (p->selFlags & SF_IncludeHidden)==0
  113557. && IsHiddenColumn(&pTab->aCol[j])
  113558. ){
  113559. continue;
  113560. }
  113561. tableSeen = 1;
  113562. if( i>0 && zTName==0 ){
  113563. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  113564. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  113565. ){
  113566. /* In a NATURAL join, omit the join columns from the
  113567. ** table to the right of the join */
  113568. continue;
  113569. }
  113570. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  113571. /* In a join with a USING clause, omit columns in the
  113572. ** using clause from the table on the right. */
  113573. continue;
  113574. }
  113575. }
  113576. pRight = sqlite3Expr(db, TK_ID, zName);
  113577. zColname = zName;
  113578. zToFree = 0;
  113579. if( longNames || pTabList->nSrc>1 ){
  113580. Expr *pLeft;
  113581. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  113582. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  113583. if( zSchemaName ){
  113584. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  113585. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
  113586. }
  113587. if( longNames ){
  113588. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  113589. zToFree = zColname;
  113590. }
  113591. }else{
  113592. pExpr = pRight;
  113593. }
  113594. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  113595. sqlite3TokenInit(&sColname, zColname);
  113596. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  113597. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  113598. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  113599. if( pSub ){
  113600. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  113601. testcase( pX->zSpan==0 );
  113602. }else{
  113603. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  113604. zSchemaName, zTabName, zColname);
  113605. testcase( pX->zSpan==0 );
  113606. }
  113607. pX->bSpanIsTab = 1;
  113608. }
  113609. sqlite3DbFree(db, zToFree);
  113610. }
  113611. }
  113612. if( !tableSeen ){
  113613. if( zTName ){
  113614. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  113615. }else{
  113616. sqlite3ErrorMsg(pParse, "no tables specified");
  113617. }
  113618. }
  113619. }
  113620. }
  113621. sqlite3ExprListDelete(db, pEList);
  113622. p->pEList = pNew;
  113623. }
  113624. #if SQLITE_MAX_COLUMN
  113625. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  113626. sqlite3ErrorMsg(pParse, "too many columns in result set");
  113627. return WRC_Abort;
  113628. }
  113629. #endif
  113630. return WRC_Continue;
  113631. }
  113632. /*
  113633. ** No-op routine for the parse-tree walker.
  113634. **
  113635. ** When this routine is the Walker.xExprCallback then expression trees
  113636. ** are walked without any actions being taken at each node. Presumably,
  113637. ** when this routine is used for Walker.xExprCallback then
  113638. ** Walker.xSelectCallback is set to do something useful for every
  113639. ** subquery in the parser tree.
  113640. */
  113641. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  113642. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  113643. return WRC_Continue;
  113644. }
  113645. /*
  113646. ** This routine "expands" a SELECT statement and all of its subqueries.
  113647. ** For additional information on what it means to "expand" a SELECT
  113648. ** statement, see the comment on the selectExpand worker callback above.
  113649. **
  113650. ** Expanding a SELECT statement is the first step in processing a
  113651. ** SELECT statement. The SELECT statement must be expanded before
  113652. ** name resolution is performed.
  113653. **
  113654. ** If anything goes wrong, an error message is written into pParse.
  113655. ** The calling function can detect the problem by looking at pParse->nErr
  113656. ** and/or pParse->db->mallocFailed.
  113657. */
  113658. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  113659. Walker w;
  113660. memset(&w, 0, sizeof(w));
  113661. w.xExprCallback = sqlite3ExprWalkNoop;
  113662. w.pParse = pParse;
  113663. if( pParse->hasCompound ){
  113664. w.xSelectCallback = convertCompoundSelectToSubquery;
  113665. sqlite3WalkSelect(&w, pSelect);
  113666. }
  113667. w.xSelectCallback = selectExpander;
  113668. w.xSelectCallback2 = selectPopWith;
  113669. sqlite3WalkSelect(&w, pSelect);
  113670. }
  113671. #ifndef SQLITE_OMIT_SUBQUERY
  113672. /*
  113673. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  113674. ** interface.
  113675. **
  113676. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  113677. ** information to the Table structure that represents the result set
  113678. ** of that subquery.
  113679. **
  113680. ** The Table structure that represents the result set was constructed
  113681. ** by selectExpander() but the type and collation information was omitted
  113682. ** at that point because identifiers had not yet been resolved. This
  113683. ** routine is called after identifier resolution.
  113684. */
  113685. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  113686. Parse *pParse;
  113687. int i;
  113688. SrcList *pTabList;
  113689. struct SrcList_item *pFrom;
  113690. assert( p->selFlags & SF_Resolved );
  113691. assert( (p->selFlags & SF_HasTypeInfo)==0 );
  113692. p->selFlags |= SF_HasTypeInfo;
  113693. pParse = pWalker->pParse;
  113694. pTabList = p->pSrc;
  113695. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  113696. Table *pTab = pFrom->pTab;
  113697. assert( pTab!=0 );
  113698. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  113699. /* A sub-query in the FROM clause of a SELECT */
  113700. Select *pSel = pFrom->pSelect;
  113701. if( pSel ){
  113702. while( pSel->pPrior ) pSel = pSel->pPrior;
  113703. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
  113704. }
  113705. }
  113706. }
  113707. }
  113708. #endif
  113709. /*
  113710. ** This routine adds datatype and collating sequence information to
  113711. ** the Table structures of all FROM-clause subqueries in a
  113712. ** SELECT statement.
  113713. **
  113714. ** Use this routine after name resolution.
  113715. */
  113716. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  113717. #ifndef SQLITE_OMIT_SUBQUERY
  113718. Walker w;
  113719. memset(&w, 0, sizeof(w));
  113720. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  113721. w.xExprCallback = sqlite3ExprWalkNoop;
  113722. w.pParse = pParse;
  113723. sqlite3WalkSelect(&w, pSelect);
  113724. #endif
  113725. }
  113726. /*
  113727. ** This routine sets up a SELECT statement for processing. The
  113728. ** following is accomplished:
  113729. **
  113730. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  113731. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  113732. ** * ON and USING clauses are shifted into WHERE statements
  113733. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  113734. ** * Identifiers in expression are matched to tables.
  113735. **
  113736. ** This routine acts recursively on all subqueries within the SELECT.
  113737. */
  113738. SQLITE_PRIVATE void sqlite3SelectPrep(
  113739. Parse *pParse, /* The parser context */
  113740. Select *p, /* The SELECT statement being coded. */
  113741. NameContext *pOuterNC /* Name context for container */
  113742. ){
  113743. sqlite3 *db;
  113744. if( NEVER(p==0) ) return;
  113745. db = pParse->db;
  113746. if( db->mallocFailed ) return;
  113747. if( p->selFlags & SF_HasTypeInfo ) return;
  113748. sqlite3SelectExpand(pParse, p);
  113749. if( pParse->nErr || db->mallocFailed ) return;
  113750. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  113751. if( pParse->nErr || db->mallocFailed ) return;
  113752. sqlite3SelectAddTypeInfo(pParse, p);
  113753. }
  113754. /*
  113755. ** Reset the aggregate accumulator.
  113756. **
  113757. ** The aggregate accumulator is a set of memory cells that hold
  113758. ** intermediate results while calculating an aggregate. This
  113759. ** routine generates code that stores NULLs in all of those memory
  113760. ** cells.
  113761. */
  113762. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  113763. Vdbe *v = pParse->pVdbe;
  113764. int i;
  113765. struct AggInfo_func *pFunc;
  113766. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  113767. if( nReg==0 ) return;
  113768. #ifdef SQLITE_DEBUG
  113769. /* Verify that all AggInfo registers are within the range specified by
  113770. ** AggInfo.mnReg..AggInfo.mxReg */
  113771. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  113772. for(i=0; i<pAggInfo->nColumn; i++){
  113773. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  113774. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  113775. }
  113776. for(i=0; i<pAggInfo->nFunc; i++){
  113777. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  113778. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  113779. }
  113780. #endif
  113781. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  113782. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  113783. if( pFunc->iDistinct>=0 ){
  113784. Expr *pE = pFunc->pExpr;
  113785. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  113786. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  113787. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  113788. "argument");
  113789. pFunc->iDistinct = -1;
  113790. }else{
  113791. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  113792. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  113793. (char*)pKeyInfo, P4_KEYINFO);
  113794. }
  113795. }
  113796. }
  113797. }
  113798. /*
  113799. ** Invoke the OP_AggFinalize opcode for every aggregate function
  113800. ** in the AggInfo structure.
  113801. */
  113802. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  113803. Vdbe *v = pParse->pVdbe;
  113804. int i;
  113805. struct AggInfo_func *pF;
  113806. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  113807. ExprList *pList = pF->pExpr->x.pList;
  113808. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  113809. sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
  113810. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  113811. }
  113812. }
  113813. /*
  113814. ** Update the accumulator memory cells for an aggregate based on
  113815. ** the current cursor position.
  113816. */
  113817. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  113818. Vdbe *v = pParse->pVdbe;
  113819. int i;
  113820. int regHit = 0;
  113821. int addrHitTest = 0;
  113822. struct AggInfo_func *pF;
  113823. struct AggInfo_col *pC;
  113824. pAggInfo->directMode = 1;
  113825. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  113826. int nArg;
  113827. int addrNext = 0;
  113828. int regAgg;
  113829. ExprList *pList = pF->pExpr->x.pList;
  113830. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  113831. if( pList ){
  113832. nArg = pList->nExpr;
  113833. regAgg = sqlite3GetTempRange(pParse, nArg);
  113834. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  113835. }else{
  113836. nArg = 0;
  113837. regAgg = 0;
  113838. }
  113839. if( pF->iDistinct>=0 ){
  113840. addrNext = sqlite3VdbeMakeLabel(v);
  113841. testcase( nArg==0 ); /* Error condition */
  113842. testcase( nArg>1 ); /* Also an error */
  113843. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  113844. }
  113845. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  113846. CollSeq *pColl = 0;
  113847. struct ExprList_item *pItem;
  113848. int j;
  113849. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  113850. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  113851. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  113852. }
  113853. if( !pColl ){
  113854. pColl = pParse->db->pDfltColl;
  113855. }
  113856. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  113857. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  113858. }
  113859. sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
  113860. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  113861. sqlite3VdbeChangeP5(v, (u8)nArg);
  113862. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  113863. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  113864. if( addrNext ){
  113865. sqlite3VdbeResolveLabel(v, addrNext);
  113866. sqlite3ExprCacheClear(pParse);
  113867. }
  113868. }
  113869. /* Before populating the accumulator registers, clear the column cache.
  113870. ** Otherwise, if any of the required column values are already present
  113871. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  113872. ** to pC->iMem. But by the time the value is used, the original register
  113873. ** may have been used, invalidating the underlying buffer holding the
  113874. ** text or blob value. See ticket [883034dcb5].
  113875. **
  113876. ** Another solution would be to change the OP_SCopy used to copy cached
  113877. ** values to an OP_Copy.
  113878. */
  113879. if( regHit ){
  113880. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  113881. }
  113882. sqlite3ExprCacheClear(pParse);
  113883. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  113884. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  113885. }
  113886. pAggInfo->directMode = 0;
  113887. sqlite3ExprCacheClear(pParse);
  113888. if( addrHitTest ){
  113889. sqlite3VdbeJumpHere(v, addrHitTest);
  113890. }
  113891. }
  113892. /*
  113893. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  113894. ** count(*) query ("SELECT count(*) FROM pTab").
  113895. */
  113896. #ifndef SQLITE_OMIT_EXPLAIN
  113897. static void explainSimpleCount(
  113898. Parse *pParse, /* Parse context */
  113899. Table *pTab, /* Table being queried */
  113900. Index *pIdx /* Index used to optimize scan, or NULL */
  113901. ){
  113902. if( pParse->explain==2 ){
  113903. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  113904. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  113905. pTab->zName,
  113906. bCover ? " USING COVERING INDEX " : "",
  113907. bCover ? pIdx->zName : ""
  113908. );
  113909. sqlite3VdbeAddOp4(
  113910. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  113911. );
  113912. }
  113913. }
  113914. #else
  113915. # define explainSimpleCount(a,b,c)
  113916. #endif
  113917. /*
  113918. ** Context object for havingToWhereExprCb().
  113919. */
  113920. struct HavingToWhereCtx {
  113921. Expr **ppWhere;
  113922. ExprList *pGroupBy;
  113923. };
  113924. /*
  113925. ** sqlite3WalkExpr() callback used by havingToWhere().
  113926. **
  113927. ** If the node passed to the callback is a TK_AND node, return
  113928. ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
  113929. **
  113930. ** Otherwise, return WRC_Prune. In this case, also check if the
  113931. ** sub-expression matches the criteria for being moved to the WHERE
  113932. ** clause. If so, add it to the WHERE clause and replace the sub-expression
  113933. ** within the HAVING expression with a constant "1".
  113934. */
  113935. static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
  113936. if( pExpr->op!=TK_AND ){
  113937. struct HavingToWhereCtx *p = pWalker->u.pHavingCtx;
  113938. if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, p->pGroupBy) ){
  113939. sqlite3 *db = pWalker->pParse->db;
  113940. Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
  113941. if( pNew ){
  113942. Expr *pWhere = *(p->ppWhere);
  113943. SWAP(Expr, *pNew, *pExpr);
  113944. pNew = sqlite3ExprAnd(db, pWhere, pNew);
  113945. *(p->ppWhere) = pNew;
  113946. }
  113947. }
  113948. return WRC_Prune;
  113949. }
  113950. return WRC_Continue;
  113951. }
  113952. /*
  113953. ** Transfer eligible terms from the HAVING clause of a query, which is
  113954. ** processed after grouping, to the WHERE clause, which is processed before
  113955. ** grouping. For example, the query:
  113956. **
  113957. ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
  113958. **
  113959. ** can be rewritten as:
  113960. **
  113961. ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
  113962. **
  113963. ** A term of the HAVING expression is eligible for transfer if it consists
  113964. ** entirely of constants and expressions that are also GROUP BY terms that
  113965. ** use the "BINARY" collation sequence.
  113966. */
  113967. static void havingToWhere(
  113968. Parse *pParse,
  113969. ExprList *pGroupBy,
  113970. Expr *pHaving,
  113971. Expr **ppWhere
  113972. ){
  113973. struct HavingToWhereCtx sCtx;
  113974. Walker sWalker;
  113975. sCtx.ppWhere = ppWhere;
  113976. sCtx.pGroupBy = pGroupBy;
  113977. memset(&sWalker, 0, sizeof(sWalker));
  113978. sWalker.pParse = pParse;
  113979. sWalker.xExprCallback = havingToWhereExprCb;
  113980. sWalker.u.pHavingCtx = &sCtx;
  113981. sqlite3WalkExpr(&sWalker, pHaving);
  113982. }
  113983. /*
  113984. ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
  113985. ** If it is, then return the SrcList_item for the prior view. If it is not,
  113986. ** then return 0.
  113987. */
  113988. static struct SrcList_item *isSelfJoinView(
  113989. SrcList *pTabList, /* Search for self-joins in this FROM clause */
  113990. struct SrcList_item *pThis /* Search for prior reference to this subquery */
  113991. ){
  113992. struct SrcList_item *pItem;
  113993. for(pItem = pTabList->a; pItem<pThis; pItem++){
  113994. if( pItem->pSelect==0 ) continue;
  113995. if( pItem->fg.viaCoroutine ) continue;
  113996. if( pItem->zName==0 ) continue;
  113997. if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
  113998. if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
  113999. if( sqlite3ExprCompare(pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1) ){
  114000. /* The view was modified by some other optimization such as
  114001. ** pushDownWhereTerms() */
  114002. continue;
  114003. }
  114004. return pItem;
  114005. }
  114006. return 0;
  114007. }
  114008. /*
  114009. ** Generate code for the SELECT statement given in the p argument.
  114010. **
  114011. ** The results are returned according to the SelectDest structure.
  114012. ** See comments in sqliteInt.h for further information.
  114013. **
  114014. ** This routine returns the number of errors. If any errors are
  114015. ** encountered, then an appropriate error message is left in
  114016. ** pParse->zErrMsg.
  114017. **
  114018. ** This routine does NOT free the Select structure passed in. The
  114019. ** calling function needs to do that.
  114020. */
  114021. SQLITE_PRIVATE int sqlite3Select(
  114022. Parse *pParse, /* The parser context */
  114023. Select *p, /* The SELECT statement being coded. */
  114024. SelectDest *pDest /* What to do with the query results */
  114025. ){
  114026. int i, j; /* Loop counters */
  114027. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  114028. Vdbe *v; /* The virtual machine under construction */
  114029. int isAgg; /* True for select lists like "count(*)" */
  114030. ExprList *pEList = 0; /* List of columns to extract. */
  114031. SrcList *pTabList; /* List of tables to select from */
  114032. Expr *pWhere; /* The WHERE clause. May be NULL */
  114033. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  114034. Expr *pHaving; /* The HAVING clause. May be NULL */
  114035. int rc = 1; /* Value to return from this function */
  114036. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  114037. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  114038. AggInfo sAggInfo; /* Information used by aggregate queries */
  114039. int iEnd; /* Address of the end of the query */
  114040. sqlite3 *db; /* The database connection */
  114041. #ifndef SQLITE_OMIT_EXPLAIN
  114042. int iRestoreSelectId = pParse->iSelectId;
  114043. pParse->iSelectId = pParse->iNextSelectId++;
  114044. #endif
  114045. db = pParse->db;
  114046. if( p==0 || db->mallocFailed || pParse->nErr ){
  114047. return 1;
  114048. }
  114049. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  114050. memset(&sAggInfo, 0, sizeof(sAggInfo));
  114051. #if SELECTTRACE_ENABLED
  114052. pParse->nSelectIndent++;
  114053. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  114054. if( sqlite3SelectTrace & 0x100 ){
  114055. sqlite3TreeViewSelect(0, p, 0);
  114056. }
  114057. #endif
  114058. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  114059. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  114060. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  114061. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  114062. if( IgnorableOrderby(pDest) ){
  114063. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  114064. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  114065. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  114066. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  114067. /* If ORDER BY makes no difference in the output then neither does
  114068. ** DISTINCT so it can be removed too. */
  114069. sqlite3ExprListDelete(db, p->pOrderBy);
  114070. p->pOrderBy = 0;
  114071. p->selFlags &= ~SF_Distinct;
  114072. }
  114073. sqlite3SelectPrep(pParse, p, 0);
  114074. memset(&sSort, 0, sizeof(sSort));
  114075. sSort.pOrderBy = p->pOrderBy;
  114076. pTabList = p->pSrc;
  114077. if( pParse->nErr || db->mallocFailed ){
  114078. goto select_end;
  114079. }
  114080. assert( p->pEList!=0 );
  114081. isAgg = (p->selFlags & SF_Aggregate)!=0;
  114082. #if SELECTTRACE_ENABLED
  114083. if( sqlite3SelectTrace & 0x100 ){
  114084. SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
  114085. sqlite3TreeViewSelect(0, p, 0);
  114086. }
  114087. #endif
  114088. /* Try to flatten subqueries in the FROM clause up into the main query
  114089. */
  114090. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  114091. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  114092. struct SrcList_item *pItem = &pTabList->a[i];
  114093. Select *pSub = pItem->pSelect;
  114094. int isAggSub;
  114095. Table *pTab = pItem->pTab;
  114096. if( pSub==0 ) continue;
  114097. /* Catch mismatch in the declared columns of a view and the number of
  114098. ** columns in the SELECT on the RHS */
  114099. if( pTab->nCol!=pSub->pEList->nExpr ){
  114100. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  114101. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  114102. goto select_end;
  114103. }
  114104. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  114105. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  114106. /* This subquery can be absorbed into its parent. */
  114107. if( isAggSub ){
  114108. isAgg = 1;
  114109. p->selFlags |= SF_Aggregate;
  114110. }
  114111. i = -1;
  114112. }
  114113. pTabList = p->pSrc;
  114114. if( db->mallocFailed ) goto select_end;
  114115. if( !IgnorableOrderby(pDest) ){
  114116. sSort.pOrderBy = p->pOrderBy;
  114117. }
  114118. }
  114119. #endif
  114120. /* Get a pointer the VDBE under construction, allocating a new VDBE if one
  114121. ** does not already exist */
  114122. v = sqlite3GetVdbe(pParse);
  114123. if( v==0 ) goto select_end;
  114124. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  114125. /* Handle compound SELECT statements using the separate multiSelect()
  114126. ** procedure.
  114127. */
  114128. if( p->pPrior ){
  114129. rc = multiSelect(pParse, p, pDest);
  114130. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  114131. #if SELECTTRACE_ENABLED
  114132. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  114133. pParse->nSelectIndent--;
  114134. #endif
  114135. return rc;
  114136. }
  114137. #endif
  114138. /* For each term in the FROM clause, do two things:
  114139. ** (1) Authorized unreferenced tables
  114140. ** (2) Generate code for all sub-queries
  114141. */
  114142. for(i=0; i<pTabList->nSrc; i++){
  114143. struct SrcList_item *pItem = &pTabList->a[i];
  114144. SelectDest dest;
  114145. Select *pSub;
  114146. /* Issue SQLITE_READ authorizations with a fake column name for any tables that
  114147. ** are referenced but from which no values are extracted. Examples of where these
  114148. ** kinds of null SQLITE_READ authorizations would occur:
  114149. **
  114150. ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
  114151. ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
  114152. **
  114153. ** The fake column name is an empty string. It is possible for a table to
  114154. ** have a column named by the empty string, in which case there is no way to
  114155. ** distinguish between an unreferenced table and an actual reference to the
  114156. ** "" column. The original design was for the fake column name to be a NULL,
  114157. ** which would be unambiguous. But legacy authorization callbacks might
  114158. ** assume the column name is non-NULL and segfault. The use of an empty string
  114159. ** for the fake column name seems safer.
  114160. */
  114161. if( pItem->colUsed==0 ){
  114162. sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
  114163. }
  114164. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  114165. /* Generate code for all sub-queries in the FROM clause
  114166. */
  114167. pSub = pItem->pSelect;
  114168. if( pSub==0 ) continue;
  114169. /* Sometimes the code for a subquery will be generated more than
  114170. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  114171. ** for example. In that case, do not regenerate the code to manifest
  114172. ** a view or the co-routine to implement a view. The first instance
  114173. ** is sufficient, though the subroutine to manifest the view does need
  114174. ** to be invoked again. */
  114175. if( pItem->addrFillSub ){
  114176. if( pItem->fg.viaCoroutine==0 ){
  114177. /* The subroutine that manifests the view might be a one-time routine,
  114178. ** or it might need to be rerun on each iteration because it
  114179. ** encodes a correlated subquery. */
  114180. testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
  114181. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  114182. }
  114183. continue;
  114184. }
  114185. /* Increment Parse.nHeight by the height of the largest expression
  114186. ** tree referred to by this, the parent select. The child select
  114187. ** may contain expression trees of at most
  114188. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  114189. ** more conservative than necessary, but much easier than enforcing
  114190. ** an exact limit.
  114191. */
  114192. pParse->nHeight += sqlite3SelectExprHeight(p);
  114193. /* Make copies of constant WHERE-clause terms in the outer query down
  114194. ** inside the subquery. This can help the subquery to run more efficiently.
  114195. */
  114196. if( (pItem->fg.jointype & JT_OUTER)==0
  114197. && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor)
  114198. ){
  114199. #if SELECTTRACE_ENABLED
  114200. if( sqlite3SelectTrace & 0x100 ){
  114201. SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
  114202. sqlite3TreeViewSelect(0, p, 0);
  114203. }
  114204. #endif
  114205. }
  114206. /* Generate code to implement the subquery
  114207. **
  114208. ** The subquery is implemented as a co-routine if all of these are true:
  114209. ** (1) The subquery is guaranteed to be the outer loop (so that it
  114210. ** does not need to be computed more than once)
  114211. ** (2) The ALL keyword after SELECT is omitted. (Applications are
  114212. ** allowed to say "SELECT ALL" instead of just "SELECT" to disable
  114213. ** the use of co-routines.)
  114214. ** (3) Co-routines are not disabled using sqlite3_test_control()
  114215. ** with SQLITE_TESTCTRL_OPTIMIZATIONS.
  114216. **
  114217. ** TODO: Are there other reasons beside (1) to use a co-routine
  114218. ** implementation?
  114219. */
  114220. if( i==0
  114221. && (pTabList->nSrc==1
  114222. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  114223. && (p->selFlags & SF_All)==0 /* (2) */
  114224. && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */
  114225. ){
  114226. /* Implement a co-routine that will return a single row of the result
  114227. ** set on each invocation.
  114228. */
  114229. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  114230. pItem->regReturn = ++pParse->nMem;
  114231. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  114232. VdbeComment((v, "%s", pItem->pTab->zName));
  114233. pItem->addrFillSub = addrTop;
  114234. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  114235. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  114236. sqlite3Select(pParse, pSub, &dest);
  114237. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  114238. pItem->fg.viaCoroutine = 1;
  114239. pItem->regResult = dest.iSdst;
  114240. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  114241. sqlite3VdbeJumpHere(v, addrTop-1);
  114242. sqlite3ClearTempRegCache(pParse);
  114243. }else{
  114244. /* Generate a subroutine that will fill an ephemeral table with
  114245. ** the content of this subquery. pItem->addrFillSub will point
  114246. ** to the address of the generated subroutine. pItem->regReturn
  114247. ** is a register allocated to hold the subroutine return address
  114248. */
  114249. int topAddr;
  114250. int onceAddr = 0;
  114251. int retAddr;
  114252. struct SrcList_item *pPrior;
  114253. assert( pItem->addrFillSub==0 );
  114254. pItem->regReturn = ++pParse->nMem;
  114255. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  114256. pItem->addrFillSub = topAddr+1;
  114257. if( pItem->fg.isCorrelated==0 ){
  114258. /* If the subquery is not correlated and if we are not inside of
  114259. ** a trigger, then we only need to compute the value of the subquery
  114260. ** once. */
  114261. onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  114262. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  114263. }else{
  114264. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  114265. }
  114266. pPrior = isSelfJoinView(pTabList, pItem);
  114267. if( pPrior ){
  114268. sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
  114269. }else{
  114270. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  114271. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  114272. sqlite3Select(pParse, pSub, &dest);
  114273. }
  114274. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  114275. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  114276. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  114277. VdbeComment((v, "end %s", pItem->pTab->zName));
  114278. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  114279. sqlite3ClearTempRegCache(pParse);
  114280. }
  114281. if( db->mallocFailed ) goto select_end;
  114282. pParse->nHeight -= sqlite3SelectExprHeight(p);
  114283. #endif
  114284. }
  114285. /* Various elements of the SELECT copied into local variables for
  114286. ** convenience */
  114287. pEList = p->pEList;
  114288. pWhere = p->pWhere;
  114289. pGroupBy = p->pGroupBy;
  114290. pHaving = p->pHaving;
  114291. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  114292. #if SELECTTRACE_ENABLED
  114293. if( sqlite3SelectTrace & 0x400 ){
  114294. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  114295. sqlite3TreeViewSelect(0, p, 0);
  114296. }
  114297. #endif
  114298. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  114299. ** if the select-list is the same as the ORDER BY list, then this query
  114300. ** can be rewritten as a GROUP BY. In other words, this:
  114301. **
  114302. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  114303. **
  114304. ** is transformed to:
  114305. **
  114306. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  114307. **
  114308. ** The second form is preferred as a single index (or temp-table) may be
  114309. ** used for both the ORDER BY and DISTINCT processing. As originally
  114310. ** written the query must use a temp-table for at least one of the ORDER
  114311. ** BY and DISTINCT, and an index or separate temp-table for the other.
  114312. */
  114313. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  114314. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  114315. ){
  114316. p->selFlags &= ~SF_Distinct;
  114317. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  114318. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  114319. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  114320. ** original setting of the SF_Distinct flag, not the current setting */
  114321. assert( sDistinct.isTnct );
  114322. #if SELECTTRACE_ENABLED
  114323. if( sqlite3SelectTrace & 0x400 ){
  114324. SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
  114325. sqlite3TreeViewSelect(0, p, 0);
  114326. }
  114327. #endif
  114328. }
  114329. /* If there is an ORDER BY clause, then create an ephemeral index to
  114330. ** do the sorting. But this sorting ephemeral index might end up
  114331. ** being unused if the data can be extracted in pre-sorted order.
  114332. ** If that is the case, then the OP_OpenEphemeral instruction will be
  114333. ** changed to an OP_Noop once we figure out that the sorting index is
  114334. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  114335. ** that change.
  114336. */
  114337. if( sSort.pOrderBy ){
  114338. KeyInfo *pKeyInfo;
  114339. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  114340. sSort.iECursor = pParse->nTab++;
  114341. sSort.addrSortIndex =
  114342. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  114343. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  114344. (char*)pKeyInfo, P4_KEYINFO
  114345. );
  114346. }else{
  114347. sSort.addrSortIndex = -1;
  114348. }
  114349. /* If the output is destined for a temporary table, open that table.
  114350. */
  114351. if( pDest->eDest==SRT_EphemTab ){
  114352. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  114353. }
  114354. /* Set the limiter.
  114355. */
  114356. iEnd = sqlite3VdbeMakeLabel(v);
  114357. if( (p->selFlags & SF_FixedLimit)==0 ){
  114358. p->nSelectRow = 320; /* 4 billion rows */
  114359. }
  114360. computeLimitRegisters(pParse, p, iEnd);
  114361. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  114362. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  114363. sSort.sortFlags |= SORTFLAG_UseSorter;
  114364. }
  114365. /* Open an ephemeral index to use for the distinct set.
  114366. */
  114367. if( p->selFlags & SF_Distinct ){
  114368. sDistinct.tabTnct = pParse->nTab++;
  114369. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  114370. sDistinct.tabTnct, 0, 0,
  114371. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  114372. P4_KEYINFO);
  114373. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  114374. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  114375. }else{
  114376. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  114377. }
  114378. if( !isAgg && pGroupBy==0 ){
  114379. /* No aggregate functions and no GROUP BY clause */
  114380. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  114381. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  114382. wctrlFlags |= p->selFlags & SF_FixedLimit;
  114383. /* Begin the database scan. */
  114384. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  114385. p->pEList, wctrlFlags, p->nSelectRow);
  114386. if( pWInfo==0 ) goto select_end;
  114387. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  114388. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  114389. }
  114390. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  114391. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  114392. }
  114393. if( sSort.pOrderBy ){
  114394. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  114395. sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
  114396. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  114397. sSort.pOrderBy = 0;
  114398. }
  114399. }
  114400. /* If sorting index that was created by a prior OP_OpenEphemeral
  114401. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  114402. ** into an OP_Noop.
  114403. */
  114404. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  114405. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  114406. }
  114407. /* Use the standard inner loop. */
  114408. selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
  114409. sqlite3WhereContinueLabel(pWInfo),
  114410. sqlite3WhereBreakLabel(pWInfo));
  114411. /* End the database scan loop.
  114412. */
  114413. sqlite3WhereEnd(pWInfo);
  114414. }else{
  114415. /* This case when there exist aggregate functions or a GROUP BY clause
  114416. ** or both */
  114417. NameContext sNC; /* Name context for processing aggregate information */
  114418. int iAMem; /* First Mem address for storing current GROUP BY */
  114419. int iBMem; /* First Mem address for previous GROUP BY */
  114420. int iUseFlag; /* Mem address holding flag indicating that at least
  114421. ** one row of the input to the aggregator has been
  114422. ** processed */
  114423. int iAbortFlag; /* Mem address which causes query abort if positive */
  114424. int groupBySort; /* Rows come from source in GROUP BY order */
  114425. int addrEnd; /* End of processing for this SELECT */
  114426. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  114427. int sortOut = 0; /* Output register from the sorter */
  114428. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  114429. /* Remove any and all aliases between the result set and the
  114430. ** GROUP BY clause.
  114431. */
  114432. if( pGroupBy ){
  114433. int k; /* Loop counter */
  114434. struct ExprList_item *pItem; /* For looping over expression in a list */
  114435. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  114436. pItem->u.x.iAlias = 0;
  114437. }
  114438. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  114439. pItem->u.x.iAlias = 0;
  114440. }
  114441. assert( 66==sqlite3LogEst(100) );
  114442. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  114443. }else{
  114444. assert( 0==sqlite3LogEst(1) );
  114445. p->nSelectRow = 0;
  114446. }
  114447. /* If there is both a GROUP BY and an ORDER BY clause and they are
  114448. ** identical, then it may be possible to disable the ORDER BY clause
  114449. ** on the grounds that the GROUP BY will cause elements to come out
  114450. ** in the correct order. It also may not - the GROUP BY might use a
  114451. ** database index that causes rows to be grouped together as required
  114452. ** but not actually sorted. Either way, record the fact that the
  114453. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  114454. ** variable. */
  114455. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  114456. orderByGrp = 1;
  114457. }
  114458. /* Create a label to jump to when we want to abort the query */
  114459. addrEnd = sqlite3VdbeMakeLabel(v);
  114460. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  114461. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  114462. ** SELECT statement.
  114463. */
  114464. memset(&sNC, 0, sizeof(sNC));
  114465. sNC.pParse = pParse;
  114466. sNC.pSrcList = pTabList;
  114467. sNC.pAggInfo = &sAggInfo;
  114468. sAggInfo.mnReg = pParse->nMem+1;
  114469. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  114470. sAggInfo.pGroupBy = pGroupBy;
  114471. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  114472. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  114473. if( pHaving ){
  114474. if( pGroupBy ){
  114475. assert( pWhere==p->pWhere );
  114476. havingToWhere(pParse, pGroupBy, pHaving, &p->pWhere);
  114477. pWhere = p->pWhere;
  114478. }
  114479. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  114480. }
  114481. sAggInfo.nAccumulator = sAggInfo.nColumn;
  114482. for(i=0; i<sAggInfo.nFunc; i++){
  114483. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  114484. sNC.ncFlags |= NC_InAggFunc;
  114485. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  114486. sNC.ncFlags &= ~NC_InAggFunc;
  114487. }
  114488. sAggInfo.mxReg = pParse->nMem;
  114489. if( db->mallocFailed ) goto select_end;
  114490. /* Processing for aggregates with GROUP BY is very different and
  114491. ** much more complex than aggregates without a GROUP BY.
  114492. */
  114493. if( pGroupBy ){
  114494. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  114495. int addr1; /* A-vs-B comparision jump */
  114496. int addrOutputRow; /* Start of subroutine that outputs a result row */
  114497. int regOutputRow; /* Return address register for output subroutine */
  114498. int addrSetAbort; /* Set the abort flag and return */
  114499. int addrTopOfLoop; /* Top of the input loop */
  114500. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  114501. int addrReset; /* Subroutine for resetting the accumulator */
  114502. int regReset; /* Return address register for reset subroutine */
  114503. /* If there is a GROUP BY clause we might need a sorting index to
  114504. ** implement it. Allocate that sorting index now. If it turns out
  114505. ** that we do not need it after all, the OP_SorterOpen instruction
  114506. ** will be converted into a Noop.
  114507. */
  114508. sAggInfo.sortingIdx = pParse->nTab++;
  114509. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  114510. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  114511. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  114512. 0, (char*)pKeyInfo, P4_KEYINFO);
  114513. /* Initialize memory locations used by GROUP BY aggregate processing
  114514. */
  114515. iUseFlag = ++pParse->nMem;
  114516. iAbortFlag = ++pParse->nMem;
  114517. regOutputRow = ++pParse->nMem;
  114518. addrOutputRow = sqlite3VdbeMakeLabel(v);
  114519. regReset = ++pParse->nMem;
  114520. addrReset = sqlite3VdbeMakeLabel(v);
  114521. iAMem = pParse->nMem + 1;
  114522. pParse->nMem += pGroupBy->nExpr;
  114523. iBMem = pParse->nMem + 1;
  114524. pParse->nMem += pGroupBy->nExpr;
  114525. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  114526. VdbeComment((v, "clear abort flag"));
  114527. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  114528. VdbeComment((v, "indicate accumulator empty"));
  114529. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  114530. /* Begin a loop that will extract all source rows in GROUP BY order.
  114531. ** This might involve two separate loops with an OP_Sort in between, or
  114532. ** it might be a single loop that uses an index to extract information
  114533. ** in the right order to begin with.
  114534. */
  114535. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  114536. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  114537. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  114538. );
  114539. if( pWInfo==0 ) goto select_end;
  114540. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  114541. /* The optimizer is able to deliver rows in group by order so
  114542. ** we do not have to sort. The OP_OpenEphemeral table will be
  114543. ** cancelled later because we still need to use the pKeyInfo
  114544. */
  114545. groupBySort = 0;
  114546. }else{
  114547. /* Rows are coming out in undetermined order. We have to push
  114548. ** each row into a sorting index, terminate the first loop,
  114549. ** then loop over the sorting index in order to get the output
  114550. ** in sorted order
  114551. */
  114552. int regBase;
  114553. int regRecord;
  114554. int nCol;
  114555. int nGroupBy;
  114556. explainTempTable(pParse,
  114557. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  114558. "DISTINCT" : "GROUP BY");
  114559. groupBySort = 1;
  114560. nGroupBy = pGroupBy->nExpr;
  114561. nCol = nGroupBy;
  114562. j = nGroupBy;
  114563. for(i=0; i<sAggInfo.nColumn; i++){
  114564. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  114565. nCol++;
  114566. j++;
  114567. }
  114568. }
  114569. regBase = sqlite3GetTempRange(pParse, nCol);
  114570. sqlite3ExprCacheClear(pParse);
  114571. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  114572. j = nGroupBy;
  114573. for(i=0; i<sAggInfo.nColumn; i++){
  114574. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  114575. if( pCol->iSorterColumn>=j ){
  114576. int r1 = j + regBase;
  114577. sqlite3ExprCodeGetColumnToReg(pParse,
  114578. pCol->pTab, pCol->iColumn, pCol->iTable, r1);
  114579. j++;
  114580. }
  114581. }
  114582. regRecord = sqlite3GetTempReg(pParse);
  114583. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  114584. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  114585. sqlite3ReleaseTempReg(pParse, regRecord);
  114586. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  114587. sqlite3WhereEnd(pWInfo);
  114588. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  114589. sortOut = sqlite3GetTempReg(pParse);
  114590. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  114591. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  114592. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  114593. sAggInfo.useSortingIdx = 1;
  114594. sqlite3ExprCacheClear(pParse);
  114595. }
  114596. /* If the index or temporary table used by the GROUP BY sort
  114597. ** will naturally deliver rows in the order required by the ORDER BY
  114598. ** clause, cancel the ephemeral table open coded earlier.
  114599. **
  114600. ** This is an optimization - the correct answer should result regardless.
  114601. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  114602. ** disable this optimization for testing purposes. */
  114603. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  114604. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  114605. ){
  114606. sSort.pOrderBy = 0;
  114607. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  114608. }
  114609. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  114610. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  114611. ** Then compare the current GROUP BY terms against the GROUP BY terms
  114612. ** from the previous row currently stored in a0, a1, a2...
  114613. */
  114614. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  114615. sqlite3ExprCacheClear(pParse);
  114616. if( groupBySort ){
  114617. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  114618. sortOut, sortPTab);
  114619. }
  114620. for(j=0; j<pGroupBy->nExpr; j++){
  114621. if( groupBySort ){
  114622. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  114623. }else{
  114624. sAggInfo.directMode = 1;
  114625. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  114626. }
  114627. }
  114628. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  114629. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  114630. addr1 = sqlite3VdbeCurrentAddr(v);
  114631. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  114632. /* Generate code that runs whenever the GROUP BY changes.
  114633. ** Changes in the GROUP BY are detected by the previous code
  114634. ** block. If there were no changes, this block is skipped.
  114635. **
  114636. ** This code copies current group by terms in b0,b1,b2,...
  114637. ** over to a0,a1,a2. It then calls the output subroutine
  114638. ** and resets the aggregate accumulator registers in preparation
  114639. ** for the next GROUP BY batch.
  114640. */
  114641. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  114642. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  114643. VdbeComment((v, "output one row"));
  114644. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  114645. VdbeComment((v, "check abort flag"));
  114646. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  114647. VdbeComment((v, "reset accumulator"));
  114648. /* Update the aggregate accumulators based on the content of
  114649. ** the current row
  114650. */
  114651. sqlite3VdbeJumpHere(v, addr1);
  114652. updateAccumulator(pParse, &sAggInfo);
  114653. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  114654. VdbeComment((v, "indicate data in accumulator"));
  114655. /* End of the loop
  114656. */
  114657. if( groupBySort ){
  114658. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  114659. VdbeCoverage(v);
  114660. }else{
  114661. sqlite3WhereEnd(pWInfo);
  114662. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  114663. }
  114664. /* Output the final row of result
  114665. */
  114666. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  114667. VdbeComment((v, "output final row"));
  114668. /* Jump over the subroutines
  114669. */
  114670. sqlite3VdbeGoto(v, addrEnd);
  114671. /* Generate a subroutine that outputs a single row of the result
  114672. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  114673. ** is less than or equal to zero, the subroutine is a no-op. If
  114674. ** the processing calls for the query to abort, this subroutine
  114675. ** increments the iAbortFlag memory location before returning in
  114676. ** order to signal the caller to abort.
  114677. */
  114678. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  114679. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  114680. VdbeComment((v, "set abort flag"));
  114681. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  114682. sqlite3VdbeResolveLabel(v, addrOutputRow);
  114683. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  114684. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  114685. VdbeCoverage(v);
  114686. VdbeComment((v, "Groupby result generator entry point"));
  114687. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  114688. finalizeAggFunctions(pParse, &sAggInfo);
  114689. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  114690. selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
  114691. &sDistinct, pDest,
  114692. addrOutputRow+1, addrSetAbort);
  114693. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  114694. VdbeComment((v, "end groupby result generator"));
  114695. /* Generate a subroutine that will reset the group-by accumulator
  114696. */
  114697. sqlite3VdbeResolveLabel(v, addrReset);
  114698. resetAccumulator(pParse, &sAggInfo);
  114699. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  114700. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  114701. else {
  114702. ExprList *pDel = 0;
  114703. #ifndef SQLITE_OMIT_BTREECOUNT
  114704. Table *pTab;
  114705. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  114706. /* If isSimpleCount() returns a pointer to a Table structure, then
  114707. ** the SQL statement is of the form:
  114708. **
  114709. ** SELECT count(*) FROM <tbl>
  114710. **
  114711. ** where the Table structure returned represents table <tbl>.
  114712. **
  114713. ** This statement is so common that it is optimized specially. The
  114714. ** OP_Count instruction is executed either on the intkey table that
  114715. ** contains the data for table <tbl> or on one of its indexes. It
  114716. ** is better to execute the op on an index, as indexes are almost
  114717. ** always spread across less pages than their corresponding tables.
  114718. */
  114719. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  114720. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  114721. Index *pIdx; /* Iterator variable */
  114722. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  114723. Index *pBest = 0; /* Best index found so far */
  114724. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  114725. sqlite3CodeVerifySchema(pParse, iDb);
  114726. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  114727. /* Search for the index that has the lowest scan cost.
  114728. **
  114729. ** (2011-04-15) Do not do a full scan of an unordered index.
  114730. **
  114731. ** (2013-10-03) Do not count the entries in a partial index.
  114732. **
  114733. ** In practice the KeyInfo structure will not be used. It is only
  114734. ** passed to keep OP_OpenRead happy.
  114735. */
  114736. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  114737. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  114738. if( pIdx->bUnordered==0
  114739. && pIdx->szIdxRow<pTab->szTabRow
  114740. && pIdx->pPartIdxWhere==0
  114741. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  114742. ){
  114743. pBest = pIdx;
  114744. }
  114745. }
  114746. if( pBest ){
  114747. iRoot = pBest->tnum;
  114748. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  114749. }
  114750. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  114751. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  114752. if( pKeyInfo ){
  114753. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  114754. }
  114755. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  114756. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  114757. explainSimpleCount(pParse, pTab, pBest);
  114758. }else
  114759. #endif /* SQLITE_OMIT_BTREECOUNT */
  114760. {
  114761. /* Check if the query is of one of the following forms:
  114762. **
  114763. ** SELECT min(x) FROM ...
  114764. ** SELECT max(x) FROM ...
  114765. **
  114766. ** If it is, then ask the code in where.c to attempt to sort results
  114767. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  114768. ** If where.c is able to produce results sorted in this order, then
  114769. ** add vdbe code to break out of the processing loop after the
  114770. ** first iteration (since the first iteration of the loop is
  114771. ** guaranteed to operate on the row with the minimum or maximum
  114772. ** value of x, the only row required).
  114773. **
  114774. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  114775. ** modify behavior as follows:
  114776. **
  114777. ** + If the query is a "SELECT min(x)", then the loop coded by
  114778. ** where.c should not iterate over any values with a NULL value
  114779. ** for x.
  114780. **
  114781. ** + The optimizer code in where.c (the thing that decides which
  114782. ** index or indices to use) should place a different priority on
  114783. ** satisfying the 'ORDER BY' clause than it does in other cases.
  114784. ** Refer to code and comments in where.c for details.
  114785. */
  114786. ExprList *pMinMax = 0;
  114787. u8 flag = WHERE_ORDERBY_NORMAL;
  114788. assert( p->pGroupBy==0 );
  114789. assert( flag==0 );
  114790. if( p->pHaving==0 ){
  114791. flag = minMaxQuery(&sAggInfo, &pMinMax);
  114792. }
  114793. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  114794. if( flag ){
  114795. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  114796. pDel = pMinMax;
  114797. assert( db->mallocFailed || pMinMax!=0 );
  114798. if( !db->mallocFailed ){
  114799. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  114800. pMinMax->a[0].pExpr->op = TK_COLUMN;
  114801. }
  114802. }
  114803. /* This case runs if the aggregate has no GROUP BY clause. The
  114804. ** processing is much simpler since there is only a single row
  114805. ** of output.
  114806. */
  114807. resetAccumulator(pParse, &sAggInfo);
  114808. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0);
  114809. if( pWInfo==0 ){
  114810. sqlite3ExprListDelete(db, pDel);
  114811. goto select_end;
  114812. }
  114813. updateAccumulator(pParse, &sAggInfo);
  114814. assert( pMinMax==0 || pMinMax->nExpr==1 );
  114815. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  114816. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  114817. VdbeComment((v, "%s() by index",
  114818. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  114819. }
  114820. sqlite3WhereEnd(pWInfo);
  114821. finalizeAggFunctions(pParse, &sAggInfo);
  114822. }
  114823. sSort.pOrderBy = 0;
  114824. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  114825. selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
  114826. pDest, addrEnd, addrEnd);
  114827. sqlite3ExprListDelete(db, pDel);
  114828. }
  114829. sqlite3VdbeResolveLabel(v, addrEnd);
  114830. } /* endif aggregate query */
  114831. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  114832. explainTempTable(pParse, "DISTINCT");
  114833. }
  114834. /* If there is an ORDER BY clause, then we need to sort the results
  114835. ** and send them to the callback one by one.
  114836. */
  114837. if( sSort.pOrderBy ){
  114838. explainTempTable(pParse,
  114839. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  114840. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  114841. }
  114842. /* Jump here to skip this query
  114843. */
  114844. sqlite3VdbeResolveLabel(v, iEnd);
  114845. /* The SELECT has been coded. If there is an error in the Parse structure,
  114846. ** set the return code to 1. Otherwise 0. */
  114847. rc = (pParse->nErr>0);
  114848. /* Control jumps to here if an error is encountered above, or upon
  114849. ** successful coding of the SELECT.
  114850. */
  114851. select_end:
  114852. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  114853. /* Identify column names if results of the SELECT are to be output.
  114854. */
  114855. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  114856. generateColumnNames(pParse, pTabList, pEList);
  114857. }
  114858. sqlite3DbFree(db, sAggInfo.aCol);
  114859. sqlite3DbFree(db, sAggInfo.aFunc);
  114860. #if SELECTTRACE_ENABLED
  114861. SELECTTRACE(1,pParse,p,("end processing\n"));
  114862. pParse->nSelectIndent--;
  114863. #endif
  114864. return rc;
  114865. }
  114866. /************** End of select.c **********************************************/
  114867. /************** Begin file table.c *******************************************/
  114868. /*
  114869. ** 2001 September 15
  114870. **
  114871. ** The author disclaims copyright to this source code. In place of
  114872. ** a legal notice, here is a blessing:
  114873. **
  114874. ** May you do good and not evil.
  114875. ** May you find forgiveness for yourself and forgive others.
  114876. ** May you share freely, never taking more than you give.
  114877. **
  114878. *************************************************************************
  114879. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  114880. ** interface routines. These are just wrappers around the main
  114881. ** interface routine of sqlite3_exec().
  114882. **
  114883. ** These routines are in a separate files so that they will not be linked
  114884. ** if they are not used.
  114885. */
  114886. /* #include "sqliteInt.h" */
  114887. #ifndef SQLITE_OMIT_GET_TABLE
  114888. /*
  114889. ** This structure is used to pass data from sqlite3_get_table() through
  114890. ** to the callback function is uses to build the result.
  114891. */
  114892. typedef struct TabResult {
  114893. char **azResult; /* Accumulated output */
  114894. char *zErrMsg; /* Error message text, if an error occurs */
  114895. u32 nAlloc; /* Slots allocated for azResult[] */
  114896. u32 nRow; /* Number of rows in the result */
  114897. u32 nColumn; /* Number of columns in the result */
  114898. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  114899. int rc; /* Return code from sqlite3_exec() */
  114900. } TabResult;
  114901. /*
  114902. ** This routine is called once for each row in the result table. Its job
  114903. ** is to fill in the TabResult structure appropriately, allocating new
  114904. ** memory as necessary.
  114905. */
  114906. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  114907. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  114908. int need; /* Slots needed in p->azResult[] */
  114909. int i; /* Loop counter */
  114910. char *z; /* A single column of result */
  114911. /* Make sure there is enough space in p->azResult to hold everything
  114912. ** we need to remember from this invocation of the callback.
  114913. */
  114914. if( p->nRow==0 && argv!=0 ){
  114915. need = nCol*2;
  114916. }else{
  114917. need = nCol;
  114918. }
  114919. if( p->nData + need > p->nAlloc ){
  114920. char **azNew;
  114921. p->nAlloc = p->nAlloc*2 + need;
  114922. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  114923. if( azNew==0 ) goto malloc_failed;
  114924. p->azResult = azNew;
  114925. }
  114926. /* If this is the first row, then generate an extra row containing
  114927. ** the names of all columns.
  114928. */
  114929. if( p->nRow==0 ){
  114930. p->nColumn = nCol;
  114931. for(i=0; i<nCol; i++){
  114932. z = sqlite3_mprintf("%s", colv[i]);
  114933. if( z==0 ) goto malloc_failed;
  114934. p->azResult[p->nData++] = z;
  114935. }
  114936. }else if( (int)p->nColumn!=nCol ){
  114937. sqlite3_free(p->zErrMsg);
  114938. p->zErrMsg = sqlite3_mprintf(
  114939. "sqlite3_get_table() called with two or more incompatible queries"
  114940. );
  114941. p->rc = SQLITE_ERROR;
  114942. return 1;
  114943. }
  114944. /* Copy over the row data
  114945. */
  114946. if( argv!=0 ){
  114947. for(i=0; i<nCol; i++){
  114948. if( argv[i]==0 ){
  114949. z = 0;
  114950. }else{
  114951. int n = sqlite3Strlen30(argv[i])+1;
  114952. z = sqlite3_malloc64( n );
  114953. if( z==0 ) goto malloc_failed;
  114954. memcpy(z, argv[i], n);
  114955. }
  114956. p->azResult[p->nData++] = z;
  114957. }
  114958. p->nRow++;
  114959. }
  114960. return 0;
  114961. malloc_failed:
  114962. p->rc = SQLITE_NOMEM_BKPT;
  114963. return 1;
  114964. }
  114965. /*
  114966. ** Query the database. But instead of invoking a callback for each row,
  114967. ** malloc() for space to hold the result and return the entire results
  114968. ** at the conclusion of the call.
  114969. **
  114970. ** The result that is written to ***pazResult is held in memory obtained
  114971. ** from malloc(). But the caller cannot free this memory directly.
  114972. ** Instead, the entire table should be passed to sqlite3_free_table() when
  114973. ** the calling procedure is finished using it.
  114974. */
  114975. SQLITE_API int sqlite3_get_table(
  114976. sqlite3 *db, /* The database on which the SQL executes */
  114977. const char *zSql, /* The SQL to be executed */
  114978. char ***pazResult, /* Write the result table here */
  114979. int *pnRow, /* Write the number of rows in the result here */
  114980. int *pnColumn, /* Write the number of columns of result here */
  114981. char **pzErrMsg /* Write error messages here */
  114982. ){
  114983. int rc;
  114984. TabResult res;
  114985. #ifdef SQLITE_ENABLE_API_ARMOR
  114986. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  114987. #endif
  114988. *pazResult = 0;
  114989. if( pnColumn ) *pnColumn = 0;
  114990. if( pnRow ) *pnRow = 0;
  114991. if( pzErrMsg ) *pzErrMsg = 0;
  114992. res.zErrMsg = 0;
  114993. res.nRow = 0;
  114994. res.nColumn = 0;
  114995. res.nData = 1;
  114996. res.nAlloc = 20;
  114997. res.rc = SQLITE_OK;
  114998. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  114999. if( res.azResult==0 ){
  115000. db->errCode = SQLITE_NOMEM;
  115001. return SQLITE_NOMEM_BKPT;
  115002. }
  115003. res.azResult[0] = 0;
  115004. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  115005. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  115006. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  115007. if( (rc&0xff)==SQLITE_ABORT ){
  115008. sqlite3_free_table(&res.azResult[1]);
  115009. if( res.zErrMsg ){
  115010. if( pzErrMsg ){
  115011. sqlite3_free(*pzErrMsg);
  115012. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  115013. }
  115014. sqlite3_free(res.zErrMsg);
  115015. }
  115016. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  115017. return res.rc;
  115018. }
  115019. sqlite3_free(res.zErrMsg);
  115020. if( rc!=SQLITE_OK ){
  115021. sqlite3_free_table(&res.azResult[1]);
  115022. return rc;
  115023. }
  115024. if( res.nAlloc>res.nData ){
  115025. char **azNew;
  115026. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  115027. if( azNew==0 ){
  115028. sqlite3_free_table(&res.azResult[1]);
  115029. db->errCode = SQLITE_NOMEM;
  115030. return SQLITE_NOMEM_BKPT;
  115031. }
  115032. res.azResult = azNew;
  115033. }
  115034. *pazResult = &res.azResult[1];
  115035. if( pnColumn ) *pnColumn = res.nColumn;
  115036. if( pnRow ) *pnRow = res.nRow;
  115037. return rc;
  115038. }
  115039. /*
  115040. ** This routine frees the space the sqlite3_get_table() malloced.
  115041. */
  115042. SQLITE_API void sqlite3_free_table(
  115043. char **azResult /* Result returned from sqlite3_get_table() */
  115044. ){
  115045. if( azResult ){
  115046. int i, n;
  115047. azResult--;
  115048. assert( azResult!=0 );
  115049. n = SQLITE_PTR_TO_INT(azResult[0]);
  115050. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  115051. sqlite3_free(azResult);
  115052. }
  115053. }
  115054. #endif /* SQLITE_OMIT_GET_TABLE */
  115055. /************** End of table.c ***********************************************/
  115056. /************** Begin file trigger.c *****************************************/
  115057. /*
  115058. **
  115059. ** The author disclaims copyright to this source code. In place of
  115060. ** a legal notice, here is a blessing:
  115061. **
  115062. ** May you do good and not evil.
  115063. ** May you find forgiveness for yourself and forgive others.
  115064. ** May you share freely, never taking more than you give.
  115065. **
  115066. *************************************************************************
  115067. ** This file contains the implementation for TRIGGERs
  115068. */
  115069. /* #include "sqliteInt.h" */
  115070. #ifndef SQLITE_OMIT_TRIGGER
  115071. /*
  115072. ** Delete a linked list of TriggerStep structures.
  115073. */
  115074. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  115075. while( pTriggerStep ){
  115076. TriggerStep * pTmp = pTriggerStep;
  115077. pTriggerStep = pTriggerStep->pNext;
  115078. sqlite3ExprDelete(db, pTmp->pWhere);
  115079. sqlite3ExprListDelete(db, pTmp->pExprList);
  115080. sqlite3SelectDelete(db, pTmp->pSelect);
  115081. sqlite3IdListDelete(db, pTmp->pIdList);
  115082. sqlite3DbFree(db, pTmp);
  115083. }
  115084. }
  115085. /*
  115086. ** Given table pTab, return a list of all the triggers attached to
  115087. ** the table. The list is connected by Trigger.pNext pointers.
  115088. **
  115089. ** All of the triggers on pTab that are in the same database as pTab
  115090. ** are already attached to pTab->pTrigger. But there might be additional
  115091. ** triggers on pTab in the TEMP schema. This routine prepends all
  115092. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  115093. ** and returns the combined list.
  115094. **
  115095. ** To state it another way: This routine returns a list of all triggers
  115096. ** that fire off of pTab. The list will include any TEMP triggers on
  115097. ** pTab as well as the triggers lised in pTab->pTrigger.
  115098. */
  115099. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  115100. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  115101. Trigger *pList = 0; /* List of triggers to return */
  115102. if( pParse->disableTriggers ){
  115103. return 0;
  115104. }
  115105. if( pTmpSchema!=pTab->pSchema ){
  115106. HashElem *p;
  115107. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  115108. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  115109. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  115110. if( pTrig->pTabSchema==pTab->pSchema
  115111. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  115112. ){
  115113. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  115114. pList = pTrig;
  115115. }
  115116. }
  115117. }
  115118. return (pList ? pList : pTab->pTrigger);
  115119. }
  115120. /*
  115121. ** This is called by the parser when it sees a CREATE TRIGGER statement
  115122. ** up to the point of the BEGIN before the trigger actions. A Trigger
  115123. ** structure is generated based on the information available and stored
  115124. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  115125. ** sqlite3FinishTrigger() function is called to complete the trigger
  115126. ** construction process.
  115127. */
  115128. SQLITE_PRIVATE void sqlite3BeginTrigger(
  115129. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  115130. Token *pName1, /* The name of the trigger */
  115131. Token *pName2, /* The name of the trigger */
  115132. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  115133. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  115134. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  115135. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  115136. Expr *pWhen, /* WHEN clause */
  115137. int isTemp, /* True if the TEMPORARY keyword is present */
  115138. int noErr /* Suppress errors if the trigger already exists */
  115139. ){
  115140. Trigger *pTrigger = 0; /* The new trigger */
  115141. Table *pTab; /* Table that the trigger fires off of */
  115142. char *zName = 0; /* Name of the trigger */
  115143. sqlite3 *db = pParse->db; /* The database connection */
  115144. int iDb; /* The database to store the trigger in */
  115145. Token *pName; /* The unqualified db name */
  115146. DbFixer sFix; /* State vector for the DB fixer */
  115147. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  115148. assert( pName2!=0 );
  115149. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  115150. assert( op>0 && op<0xff );
  115151. if( isTemp ){
  115152. /* If TEMP was specified, then the trigger name may not be qualified. */
  115153. if( pName2->n>0 ){
  115154. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  115155. goto trigger_cleanup;
  115156. }
  115157. iDb = 1;
  115158. pName = pName1;
  115159. }else{
  115160. /* Figure out the db that the trigger will be created in */
  115161. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  115162. if( iDb<0 ){
  115163. goto trigger_cleanup;
  115164. }
  115165. }
  115166. if( !pTableName || db->mallocFailed ){
  115167. goto trigger_cleanup;
  115168. }
  115169. /* A long-standing parser bug is that this syntax was allowed:
  115170. **
  115171. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  115172. ** ^^^^^^^^
  115173. **
  115174. ** To maintain backwards compatibility, ignore the database
  115175. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  115176. */
  115177. if( db->init.busy && iDb!=1 ){
  115178. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  115179. pTableName->a[0].zDatabase = 0;
  115180. }
  115181. /* If the trigger name was unqualified, and the table is a temp table,
  115182. ** then set iDb to 1 to create the trigger in the temporary database.
  115183. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  115184. ** exist, the error is caught by the block below.
  115185. */
  115186. pTab = sqlite3SrcListLookup(pParse, pTableName);
  115187. if( db->init.busy==0 && pName2->n==0 && pTab
  115188. && pTab->pSchema==db->aDb[1].pSchema ){
  115189. iDb = 1;
  115190. }
  115191. /* Ensure the table name matches database name and that the table exists */
  115192. if( db->mallocFailed ) goto trigger_cleanup;
  115193. assert( pTableName->nSrc==1 );
  115194. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  115195. if( sqlite3FixSrcList(&sFix, pTableName) ){
  115196. goto trigger_cleanup;
  115197. }
  115198. pTab = sqlite3SrcListLookup(pParse, pTableName);
  115199. if( !pTab ){
  115200. /* The table does not exist. */
  115201. if( db->init.iDb==1 ){
  115202. /* Ticket #3810.
  115203. ** Normally, whenever a table is dropped, all associated triggers are
  115204. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  115205. ** and the table is dropped by a different database connection, the
  115206. ** trigger is not visible to the database connection that does the
  115207. ** drop so the trigger cannot be dropped. This results in an
  115208. ** "orphaned trigger" - a trigger whose associated table is missing.
  115209. */
  115210. db->init.orphanTrigger = 1;
  115211. }
  115212. goto trigger_cleanup;
  115213. }
  115214. if( IsVirtual(pTab) ){
  115215. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  115216. goto trigger_cleanup;
  115217. }
  115218. /* Check that the trigger name is not reserved and that no trigger of the
  115219. ** specified name exists */
  115220. zName = sqlite3NameFromToken(db, pName);
  115221. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  115222. goto trigger_cleanup;
  115223. }
  115224. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115225. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  115226. if( !noErr ){
  115227. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  115228. }else{
  115229. assert( !db->init.busy );
  115230. sqlite3CodeVerifySchema(pParse, iDb);
  115231. }
  115232. goto trigger_cleanup;
  115233. }
  115234. /* Do not create a trigger on a system table */
  115235. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  115236. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  115237. goto trigger_cleanup;
  115238. }
  115239. /* INSTEAD of triggers are only for views and views only support INSTEAD
  115240. ** of triggers.
  115241. */
  115242. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  115243. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  115244. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  115245. goto trigger_cleanup;
  115246. }
  115247. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  115248. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  115249. " trigger on table: %S", pTableName, 0);
  115250. goto trigger_cleanup;
  115251. }
  115252. #ifndef SQLITE_OMIT_AUTHORIZATION
  115253. {
  115254. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  115255. int code = SQLITE_CREATE_TRIGGER;
  115256. const char *zDb = db->aDb[iTabDb].zDbSName;
  115257. const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
  115258. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  115259. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  115260. goto trigger_cleanup;
  115261. }
  115262. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  115263. goto trigger_cleanup;
  115264. }
  115265. }
  115266. #endif
  115267. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  115268. ** cannot appear on views. So we might as well translate every
  115269. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  115270. ** elsewhere.
  115271. */
  115272. if (tr_tm == TK_INSTEAD){
  115273. tr_tm = TK_BEFORE;
  115274. }
  115275. /* Build the Trigger object */
  115276. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  115277. if( pTrigger==0 ) goto trigger_cleanup;
  115278. pTrigger->zName = zName;
  115279. zName = 0;
  115280. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  115281. pTrigger->pSchema = db->aDb[iDb].pSchema;
  115282. pTrigger->pTabSchema = pTab->pSchema;
  115283. pTrigger->op = (u8)op;
  115284. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  115285. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  115286. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  115287. assert( pParse->pNewTrigger==0 );
  115288. pParse->pNewTrigger = pTrigger;
  115289. trigger_cleanup:
  115290. sqlite3DbFree(db, zName);
  115291. sqlite3SrcListDelete(db, pTableName);
  115292. sqlite3IdListDelete(db, pColumns);
  115293. sqlite3ExprDelete(db, pWhen);
  115294. if( !pParse->pNewTrigger ){
  115295. sqlite3DeleteTrigger(db, pTrigger);
  115296. }else{
  115297. assert( pParse->pNewTrigger==pTrigger );
  115298. }
  115299. }
  115300. /*
  115301. ** This routine is called after all of the trigger actions have been parsed
  115302. ** in order to complete the process of building the trigger.
  115303. */
  115304. SQLITE_PRIVATE void sqlite3FinishTrigger(
  115305. Parse *pParse, /* Parser context */
  115306. TriggerStep *pStepList, /* The triggered program */
  115307. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  115308. ){
  115309. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  115310. char *zName; /* Name of trigger */
  115311. sqlite3 *db = pParse->db; /* The database */
  115312. DbFixer sFix; /* Fixer object */
  115313. int iDb; /* Database containing the trigger */
  115314. Token nameToken; /* Trigger name for error reporting */
  115315. pParse->pNewTrigger = 0;
  115316. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  115317. zName = pTrig->zName;
  115318. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  115319. pTrig->step_list = pStepList;
  115320. while( pStepList ){
  115321. pStepList->pTrig = pTrig;
  115322. pStepList = pStepList->pNext;
  115323. }
  115324. sqlite3TokenInit(&nameToken, pTrig->zName);
  115325. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  115326. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  115327. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  115328. ){
  115329. goto triggerfinish_cleanup;
  115330. }
  115331. /* if we are not initializing,
  115332. ** build the sqlite_master entry
  115333. */
  115334. if( !db->init.busy ){
  115335. Vdbe *v;
  115336. char *z;
  115337. /* Make an entry in the sqlite_master table */
  115338. v = sqlite3GetVdbe(pParse);
  115339. if( v==0 ) goto triggerfinish_cleanup;
  115340. sqlite3BeginWriteOperation(pParse, 0, iDb);
  115341. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  115342. sqlite3NestedParse(pParse,
  115343. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  115344. db->aDb[iDb].zDbSName, MASTER_NAME, zName,
  115345. pTrig->table, z);
  115346. sqlite3DbFree(db, z);
  115347. sqlite3ChangeCookie(pParse, iDb);
  115348. sqlite3VdbeAddParseSchemaOp(v, iDb,
  115349. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  115350. }
  115351. if( db->init.busy ){
  115352. Trigger *pLink = pTrig;
  115353. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  115354. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115355. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  115356. if( pTrig ){
  115357. sqlite3OomFault(db);
  115358. }else if( pLink->pSchema==pLink->pTabSchema ){
  115359. Table *pTab;
  115360. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  115361. assert( pTab!=0 );
  115362. pLink->pNext = pTab->pTrigger;
  115363. pTab->pTrigger = pLink;
  115364. }
  115365. }
  115366. triggerfinish_cleanup:
  115367. sqlite3DeleteTrigger(db, pTrig);
  115368. assert( !pParse->pNewTrigger );
  115369. sqlite3DeleteTriggerStep(db, pStepList);
  115370. }
  115371. /*
  115372. ** Turn a SELECT statement (that the pSelect parameter points to) into
  115373. ** a trigger step. Return a pointer to a TriggerStep structure.
  115374. **
  115375. ** The parser calls this routine when it finds a SELECT statement in
  115376. ** body of a TRIGGER.
  115377. */
  115378. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  115379. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  115380. if( pTriggerStep==0 ) {
  115381. sqlite3SelectDelete(db, pSelect);
  115382. return 0;
  115383. }
  115384. pTriggerStep->op = TK_SELECT;
  115385. pTriggerStep->pSelect = pSelect;
  115386. pTriggerStep->orconf = OE_Default;
  115387. return pTriggerStep;
  115388. }
  115389. /*
  115390. ** Allocate space to hold a new trigger step. The allocated space
  115391. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  115392. **
  115393. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  115394. */
  115395. static TriggerStep *triggerStepAllocate(
  115396. sqlite3 *db, /* Database connection */
  115397. u8 op, /* Trigger opcode */
  115398. Token *pName /* The target name */
  115399. ){
  115400. TriggerStep *pTriggerStep;
  115401. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  115402. if( pTriggerStep ){
  115403. char *z = (char*)&pTriggerStep[1];
  115404. memcpy(z, pName->z, pName->n);
  115405. sqlite3Dequote(z);
  115406. pTriggerStep->zTarget = z;
  115407. pTriggerStep->op = op;
  115408. }
  115409. return pTriggerStep;
  115410. }
  115411. /*
  115412. ** Build a trigger step out of an INSERT statement. Return a pointer
  115413. ** to the new trigger step.
  115414. **
  115415. ** The parser calls this routine when it sees an INSERT inside the
  115416. ** body of a trigger.
  115417. */
  115418. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  115419. sqlite3 *db, /* The database connection */
  115420. Token *pTableName, /* Name of the table into which we insert */
  115421. IdList *pColumn, /* List of columns in pTableName to insert into */
  115422. Select *pSelect, /* A SELECT statement that supplies values */
  115423. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  115424. ){
  115425. TriggerStep *pTriggerStep;
  115426. assert(pSelect != 0 || db->mallocFailed);
  115427. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  115428. if( pTriggerStep ){
  115429. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  115430. pTriggerStep->pIdList = pColumn;
  115431. pTriggerStep->orconf = orconf;
  115432. }else{
  115433. sqlite3IdListDelete(db, pColumn);
  115434. }
  115435. sqlite3SelectDelete(db, pSelect);
  115436. return pTriggerStep;
  115437. }
  115438. /*
  115439. ** Construct a trigger step that implements an UPDATE statement and return
  115440. ** a pointer to that trigger step. The parser calls this routine when it
  115441. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  115442. */
  115443. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  115444. sqlite3 *db, /* The database connection */
  115445. Token *pTableName, /* Name of the table to be updated */
  115446. ExprList *pEList, /* The SET clause: list of column and new values */
  115447. Expr *pWhere, /* The WHERE clause */
  115448. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  115449. ){
  115450. TriggerStep *pTriggerStep;
  115451. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  115452. if( pTriggerStep ){
  115453. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  115454. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  115455. pTriggerStep->orconf = orconf;
  115456. }
  115457. sqlite3ExprListDelete(db, pEList);
  115458. sqlite3ExprDelete(db, pWhere);
  115459. return pTriggerStep;
  115460. }
  115461. /*
  115462. ** Construct a trigger step that implements a DELETE statement and return
  115463. ** a pointer to that trigger step. The parser calls this routine when it
  115464. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  115465. */
  115466. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  115467. sqlite3 *db, /* Database connection */
  115468. Token *pTableName, /* The table from which rows are deleted */
  115469. Expr *pWhere /* The WHERE clause */
  115470. ){
  115471. TriggerStep *pTriggerStep;
  115472. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  115473. if( pTriggerStep ){
  115474. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  115475. pTriggerStep->orconf = OE_Default;
  115476. }
  115477. sqlite3ExprDelete(db, pWhere);
  115478. return pTriggerStep;
  115479. }
  115480. /*
  115481. ** Recursively delete a Trigger structure
  115482. */
  115483. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  115484. if( pTrigger==0 ) return;
  115485. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  115486. sqlite3DbFree(db, pTrigger->zName);
  115487. sqlite3DbFree(db, pTrigger->table);
  115488. sqlite3ExprDelete(db, pTrigger->pWhen);
  115489. sqlite3IdListDelete(db, pTrigger->pColumns);
  115490. sqlite3DbFree(db, pTrigger);
  115491. }
  115492. /*
  115493. ** This function is called to drop a trigger from the database schema.
  115494. **
  115495. ** This may be called directly from the parser and therefore identifies
  115496. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  115497. ** same job as this routine except it takes a pointer to the trigger
  115498. ** instead of the trigger name.
  115499. **/
  115500. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  115501. Trigger *pTrigger = 0;
  115502. int i;
  115503. const char *zDb;
  115504. const char *zName;
  115505. sqlite3 *db = pParse->db;
  115506. if( db->mallocFailed ) goto drop_trigger_cleanup;
  115507. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  115508. goto drop_trigger_cleanup;
  115509. }
  115510. assert( pName->nSrc==1 );
  115511. zDb = pName->a[0].zDatabase;
  115512. zName = pName->a[0].zName;
  115513. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  115514. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  115515. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  115516. if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
  115517. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  115518. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  115519. if( pTrigger ) break;
  115520. }
  115521. if( !pTrigger ){
  115522. if( !noErr ){
  115523. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  115524. }else{
  115525. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  115526. }
  115527. pParse->checkSchema = 1;
  115528. goto drop_trigger_cleanup;
  115529. }
  115530. sqlite3DropTriggerPtr(pParse, pTrigger);
  115531. drop_trigger_cleanup:
  115532. sqlite3SrcListDelete(db, pName);
  115533. }
  115534. /*
  115535. ** Return a pointer to the Table structure for the table that a trigger
  115536. ** is set on.
  115537. */
  115538. static Table *tableOfTrigger(Trigger *pTrigger){
  115539. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  115540. }
  115541. /*
  115542. ** Drop a trigger given a pointer to that trigger.
  115543. */
  115544. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  115545. Table *pTable;
  115546. Vdbe *v;
  115547. sqlite3 *db = pParse->db;
  115548. int iDb;
  115549. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  115550. assert( iDb>=0 && iDb<db->nDb );
  115551. pTable = tableOfTrigger(pTrigger);
  115552. assert( pTable );
  115553. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  115554. #ifndef SQLITE_OMIT_AUTHORIZATION
  115555. {
  115556. int code = SQLITE_DROP_TRIGGER;
  115557. const char *zDb = db->aDb[iDb].zDbSName;
  115558. const char *zTab = SCHEMA_TABLE(iDb);
  115559. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  115560. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  115561. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  115562. return;
  115563. }
  115564. }
  115565. #endif
  115566. /* Generate code to destroy the database record of the trigger.
  115567. */
  115568. assert( pTable!=0 );
  115569. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  115570. sqlite3NestedParse(pParse,
  115571. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  115572. db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
  115573. );
  115574. sqlite3ChangeCookie(pParse, iDb);
  115575. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  115576. }
  115577. }
  115578. /*
  115579. ** Remove a trigger from the hash tables of the sqlite* pointer.
  115580. */
  115581. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  115582. Trigger *pTrigger;
  115583. Hash *pHash;
  115584. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115585. pHash = &(db->aDb[iDb].pSchema->trigHash);
  115586. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  115587. if( ALWAYS(pTrigger) ){
  115588. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  115589. Table *pTab = tableOfTrigger(pTrigger);
  115590. Trigger **pp;
  115591. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  115592. *pp = (*pp)->pNext;
  115593. }
  115594. sqlite3DeleteTrigger(db, pTrigger);
  115595. db->flags |= SQLITE_InternChanges;
  115596. }
  115597. }
  115598. /*
  115599. ** pEList is the SET clause of an UPDATE statement. Each entry
  115600. ** in pEList is of the format <id>=<expr>. If any of the entries
  115601. ** in pEList have an <id> which matches an identifier in pIdList,
  115602. ** then return TRUE. If pIdList==NULL, then it is considered a
  115603. ** wildcard that matches anything. Likewise if pEList==NULL then
  115604. ** it matches anything so always return true. Return false only
  115605. ** if there is no match.
  115606. */
  115607. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  115608. int e;
  115609. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  115610. for(e=0; e<pEList->nExpr; e++){
  115611. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  115612. }
  115613. return 0;
  115614. }
  115615. /*
  115616. ** Return a list of all triggers on table pTab if there exists at least
  115617. ** one trigger that must be fired when an operation of type 'op' is
  115618. ** performed on the table, and, if that operation is an UPDATE, if at
  115619. ** least one of the columns in pChanges is being modified.
  115620. */
  115621. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  115622. Parse *pParse, /* Parse context */
  115623. Table *pTab, /* The table the contains the triggers */
  115624. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  115625. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  115626. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  115627. ){
  115628. int mask = 0;
  115629. Trigger *pList = 0;
  115630. Trigger *p;
  115631. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  115632. pList = sqlite3TriggerList(pParse, pTab);
  115633. }
  115634. assert( pList==0 || IsVirtual(pTab)==0 );
  115635. for(p=pList; p; p=p->pNext){
  115636. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  115637. mask |= p->tr_tm;
  115638. }
  115639. }
  115640. if( pMask ){
  115641. *pMask = mask;
  115642. }
  115643. return (mask ? pList : 0);
  115644. }
  115645. /*
  115646. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  115647. ** to that SrcList.
  115648. **
  115649. ** This routine adds a specific database name, if needed, to the target when
  115650. ** forming the SrcList. This prevents a trigger in one database from
  115651. ** referring to a target in another database. An exception is when the
  115652. ** trigger is in TEMP in which case it can refer to any other database it
  115653. ** wants.
  115654. */
  115655. static SrcList *targetSrcList(
  115656. Parse *pParse, /* The parsing context */
  115657. TriggerStep *pStep /* The trigger containing the target token */
  115658. ){
  115659. sqlite3 *db = pParse->db;
  115660. int iDb; /* Index of the database to use */
  115661. SrcList *pSrc; /* SrcList to be returned */
  115662. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  115663. if( pSrc ){
  115664. assert( pSrc->nSrc>0 );
  115665. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  115666. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  115667. if( iDb==0 || iDb>=2 ){
  115668. const char *zDb;
  115669. assert( iDb<db->nDb );
  115670. zDb = db->aDb[iDb].zDbSName;
  115671. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
  115672. }
  115673. }
  115674. return pSrc;
  115675. }
  115676. /*
  115677. ** Generate VDBE code for the statements inside the body of a single
  115678. ** trigger.
  115679. */
  115680. static int codeTriggerProgram(
  115681. Parse *pParse, /* The parser context */
  115682. TriggerStep *pStepList, /* List of statements inside the trigger body */
  115683. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  115684. ){
  115685. TriggerStep *pStep;
  115686. Vdbe *v = pParse->pVdbe;
  115687. sqlite3 *db = pParse->db;
  115688. assert( pParse->pTriggerTab && pParse->pToplevel );
  115689. assert( pStepList );
  115690. assert( v!=0 );
  115691. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  115692. /* Figure out the ON CONFLICT policy that will be used for this step
  115693. ** of the trigger program. If the statement that caused this trigger
  115694. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  115695. ** the ON CONFLICT policy that was specified as part of the trigger
  115696. ** step statement. Example:
  115697. **
  115698. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  115699. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  115700. ** END;
  115701. **
  115702. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  115703. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  115704. */
  115705. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  115706. assert( pParse->okConstFactor==0 );
  115707. switch( pStep->op ){
  115708. case TK_UPDATE: {
  115709. sqlite3Update(pParse,
  115710. targetSrcList(pParse, pStep),
  115711. sqlite3ExprListDup(db, pStep->pExprList, 0),
  115712. sqlite3ExprDup(db, pStep->pWhere, 0),
  115713. pParse->eOrconf
  115714. );
  115715. break;
  115716. }
  115717. case TK_INSERT: {
  115718. sqlite3Insert(pParse,
  115719. targetSrcList(pParse, pStep),
  115720. sqlite3SelectDup(db, pStep->pSelect, 0),
  115721. sqlite3IdListDup(db, pStep->pIdList),
  115722. pParse->eOrconf
  115723. );
  115724. break;
  115725. }
  115726. case TK_DELETE: {
  115727. sqlite3DeleteFrom(pParse,
  115728. targetSrcList(pParse, pStep),
  115729. sqlite3ExprDup(db, pStep->pWhere, 0)
  115730. );
  115731. break;
  115732. }
  115733. default: assert( pStep->op==TK_SELECT ); {
  115734. SelectDest sDest;
  115735. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  115736. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  115737. sqlite3Select(pParse, pSelect, &sDest);
  115738. sqlite3SelectDelete(db, pSelect);
  115739. break;
  115740. }
  115741. }
  115742. if( pStep->op!=TK_SELECT ){
  115743. sqlite3VdbeAddOp0(v, OP_ResetCount);
  115744. }
  115745. }
  115746. return 0;
  115747. }
  115748. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  115749. /*
  115750. ** This function is used to add VdbeComment() annotations to a VDBE
  115751. ** program. It is not used in production code, only for debugging.
  115752. */
  115753. static const char *onErrorText(int onError){
  115754. switch( onError ){
  115755. case OE_Abort: return "abort";
  115756. case OE_Rollback: return "rollback";
  115757. case OE_Fail: return "fail";
  115758. case OE_Replace: return "replace";
  115759. case OE_Ignore: return "ignore";
  115760. case OE_Default: return "default";
  115761. }
  115762. return "n/a";
  115763. }
  115764. #endif
  115765. /*
  115766. ** Parse context structure pFrom has just been used to create a sub-vdbe
  115767. ** (trigger program). If an error has occurred, transfer error information
  115768. ** from pFrom to pTo.
  115769. */
  115770. static void transferParseError(Parse *pTo, Parse *pFrom){
  115771. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  115772. assert( pTo->zErrMsg==0 || pTo->nErr );
  115773. if( pTo->nErr==0 ){
  115774. pTo->zErrMsg = pFrom->zErrMsg;
  115775. pTo->nErr = pFrom->nErr;
  115776. pTo->rc = pFrom->rc;
  115777. }else{
  115778. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  115779. }
  115780. }
  115781. /*
  115782. ** Create and populate a new TriggerPrg object with a sub-program
  115783. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  115784. */
  115785. static TriggerPrg *codeRowTrigger(
  115786. Parse *pParse, /* Current parse context */
  115787. Trigger *pTrigger, /* Trigger to code */
  115788. Table *pTab, /* The table pTrigger is attached to */
  115789. int orconf /* ON CONFLICT policy to code trigger program with */
  115790. ){
  115791. Parse *pTop = sqlite3ParseToplevel(pParse);
  115792. sqlite3 *db = pParse->db; /* Database handle */
  115793. TriggerPrg *pPrg; /* Value to return */
  115794. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  115795. Vdbe *v; /* Temporary VM */
  115796. NameContext sNC; /* Name context for sub-vdbe */
  115797. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  115798. Parse *pSubParse; /* Parse context for sub-vdbe */
  115799. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  115800. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  115801. assert( pTop->pVdbe );
  115802. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  115803. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  115804. ** list of the top-level Parse object sooner rather than later. */
  115805. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  115806. if( !pPrg ) return 0;
  115807. pPrg->pNext = pTop->pTriggerPrg;
  115808. pTop->pTriggerPrg = pPrg;
  115809. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  115810. if( !pProgram ) return 0;
  115811. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  115812. pPrg->pTrigger = pTrigger;
  115813. pPrg->orconf = orconf;
  115814. pPrg->aColmask[0] = 0xffffffff;
  115815. pPrg->aColmask[1] = 0xffffffff;
  115816. /* Allocate and populate a new Parse context to use for coding the
  115817. ** trigger sub-program. */
  115818. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  115819. if( !pSubParse ) return 0;
  115820. memset(&sNC, 0, sizeof(sNC));
  115821. sNC.pParse = pSubParse;
  115822. pSubParse->db = db;
  115823. pSubParse->pTriggerTab = pTab;
  115824. pSubParse->pToplevel = pTop;
  115825. pSubParse->zAuthContext = pTrigger->zName;
  115826. pSubParse->eTriggerOp = pTrigger->op;
  115827. pSubParse->nQueryLoop = pParse->nQueryLoop;
  115828. v = sqlite3GetVdbe(pSubParse);
  115829. if( v ){
  115830. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  115831. pTrigger->zName, onErrorText(orconf),
  115832. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  115833. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  115834. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  115835. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  115836. pTab->zName
  115837. ));
  115838. #ifndef SQLITE_OMIT_TRACE
  115839. sqlite3VdbeChangeP4(v, -1,
  115840. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  115841. );
  115842. #endif
  115843. /* If one was specified, code the WHEN clause. If it evaluates to false
  115844. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  115845. ** OP_Halt inserted at the end of the program. */
  115846. if( pTrigger->pWhen ){
  115847. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  115848. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  115849. && db->mallocFailed==0
  115850. ){
  115851. iEndTrigger = sqlite3VdbeMakeLabel(v);
  115852. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  115853. }
  115854. sqlite3ExprDelete(db, pWhen);
  115855. }
  115856. /* Code the trigger program into the sub-vdbe. */
  115857. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  115858. /* Insert an OP_Halt at the end of the sub-program. */
  115859. if( iEndTrigger ){
  115860. sqlite3VdbeResolveLabel(v, iEndTrigger);
  115861. }
  115862. sqlite3VdbeAddOp0(v, OP_Halt);
  115863. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  115864. transferParseError(pParse, pSubParse);
  115865. if( db->mallocFailed==0 ){
  115866. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  115867. }
  115868. pProgram->nMem = pSubParse->nMem;
  115869. pProgram->nCsr = pSubParse->nTab;
  115870. pProgram->token = (void *)pTrigger;
  115871. pPrg->aColmask[0] = pSubParse->oldmask;
  115872. pPrg->aColmask[1] = pSubParse->newmask;
  115873. sqlite3VdbeDelete(v);
  115874. }
  115875. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  115876. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  115877. sqlite3ParserReset(pSubParse);
  115878. sqlite3StackFree(db, pSubParse);
  115879. return pPrg;
  115880. }
  115881. /*
  115882. ** Return a pointer to a TriggerPrg object containing the sub-program for
  115883. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  115884. ** TriggerPrg object exists, a new object is allocated and populated before
  115885. ** being returned.
  115886. */
  115887. static TriggerPrg *getRowTrigger(
  115888. Parse *pParse, /* Current parse context */
  115889. Trigger *pTrigger, /* Trigger to code */
  115890. Table *pTab, /* The table trigger pTrigger is attached to */
  115891. int orconf /* ON CONFLICT algorithm. */
  115892. ){
  115893. Parse *pRoot = sqlite3ParseToplevel(pParse);
  115894. TriggerPrg *pPrg;
  115895. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  115896. /* It may be that this trigger has already been coded (or is in the
  115897. ** process of being coded). If this is the case, then an entry with
  115898. ** a matching TriggerPrg.pTrigger field will be present somewhere
  115899. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  115900. for(pPrg=pRoot->pTriggerPrg;
  115901. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  115902. pPrg=pPrg->pNext
  115903. );
  115904. /* If an existing TriggerPrg could not be located, create a new one. */
  115905. if( !pPrg ){
  115906. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  115907. }
  115908. return pPrg;
  115909. }
  115910. /*
  115911. ** Generate code for the trigger program associated with trigger p on
  115912. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  115913. ** function are the same as those described in the header function for
  115914. ** sqlite3CodeRowTrigger()
  115915. */
  115916. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  115917. Parse *pParse, /* Parse context */
  115918. Trigger *p, /* Trigger to code */
  115919. Table *pTab, /* The table to code triggers from */
  115920. int reg, /* Reg array containing OLD.* and NEW.* values */
  115921. int orconf, /* ON CONFLICT policy */
  115922. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  115923. ){
  115924. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  115925. TriggerPrg *pPrg;
  115926. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  115927. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  115928. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  115929. ** is a pointer to the sub-vdbe containing the trigger program. */
  115930. if( pPrg ){
  115931. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  115932. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  115933. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  115934. VdbeComment(
  115935. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  115936. /* Set the P5 operand of the OP_Program instruction to non-zero if
  115937. ** recursive invocation of this trigger program is disallowed. Recursive
  115938. ** invocation is disallowed if (a) the sub-program is really a trigger,
  115939. ** not a foreign key action, and (b) the flag to enable recursive triggers
  115940. ** is clear. */
  115941. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  115942. }
  115943. }
  115944. /*
  115945. ** This is called to code the required FOR EACH ROW triggers for an operation
  115946. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  115947. ** is given by the op parameter. The tr_tm parameter determines whether the
  115948. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  115949. ** parameter pChanges is passed the list of columns being modified.
  115950. **
  115951. ** If there are no triggers that fire at the specified time for the specified
  115952. ** operation on pTab, this function is a no-op.
  115953. **
  115954. ** The reg argument is the address of the first in an array of registers
  115955. ** that contain the values substituted for the new.* and old.* references
  115956. ** in the trigger program. If N is the number of columns in table pTab
  115957. ** (a copy of pTab->nCol), then registers are populated as follows:
  115958. **
  115959. ** Register Contains
  115960. ** ------------------------------------------------------
  115961. ** reg+0 OLD.rowid
  115962. ** reg+1 OLD.* value of left-most column of pTab
  115963. ** ... ...
  115964. ** reg+N OLD.* value of right-most column of pTab
  115965. ** reg+N+1 NEW.rowid
  115966. ** reg+N+2 OLD.* value of left-most column of pTab
  115967. ** ... ...
  115968. ** reg+N+N+1 NEW.* value of right-most column of pTab
  115969. **
  115970. ** For ON DELETE triggers, the registers containing the NEW.* values will
  115971. ** never be accessed by the trigger program, so they are not allocated or
  115972. ** populated by the caller (there is no data to populate them with anyway).
  115973. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  115974. ** are never accessed, and so are not allocated by the caller. So, for an
  115975. ** ON INSERT trigger, the value passed to this function as parameter reg
  115976. ** is not a readable register, although registers (reg+N) through
  115977. ** (reg+N+N+1) are.
  115978. **
  115979. ** Parameter orconf is the default conflict resolution algorithm for the
  115980. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  115981. ** is the instruction that control should jump to if a trigger program
  115982. ** raises an IGNORE exception.
  115983. */
  115984. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  115985. Parse *pParse, /* Parse context */
  115986. Trigger *pTrigger, /* List of triggers on table pTab */
  115987. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  115988. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  115989. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  115990. Table *pTab, /* The table to code triggers from */
  115991. int reg, /* The first in an array of registers (see above) */
  115992. int orconf, /* ON CONFLICT policy */
  115993. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  115994. ){
  115995. Trigger *p; /* Used to iterate through pTrigger list */
  115996. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  115997. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  115998. assert( (op==TK_UPDATE)==(pChanges!=0) );
  115999. for(p=pTrigger; p; p=p->pNext){
  116000. /* Sanity checking: The schema for the trigger and for the table are
  116001. ** always defined. The trigger must be in the same schema as the table
  116002. ** or else it must be a TEMP trigger. */
  116003. assert( p->pSchema!=0 );
  116004. assert( p->pTabSchema!=0 );
  116005. assert( p->pSchema==p->pTabSchema
  116006. || p->pSchema==pParse->db->aDb[1].pSchema );
  116007. /* Determine whether we should code this trigger */
  116008. if( p->op==op
  116009. && p->tr_tm==tr_tm
  116010. && checkColumnOverlap(p->pColumns, pChanges)
  116011. ){
  116012. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  116013. }
  116014. }
  116015. }
  116016. /*
  116017. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  116018. ** This function returns a 32-bit bitmask indicating which columns of the
  116019. ** old.* or new.* tables actually are used by triggers. This information
  116020. ** may be used by the caller, for example, to avoid having to load the entire
  116021. ** old.* record into memory when executing an UPDATE or DELETE command.
  116022. **
  116023. ** Bit 0 of the returned mask is set if the left-most column of the
  116024. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  116025. ** the second leftmost column value is required, and so on. If there
  116026. ** are more than 32 columns in the table, and at least one of the columns
  116027. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  116028. **
  116029. ** It is not possible to determine if the old.rowid or new.rowid column is
  116030. ** accessed by triggers. The caller must always assume that it is.
  116031. **
  116032. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  116033. ** applies to the old.* table. If 1, the new.* table.
  116034. **
  116035. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  116036. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  116037. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  116038. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  116039. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  116040. */
  116041. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  116042. Parse *pParse, /* Parse context */
  116043. Trigger *pTrigger, /* List of triggers on table pTab */
  116044. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  116045. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  116046. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  116047. Table *pTab, /* The table to code triggers from */
  116048. int orconf /* Default ON CONFLICT policy for trigger steps */
  116049. ){
  116050. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  116051. u32 mask = 0;
  116052. Trigger *p;
  116053. assert( isNew==1 || isNew==0 );
  116054. for(p=pTrigger; p; p=p->pNext){
  116055. if( p->op==op && (tr_tm&p->tr_tm)
  116056. && checkColumnOverlap(p->pColumns,pChanges)
  116057. ){
  116058. TriggerPrg *pPrg;
  116059. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  116060. if( pPrg ){
  116061. mask |= pPrg->aColmask[isNew];
  116062. }
  116063. }
  116064. }
  116065. return mask;
  116066. }
  116067. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  116068. /************** End of trigger.c *********************************************/
  116069. /************** Begin file update.c ******************************************/
  116070. /*
  116071. ** 2001 September 15
  116072. **
  116073. ** The author disclaims copyright to this source code. In place of
  116074. ** a legal notice, here is a blessing:
  116075. **
  116076. ** May you do good and not evil.
  116077. ** May you find forgiveness for yourself and forgive others.
  116078. ** May you share freely, never taking more than you give.
  116079. **
  116080. *************************************************************************
  116081. ** This file contains C code routines that are called by the parser
  116082. ** to handle UPDATE statements.
  116083. */
  116084. /* #include "sqliteInt.h" */
  116085. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116086. /* Forward declaration */
  116087. static void updateVirtualTable(
  116088. Parse *pParse, /* The parsing context */
  116089. SrcList *pSrc, /* The virtual table to be modified */
  116090. Table *pTab, /* The virtual table */
  116091. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  116092. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  116093. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  116094. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  116095. int onError /* ON CONFLICT strategy */
  116096. );
  116097. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  116098. /*
  116099. ** The most recently coded instruction was an OP_Column to retrieve the
  116100. ** i-th column of table pTab. This routine sets the P4 parameter of the
  116101. ** OP_Column to the default value, if any.
  116102. **
  116103. ** The default value of a column is specified by a DEFAULT clause in the
  116104. ** column definition. This was either supplied by the user when the table
  116105. ** was created, or added later to the table definition by an ALTER TABLE
  116106. ** command. If the latter, then the row-records in the table btree on disk
  116107. ** may not contain a value for the column and the default value, taken
  116108. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  116109. ** If the former, then all row-records are guaranteed to include a value
  116110. ** for the column and the P4 value is not required.
  116111. **
  116112. ** Column definitions created by an ALTER TABLE command may only have
  116113. ** literal default values specified: a number, null or a string. (If a more
  116114. ** complicated default expression value was provided, it is evaluated
  116115. ** when the ALTER TABLE is executed and one of the literal values written
  116116. ** into the sqlite_master table.)
  116117. **
  116118. ** Therefore, the P4 parameter is only required if the default value for
  116119. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  116120. ** function is capable of transforming these types of expressions into
  116121. ** sqlite3_value objects.
  116122. **
  116123. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  116124. ** on register iReg. This is used when an equivalent integer value is
  116125. ** stored in place of an 8-byte floating point value in order to save
  116126. ** space.
  116127. */
  116128. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  116129. assert( pTab!=0 );
  116130. if( !pTab->pSelect ){
  116131. sqlite3_value *pValue = 0;
  116132. u8 enc = ENC(sqlite3VdbeDb(v));
  116133. Column *pCol = &pTab->aCol[i];
  116134. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  116135. assert( i<pTab->nCol );
  116136. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  116137. pCol->affinity, &pValue);
  116138. if( pValue ){
  116139. sqlite3VdbeAppendP4(v, pValue, P4_MEM);
  116140. }
  116141. }
  116142. #ifndef SQLITE_OMIT_FLOATING_POINT
  116143. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  116144. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  116145. }
  116146. #endif
  116147. }
  116148. /*
  116149. ** Process an UPDATE statement.
  116150. **
  116151. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  116152. ** \_______/ \________/ \______/ \________________/
  116153. * onError pTabList pChanges pWhere
  116154. */
  116155. SQLITE_PRIVATE void sqlite3Update(
  116156. Parse *pParse, /* The parser context */
  116157. SrcList *pTabList, /* The table in which we should change things */
  116158. ExprList *pChanges, /* Things to be changed */
  116159. Expr *pWhere, /* The WHERE clause. May be null */
  116160. int onError /* How to handle constraint errors */
  116161. ){
  116162. int i, j; /* Loop counters */
  116163. Table *pTab; /* The table to be updated */
  116164. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  116165. WhereInfo *pWInfo; /* Information about the WHERE clause */
  116166. Vdbe *v; /* The virtual database engine */
  116167. Index *pIdx; /* For looping over indices */
  116168. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  116169. int nIdx; /* Number of indices that need updating */
  116170. int iBaseCur; /* Base cursor number */
  116171. int iDataCur; /* Cursor for the canonical data btree */
  116172. int iIdxCur; /* Cursor for the first index */
  116173. sqlite3 *db; /* The database structure */
  116174. int *aRegIdx = 0; /* First register in array assigned to each index */
  116175. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  116176. ** an expression for the i-th column of the table.
  116177. ** aXRef[i]==-1 if the i-th column is not changed. */
  116178. u8 *aToOpen; /* 1 for tables and indices to be opened */
  116179. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  116180. u8 chngRowid; /* Rowid changed in a normal table */
  116181. u8 chngKey; /* Either chngPk or chngRowid */
  116182. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  116183. AuthContext sContext; /* The authorization context */
  116184. NameContext sNC; /* The name-context to resolve expressions in */
  116185. int iDb; /* Database containing the table being updated */
  116186. int eOnePass; /* ONEPASS_XXX value from where.c */
  116187. int hasFK; /* True if foreign key processing is required */
  116188. int labelBreak; /* Jump here to break out of UPDATE loop */
  116189. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  116190. int flags; /* Flags for sqlite3WhereBegin() */
  116191. #ifndef SQLITE_OMIT_TRIGGER
  116192. int isView; /* True when updating a view (INSTEAD OF trigger) */
  116193. Trigger *pTrigger; /* List of triggers on pTab, if required */
  116194. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  116195. #endif
  116196. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  116197. int iEph = 0; /* Ephemeral table holding all primary key values */
  116198. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  116199. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  116200. int addrOpen = 0; /* Address of OP_OpenEphemeral */
  116201. int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
  116202. i16 nPk = 0; /* Number of components of the PRIMARY KEY */
  116203. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  116204. /* Register Allocations */
  116205. int regRowCount = 0; /* A count of rows changed */
  116206. int regOldRowid = 0; /* The old rowid */
  116207. int regNewRowid = 0; /* The new rowid */
  116208. int regNew = 0; /* Content of the NEW.* table in triggers */
  116209. int regOld = 0; /* Content of OLD.* table in triggers */
  116210. int regRowSet = 0; /* Rowset of rows to be updated */
  116211. int regKey = 0; /* composite PRIMARY KEY value */
  116212. memset(&sContext, 0, sizeof(sContext));
  116213. db = pParse->db;
  116214. if( pParse->nErr || db->mallocFailed ){
  116215. goto update_cleanup;
  116216. }
  116217. assert( pTabList->nSrc==1 );
  116218. /* Locate the table which we want to update.
  116219. */
  116220. pTab = sqlite3SrcListLookup(pParse, pTabList);
  116221. if( pTab==0 ) goto update_cleanup;
  116222. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  116223. /* Figure out if we have any triggers and if the table being
  116224. ** updated is a view.
  116225. */
  116226. #ifndef SQLITE_OMIT_TRIGGER
  116227. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  116228. isView = pTab->pSelect!=0;
  116229. assert( pTrigger || tmask==0 );
  116230. #else
  116231. # define pTrigger 0
  116232. # define isView 0
  116233. # define tmask 0
  116234. #endif
  116235. #ifdef SQLITE_OMIT_VIEW
  116236. # undef isView
  116237. # define isView 0
  116238. #endif
  116239. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  116240. goto update_cleanup;
  116241. }
  116242. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  116243. goto update_cleanup;
  116244. }
  116245. /* Allocate a cursors for the main database table and for all indices.
  116246. ** The index cursors might not be used, but if they are used they
  116247. ** need to occur right after the database cursor. So go ahead and
  116248. ** allocate enough space, just in case.
  116249. */
  116250. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  116251. iIdxCur = iDataCur+1;
  116252. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  116253. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  116254. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  116255. iDataCur = pParse->nTab;
  116256. pTabList->a[0].iCursor = iDataCur;
  116257. }
  116258. pParse->nTab++;
  116259. }
  116260. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  116261. ** Initialize aXRef[] and aToOpen[] to their default values.
  116262. */
  116263. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  116264. if( aXRef==0 ) goto update_cleanup;
  116265. aRegIdx = aXRef+pTab->nCol;
  116266. aToOpen = (u8*)(aRegIdx+nIdx);
  116267. memset(aToOpen, 1, nIdx+1);
  116268. aToOpen[nIdx+1] = 0;
  116269. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  116270. /* Initialize the name-context */
  116271. memset(&sNC, 0, sizeof(sNC));
  116272. sNC.pParse = pParse;
  116273. sNC.pSrcList = pTabList;
  116274. /* Resolve the column names in all the expressions of the
  116275. ** of the UPDATE statement. Also find the column index
  116276. ** for each column to be updated in the pChanges array. For each
  116277. ** column to be updated, make sure we have authorization to change
  116278. ** that column.
  116279. */
  116280. chngRowid = chngPk = 0;
  116281. for(i=0; i<pChanges->nExpr; i++){
  116282. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  116283. goto update_cleanup;
  116284. }
  116285. for(j=0; j<pTab->nCol; j++){
  116286. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  116287. if( j==pTab->iPKey ){
  116288. chngRowid = 1;
  116289. pRowidExpr = pChanges->a[i].pExpr;
  116290. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  116291. chngPk = 1;
  116292. }
  116293. aXRef[j] = i;
  116294. break;
  116295. }
  116296. }
  116297. if( j>=pTab->nCol ){
  116298. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  116299. j = -1;
  116300. chngRowid = 1;
  116301. pRowidExpr = pChanges->a[i].pExpr;
  116302. }else{
  116303. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  116304. pParse->checkSchema = 1;
  116305. goto update_cleanup;
  116306. }
  116307. }
  116308. #ifndef SQLITE_OMIT_AUTHORIZATION
  116309. {
  116310. int rc;
  116311. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  116312. j<0 ? "ROWID" : pTab->aCol[j].zName,
  116313. db->aDb[iDb].zDbSName);
  116314. if( rc==SQLITE_DENY ){
  116315. goto update_cleanup;
  116316. }else if( rc==SQLITE_IGNORE ){
  116317. aXRef[j] = -1;
  116318. }
  116319. }
  116320. #endif
  116321. }
  116322. assert( (chngRowid & chngPk)==0 );
  116323. assert( chngRowid==0 || chngRowid==1 );
  116324. assert( chngPk==0 || chngPk==1 );
  116325. chngKey = chngRowid + chngPk;
  116326. /* The SET expressions are not actually used inside the WHERE loop.
  116327. ** So reset the colUsed mask. Unless this is a virtual table. In that
  116328. ** case, set all bits of the colUsed mask (to ensure that the virtual
  116329. ** table implementation makes all columns available).
  116330. */
  116331. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  116332. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  116333. /* There is one entry in the aRegIdx[] array for each index on the table
  116334. ** being updated. Fill in aRegIdx[] with a register number that will hold
  116335. ** the key for accessing each index.
  116336. **
  116337. ** FIXME: Be smarter about omitting indexes that use expressions.
  116338. */
  116339. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  116340. int reg;
  116341. if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
  116342. reg = ++pParse->nMem;
  116343. pParse->nMem += pIdx->nColumn;
  116344. }else{
  116345. reg = 0;
  116346. for(i=0; i<pIdx->nKeyCol; i++){
  116347. i16 iIdxCol = pIdx->aiColumn[i];
  116348. if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
  116349. reg = ++pParse->nMem;
  116350. pParse->nMem += pIdx->nColumn;
  116351. if( (onError==OE_Replace)
  116352. || (onError==OE_Default && pIdx->onError==OE_Replace)
  116353. ){
  116354. bReplace = 1;
  116355. }
  116356. break;
  116357. }
  116358. }
  116359. }
  116360. if( reg==0 ) aToOpen[j+1] = 0;
  116361. aRegIdx[j] = reg;
  116362. }
  116363. if( bReplace ){
  116364. /* If REPLACE conflict resolution might be invoked, open cursors on all
  116365. ** indexes in case they are needed to delete records. */
  116366. memset(aToOpen, 1, nIdx+1);
  116367. }
  116368. /* Begin generating code. */
  116369. v = sqlite3GetVdbe(pParse);
  116370. if( v==0 ) goto update_cleanup;
  116371. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  116372. sqlite3BeginWriteOperation(pParse, 1, iDb);
  116373. /* Allocate required registers. */
  116374. if( !IsVirtual(pTab) ){
  116375. regRowSet = ++pParse->nMem;
  116376. regOldRowid = regNewRowid = ++pParse->nMem;
  116377. if( chngPk || pTrigger || hasFK ){
  116378. regOld = pParse->nMem + 1;
  116379. pParse->nMem += pTab->nCol;
  116380. }
  116381. if( chngKey || pTrigger || hasFK ){
  116382. regNewRowid = ++pParse->nMem;
  116383. }
  116384. regNew = pParse->nMem + 1;
  116385. pParse->nMem += pTab->nCol;
  116386. }
  116387. /* Start the view context. */
  116388. if( isView ){
  116389. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  116390. }
  116391. /* If we are trying to update a view, realize that view into
  116392. ** an ephemeral table.
  116393. */
  116394. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  116395. if( isView ){
  116396. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  116397. }
  116398. #endif
  116399. /* Resolve the column names in all the expressions in the
  116400. ** WHERE clause.
  116401. */
  116402. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  116403. goto update_cleanup;
  116404. }
  116405. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116406. /* Virtual tables must be handled separately */
  116407. if( IsVirtual(pTab) ){
  116408. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  116409. pWhere, onError);
  116410. goto update_cleanup;
  116411. }
  116412. #endif
  116413. /* Initialize the count of updated rows */
  116414. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  116415. regRowCount = ++pParse->nMem;
  116416. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  116417. }
  116418. if( HasRowid(pTab) ){
  116419. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  116420. }else{
  116421. assert( pPk!=0 );
  116422. nPk = pPk->nKeyCol;
  116423. iPk = pParse->nMem+1;
  116424. pParse->nMem += nPk;
  116425. regKey = ++pParse->nMem;
  116426. iEph = pParse->nTab++;
  116427. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  116428. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  116429. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  116430. }
  116431. /* Begin the database scan.
  116432. **
  116433. ** Do not consider a single-pass strategy for a multi-row update if
  116434. ** there are any triggers or foreign keys to process, or rows may
  116435. ** be deleted as a result of REPLACE conflict handling. Any of these
  116436. ** things might disturb a cursor being used to scan through the table
  116437. ** or index, causing a single-pass approach to malfunction. */
  116438. flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
  116439. if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
  116440. flags |= WHERE_ONEPASS_MULTIROW;
  116441. }
  116442. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
  116443. if( pWInfo==0 ) goto update_cleanup;
  116444. /* A one-pass strategy that might update more than one row may not
  116445. ** be used if any column of the index used for the scan is being
  116446. ** updated. Otherwise, if there is an index on "b", statements like
  116447. ** the following could create an infinite loop:
  116448. **
  116449. ** UPDATE t1 SET b=b+1 WHERE b>?
  116450. **
  116451. ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
  116452. ** strategy that uses an index for which one or more columns are being
  116453. ** updated. */
  116454. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  116455. if( eOnePass==ONEPASS_MULTI ){
  116456. int iCur = aiCurOnePass[1];
  116457. if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
  116458. eOnePass = ONEPASS_OFF;
  116459. }
  116460. assert( iCur!=iDataCur || !HasRowid(pTab) );
  116461. }
  116462. if( HasRowid(pTab) ){
  116463. /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
  116464. ** mode, write the rowid into the FIFO. In either of the one-pass modes,
  116465. ** leave it in register regOldRowid. */
  116466. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  116467. if( eOnePass==ONEPASS_OFF ){
  116468. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  116469. }
  116470. }else{
  116471. /* Read the PK of the current row into an array of registers. In
  116472. ** ONEPASS_OFF mode, serialize the array into a record and store it in
  116473. ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
  116474. ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
  116475. ** is not required) and leave the PK fields in the array of registers. */
  116476. for(i=0; i<nPk; i++){
  116477. assert( pPk->aiColumn[i]>=0 );
  116478. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
  116479. }
  116480. if( eOnePass ){
  116481. sqlite3VdbeChangeToNoop(v, addrOpen);
  116482. nKey = nPk;
  116483. regKey = iPk;
  116484. }else{
  116485. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  116486. sqlite3IndexAffinityStr(db, pPk), nPk);
  116487. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
  116488. }
  116489. }
  116490. if( eOnePass!=ONEPASS_MULTI ){
  116491. sqlite3WhereEnd(pWInfo);
  116492. }
  116493. labelBreak = sqlite3VdbeMakeLabel(v);
  116494. if( !isView ){
  116495. int addrOnce = 0;
  116496. /* Open every index that needs updating. */
  116497. if( eOnePass!=ONEPASS_OFF ){
  116498. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  116499. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  116500. }
  116501. if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
  116502. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  116503. }
  116504. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
  116505. 0, 0);
  116506. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  116507. }
  116508. /* Top of the update loop */
  116509. if( eOnePass!=ONEPASS_OFF ){
  116510. if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
  116511. assert( pPk );
  116512. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  116513. VdbeCoverageNeverTaken(v);
  116514. }
  116515. if( eOnePass==ONEPASS_SINGLE ){
  116516. labelContinue = labelBreak;
  116517. }else{
  116518. labelContinue = sqlite3VdbeMakeLabel(v);
  116519. }
  116520. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  116521. VdbeCoverageIf(v, pPk==0);
  116522. VdbeCoverageIf(v, pPk!=0);
  116523. }else if( pPk ){
  116524. labelContinue = sqlite3VdbeMakeLabel(v);
  116525. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  116526. addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
  116527. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  116528. VdbeCoverage(v);
  116529. }else{
  116530. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  116531. regOldRowid);
  116532. VdbeCoverage(v);
  116533. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  116534. VdbeCoverage(v);
  116535. }
  116536. /* If the record number will change, set register regNewRowid to
  116537. ** contain the new value. If the record number is not being modified,
  116538. ** then regNewRowid is the same register as regOldRowid, which is
  116539. ** already populated. */
  116540. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  116541. if( chngRowid ){
  116542. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  116543. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  116544. }
  116545. /* Compute the old pre-UPDATE content of the row being changed, if that
  116546. ** information is needed */
  116547. if( chngPk || hasFK || pTrigger ){
  116548. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  116549. oldmask |= sqlite3TriggerColmask(pParse,
  116550. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  116551. );
  116552. for(i=0; i<pTab->nCol; i++){
  116553. if( oldmask==0xffffffff
  116554. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  116555. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  116556. ){
  116557. testcase( oldmask!=0xffffffff && i==31 );
  116558. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  116559. }else{
  116560. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  116561. }
  116562. }
  116563. if( chngRowid==0 && pPk==0 ){
  116564. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  116565. }
  116566. }
  116567. /* Populate the array of registers beginning at regNew with the new
  116568. ** row data. This array is used to check constants, create the new
  116569. ** table and index records, and as the values for any new.* references
  116570. ** made by triggers.
  116571. **
  116572. ** If there are one or more BEFORE triggers, then do not populate the
  116573. ** registers associated with columns that are (a) not modified by
  116574. ** this UPDATE statement and (b) not accessed by new.* references. The
  116575. ** values for registers not modified by the UPDATE must be reloaded from
  116576. ** the database after the BEFORE triggers are fired anyway (as the trigger
  116577. ** may have modified them). So not loading those that are not going to
  116578. ** be used eliminates some redundant opcodes.
  116579. */
  116580. newmask = sqlite3TriggerColmask(
  116581. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  116582. );
  116583. for(i=0; i<pTab->nCol; i++){
  116584. if( i==pTab->iPKey ){
  116585. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  116586. }else{
  116587. j = aXRef[i];
  116588. if( j>=0 ){
  116589. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  116590. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  116591. /* This branch loads the value of a column that will not be changed
  116592. ** into a register. This is done if there are no BEFORE triggers, or
  116593. ** if there are one or more BEFORE triggers that use this value via
  116594. ** a new.* reference in a trigger program.
  116595. */
  116596. testcase( i==31 );
  116597. testcase( i==32 );
  116598. sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
  116599. }else{
  116600. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  116601. }
  116602. }
  116603. }
  116604. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  116605. ** verified. One could argue that this is wrong.
  116606. */
  116607. if( tmask&TRIGGER_BEFORE ){
  116608. sqlite3TableAffinity(v, pTab, regNew);
  116609. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  116610. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  116611. /* The row-trigger may have deleted the row being updated. In this
  116612. ** case, jump to the next row. No updates or AFTER triggers are
  116613. ** required. This behavior - what happens when the row being updated
  116614. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  116615. ** documentation.
  116616. */
  116617. if( pPk ){
  116618. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  116619. VdbeCoverage(v);
  116620. }else{
  116621. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  116622. VdbeCoverage(v);
  116623. }
  116624. /* If it did not delete it, the row-trigger may still have modified
  116625. ** some of the columns of the row being updated. Load the values for
  116626. ** all columns not modified by the update statement into their
  116627. ** registers in case this has happened.
  116628. */
  116629. for(i=0; i<pTab->nCol; i++){
  116630. if( aXRef[i]<0 && i!=pTab->iPKey ){
  116631. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  116632. }
  116633. }
  116634. }
  116635. if( !isView ){
  116636. int addr1 = 0; /* Address of jump instruction */
  116637. /* Do constraint checks. */
  116638. assert( regOldRowid>0 );
  116639. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  116640. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  116641. aXRef);
  116642. /* Do FK constraint checks. */
  116643. if( hasFK ){
  116644. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  116645. }
  116646. /* Delete the index entries associated with the current record. */
  116647. if( bReplace || chngKey ){
  116648. if( pPk ){
  116649. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  116650. }else{
  116651. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  116652. }
  116653. VdbeCoverageNeverTaken(v);
  116654. }
  116655. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  116656. /* If changing the rowid value, or if there are foreign key constraints
  116657. ** to process, delete the old record. Otherwise, add a noop OP_Delete
  116658. ** to invoke the pre-update hook.
  116659. **
  116660. ** That (regNew==regnewRowid+1) is true is also important for the
  116661. ** pre-update hook. If the caller invokes preupdate_new(), the returned
  116662. ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
  116663. ** is the column index supplied by the user.
  116664. */
  116665. assert( regNew==regNewRowid+1 );
  116666. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  116667. sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
  116668. OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
  116669. regNewRowid
  116670. );
  116671. if( eOnePass==ONEPASS_MULTI ){
  116672. assert( hasFK==0 && chngKey==0 );
  116673. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  116674. }
  116675. if( !pParse->nested ){
  116676. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  116677. }
  116678. #else
  116679. if( hasFK>1 || chngKey ){
  116680. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  116681. }
  116682. #endif
  116683. if( bReplace || chngKey ){
  116684. sqlite3VdbeJumpHere(v, addr1);
  116685. }
  116686. if( hasFK ){
  116687. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  116688. }
  116689. /* Insert the new index entries and the new record. */
  116690. sqlite3CompleteInsertion(
  116691. pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
  116692. OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
  116693. 0, 0
  116694. );
  116695. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  116696. ** handle rows (possibly in other tables) that refer via a foreign key
  116697. ** to the row just updated. */
  116698. if( hasFK ){
  116699. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  116700. }
  116701. }
  116702. /* Increment the row counter
  116703. */
  116704. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  116705. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  116706. }
  116707. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  116708. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  116709. /* Repeat the above with the next record to be updated, until
  116710. ** all record selected by the WHERE clause have been updated.
  116711. */
  116712. if( eOnePass==ONEPASS_SINGLE ){
  116713. /* Nothing to do at end-of-loop for a single-pass */
  116714. }else if( eOnePass==ONEPASS_MULTI ){
  116715. sqlite3VdbeResolveLabel(v, labelContinue);
  116716. sqlite3WhereEnd(pWInfo);
  116717. }else if( pPk ){
  116718. sqlite3VdbeResolveLabel(v, labelContinue);
  116719. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  116720. }else{
  116721. sqlite3VdbeGoto(v, labelContinue);
  116722. }
  116723. sqlite3VdbeResolveLabel(v, labelBreak);
  116724. /* Update the sqlite_sequence table by storing the content of the
  116725. ** maximum rowid counter values recorded while inserting into
  116726. ** autoincrement tables.
  116727. */
  116728. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  116729. sqlite3AutoincrementEnd(pParse);
  116730. }
  116731. /*
  116732. ** Return the number of rows that were changed. If this routine is
  116733. ** generating code because of a call to sqlite3NestedParse(), do not
  116734. ** invoke the callback function.
  116735. */
  116736. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  116737. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  116738. sqlite3VdbeSetNumCols(v, 1);
  116739. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  116740. }
  116741. update_cleanup:
  116742. sqlite3AuthContextPop(&sContext);
  116743. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  116744. sqlite3SrcListDelete(db, pTabList);
  116745. sqlite3ExprListDelete(db, pChanges);
  116746. sqlite3ExprDelete(db, pWhere);
  116747. return;
  116748. }
  116749. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  116750. ** they may interfere with compilation of other functions in this file
  116751. ** (or in another file, if this file becomes part of the amalgamation). */
  116752. #ifdef isView
  116753. #undef isView
  116754. #endif
  116755. #ifdef pTrigger
  116756. #undef pTrigger
  116757. #endif
  116758. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116759. /*
  116760. ** Generate code for an UPDATE of a virtual table.
  116761. **
  116762. ** There are two possible strategies - the default and the special
  116763. ** "onepass" strategy. Onepass is only used if the virtual table
  116764. ** implementation indicates that pWhere may match at most one row.
  116765. **
  116766. ** The default strategy is to create an ephemeral table that contains
  116767. ** for each row to be changed:
  116768. **
  116769. ** (A) The original rowid of that row.
  116770. ** (B) The revised rowid for the row.
  116771. ** (C) The content of every column in the row.
  116772. **
  116773. ** Then loop through the contents of this ephemeral table executing a
  116774. ** VUpdate for each row. When finished, drop the ephemeral table.
  116775. **
  116776. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  116777. ** stores the same values (A, B and C above) in a register array and
  116778. ** makes a single invocation of VUpdate.
  116779. */
  116780. static void updateVirtualTable(
  116781. Parse *pParse, /* The parsing context */
  116782. SrcList *pSrc, /* The virtual table to be modified */
  116783. Table *pTab, /* The virtual table */
  116784. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  116785. Expr *pRowid, /* Expression used to recompute the rowid */
  116786. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  116787. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  116788. int onError /* ON CONFLICT strategy */
  116789. ){
  116790. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  116791. int ephemTab; /* Table holding the result of the SELECT */
  116792. int i; /* Loop counter */
  116793. sqlite3 *db = pParse->db; /* Database connection */
  116794. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  116795. WhereInfo *pWInfo;
  116796. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  116797. int regArg; /* First register in VUpdate arg array */
  116798. int regRec; /* Register in which to assemble record */
  116799. int regRowid; /* Register for ephem table rowid */
  116800. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  116801. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  116802. int bOnePass; /* True to use onepass strategy */
  116803. int addr; /* Address of OP_OpenEphemeral */
  116804. /* Allocate nArg registers to martial the arguments to VUpdate. Then
  116805. ** create and open the ephemeral table in which the records created from
  116806. ** these arguments will be temporarily stored. */
  116807. assert( v );
  116808. ephemTab = pParse->nTab++;
  116809. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  116810. regArg = pParse->nMem + 1;
  116811. pParse->nMem += nArg;
  116812. regRec = ++pParse->nMem;
  116813. regRowid = ++pParse->nMem;
  116814. /* Start scanning the virtual table */
  116815. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  116816. if( pWInfo==0 ) return;
  116817. /* Populate the argument registers. */
  116818. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  116819. if( pRowid ){
  116820. sqlite3ExprCode(pParse, pRowid, regArg+1);
  116821. }else{
  116822. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  116823. }
  116824. for(i=0; i<pTab->nCol; i++){
  116825. if( aXRef[i]>=0 ){
  116826. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  116827. }else{
  116828. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  116829. }
  116830. }
  116831. bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  116832. if( bOnePass ){
  116833. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  116834. ** above. Also, if this is a top-level parse (not a trigger), clear the
  116835. ** multi-write flag so that the VM does not open a statement journal */
  116836. sqlite3VdbeChangeToNoop(v, addr);
  116837. if( sqlite3IsToplevel(pParse) ){
  116838. pParse->isMultiWrite = 0;
  116839. }
  116840. }else{
  116841. /* Create a record from the argument register contents and insert it into
  116842. ** the ephemeral table. */
  116843. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  116844. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  116845. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  116846. }
  116847. if( bOnePass==0 ){
  116848. /* End the virtual table scan */
  116849. sqlite3WhereEnd(pWInfo);
  116850. /* Begin scannning through the ephemeral table. */
  116851. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  116852. /* Extract arguments from the current row of the ephemeral table and
  116853. ** invoke the VUpdate method. */
  116854. for(i=0; i<nArg; i++){
  116855. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  116856. }
  116857. }
  116858. sqlite3VtabMakeWritable(pParse, pTab);
  116859. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  116860. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  116861. sqlite3MayAbort(pParse);
  116862. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  116863. ** jump to here if the scan visited zero rows. */
  116864. if( bOnePass==0 ){
  116865. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  116866. sqlite3VdbeJumpHere(v, addr);
  116867. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  116868. }else{
  116869. sqlite3WhereEnd(pWInfo);
  116870. }
  116871. }
  116872. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  116873. /************** End of update.c **********************************************/
  116874. /************** Begin file vacuum.c ******************************************/
  116875. /*
  116876. ** 2003 April 6
  116877. **
  116878. ** The author disclaims copyright to this source code. In place of
  116879. ** a legal notice, here is a blessing:
  116880. **
  116881. ** May you do good and not evil.
  116882. ** May you find forgiveness for yourself and forgive others.
  116883. ** May you share freely, never taking more than you give.
  116884. **
  116885. *************************************************************************
  116886. ** This file contains code used to implement the VACUUM command.
  116887. **
  116888. ** Most of the code in this file may be omitted by defining the
  116889. ** SQLITE_OMIT_VACUUM macro.
  116890. */
  116891. /* #include "sqliteInt.h" */
  116892. /* #include "vdbeInt.h" */
  116893. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  116894. /*
  116895. ** Execute zSql on database db.
  116896. **
  116897. ** If zSql returns rows, then each row will have exactly one
  116898. ** column. (This will only happen if zSql begins with "SELECT".)
  116899. ** Take each row of result and call execSql() again recursively.
  116900. **
  116901. ** The execSqlF() routine does the same thing, except it accepts
  116902. ** a format string as its third argument
  116903. */
  116904. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  116905. sqlite3_stmt *pStmt;
  116906. int rc;
  116907. /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
  116908. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  116909. if( rc!=SQLITE_OK ) return rc;
  116910. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  116911. const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
  116912. assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
  116913. if( zSubSql ){
  116914. assert( zSubSql[0]!='S' );
  116915. rc = execSql(db, pzErrMsg, zSubSql);
  116916. if( rc!=SQLITE_OK ) break;
  116917. }
  116918. }
  116919. assert( rc!=SQLITE_ROW );
  116920. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  116921. if( rc ){
  116922. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  116923. }
  116924. (void)sqlite3_finalize(pStmt);
  116925. return rc;
  116926. }
  116927. static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
  116928. char *z;
  116929. va_list ap;
  116930. int rc;
  116931. va_start(ap, zSql);
  116932. z = sqlite3VMPrintf(db, zSql, ap);
  116933. va_end(ap);
  116934. if( z==0 ) return SQLITE_NOMEM;
  116935. rc = execSql(db, pzErrMsg, z);
  116936. sqlite3DbFree(db, z);
  116937. return rc;
  116938. }
  116939. /*
  116940. ** The VACUUM command is used to clean up the database,
  116941. ** collapse free space, etc. It is modelled after the VACUUM command
  116942. ** in PostgreSQL. The VACUUM command works as follows:
  116943. **
  116944. ** (1) Create a new transient database file
  116945. ** (2) Copy all content from the database being vacuumed into
  116946. ** the new transient database file
  116947. ** (3) Copy content from the transient database back into the
  116948. ** original database.
  116949. **
  116950. ** The transient database requires temporary disk space approximately
  116951. ** equal to the size of the original database. The copy operation of
  116952. ** step (3) requires additional temporary disk space approximately equal
  116953. ** to the size of the original database for the rollback journal.
  116954. ** Hence, temporary disk space that is approximately 2x the size of the
  116955. ** original database is required. Every page of the database is written
  116956. ** approximately 3 times: Once for step (2) and twice for step (3).
  116957. ** Two writes per page are required in step (3) because the original
  116958. ** database content must be written into the rollback journal prior to
  116959. ** overwriting the database with the vacuumed content.
  116960. **
  116961. ** Only 1x temporary space and only 1x writes would be required if
  116962. ** the copy of step (3) were replaced by deleting the original database
  116963. ** and renaming the transient database as the original. But that will
  116964. ** not work if other processes are attached to the original database.
  116965. ** And a power loss in between deleting the original and renaming the
  116966. ** transient would cause the database file to appear to be deleted
  116967. ** following reboot.
  116968. */
  116969. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
  116970. Vdbe *v = sqlite3GetVdbe(pParse);
  116971. int iDb = 0;
  116972. if( v==0 ) return;
  116973. if( pNm ){
  116974. #ifndef SQLITE_BUG_COMPATIBLE_20160819
  116975. /* Default behavior: Report an error if the argument to VACUUM is
  116976. ** not recognized */
  116977. iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
  116978. if( iDb<0 ) return;
  116979. #else
  116980. /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
  116981. ** to VACUUM are silently ignored. This is a back-out of a bug fix that
  116982. ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
  116983. ** The buggy behavior is required for binary compatibility with some
  116984. ** legacy applications. */
  116985. iDb = sqlite3FindDb(pParse->db, pNm);
  116986. if( iDb<0 ) iDb = 0;
  116987. #endif
  116988. }
  116989. if( iDb!=1 ){
  116990. sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
  116991. sqlite3VdbeUsesBtree(v, iDb);
  116992. }
  116993. return;
  116994. }
  116995. /*
  116996. ** This routine implements the OP_Vacuum opcode of the VDBE.
  116997. */
  116998. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
  116999. int rc = SQLITE_OK; /* Return code from service routines */
  117000. Btree *pMain; /* The database being vacuumed */
  117001. Btree *pTemp; /* The temporary database we vacuum into */
  117002. int saved_flags; /* Saved value of the db->flags */
  117003. int saved_nChange; /* Saved value of db->nChange */
  117004. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  117005. u8 saved_mTrace; /* Saved trace settings */
  117006. Db *pDb = 0; /* Database to detach at end of vacuum */
  117007. int isMemDb; /* True if vacuuming a :memory: database */
  117008. int nRes; /* Bytes of reserved space at the end of each page */
  117009. int nDb; /* Number of attached databases */
  117010. const char *zDbMain; /* Schema name of database to vacuum */
  117011. if( !db->autoCommit ){
  117012. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  117013. return SQLITE_ERROR;
  117014. }
  117015. if( db->nVdbeActive>1 ){
  117016. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  117017. return SQLITE_ERROR;
  117018. }
  117019. /* Save the current value of the database flags so that it can be
  117020. ** restored before returning. Then set the writable-schema flag, and
  117021. ** disable CHECK and foreign key constraints. */
  117022. saved_flags = db->flags;
  117023. saved_nChange = db->nChange;
  117024. saved_nTotalChange = db->nTotalChange;
  117025. saved_mTrace = db->mTrace;
  117026. db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks
  117027. | SQLITE_PreferBuiltin | SQLITE_Vacuum);
  117028. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
  117029. db->mTrace = 0;
  117030. zDbMain = db->aDb[iDb].zDbSName;
  117031. pMain = db->aDb[iDb].pBt;
  117032. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  117033. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  117034. ** can be set to 'off' for this file, as it is not recovered if a crash
  117035. ** occurs anyway. The integrity of the database is maintained by a
  117036. ** (possibly synchronous) transaction opened on the main database before
  117037. ** sqlite3BtreeCopyFile() is called.
  117038. **
  117039. ** An optimisation would be to use a non-journaled pager.
  117040. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  117041. ** that actually made the VACUUM run slower. Very little journalling
  117042. ** actually occurs when doing a vacuum since the vacuum_db is initially
  117043. ** empty. Only the journal header is written. Apparently it takes more
  117044. ** time to parse and run the PRAGMA to turn journalling off than it does
  117045. ** to write the journal header file.
  117046. */
  117047. nDb = db->nDb;
  117048. rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
  117049. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117050. assert( (db->nDb-1)==nDb );
  117051. pDb = &db->aDb[nDb];
  117052. assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
  117053. pTemp = pDb->pBt;
  117054. /* The call to execSql() to attach the temp database has left the file
  117055. ** locked (as there was more than one active statement when the transaction
  117056. ** to read the schema was concluded. Unlock it here so that this doesn't
  117057. ** cause problems for the call to BtreeSetPageSize() below. */
  117058. sqlite3BtreeCommit(pTemp);
  117059. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  117060. /* A VACUUM cannot change the pagesize of an encrypted database. */
  117061. #ifdef SQLITE_HAS_CODEC
  117062. if( db->nextPagesize ){
  117063. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  117064. int nKey;
  117065. char *zKey;
  117066. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  117067. if( nKey ) db->nextPagesize = 0;
  117068. }
  117069. #endif
  117070. sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
  117071. sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
  117072. sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
  117073. /* Begin a transaction and take an exclusive lock on the main database
  117074. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  117075. ** to ensure that we do not try to change the page-size on a WAL database.
  117076. */
  117077. rc = execSql(db, pzErrMsg, "BEGIN");
  117078. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117079. rc = sqlite3BtreeBeginTrans(pMain, 2);
  117080. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117081. /* Do not attempt to change the page size for a WAL database */
  117082. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  117083. ==PAGER_JOURNALMODE_WAL ){
  117084. db->nextPagesize = 0;
  117085. }
  117086. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  117087. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  117088. || NEVER(db->mallocFailed)
  117089. ){
  117090. rc = SQLITE_NOMEM_BKPT;
  117091. goto end_of_vacuum;
  117092. }
  117093. #ifndef SQLITE_OMIT_AUTOVACUUM
  117094. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  117095. sqlite3BtreeGetAutoVacuum(pMain));
  117096. #endif
  117097. /* Query the schema of the main database. Create a mirror schema
  117098. ** in the temporary database.
  117099. */
  117100. db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
  117101. rc = execSqlF(db, pzErrMsg,
  117102. "SELECT sql FROM \"%w\".sqlite_master"
  117103. " WHERE type='table'AND name<>'sqlite_sequence'"
  117104. " AND coalesce(rootpage,1)>0",
  117105. zDbMain
  117106. );
  117107. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117108. rc = execSqlF(db, pzErrMsg,
  117109. "SELECT sql FROM \"%w\".sqlite_master"
  117110. " WHERE type='index' AND length(sql)>10",
  117111. zDbMain
  117112. );
  117113. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117114. db->init.iDb = 0;
  117115. /* Loop through the tables in the main database. For each, do
  117116. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  117117. ** the contents to the temporary database.
  117118. */
  117119. rc = execSqlF(db, pzErrMsg,
  117120. "SELECT'INSERT INTO vacuum_db.'||quote(name)"
  117121. "||' SELECT*FROM\"%w\".'||quote(name)"
  117122. "FROM vacuum_db.sqlite_master "
  117123. "WHERE type='table'AND coalesce(rootpage,1)>0",
  117124. zDbMain
  117125. );
  117126. assert( (db->flags & SQLITE_Vacuum)!=0 );
  117127. db->flags &= ~SQLITE_Vacuum;
  117128. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117129. /* Copy the triggers, views, and virtual tables from the main database
  117130. ** over to the temporary database. None of these objects has any
  117131. ** associated storage, so all we have to do is copy their entries
  117132. ** from the SQLITE_MASTER table.
  117133. */
  117134. rc = execSqlF(db, pzErrMsg,
  117135. "INSERT INTO vacuum_db.sqlite_master"
  117136. " SELECT*FROM \"%w\".sqlite_master"
  117137. " WHERE type IN('view','trigger')"
  117138. " OR(type='table'AND rootpage=0)",
  117139. zDbMain
  117140. );
  117141. if( rc ) goto end_of_vacuum;
  117142. /* At this point, there is a write transaction open on both the
  117143. ** vacuum database and the main database. Assuming no error occurs,
  117144. ** both transactions are closed by this block - the main database
  117145. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  117146. ** call to sqlite3BtreeCommit().
  117147. */
  117148. {
  117149. u32 meta;
  117150. int i;
  117151. /* This array determines which meta meta values are preserved in the
  117152. ** vacuum. Even entries are the meta value number and odd entries
  117153. ** are an increment to apply to the meta value after the vacuum.
  117154. ** The increment is used to increase the schema cookie so that other
  117155. ** connections to the same database will know to reread the schema.
  117156. */
  117157. static const unsigned char aCopy[] = {
  117158. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  117159. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  117160. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  117161. BTREE_USER_VERSION, 0, /* Preserve the user version */
  117162. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  117163. };
  117164. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  117165. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  117166. /* Copy Btree meta values */
  117167. for(i=0; i<ArraySize(aCopy); i+=2){
  117168. /* GetMeta() and UpdateMeta() cannot fail in this context because
  117169. ** we already have page 1 loaded into cache and marked dirty. */
  117170. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  117171. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  117172. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  117173. }
  117174. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  117175. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117176. rc = sqlite3BtreeCommit(pTemp);
  117177. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117178. #ifndef SQLITE_OMIT_AUTOVACUUM
  117179. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  117180. #endif
  117181. }
  117182. assert( rc==SQLITE_OK );
  117183. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  117184. end_of_vacuum:
  117185. /* Restore the original value of db->flags */
  117186. db->init.iDb = 0;
  117187. db->flags = saved_flags;
  117188. db->nChange = saved_nChange;
  117189. db->nTotalChange = saved_nTotalChange;
  117190. db->mTrace = saved_mTrace;
  117191. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  117192. /* Currently there is an SQL level transaction open on the vacuum
  117193. ** database. No locks are held on any other files (since the main file
  117194. ** was committed at the btree level). So it safe to end the transaction
  117195. ** by manually setting the autoCommit flag to true and detaching the
  117196. ** vacuum database. The vacuum_db journal file is deleted when the pager
  117197. ** is closed by the DETACH.
  117198. */
  117199. db->autoCommit = 1;
  117200. if( pDb ){
  117201. sqlite3BtreeClose(pDb->pBt);
  117202. pDb->pBt = 0;
  117203. pDb->pSchema = 0;
  117204. }
  117205. /* This both clears the schemas and reduces the size of the db->aDb[]
  117206. ** array. */
  117207. sqlite3ResetAllSchemasOfConnection(db);
  117208. return rc;
  117209. }
  117210. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  117211. /************** End of vacuum.c **********************************************/
  117212. /************** Begin file vtab.c ********************************************/
  117213. /*
  117214. ** 2006 June 10
  117215. **
  117216. ** The author disclaims copyright to this source code. In place of
  117217. ** a legal notice, here is a blessing:
  117218. **
  117219. ** May you do good and not evil.
  117220. ** May you find forgiveness for yourself and forgive others.
  117221. ** May you share freely, never taking more than you give.
  117222. **
  117223. *************************************************************************
  117224. ** This file contains code used to help implement virtual tables.
  117225. */
  117226. #ifndef SQLITE_OMIT_VIRTUALTABLE
  117227. /* #include "sqliteInt.h" */
  117228. /*
  117229. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  117230. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  117231. ** this struct allocated on the stack. It is used by the implementation of
  117232. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  117233. ** are invoked only from within xCreate and xConnect methods.
  117234. */
  117235. struct VtabCtx {
  117236. VTable *pVTable; /* The virtual table being constructed */
  117237. Table *pTab; /* The Table object to which the virtual table belongs */
  117238. VtabCtx *pPrior; /* Parent context (if any) */
  117239. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  117240. };
  117241. /*
  117242. ** Construct and install a Module object for a virtual table. When this
  117243. ** routine is called, it is guaranteed that all appropriate locks are held
  117244. ** and the module is not already part of the connection.
  117245. */
  117246. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  117247. sqlite3 *db, /* Database in which module is registered */
  117248. const char *zName, /* Name assigned to this module */
  117249. const sqlite3_module *pModule, /* The definition of the module */
  117250. void *pAux, /* Context pointer for xCreate/xConnect */
  117251. void (*xDestroy)(void *) /* Module destructor function */
  117252. ){
  117253. Module *pMod;
  117254. int nName = sqlite3Strlen30(zName);
  117255. pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
  117256. if( pMod ){
  117257. Module *pDel;
  117258. char *zCopy = (char *)(&pMod[1]);
  117259. memcpy(zCopy, zName, nName+1);
  117260. pMod->zName = zCopy;
  117261. pMod->pModule = pModule;
  117262. pMod->pAux = pAux;
  117263. pMod->xDestroy = xDestroy;
  117264. pMod->pEpoTab = 0;
  117265. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  117266. assert( pDel==0 || pDel==pMod );
  117267. if( pDel ){
  117268. sqlite3OomFault(db);
  117269. sqlite3DbFree(db, pDel);
  117270. pMod = 0;
  117271. }
  117272. }
  117273. return pMod;
  117274. }
  117275. /*
  117276. ** The actual function that does the work of creating a new module.
  117277. ** This function implements the sqlite3_create_module() and
  117278. ** sqlite3_create_module_v2() interfaces.
  117279. */
  117280. static int createModule(
  117281. sqlite3 *db, /* Database in which module is registered */
  117282. const char *zName, /* Name assigned to this module */
  117283. const sqlite3_module *pModule, /* The definition of the module */
  117284. void *pAux, /* Context pointer for xCreate/xConnect */
  117285. void (*xDestroy)(void *) /* Module destructor function */
  117286. ){
  117287. int rc = SQLITE_OK;
  117288. sqlite3_mutex_enter(db->mutex);
  117289. if( sqlite3HashFind(&db->aModule, zName) ){
  117290. rc = SQLITE_MISUSE_BKPT;
  117291. }else{
  117292. (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
  117293. }
  117294. rc = sqlite3ApiExit(db, rc);
  117295. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  117296. sqlite3_mutex_leave(db->mutex);
  117297. return rc;
  117298. }
  117299. /*
  117300. ** External API function used to create a new virtual-table module.
  117301. */
  117302. SQLITE_API int sqlite3_create_module(
  117303. sqlite3 *db, /* Database in which module is registered */
  117304. const char *zName, /* Name assigned to this module */
  117305. const sqlite3_module *pModule, /* The definition of the module */
  117306. void *pAux /* Context pointer for xCreate/xConnect */
  117307. ){
  117308. #ifdef SQLITE_ENABLE_API_ARMOR
  117309. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  117310. #endif
  117311. return createModule(db, zName, pModule, pAux, 0);
  117312. }
  117313. /*
  117314. ** External API function used to create a new virtual-table module.
  117315. */
  117316. SQLITE_API int sqlite3_create_module_v2(
  117317. sqlite3 *db, /* Database in which module is registered */
  117318. const char *zName, /* Name assigned to this module */
  117319. const sqlite3_module *pModule, /* The definition of the module */
  117320. void *pAux, /* Context pointer for xCreate/xConnect */
  117321. void (*xDestroy)(void *) /* Module destructor function */
  117322. ){
  117323. #ifdef SQLITE_ENABLE_API_ARMOR
  117324. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  117325. #endif
  117326. return createModule(db, zName, pModule, pAux, xDestroy);
  117327. }
  117328. /*
  117329. ** Lock the virtual table so that it cannot be disconnected.
  117330. ** Locks nest. Every lock should have a corresponding unlock.
  117331. ** If an unlock is omitted, resources leaks will occur.
  117332. **
  117333. ** If a disconnect is attempted while a virtual table is locked,
  117334. ** the disconnect is deferred until all locks have been removed.
  117335. */
  117336. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  117337. pVTab->nRef++;
  117338. }
  117339. /*
  117340. ** pTab is a pointer to a Table structure representing a virtual-table.
  117341. ** Return a pointer to the VTable object used by connection db to access
  117342. ** this virtual-table, if one has been created, or NULL otherwise.
  117343. */
  117344. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  117345. VTable *pVtab;
  117346. assert( IsVirtual(pTab) );
  117347. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  117348. return pVtab;
  117349. }
  117350. /*
  117351. ** Decrement the ref-count on a virtual table object. When the ref-count
  117352. ** reaches zero, call the xDisconnect() method to delete the object.
  117353. */
  117354. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  117355. sqlite3 *db = pVTab->db;
  117356. assert( db );
  117357. assert( pVTab->nRef>0 );
  117358. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  117359. pVTab->nRef--;
  117360. if( pVTab->nRef==0 ){
  117361. sqlite3_vtab *p = pVTab->pVtab;
  117362. if( p ){
  117363. p->pModule->xDisconnect(p);
  117364. }
  117365. sqlite3DbFree(db, pVTab);
  117366. }
  117367. }
  117368. /*
  117369. ** Table p is a virtual table. This function moves all elements in the
  117370. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  117371. ** database connections to be disconnected at the next opportunity.
  117372. ** Except, if argument db is not NULL, then the entry associated with
  117373. ** connection db is left in the p->pVTable list.
  117374. */
  117375. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  117376. VTable *pRet = 0;
  117377. VTable *pVTable = p->pVTable;
  117378. p->pVTable = 0;
  117379. /* Assert that the mutex (if any) associated with the BtShared database
  117380. ** that contains table p is held by the caller. See header comments
  117381. ** above function sqlite3VtabUnlockList() for an explanation of why
  117382. ** this makes it safe to access the sqlite3.pDisconnect list of any
  117383. ** database connection that may have an entry in the p->pVTable list.
  117384. */
  117385. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  117386. while( pVTable ){
  117387. sqlite3 *db2 = pVTable->db;
  117388. VTable *pNext = pVTable->pNext;
  117389. assert( db2 );
  117390. if( db2==db ){
  117391. pRet = pVTable;
  117392. p->pVTable = pRet;
  117393. pRet->pNext = 0;
  117394. }else{
  117395. pVTable->pNext = db2->pDisconnect;
  117396. db2->pDisconnect = pVTable;
  117397. }
  117398. pVTable = pNext;
  117399. }
  117400. assert( !db || pRet );
  117401. return pRet;
  117402. }
  117403. /*
  117404. ** Table *p is a virtual table. This function removes the VTable object
  117405. ** for table *p associated with database connection db from the linked
  117406. ** list in p->pVTab. It also decrements the VTable ref count. This is
  117407. ** used when closing database connection db to free all of its VTable
  117408. ** objects without disturbing the rest of the Schema object (which may
  117409. ** be being used by other shared-cache connections).
  117410. */
  117411. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  117412. VTable **ppVTab;
  117413. assert( IsVirtual(p) );
  117414. assert( sqlite3BtreeHoldsAllMutexes(db) );
  117415. assert( sqlite3_mutex_held(db->mutex) );
  117416. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  117417. if( (*ppVTab)->db==db ){
  117418. VTable *pVTab = *ppVTab;
  117419. *ppVTab = pVTab->pNext;
  117420. sqlite3VtabUnlock(pVTab);
  117421. break;
  117422. }
  117423. }
  117424. }
  117425. /*
  117426. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  117427. **
  117428. ** This function may only be called when the mutexes associated with all
  117429. ** shared b-tree databases opened using connection db are held by the
  117430. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  117431. ** sqlite3.pDisconnect list is accessed only as follows:
  117432. **
  117433. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  117434. ** associated with the database handle itself must be held.
  117435. **
  117436. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  117437. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  117438. ** associated with the database the virtual table is stored in is held
  117439. ** or, if the virtual table is stored in a non-sharable database, then
  117440. ** the database handle mutex is held.
  117441. **
  117442. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  117443. ** by multiple threads. It is thread-safe.
  117444. */
  117445. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  117446. VTable *p = db->pDisconnect;
  117447. db->pDisconnect = 0;
  117448. assert( sqlite3BtreeHoldsAllMutexes(db) );
  117449. assert( sqlite3_mutex_held(db->mutex) );
  117450. if( p ){
  117451. sqlite3ExpirePreparedStatements(db);
  117452. do {
  117453. VTable *pNext = p->pNext;
  117454. sqlite3VtabUnlock(p);
  117455. p = pNext;
  117456. }while( p );
  117457. }
  117458. }
  117459. /*
  117460. ** Clear any and all virtual-table information from the Table record.
  117461. ** This routine is called, for example, just before deleting the Table
  117462. ** record.
  117463. **
  117464. ** Since it is a virtual-table, the Table structure contains a pointer
  117465. ** to the head of a linked list of VTable structures. Each VTable
  117466. ** structure is associated with a single sqlite3* user of the schema.
  117467. ** The reference count of the VTable structure associated with database
  117468. ** connection db is decremented immediately (which may lead to the
  117469. ** structure being xDisconnected and free). Any other VTable structures
  117470. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  117471. ** database connection.
  117472. */
  117473. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  117474. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  117475. if( p->azModuleArg ){
  117476. int i;
  117477. for(i=0; i<p->nModuleArg; i++){
  117478. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  117479. }
  117480. sqlite3DbFree(db, p->azModuleArg);
  117481. }
  117482. }
  117483. /*
  117484. ** Add a new module argument to pTable->azModuleArg[].
  117485. ** The string is not copied - the pointer is stored. The
  117486. ** string will be freed automatically when the table is
  117487. ** deleted.
  117488. */
  117489. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  117490. int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  117491. char **azModuleArg;
  117492. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  117493. if( azModuleArg==0 ){
  117494. sqlite3DbFree(db, zArg);
  117495. }else{
  117496. int i = pTable->nModuleArg++;
  117497. azModuleArg[i] = zArg;
  117498. azModuleArg[i+1] = 0;
  117499. pTable->azModuleArg = azModuleArg;
  117500. }
  117501. }
  117502. /*
  117503. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  117504. ** statement. The module name has been parsed, but the optional list
  117505. ** of parameters that follow the module name are still pending.
  117506. */
  117507. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  117508. Parse *pParse, /* Parsing context */
  117509. Token *pName1, /* Name of new table, or database name */
  117510. Token *pName2, /* Name of new table or NULL */
  117511. Token *pModuleName, /* Name of the module for the virtual table */
  117512. int ifNotExists /* No error if the table already exists */
  117513. ){
  117514. int iDb; /* The database the table is being created in */
  117515. Table *pTable; /* The new virtual table */
  117516. sqlite3 *db; /* Database connection */
  117517. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  117518. pTable = pParse->pNewTable;
  117519. if( pTable==0 ) return;
  117520. assert( 0==pTable->pIndex );
  117521. db = pParse->db;
  117522. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  117523. assert( iDb>=0 );
  117524. assert( pTable->nModuleArg==0 );
  117525. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  117526. addModuleArgument(db, pTable, 0);
  117527. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  117528. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  117529. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  117530. );
  117531. pParse->sNameToken.n = (int)(
  117532. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  117533. );
  117534. #ifndef SQLITE_OMIT_AUTHORIZATION
  117535. /* Creating a virtual table invokes the authorization callback twice.
  117536. ** The first invocation, to obtain permission to INSERT a row into the
  117537. ** sqlite_master table, has already been made by sqlite3StartTable().
  117538. ** The second call, to obtain permission to create the table, is made now.
  117539. */
  117540. if( pTable->azModuleArg ){
  117541. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  117542. pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
  117543. }
  117544. #endif
  117545. }
  117546. /*
  117547. ** This routine takes the module argument that has been accumulating
  117548. ** in pParse->zArg[] and appends it to the list of arguments on the
  117549. ** virtual table currently under construction in pParse->pTable.
  117550. */
  117551. static void addArgumentToVtab(Parse *pParse){
  117552. if( pParse->sArg.z && pParse->pNewTable ){
  117553. const char *z = (const char*)pParse->sArg.z;
  117554. int n = pParse->sArg.n;
  117555. sqlite3 *db = pParse->db;
  117556. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  117557. }
  117558. }
  117559. /*
  117560. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  117561. ** has been completely parsed.
  117562. */
  117563. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  117564. Table *pTab = pParse->pNewTable; /* The table being constructed */
  117565. sqlite3 *db = pParse->db; /* The database connection */
  117566. if( pTab==0 ) return;
  117567. addArgumentToVtab(pParse);
  117568. pParse->sArg.z = 0;
  117569. if( pTab->nModuleArg<1 ) return;
  117570. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  117571. ** first time (in other words if the virtual table is actually being
  117572. ** created now instead of just being read out of sqlite_master) then
  117573. ** do additional initialization work and store the statement text
  117574. ** in the sqlite_master table.
  117575. */
  117576. if( !db->init.busy ){
  117577. char *zStmt;
  117578. char *zWhere;
  117579. int iDb;
  117580. int iReg;
  117581. Vdbe *v;
  117582. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  117583. if( pEnd ){
  117584. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  117585. }
  117586. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  117587. /* A slot for the record has already been allocated in the
  117588. ** SQLITE_MASTER table. We just need to update that slot with all
  117589. ** the information we've collected.
  117590. **
  117591. ** The VM register number pParse->regRowid holds the rowid of an
  117592. ** entry in the sqlite_master table tht was created for this vtab
  117593. ** by sqlite3StartTable().
  117594. */
  117595. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  117596. sqlite3NestedParse(pParse,
  117597. "UPDATE %Q.%s "
  117598. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  117599. "WHERE rowid=#%d",
  117600. db->aDb[iDb].zDbSName, MASTER_NAME,
  117601. pTab->zName,
  117602. pTab->zName,
  117603. zStmt,
  117604. pParse->regRowid
  117605. );
  117606. sqlite3DbFree(db, zStmt);
  117607. v = sqlite3GetVdbe(pParse);
  117608. sqlite3ChangeCookie(pParse, iDb);
  117609. sqlite3VdbeAddOp0(v, OP_Expire);
  117610. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  117611. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  117612. iReg = ++pParse->nMem;
  117613. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  117614. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  117615. }
  117616. /* If we are rereading the sqlite_master table create the in-memory
  117617. ** record of the table. The xConnect() method is not called until
  117618. ** the first time the virtual table is used in an SQL statement. This
  117619. ** allows a schema that contains virtual tables to be loaded before
  117620. ** the required virtual table implementations are registered. */
  117621. else {
  117622. Table *pOld;
  117623. Schema *pSchema = pTab->pSchema;
  117624. const char *zName = pTab->zName;
  117625. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  117626. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  117627. if( pOld ){
  117628. sqlite3OomFault(db);
  117629. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  117630. return;
  117631. }
  117632. pParse->pNewTable = 0;
  117633. }
  117634. }
  117635. /*
  117636. ** The parser calls this routine when it sees the first token
  117637. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  117638. */
  117639. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  117640. addArgumentToVtab(pParse);
  117641. pParse->sArg.z = 0;
  117642. pParse->sArg.n = 0;
  117643. }
  117644. /*
  117645. ** The parser calls this routine for each token after the first token
  117646. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  117647. */
  117648. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  117649. Token *pArg = &pParse->sArg;
  117650. if( pArg->z==0 ){
  117651. pArg->z = p->z;
  117652. pArg->n = p->n;
  117653. }else{
  117654. assert(pArg->z <= p->z);
  117655. pArg->n = (int)(&p->z[p->n] - pArg->z);
  117656. }
  117657. }
  117658. /*
  117659. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  117660. ** pointer to the function to invoke is passed as the fourth parameter
  117661. ** to this procedure.
  117662. */
  117663. static int vtabCallConstructor(
  117664. sqlite3 *db,
  117665. Table *pTab,
  117666. Module *pMod,
  117667. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  117668. char **pzErr
  117669. ){
  117670. VtabCtx sCtx;
  117671. VTable *pVTable;
  117672. int rc;
  117673. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  117674. int nArg = pTab->nModuleArg;
  117675. char *zErr = 0;
  117676. char *zModuleName;
  117677. int iDb;
  117678. VtabCtx *pCtx;
  117679. /* Check that the virtual-table is not already being initialized */
  117680. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  117681. if( pCtx->pTab==pTab ){
  117682. *pzErr = sqlite3MPrintf(db,
  117683. "vtable constructor called recursively: %s", pTab->zName
  117684. );
  117685. return SQLITE_LOCKED;
  117686. }
  117687. }
  117688. zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  117689. if( !zModuleName ){
  117690. return SQLITE_NOMEM_BKPT;
  117691. }
  117692. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  117693. if( !pVTable ){
  117694. sqlite3DbFree(db, zModuleName);
  117695. return SQLITE_NOMEM_BKPT;
  117696. }
  117697. pVTable->db = db;
  117698. pVTable->pMod = pMod;
  117699. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  117700. pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
  117701. /* Invoke the virtual table constructor */
  117702. assert( &db->pVtabCtx );
  117703. assert( xConstruct );
  117704. sCtx.pTab = pTab;
  117705. sCtx.pVTable = pVTable;
  117706. sCtx.pPrior = db->pVtabCtx;
  117707. sCtx.bDeclared = 0;
  117708. db->pVtabCtx = &sCtx;
  117709. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  117710. db->pVtabCtx = sCtx.pPrior;
  117711. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  117712. assert( sCtx.pTab==pTab );
  117713. if( SQLITE_OK!=rc ){
  117714. if( zErr==0 ){
  117715. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  117716. }else {
  117717. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  117718. sqlite3_free(zErr);
  117719. }
  117720. sqlite3DbFree(db, pVTable);
  117721. }else if( ALWAYS(pVTable->pVtab) ){
  117722. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  117723. ** the sqlite3_vtab object if successful. */
  117724. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  117725. pVTable->pVtab->pModule = pMod->pModule;
  117726. pVTable->nRef = 1;
  117727. if( sCtx.bDeclared==0 ){
  117728. const char *zFormat = "vtable constructor did not declare schema: %s";
  117729. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  117730. sqlite3VtabUnlock(pVTable);
  117731. rc = SQLITE_ERROR;
  117732. }else{
  117733. int iCol;
  117734. u8 oooHidden = 0;
  117735. /* If everything went according to plan, link the new VTable structure
  117736. ** into the linked list headed by pTab->pVTable. Then loop through the
  117737. ** columns of the table to see if any of them contain the token "hidden".
  117738. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  117739. ** the type string. */
  117740. pVTable->pNext = pTab->pVTable;
  117741. pTab->pVTable = pVTable;
  117742. for(iCol=0; iCol<pTab->nCol; iCol++){
  117743. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  117744. int nType;
  117745. int i = 0;
  117746. nType = sqlite3Strlen30(zType);
  117747. for(i=0; i<nType; i++){
  117748. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  117749. && (i==0 || zType[i-1]==' ')
  117750. && (zType[i+6]=='\0' || zType[i+6]==' ')
  117751. ){
  117752. break;
  117753. }
  117754. }
  117755. if( i<nType ){
  117756. int j;
  117757. int nDel = 6 + (zType[i+6] ? 1 : 0);
  117758. for(j=i; (j+nDel)<=nType; j++){
  117759. zType[j] = zType[j+nDel];
  117760. }
  117761. if( zType[i]=='\0' && i>0 ){
  117762. assert(zType[i-1]==' ');
  117763. zType[i-1] = '\0';
  117764. }
  117765. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  117766. oooHidden = TF_OOOHidden;
  117767. }else{
  117768. pTab->tabFlags |= oooHidden;
  117769. }
  117770. }
  117771. }
  117772. }
  117773. sqlite3DbFree(db, zModuleName);
  117774. return rc;
  117775. }
  117776. /*
  117777. ** This function is invoked by the parser to call the xConnect() method
  117778. ** of the virtual table pTab. If an error occurs, an error code is returned
  117779. ** and an error left in pParse.
  117780. **
  117781. ** This call is a no-op if table pTab is not a virtual table.
  117782. */
  117783. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  117784. sqlite3 *db = pParse->db;
  117785. const char *zMod;
  117786. Module *pMod;
  117787. int rc;
  117788. assert( pTab );
  117789. if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
  117790. return SQLITE_OK;
  117791. }
  117792. /* Locate the required virtual table module */
  117793. zMod = pTab->azModuleArg[0];
  117794. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  117795. if( !pMod ){
  117796. const char *zModule = pTab->azModuleArg[0];
  117797. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  117798. rc = SQLITE_ERROR;
  117799. }else{
  117800. char *zErr = 0;
  117801. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  117802. if( rc!=SQLITE_OK ){
  117803. sqlite3ErrorMsg(pParse, "%s", zErr);
  117804. }
  117805. sqlite3DbFree(db, zErr);
  117806. }
  117807. return rc;
  117808. }
  117809. /*
  117810. ** Grow the db->aVTrans[] array so that there is room for at least one
  117811. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  117812. */
  117813. static int growVTrans(sqlite3 *db){
  117814. const int ARRAY_INCR = 5;
  117815. /* Grow the sqlite3.aVTrans array if required */
  117816. if( (db->nVTrans%ARRAY_INCR)==0 ){
  117817. VTable **aVTrans;
  117818. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  117819. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  117820. if( !aVTrans ){
  117821. return SQLITE_NOMEM_BKPT;
  117822. }
  117823. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  117824. db->aVTrans = aVTrans;
  117825. }
  117826. return SQLITE_OK;
  117827. }
  117828. /*
  117829. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  117830. ** have already been reserved using growVTrans().
  117831. */
  117832. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  117833. /* Add pVtab to the end of sqlite3.aVTrans */
  117834. db->aVTrans[db->nVTrans++] = pVTab;
  117835. sqlite3VtabLock(pVTab);
  117836. }
  117837. /*
  117838. ** This function is invoked by the vdbe to call the xCreate method
  117839. ** of the virtual table named zTab in database iDb.
  117840. **
  117841. ** If an error occurs, *pzErr is set to point to an English language
  117842. ** description of the error and an SQLITE_XXX error code is returned.
  117843. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  117844. */
  117845. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  117846. int rc = SQLITE_OK;
  117847. Table *pTab;
  117848. Module *pMod;
  117849. const char *zMod;
  117850. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  117851. assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
  117852. /* Locate the required virtual table module */
  117853. zMod = pTab->azModuleArg[0];
  117854. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  117855. /* If the module has been registered and includes a Create method,
  117856. ** invoke it now. If the module has not been registered, return an
  117857. ** error. Otherwise, do nothing.
  117858. */
  117859. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  117860. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  117861. rc = SQLITE_ERROR;
  117862. }else{
  117863. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  117864. }
  117865. /* Justification of ALWAYS(): The xConstructor method is required to
  117866. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  117867. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  117868. rc = growVTrans(db);
  117869. if( rc==SQLITE_OK ){
  117870. addToVTrans(db, sqlite3GetVTable(db, pTab));
  117871. }
  117872. }
  117873. return rc;
  117874. }
  117875. /*
  117876. ** This function is used to set the schema of a virtual table. It is only
  117877. ** valid to call this function from within the xCreate() or xConnect() of a
  117878. ** virtual table module.
  117879. */
  117880. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  117881. VtabCtx *pCtx;
  117882. Parse *pParse;
  117883. int rc = SQLITE_OK;
  117884. Table *pTab;
  117885. char *zErr = 0;
  117886. #ifdef SQLITE_ENABLE_API_ARMOR
  117887. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  117888. return SQLITE_MISUSE_BKPT;
  117889. }
  117890. #endif
  117891. sqlite3_mutex_enter(db->mutex);
  117892. pCtx = db->pVtabCtx;
  117893. if( !pCtx || pCtx->bDeclared ){
  117894. sqlite3Error(db, SQLITE_MISUSE);
  117895. sqlite3_mutex_leave(db->mutex);
  117896. return SQLITE_MISUSE_BKPT;
  117897. }
  117898. pTab = pCtx->pTab;
  117899. assert( IsVirtual(pTab) );
  117900. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  117901. if( pParse==0 ){
  117902. rc = SQLITE_NOMEM_BKPT;
  117903. }else{
  117904. pParse->declareVtab = 1;
  117905. pParse->db = db;
  117906. pParse->nQueryLoop = 1;
  117907. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  117908. && pParse->pNewTable
  117909. && !db->mallocFailed
  117910. && !pParse->pNewTable->pSelect
  117911. && !IsVirtual(pParse->pNewTable)
  117912. ){
  117913. if( !pTab->aCol ){
  117914. Table *pNew = pParse->pNewTable;
  117915. Index *pIdx;
  117916. pTab->aCol = pNew->aCol;
  117917. pTab->nCol = pNew->nCol;
  117918. pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
  117919. pNew->nCol = 0;
  117920. pNew->aCol = 0;
  117921. assert( pTab->pIndex==0 );
  117922. if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){
  117923. rc = SQLITE_ERROR;
  117924. }
  117925. pIdx = pNew->pIndex;
  117926. if( pIdx ){
  117927. assert( pIdx->pNext==0 );
  117928. pTab->pIndex = pIdx;
  117929. pNew->pIndex = 0;
  117930. pIdx->pTable = pTab;
  117931. }
  117932. }
  117933. pCtx->bDeclared = 1;
  117934. }else{
  117935. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  117936. sqlite3DbFree(db, zErr);
  117937. rc = SQLITE_ERROR;
  117938. }
  117939. pParse->declareVtab = 0;
  117940. if( pParse->pVdbe ){
  117941. sqlite3VdbeFinalize(pParse->pVdbe);
  117942. }
  117943. sqlite3DeleteTable(db, pParse->pNewTable);
  117944. sqlite3ParserReset(pParse);
  117945. sqlite3StackFree(db, pParse);
  117946. }
  117947. assert( (rc&0xff)==rc );
  117948. rc = sqlite3ApiExit(db, rc);
  117949. sqlite3_mutex_leave(db->mutex);
  117950. return rc;
  117951. }
  117952. /*
  117953. ** This function is invoked by the vdbe to call the xDestroy method
  117954. ** of the virtual table named zTab in database iDb. This occurs
  117955. ** when a DROP TABLE is mentioned.
  117956. **
  117957. ** This call is a no-op if zTab is not a virtual table.
  117958. */
  117959. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  117960. int rc = SQLITE_OK;
  117961. Table *pTab;
  117962. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  117963. if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
  117964. VTable *p;
  117965. int (*xDestroy)(sqlite3_vtab *);
  117966. for(p=pTab->pVTable; p; p=p->pNext){
  117967. assert( p->pVtab );
  117968. if( p->pVtab->nRef>0 ){
  117969. return SQLITE_LOCKED;
  117970. }
  117971. }
  117972. p = vtabDisconnectAll(db, pTab);
  117973. xDestroy = p->pMod->pModule->xDestroy;
  117974. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  117975. rc = xDestroy(p->pVtab);
  117976. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  117977. if( rc==SQLITE_OK ){
  117978. assert( pTab->pVTable==p && p->pNext==0 );
  117979. p->pVtab = 0;
  117980. pTab->pVTable = 0;
  117981. sqlite3VtabUnlock(p);
  117982. }
  117983. }
  117984. return rc;
  117985. }
  117986. /*
  117987. ** This function invokes either the xRollback or xCommit method
  117988. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  117989. ** called is identified by the second argument, "offset", which is
  117990. ** the offset of the method to call in the sqlite3_module structure.
  117991. **
  117992. ** The array is cleared after invoking the callbacks.
  117993. */
  117994. static void callFinaliser(sqlite3 *db, int offset){
  117995. int i;
  117996. if( db->aVTrans ){
  117997. VTable **aVTrans = db->aVTrans;
  117998. db->aVTrans = 0;
  117999. for(i=0; i<db->nVTrans; i++){
  118000. VTable *pVTab = aVTrans[i];
  118001. sqlite3_vtab *p = pVTab->pVtab;
  118002. if( p ){
  118003. int (*x)(sqlite3_vtab *);
  118004. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  118005. if( x ) x(p);
  118006. }
  118007. pVTab->iSavepoint = 0;
  118008. sqlite3VtabUnlock(pVTab);
  118009. }
  118010. sqlite3DbFree(db, aVTrans);
  118011. db->nVTrans = 0;
  118012. }
  118013. }
  118014. /*
  118015. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  118016. ** array. Return the error code for the first error that occurs, or
  118017. ** SQLITE_OK if all xSync operations are successful.
  118018. **
  118019. ** If an error message is available, leave it in p->zErrMsg.
  118020. */
  118021. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  118022. int i;
  118023. int rc = SQLITE_OK;
  118024. VTable **aVTrans = db->aVTrans;
  118025. db->aVTrans = 0;
  118026. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  118027. int (*x)(sqlite3_vtab *);
  118028. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  118029. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  118030. rc = x(pVtab);
  118031. sqlite3VtabImportErrmsg(p, pVtab);
  118032. }
  118033. }
  118034. db->aVTrans = aVTrans;
  118035. return rc;
  118036. }
  118037. /*
  118038. ** Invoke the xRollback method of all virtual tables in the
  118039. ** sqlite3.aVTrans array. Then clear the array itself.
  118040. */
  118041. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  118042. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  118043. return SQLITE_OK;
  118044. }
  118045. /*
  118046. ** Invoke the xCommit method of all virtual tables in the
  118047. ** sqlite3.aVTrans array. Then clear the array itself.
  118048. */
  118049. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  118050. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  118051. return SQLITE_OK;
  118052. }
  118053. /*
  118054. ** If the virtual table pVtab supports the transaction interface
  118055. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  118056. ** not currently open, invoke the xBegin method now.
  118057. **
  118058. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  118059. ** in the sqlite3.aVTrans array.
  118060. */
  118061. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  118062. int rc = SQLITE_OK;
  118063. const sqlite3_module *pModule;
  118064. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  118065. ** than zero, then this function is being called from within a
  118066. ** virtual module xSync() callback. It is illegal to write to
  118067. ** virtual module tables in this case, so return SQLITE_LOCKED.
  118068. */
  118069. if( sqlite3VtabInSync(db) ){
  118070. return SQLITE_LOCKED;
  118071. }
  118072. if( !pVTab ){
  118073. return SQLITE_OK;
  118074. }
  118075. pModule = pVTab->pVtab->pModule;
  118076. if( pModule->xBegin ){
  118077. int i;
  118078. /* If pVtab is already in the aVTrans array, return early */
  118079. for(i=0; i<db->nVTrans; i++){
  118080. if( db->aVTrans[i]==pVTab ){
  118081. return SQLITE_OK;
  118082. }
  118083. }
  118084. /* Invoke the xBegin method. If successful, add the vtab to the
  118085. ** sqlite3.aVTrans[] array. */
  118086. rc = growVTrans(db);
  118087. if( rc==SQLITE_OK ){
  118088. rc = pModule->xBegin(pVTab->pVtab);
  118089. if( rc==SQLITE_OK ){
  118090. int iSvpt = db->nStatement + db->nSavepoint;
  118091. addToVTrans(db, pVTab);
  118092. if( iSvpt && pModule->xSavepoint ){
  118093. pVTab->iSavepoint = iSvpt;
  118094. rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
  118095. }
  118096. }
  118097. }
  118098. }
  118099. return rc;
  118100. }
  118101. /*
  118102. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  118103. ** virtual tables that currently have an open transaction. Pass iSavepoint
  118104. ** as the second argument to the virtual table method invoked.
  118105. **
  118106. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  118107. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  118108. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  118109. ** an open transaction is invoked.
  118110. **
  118111. ** If any virtual table method returns an error code other than SQLITE_OK,
  118112. ** processing is abandoned and the error returned to the caller of this
  118113. ** function immediately. If all calls to virtual table methods are successful,
  118114. ** SQLITE_OK is returned.
  118115. */
  118116. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  118117. int rc = SQLITE_OK;
  118118. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  118119. assert( iSavepoint>=-1 );
  118120. if( db->aVTrans ){
  118121. int i;
  118122. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  118123. VTable *pVTab = db->aVTrans[i];
  118124. const sqlite3_module *pMod = pVTab->pMod->pModule;
  118125. if( pVTab->pVtab && pMod->iVersion>=2 ){
  118126. int (*xMethod)(sqlite3_vtab *, int);
  118127. switch( op ){
  118128. case SAVEPOINT_BEGIN:
  118129. xMethod = pMod->xSavepoint;
  118130. pVTab->iSavepoint = iSavepoint+1;
  118131. break;
  118132. case SAVEPOINT_ROLLBACK:
  118133. xMethod = pMod->xRollbackTo;
  118134. break;
  118135. default:
  118136. xMethod = pMod->xRelease;
  118137. break;
  118138. }
  118139. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  118140. rc = xMethod(pVTab->pVtab, iSavepoint);
  118141. }
  118142. }
  118143. }
  118144. }
  118145. return rc;
  118146. }
  118147. /*
  118148. ** The first parameter (pDef) is a function implementation. The
  118149. ** second parameter (pExpr) is the first argument to this function.
  118150. ** If pExpr is a column in a virtual table, then let the virtual
  118151. ** table implementation have an opportunity to overload the function.
  118152. **
  118153. ** This routine is used to allow virtual table implementations to
  118154. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  118155. **
  118156. ** Return either the pDef argument (indicating no change) or a
  118157. ** new FuncDef structure that is marked as ephemeral using the
  118158. ** SQLITE_FUNC_EPHEM flag.
  118159. */
  118160. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  118161. sqlite3 *db, /* Database connection for reporting malloc problems */
  118162. FuncDef *pDef, /* Function to possibly overload */
  118163. int nArg, /* Number of arguments to the function */
  118164. Expr *pExpr /* First argument to the function */
  118165. ){
  118166. Table *pTab;
  118167. sqlite3_vtab *pVtab;
  118168. sqlite3_module *pMod;
  118169. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  118170. void *pArg = 0;
  118171. FuncDef *pNew;
  118172. int rc = 0;
  118173. char *zLowerName;
  118174. unsigned char *z;
  118175. /* Check to see the left operand is a column in a virtual table */
  118176. if( NEVER(pExpr==0) ) return pDef;
  118177. if( pExpr->op!=TK_COLUMN ) return pDef;
  118178. pTab = pExpr->pTab;
  118179. if( pTab==0 ) return pDef;
  118180. if( !IsVirtual(pTab) ) return pDef;
  118181. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  118182. assert( pVtab!=0 );
  118183. assert( pVtab->pModule!=0 );
  118184. pMod = (sqlite3_module *)pVtab->pModule;
  118185. if( pMod->xFindFunction==0 ) return pDef;
  118186. /* Call the xFindFunction method on the virtual table implementation
  118187. ** to see if the implementation wants to overload this function
  118188. */
  118189. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  118190. if( zLowerName ){
  118191. for(z=(unsigned char*)zLowerName; *z; z++){
  118192. *z = sqlite3UpperToLower[*z];
  118193. }
  118194. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
  118195. sqlite3DbFree(db, zLowerName);
  118196. }
  118197. if( rc==0 ){
  118198. return pDef;
  118199. }
  118200. /* Create a new ephemeral function definition for the overloaded
  118201. ** function */
  118202. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  118203. + sqlite3Strlen30(pDef->zName) + 1);
  118204. if( pNew==0 ){
  118205. return pDef;
  118206. }
  118207. *pNew = *pDef;
  118208. pNew->zName = (const char*)&pNew[1];
  118209. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  118210. pNew->xSFunc = xSFunc;
  118211. pNew->pUserData = pArg;
  118212. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  118213. return pNew;
  118214. }
  118215. /*
  118216. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  118217. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  118218. ** array if it is missing. If pTab is already in the array, this routine
  118219. ** is a no-op.
  118220. */
  118221. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  118222. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  118223. int i, n;
  118224. Table **apVtabLock;
  118225. assert( IsVirtual(pTab) );
  118226. for(i=0; i<pToplevel->nVtabLock; i++){
  118227. if( pTab==pToplevel->apVtabLock[i] ) return;
  118228. }
  118229. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  118230. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  118231. if( apVtabLock ){
  118232. pToplevel->apVtabLock = apVtabLock;
  118233. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  118234. }else{
  118235. sqlite3OomFault(pToplevel->db);
  118236. }
  118237. }
  118238. /*
  118239. ** Check to see if virtual table module pMod can be have an eponymous
  118240. ** virtual table instance. If it can, create one if one does not already
  118241. ** exist. Return non-zero if the eponymous virtual table instance exists
  118242. ** when this routine returns, and return zero if it does not exist.
  118243. **
  118244. ** An eponymous virtual table instance is one that is named after its
  118245. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  118246. ** statement in order to come into existance. Eponymous virtual table
  118247. ** instances always exist. They cannot be DROP-ed.
  118248. **
  118249. ** Any virtual table module for which xConnect and xCreate are the same
  118250. ** method can have an eponymous virtual table instance.
  118251. */
  118252. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  118253. const sqlite3_module *pModule = pMod->pModule;
  118254. Table *pTab;
  118255. char *zErr = 0;
  118256. int rc;
  118257. sqlite3 *db = pParse->db;
  118258. if( pMod->pEpoTab ) return 1;
  118259. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  118260. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  118261. if( pTab==0 ) return 0;
  118262. pTab->zName = sqlite3DbStrDup(db, pMod->zName);
  118263. if( pTab->zName==0 ){
  118264. sqlite3DbFree(db, pTab);
  118265. return 0;
  118266. }
  118267. pMod->pEpoTab = pTab;
  118268. pTab->nTabRef = 1;
  118269. pTab->pSchema = db->aDb[0].pSchema;
  118270. assert( pTab->nModuleArg==0 );
  118271. pTab->iPKey = -1;
  118272. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  118273. addModuleArgument(db, pTab, 0);
  118274. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  118275. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  118276. if( rc ){
  118277. sqlite3ErrorMsg(pParse, "%s", zErr);
  118278. sqlite3DbFree(db, zErr);
  118279. sqlite3VtabEponymousTableClear(db, pMod);
  118280. return 0;
  118281. }
  118282. return 1;
  118283. }
  118284. /*
  118285. ** Erase the eponymous virtual table instance associated with
  118286. ** virtual table module pMod, if it exists.
  118287. */
  118288. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  118289. Table *pTab = pMod->pEpoTab;
  118290. if( pTab!=0 ){
  118291. /* Mark the table as Ephemeral prior to deleting it, so that the
  118292. ** sqlite3DeleteTable() routine will know that it is not stored in
  118293. ** the schema. */
  118294. pTab->tabFlags |= TF_Ephemeral;
  118295. sqlite3DeleteTable(db, pTab);
  118296. pMod->pEpoTab = 0;
  118297. }
  118298. }
  118299. /*
  118300. ** Return the ON CONFLICT resolution mode in effect for the virtual
  118301. ** table update operation currently in progress.
  118302. **
  118303. ** The results of this routine are undefined unless it is called from
  118304. ** within an xUpdate method.
  118305. */
  118306. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  118307. static const unsigned char aMap[] = {
  118308. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  118309. };
  118310. #ifdef SQLITE_ENABLE_API_ARMOR
  118311. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  118312. #endif
  118313. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  118314. assert( OE_Ignore==4 && OE_Replace==5 );
  118315. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  118316. return (int)aMap[db->vtabOnConflict-1];
  118317. }
  118318. /*
  118319. ** Call from within the xCreate() or xConnect() methods to provide
  118320. ** the SQLite core with additional information about the behavior
  118321. ** of the virtual table being implemented.
  118322. */
  118323. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  118324. va_list ap;
  118325. int rc = SQLITE_OK;
  118326. #ifdef SQLITE_ENABLE_API_ARMOR
  118327. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  118328. #endif
  118329. sqlite3_mutex_enter(db->mutex);
  118330. va_start(ap, op);
  118331. switch( op ){
  118332. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  118333. VtabCtx *p = db->pVtabCtx;
  118334. if( !p ){
  118335. rc = SQLITE_MISUSE_BKPT;
  118336. }else{
  118337. assert( p->pTab==0 || IsVirtual(p->pTab) );
  118338. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  118339. }
  118340. break;
  118341. }
  118342. default:
  118343. rc = SQLITE_MISUSE_BKPT;
  118344. break;
  118345. }
  118346. va_end(ap);
  118347. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  118348. sqlite3_mutex_leave(db->mutex);
  118349. return rc;
  118350. }
  118351. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  118352. /************** End of vtab.c ************************************************/
  118353. /************** Begin file wherecode.c ***************************************/
  118354. /*
  118355. ** 2015-06-06
  118356. **
  118357. ** The author disclaims copyright to this source code. In place of
  118358. ** a legal notice, here is a blessing:
  118359. **
  118360. ** May you do good and not evil.
  118361. ** May you find forgiveness for yourself and forgive others.
  118362. ** May you share freely, never taking more than you give.
  118363. **
  118364. *************************************************************************
  118365. ** This module contains C code that generates VDBE code used to process
  118366. ** the WHERE clause of SQL statements.
  118367. **
  118368. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  118369. ** size of where.c and make it easier to edit. This file contains the routines
  118370. ** that actually generate the bulk of the WHERE loop code. The original where.c
  118371. ** file retains the code that does query planning and analysis.
  118372. */
  118373. /* #include "sqliteInt.h" */
  118374. /************** Include whereInt.h in the middle of wherecode.c **************/
  118375. /************** Begin file whereInt.h ****************************************/
  118376. /*
  118377. ** 2013-11-12
  118378. **
  118379. ** The author disclaims copyright to this source code. In place of
  118380. ** a legal notice, here is a blessing:
  118381. **
  118382. ** May you do good and not evil.
  118383. ** May you find forgiveness for yourself and forgive others.
  118384. ** May you share freely, never taking more than you give.
  118385. **
  118386. *************************************************************************
  118387. **
  118388. ** This file contains structure and macro definitions for the query
  118389. ** planner logic in "where.c". These definitions are broken out into
  118390. ** a separate source file for easier editing.
  118391. */
  118392. /*
  118393. ** Trace output macros
  118394. */
  118395. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  118396. /***/ int sqlite3WhereTrace;
  118397. #endif
  118398. #if defined(SQLITE_DEBUG) \
  118399. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  118400. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  118401. # define WHERETRACE_ENABLED 1
  118402. #else
  118403. # define WHERETRACE(K,X)
  118404. #endif
  118405. /* Forward references
  118406. */
  118407. typedef struct WhereClause WhereClause;
  118408. typedef struct WhereMaskSet WhereMaskSet;
  118409. typedef struct WhereOrInfo WhereOrInfo;
  118410. typedef struct WhereAndInfo WhereAndInfo;
  118411. typedef struct WhereLevel WhereLevel;
  118412. typedef struct WhereLoop WhereLoop;
  118413. typedef struct WherePath WherePath;
  118414. typedef struct WhereTerm WhereTerm;
  118415. typedef struct WhereLoopBuilder WhereLoopBuilder;
  118416. typedef struct WhereScan WhereScan;
  118417. typedef struct WhereOrCost WhereOrCost;
  118418. typedef struct WhereOrSet WhereOrSet;
  118419. /*
  118420. ** This object contains information needed to implement a single nested
  118421. ** loop in WHERE clause.
  118422. **
  118423. ** Contrast this object with WhereLoop. This object describes the
  118424. ** implementation of the loop. WhereLoop describes the algorithm.
  118425. ** This object contains a pointer to the WhereLoop algorithm as one of
  118426. ** its elements.
  118427. **
  118428. ** The WhereInfo object contains a single instance of this object for
  118429. ** each term in the FROM clause (which is to say, for each of the
  118430. ** nested loops as implemented). The order of WhereLevel objects determines
  118431. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  118432. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  118433. */
  118434. struct WhereLevel {
  118435. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  118436. int iTabCur; /* The VDBE cursor used to access the table */
  118437. int iIdxCur; /* The VDBE cursor used to access pIdx */
  118438. int addrBrk; /* Jump here to break out of the loop */
  118439. int addrNxt; /* Jump here to start the next IN combination */
  118440. int addrSkip; /* Jump here for next iteration of skip-scan */
  118441. int addrCont; /* Jump here to continue with the next loop cycle */
  118442. int addrFirst; /* First instruction of interior of the loop */
  118443. int addrBody; /* Beginning of the body of this loop */
  118444. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  118445. u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
  118446. int addrLikeRep; /* LIKE range processing address */
  118447. #endif
  118448. u8 iFrom; /* Which entry in the FROM clause */
  118449. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  118450. int p1, p2; /* Operands of the opcode used to ends the loop */
  118451. union { /* Information that depends on pWLoop->wsFlags */
  118452. struct {
  118453. int nIn; /* Number of entries in aInLoop[] */
  118454. struct InLoop {
  118455. int iCur; /* The VDBE cursor used by this IN operator */
  118456. int addrInTop; /* Top of the IN loop */
  118457. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  118458. } *aInLoop; /* Information about each nested IN operator */
  118459. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  118460. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  118461. } u;
  118462. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  118463. Bitmask notReady; /* FROM entries not usable at this level */
  118464. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  118465. int addrVisit; /* Address at which row is visited */
  118466. #endif
  118467. };
  118468. /*
  118469. ** Each instance of this object represents an algorithm for evaluating one
  118470. ** term of a join. Every term of the FROM clause will have at least
  118471. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  118472. ** prevent a query solution - which is an error) and many terms of the
  118473. ** FROM clause will have multiple WhereLoop objects, each describing a
  118474. ** potential way of implementing that FROM-clause term, together with
  118475. ** dependencies and cost estimates for using the chosen algorithm.
  118476. **
  118477. ** Query planning consists of building up a collection of these WhereLoop
  118478. ** objects, then computing a particular sequence of WhereLoop objects, with
  118479. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  118480. ** and that minimize the overall cost.
  118481. */
  118482. struct WhereLoop {
  118483. Bitmask prereq; /* Bitmask of other loops that must run first */
  118484. Bitmask maskSelf; /* Bitmask identifying table iTab */
  118485. #ifdef SQLITE_DEBUG
  118486. char cId; /* Symbolic ID of this loop for debugging use */
  118487. #endif
  118488. u8 iTab; /* Position in FROM clause of table for this loop */
  118489. u8 iSortIdx; /* Sorting index number. 0==None */
  118490. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  118491. LogEst rRun; /* Cost of running each loop */
  118492. LogEst nOut; /* Estimated number of output rows */
  118493. union {
  118494. struct { /* Information for internal btree tables */
  118495. u16 nEq; /* Number of equality constraints */
  118496. u16 nBtm; /* Size of BTM vector */
  118497. u16 nTop; /* Size of TOP vector */
  118498. u16 nIdxCol; /* Index column used for ORDER BY */
  118499. Index *pIndex; /* Index used, or NULL */
  118500. } btree;
  118501. struct { /* Information for virtual tables */
  118502. int idxNum; /* Index number */
  118503. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  118504. i8 isOrdered; /* True if satisfies ORDER BY */
  118505. u16 omitMask; /* Terms that may be omitted */
  118506. char *idxStr; /* Index identifier string */
  118507. } vtab;
  118508. } u;
  118509. u32 wsFlags; /* WHERE_* flags describing the plan */
  118510. u16 nLTerm; /* Number of entries in aLTerm[] */
  118511. u16 nSkip; /* Number of NULL aLTerm[] entries */
  118512. /**** whereLoopXfer() copies fields above ***********************/
  118513. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  118514. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  118515. WhereTerm **aLTerm; /* WhereTerms used */
  118516. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  118517. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  118518. };
  118519. /* This object holds the prerequisites and the cost of running a
  118520. ** subquery on one operand of an OR operator in the WHERE clause.
  118521. ** See WhereOrSet for additional information
  118522. */
  118523. struct WhereOrCost {
  118524. Bitmask prereq; /* Prerequisites */
  118525. LogEst rRun; /* Cost of running this subquery */
  118526. LogEst nOut; /* Number of outputs for this subquery */
  118527. };
  118528. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  118529. ** correspond to the subquery(s) of OR-clause processing. Only the
  118530. ** best N_OR_COST elements are retained.
  118531. */
  118532. #define N_OR_COST 3
  118533. struct WhereOrSet {
  118534. u16 n; /* Number of valid a[] entries */
  118535. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  118536. };
  118537. /*
  118538. ** Each instance of this object holds a sequence of WhereLoop objects
  118539. ** that implement some or all of a query plan.
  118540. **
  118541. ** Think of each WhereLoop object as a node in a graph with arcs
  118542. ** showing dependencies and costs for travelling between nodes. (That is
  118543. ** not a completely accurate description because WhereLoop costs are a
  118544. ** vector, not a scalar, and because dependencies are many-to-one, not
  118545. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  118546. ** Then a WherePath object is a path through the graph that visits some
  118547. ** or all of the WhereLoop objects once.
  118548. **
  118549. ** The "solver" works by creating the N best WherePath objects of length
  118550. ** 1. Then using those as a basis to compute the N best WherePath objects
  118551. ** of length 2. And so forth until the length of WherePaths equals the
  118552. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  118553. ** at the end is the chosen query plan.
  118554. */
  118555. struct WherePath {
  118556. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  118557. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  118558. LogEst nRow; /* Estimated number of rows generated by this path */
  118559. LogEst rCost; /* Total cost of this path */
  118560. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  118561. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  118562. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  118563. };
  118564. /*
  118565. ** The query generator uses an array of instances of this structure to
  118566. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  118567. ** clause subexpression is separated from the others by AND operators,
  118568. ** usually, or sometimes subexpressions separated by OR.
  118569. **
  118570. ** All WhereTerms are collected into a single WhereClause structure.
  118571. ** The following identity holds:
  118572. **
  118573. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  118574. **
  118575. ** When a term is of the form:
  118576. **
  118577. ** X <op> <expr>
  118578. **
  118579. ** where X is a column name and <op> is one of certain operators,
  118580. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  118581. ** cursor number and column number for X. WhereTerm.eOperator records
  118582. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  118583. ** use of a bitmask encoding for the operator allows us to search
  118584. ** quickly for terms that match any of several different operators.
  118585. **
  118586. ** A WhereTerm might also be two or more subterms connected by OR:
  118587. **
  118588. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  118589. **
  118590. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  118591. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  118592. ** is collected about the OR clause.
  118593. **
  118594. ** If a term in the WHERE clause does not match either of the two previous
  118595. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  118596. ** to the original subexpression content and wtFlags is set up appropriately
  118597. ** but no other fields in the WhereTerm object are meaningful.
  118598. **
  118599. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  118600. ** but they do so indirectly. A single WhereMaskSet structure translates
  118601. ** cursor number into bits and the translated bit is stored in the prereq
  118602. ** fields. The translation is used in order to maximize the number of
  118603. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  118604. ** spread out over the non-negative integers. For example, the cursor
  118605. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  118606. ** translates these sparse cursor numbers into consecutive integers
  118607. ** beginning with 0 in order to make the best possible use of the available
  118608. ** bits in the Bitmask. So, in the example above, the cursor numbers
  118609. ** would be mapped into integers 0 through 7.
  118610. **
  118611. ** The number of terms in a join is limited by the number of bits
  118612. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  118613. ** is only able to process joins with 64 or fewer tables.
  118614. */
  118615. struct WhereTerm {
  118616. Expr *pExpr; /* Pointer to the subexpression that is this term */
  118617. WhereClause *pWC; /* The clause this term is part of */
  118618. LogEst truthProb; /* Probability of truth for this expression */
  118619. u16 wtFlags; /* TERM_xxx bit flags. See below */
  118620. u16 eOperator; /* A WO_xx value describing <op> */
  118621. u8 nChild; /* Number of children that must disable us */
  118622. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  118623. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  118624. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  118625. int iField; /* Field in (?,?,?) IN (SELECT...) vector */
  118626. union {
  118627. int leftColumn; /* Column number of X in "X <op> <expr>" */
  118628. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  118629. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  118630. } u;
  118631. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  118632. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  118633. };
  118634. /*
  118635. ** Allowed values of WhereTerm.wtFlags
  118636. */
  118637. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  118638. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  118639. #define TERM_CODED 0x04 /* This term is already coded */
  118640. #define TERM_COPIED 0x08 /* Has a child */
  118641. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  118642. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  118643. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  118644. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  118645. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  118646. #else
  118647. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  118648. #endif
  118649. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  118650. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  118651. #define TERM_LIKE 0x400 /* The original LIKE operator */
  118652. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  118653. /*
  118654. ** An instance of the WhereScan object is used as an iterator for locating
  118655. ** terms in the WHERE clause that are useful to the query planner.
  118656. */
  118657. struct WhereScan {
  118658. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  118659. WhereClause *pWC; /* WhereClause currently being scanned */
  118660. const char *zCollName; /* Required collating sequence, if not NULL */
  118661. Expr *pIdxExpr; /* Search for this index expression */
  118662. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  118663. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  118664. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  118665. u32 opMask; /* Acceptable operators */
  118666. int k; /* Resume scanning at this->pWC->a[this->k] */
  118667. int aiCur[11]; /* Cursors in the equivalence class */
  118668. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  118669. };
  118670. /*
  118671. ** An instance of the following structure holds all information about a
  118672. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  118673. **
  118674. ** Explanation of pOuter: For a WHERE clause of the form
  118675. **
  118676. ** a AND ((b AND c) OR (d AND e)) AND f
  118677. **
  118678. ** There are separate WhereClause objects for the whole clause and for
  118679. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  118680. ** subclauses points to the WhereClause object for the whole clause.
  118681. */
  118682. struct WhereClause {
  118683. WhereInfo *pWInfo; /* WHERE clause processing context */
  118684. WhereClause *pOuter; /* Outer conjunction */
  118685. u8 op; /* Split operator. TK_AND or TK_OR */
  118686. int nTerm; /* Number of terms */
  118687. int nSlot; /* Number of entries in a[] */
  118688. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  118689. #if defined(SQLITE_SMALL_STACK)
  118690. WhereTerm aStatic[1]; /* Initial static space for a[] */
  118691. #else
  118692. WhereTerm aStatic[8]; /* Initial static space for a[] */
  118693. #endif
  118694. };
  118695. /*
  118696. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  118697. ** a dynamically allocated instance of the following structure.
  118698. */
  118699. struct WhereOrInfo {
  118700. WhereClause wc; /* Decomposition into subterms */
  118701. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  118702. };
  118703. /*
  118704. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  118705. ** a dynamically allocated instance of the following structure.
  118706. */
  118707. struct WhereAndInfo {
  118708. WhereClause wc; /* The subexpression broken out */
  118709. };
  118710. /*
  118711. ** An instance of the following structure keeps track of a mapping
  118712. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  118713. **
  118714. ** The VDBE cursor numbers are small integers contained in
  118715. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  118716. ** clause, the cursor numbers might not begin with 0 and they might
  118717. ** contain gaps in the numbering sequence. But we want to make maximum
  118718. ** use of the bits in our bitmasks. This structure provides a mapping
  118719. ** from the sparse cursor numbers into consecutive integers beginning
  118720. ** with 0.
  118721. **
  118722. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  118723. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  118724. **
  118725. ** For example, if the WHERE clause expression used these VDBE
  118726. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  118727. ** would map those cursor numbers into bits 0 through 5.
  118728. **
  118729. ** Note that the mapping is not necessarily ordered. In the example
  118730. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  118731. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  118732. ** does not really matter. What is important is that sparse cursor
  118733. ** numbers all get mapped into bit numbers that begin with 0 and contain
  118734. ** no gaps.
  118735. */
  118736. struct WhereMaskSet {
  118737. int n; /* Number of assigned cursor values */
  118738. int ix[BMS]; /* Cursor assigned to each bit */
  118739. };
  118740. /*
  118741. ** Initialize a WhereMaskSet object
  118742. */
  118743. #define initMaskSet(P) (P)->n=0
  118744. /*
  118745. ** This object is a convenience wrapper holding all information needed
  118746. ** to construct WhereLoop objects for a particular query.
  118747. */
  118748. struct WhereLoopBuilder {
  118749. WhereInfo *pWInfo; /* Information about this WHERE */
  118750. WhereClause *pWC; /* WHERE clause terms */
  118751. ExprList *pOrderBy; /* ORDER BY clause */
  118752. WhereLoop *pNew; /* Template WhereLoop */
  118753. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  118754. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  118755. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  118756. int nRecValid; /* Number of valid fields currently in pRec */
  118757. #endif
  118758. unsigned int bldFlags; /* SQLITE_BLDF_* flags */
  118759. };
  118760. /* Allowed values for WhereLoopBuider.bldFlags */
  118761. #define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */
  118762. #define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
  118763. /*
  118764. ** The WHERE clause processing routine has two halves. The
  118765. ** first part does the start of the WHERE loop and the second
  118766. ** half does the tail of the WHERE loop. An instance of
  118767. ** this structure is returned by the first half and passed
  118768. ** into the second half to give some continuity.
  118769. **
  118770. ** An instance of this object holds the complete state of the query
  118771. ** planner.
  118772. */
  118773. struct WhereInfo {
  118774. Parse *pParse; /* Parsing and code generating context */
  118775. SrcList *pTabList; /* List of tables in the join */
  118776. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  118777. ExprList *pResultSet; /* Result set of the query */
  118778. Expr *pWhere; /* The complete WHERE clause */
  118779. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  118780. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  118781. int iContinue; /* Jump here to continue with next record */
  118782. int iBreak; /* Jump here to break out of the loop */
  118783. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  118784. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  118785. u8 nLevel; /* Number of nested loop */
  118786. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  118787. u8 sorted; /* True if really sorted (not just grouped) */
  118788. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  118789. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  118790. u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
  118791. u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
  118792. int iTop; /* The very beginning of the WHERE loop */
  118793. WhereLoop *pLoops; /* List of all WhereLoop objects */
  118794. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  118795. LogEst nRowOut; /* Estimated number of output rows */
  118796. WhereClause sWC; /* Decomposition of the WHERE clause */
  118797. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  118798. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  118799. };
  118800. /*
  118801. ** Private interfaces - callable only by other where.c routines.
  118802. **
  118803. ** where.c:
  118804. */
  118805. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  118806. #ifdef WHERETRACE_ENABLED
  118807. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
  118808. #endif
  118809. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  118810. WhereClause *pWC, /* The WHERE clause to be searched */
  118811. int iCur, /* Cursor number of LHS */
  118812. int iColumn, /* Column number of LHS */
  118813. Bitmask notReady, /* RHS must not overlap with this mask */
  118814. u32 op, /* Mask of WO_xx values describing operator */
  118815. Index *pIdx /* Must be compatible with this index, if not NULL */
  118816. );
  118817. /* wherecode.c: */
  118818. #ifndef SQLITE_OMIT_EXPLAIN
  118819. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  118820. Parse *pParse, /* Parse context */
  118821. SrcList *pTabList, /* Table list this loop refers to */
  118822. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  118823. int iLevel, /* Value for "level" column of output */
  118824. int iFrom, /* Value for "from" column of output */
  118825. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  118826. );
  118827. #else
  118828. # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
  118829. #endif /* SQLITE_OMIT_EXPLAIN */
  118830. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  118831. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  118832. Vdbe *v, /* Vdbe to add scanstatus entry to */
  118833. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  118834. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  118835. int addrExplain /* Address of OP_Explain (or 0) */
  118836. );
  118837. #else
  118838. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  118839. #endif
  118840. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  118841. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  118842. int iLevel, /* Which level of pWInfo->a[] should be coded */
  118843. Bitmask notReady /* Which tables are currently available */
  118844. );
  118845. /* whereexpr.c: */
  118846. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  118847. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  118848. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  118849. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  118850. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  118851. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  118852. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  118853. /*
  118854. ** Bitmasks for the operators on WhereTerm objects. These are all
  118855. ** operators that are of interest to the query planner. An
  118856. ** OR-ed combination of these values can be used when searching for
  118857. ** particular WhereTerms within a WhereClause.
  118858. **
  118859. ** Value constraints:
  118860. ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
  118861. ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
  118862. ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
  118863. ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
  118864. ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
  118865. ** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
  118866. */
  118867. #define WO_IN 0x0001
  118868. #define WO_EQ 0x0002
  118869. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  118870. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  118871. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  118872. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  118873. #define WO_MATCH 0x0040
  118874. #define WO_IS 0x0080
  118875. #define WO_ISNULL 0x0100
  118876. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  118877. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  118878. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  118879. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  118880. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  118881. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  118882. /*
  118883. ** These are definitions of bits in the WhereLoop.wsFlags field.
  118884. ** The particular combination of bits in each WhereLoop help to
  118885. ** determine the algorithm that WhereLoop represents.
  118886. */
  118887. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  118888. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  118889. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  118890. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  118891. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  118892. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  118893. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  118894. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  118895. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  118896. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  118897. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  118898. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  118899. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  118900. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  118901. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  118902. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  118903. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  118904. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  118905. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  118906. /************** End of whereInt.h ********************************************/
  118907. /************** Continuing where we left off in wherecode.c ******************/
  118908. #ifndef SQLITE_OMIT_EXPLAIN
  118909. /*
  118910. ** Return the name of the i-th column of the pIdx index.
  118911. */
  118912. static const char *explainIndexColumnName(Index *pIdx, int i){
  118913. i = pIdx->aiColumn[i];
  118914. if( i==XN_EXPR ) return "<expr>";
  118915. if( i==XN_ROWID ) return "rowid";
  118916. return pIdx->pTable->aCol[i].zName;
  118917. }
  118918. /*
  118919. ** This routine is a helper for explainIndexRange() below
  118920. **
  118921. ** pStr holds the text of an expression that we are building up one term
  118922. ** at a time. This routine adds a new term to the end of the expression.
  118923. ** Terms are separated by AND so add the "AND" text for second and subsequent
  118924. ** terms only.
  118925. */
  118926. static void explainAppendTerm(
  118927. StrAccum *pStr, /* The text expression being built */
  118928. Index *pIdx, /* Index to read column names from */
  118929. int nTerm, /* Number of terms */
  118930. int iTerm, /* Zero-based index of first term. */
  118931. int bAnd, /* Non-zero to append " AND " */
  118932. const char *zOp /* Name of the operator */
  118933. ){
  118934. int i;
  118935. assert( nTerm>=1 );
  118936. if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  118937. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
  118938. for(i=0; i<nTerm; i++){
  118939. if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
  118940. sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
  118941. }
  118942. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
  118943. sqlite3StrAccumAppend(pStr, zOp, 1);
  118944. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
  118945. for(i=0; i<nTerm; i++){
  118946. if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
  118947. sqlite3StrAccumAppend(pStr, "?", 1);
  118948. }
  118949. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
  118950. }
  118951. /*
  118952. ** Argument pLevel describes a strategy for scanning table pTab. This
  118953. ** function appends text to pStr that describes the subset of table
  118954. ** rows scanned by the strategy in the form of an SQL expression.
  118955. **
  118956. ** For example, if the query:
  118957. **
  118958. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  118959. **
  118960. ** is run and there is an index on (a, b), then this function returns a
  118961. ** string similar to:
  118962. **
  118963. ** "a=? AND b>?"
  118964. */
  118965. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  118966. Index *pIndex = pLoop->u.btree.pIndex;
  118967. u16 nEq = pLoop->u.btree.nEq;
  118968. u16 nSkip = pLoop->nSkip;
  118969. int i, j;
  118970. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  118971. sqlite3StrAccumAppend(pStr, " (", 2);
  118972. for(i=0; i<nEq; i++){
  118973. const char *z = explainIndexColumnName(pIndex, i);
  118974. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  118975. sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  118976. }
  118977. j = i;
  118978. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  118979. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
  118980. i = 1;
  118981. }
  118982. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  118983. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  118984. }
  118985. sqlite3StrAccumAppend(pStr, ")", 1);
  118986. }
  118987. /*
  118988. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  118989. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  118990. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  118991. ** is added to the output to describe the table scan strategy in pLevel.
  118992. **
  118993. ** If an OP_Explain opcode is added to the VM, its address is returned.
  118994. ** Otherwise, if no OP_Explain is coded, zero is returned.
  118995. */
  118996. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  118997. Parse *pParse, /* Parse context */
  118998. SrcList *pTabList, /* Table list this loop refers to */
  118999. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  119000. int iLevel, /* Value for "level" column of output */
  119001. int iFrom, /* Value for "from" column of output */
  119002. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  119003. ){
  119004. int ret = 0;
  119005. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  119006. if( pParse->explain==2 )
  119007. #endif
  119008. {
  119009. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  119010. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  119011. sqlite3 *db = pParse->db; /* Database handle */
  119012. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  119013. int isSearch; /* True for a SEARCH. False for SCAN. */
  119014. WhereLoop *pLoop; /* The controlling WhereLoop object */
  119015. u32 flags; /* Flags that describe this loop */
  119016. char *zMsg; /* Text to add to EQP output */
  119017. StrAccum str; /* EQP output string */
  119018. char zBuf[100]; /* Initial space for EQP output string */
  119019. pLoop = pLevel->pWLoop;
  119020. flags = pLoop->wsFlags;
  119021. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
  119022. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  119023. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  119024. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  119025. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  119026. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  119027. if( pItem->pSelect ){
  119028. sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
  119029. }else{
  119030. sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
  119031. }
  119032. if( pItem->zAlias ){
  119033. sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
  119034. }
  119035. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  119036. const char *zFmt = 0;
  119037. Index *pIdx;
  119038. assert( pLoop->u.btree.pIndex!=0 );
  119039. pIdx = pLoop->u.btree.pIndex;
  119040. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  119041. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  119042. if( isSearch ){
  119043. zFmt = "PRIMARY KEY";
  119044. }
  119045. }else if( flags & WHERE_PARTIALIDX ){
  119046. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  119047. }else if( flags & WHERE_AUTO_INDEX ){
  119048. zFmt = "AUTOMATIC COVERING INDEX";
  119049. }else if( flags & WHERE_IDX_ONLY ){
  119050. zFmt = "COVERING INDEX %s";
  119051. }else{
  119052. zFmt = "INDEX %s";
  119053. }
  119054. if( zFmt ){
  119055. sqlite3StrAccumAppend(&str, " USING ", 7);
  119056. sqlite3XPrintf(&str, zFmt, pIdx->zName);
  119057. explainIndexRange(&str, pLoop);
  119058. }
  119059. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  119060. const char *zRangeOp;
  119061. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  119062. zRangeOp = "=";
  119063. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  119064. zRangeOp = ">? AND rowid<";
  119065. }else if( flags&WHERE_BTM_LIMIT ){
  119066. zRangeOp = ">";
  119067. }else{
  119068. assert( flags&WHERE_TOP_LIMIT);
  119069. zRangeOp = "<";
  119070. }
  119071. sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  119072. }
  119073. #ifndef SQLITE_OMIT_VIRTUALTABLE
  119074. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  119075. sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
  119076. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  119077. }
  119078. #endif
  119079. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  119080. if( pLoop->nOut>=10 ){
  119081. sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  119082. }else{
  119083. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  119084. }
  119085. #endif
  119086. zMsg = sqlite3StrAccumFinish(&str);
  119087. ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
  119088. }
  119089. return ret;
  119090. }
  119091. #endif /* SQLITE_OMIT_EXPLAIN */
  119092. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  119093. /*
  119094. ** Configure the VM passed as the first argument with an
  119095. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  119096. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  119097. ** clause that the scan reads data from.
  119098. **
  119099. ** If argument addrExplain is not 0, it must be the address of an
  119100. ** OP_Explain instruction that describes the same loop.
  119101. */
  119102. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  119103. Vdbe *v, /* Vdbe to add scanstatus entry to */
  119104. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  119105. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  119106. int addrExplain /* Address of OP_Explain (or 0) */
  119107. ){
  119108. const char *zObj = 0;
  119109. WhereLoop *pLoop = pLvl->pWLoop;
  119110. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  119111. zObj = pLoop->u.btree.pIndex->zName;
  119112. }else{
  119113. zObj = pSrclist->a[pLvl->iFrom].zName;
  119114. }
  119115. sqlite3VdbeScanStatus(
  119116. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  119117. );
  119118. }
  119119. #endif
  119120. /*
  119121. ** Disable a term in the WHERE clause. Except, do not disable the term
  119122. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  119123. ** or USING clause of that join.
  119124. **
  119125. ** Consider the term t2.z='ok' in the following queries:
  119126. **
  119127. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  119128. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  119129. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  119130. **
  119131. ** The t2.z='ok' is disabled in the in (2) because it originates
  119132. ** in the ON clause. The term is disabled in (3) because it is not part
  119133. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  119134. **
  119135. ** Disabling a term causes that term to not be tested in the inner loop
  119136. ** of the join. Disabling is an optimization. When terms are satisfied
  119137. ** by indices, we disable them to prevent redundant tests in the inner
  119138. ** loop. We would get the correct results if nothing were ever disabled,
  119139. ** but joins might run a little slower. The trick is to disable as much
  119140. ** as we can without disabling too much. If we disabled in (1), we'd get
  119141. ** the wrong answer. See ticket #813.
  119142. **
  119143. ** If all the children of a term are disabled, then that term is also
  119144. ** automatically disabled. In this way, terms get disabled if derived
  119145. ** virtual terms are tested first. For example:
  119146. **
  119147. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  119148. ** \___________/ \______/ \_____/
  119149. ** parent child1 child2
  119150. **
  119151. ** Only the parent term was in the original WHERE clause. The child1
  119152. ** and child2 terms were added by the LIKE optimization. If both of
  119153. ** the virtual child terms are valid, then testing of the parent can be
  119154. ** skipped.
  119155. **
  119156. ** Usually the parent term is marked as TERM_CODED. But if the parent
  119157. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  119158. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  119159. ** a conditional such that is only evaluated on the second pass of a
  119160. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  119161. */
  119162. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  119163. int nLoop = 0;
  119164. while( ALWAYS(pTerm!=0)
  119165. && (pTerm->wtFlags & TERM_CODED)==0
  119166. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  119167. && (pLevel->notReady & pTerm->prereqAll)==0
  119168. ){
  119169. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  119170. pTerm->wtFlags |= TERM_LIKECOND;
  119171. }else{
  119172. pTerm->wtFlags |= TERM_CODED;
  119173. }
  119174. if( pTerm->iParent<0 ) break;
  119175. pTerm = &pTerm->pWC->a[pTerm->iParent];
  119176. pTerm->nChild--;
  119177. if( pTerm->nChild!=0 ) break;
  119178. nLoop++;
  119179. }
  119180. }
  119181. /*
  119182. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  119183. ** to the n registers starting at base.
  119184. **
  119185. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  119186. ** beginning and end of zAff are ignored. If all entries in zAff are
  119187. ** SQLITE_AFF_BLOB, then no code gets generated.
  119188. **
  119189. ** This routine makes its own copy of zAff so that the caller is free
  119190. ** to modify zAff after this routine returns.
  119191. */
  119192. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  119193. Vdbe *v = pParse->pVdbe;
  119194. if( zAff==0 ){
  119195. assert( pParse->db->mallocFailed );
  119196. return;
  119197. }
  119198. assert( v!=0 );
  119199. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  119200. ** and end of the affinity string.
  119201. */
  119202. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  119203. n--;
  119204. base++;
  119205. zAff++;
  119206. }
  119207. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  119208. n--;
  119209. }
  119210. /* Code the OP_Affinity opcode if there is anything left to do. */
  119211. if( n>0 ){
  119212. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  119213. sqlite3ExprCacheAffinityChange(pParse, base, n);
  119214. }
  119215. }
  119216. /*
  119217. ** Expression pRight, which is the RHS of a comparison operation, is
  119218. ** either a vector of n elements or, if n==1, a scalar expression.
  119219. ** Before the comparison operation, affinity zAff is to be applied
  119220. ** to the pRight values. This function modifies characters within the
  119221. ** affinity string to SQLITE_AFF_BLOB if either:
  119222. **
  119223. ** * the comparison will be performed with no affinity, or
  119224. ** * the affinity change in zAff is guaranteed not to change the value.
  119225. */
  119226. static void updateRangeAffinityStr(
  119227. Expr *pRight, /* RHS of comparison */
  119228. int n, /* Number of vector elements in comparison */
  119229. char *zAff /* Affinity string to modify */
  119230. ){
  119231. int i;
  119232. for(i=0; i<n; i++){
  119233. Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
  119234. if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
  119235. || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
  119236. ){
  119237. zAff[i] = SQLITE_AFF_BLOB;
  119238. }
  119239. }
  119240. }
  119241. /*
  119242. ** Generate code for a single equality term of the WHERE clause. An equality
  119243. ** term can be either X=expr or X IN (...). pTerm is the term to be
  119244. ** coded.
  119245. **
  119246. ** The current value for the constraint is left in a register, the index
  119247. ** of which is returned. An attempt is made store the result in iTarget but
  119248. ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
  119249. ** constraint is a TK_EQ or TK_IS, then the current value might be left in
  119250. ** some other register and it is the caller's responsibility to compensate.
  119251. **
  119252. ** For a constraint of the form X=expr, the expression is evaluated in
  119253. ** straight-line code. For constraints of the form X IN (...)
  119254. ** this routine sets up a loop that will iterate over all values of X.
  119255. */
  119256. static int codeEqualityTerm(
  119257. Parse *pParse, /* The parsing context */
  119258. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  119259. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  119260. int iEq, /* Index of the equality term within this level */
  119261. int bRev, /* True for reverse-order IN operations */
  119262. int iTarget /* Attempt to leave results in this register */
  119263. ){
  119264. Expr *pX = pTerm->pExpr;
  119265. Vdbe *v = pParse->pVdbe;
  119266. int iReg; /* Register holding results */
  119267. assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  119268. assert( iTarget>0 );
  119269. if( pX->op==TK_EQ || pX->op==TK_IS ){
  119270. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  119271. }else if( pX->op==TK_ISNULL ){
  119272. iReg = iTarget;
  119273. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  119274. #ifndef SQLITE_OMIT_SUBQUERY
  119275. }else{
  119276. int eType = IN_INDEX_NOOP;
  119277. int iTab;
  119278. struct InLoop *pIn;
  119279. WhereLoop *pLoop = pLevel->pWLoop;
  119280. int i;
  119281. int nEq = 0;
  119282. int *aiMap = 0;
  119283. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  119284. && pLoop->u.btree.pIndex!=0
  119285. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  119286. ){
  119287. testcase( iEq==0 );
  119288. testcase( bRev );
  119289. bRev = !bRev;
  119290. }
  119291. assert( pX->op==TK_IN );
  119292. iReg = iTarget;
  119293. for(i=0; i<iEq; i++){
  119294. if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
  119295. disableTerm(pLevel, pTerm);
  119296. return iTarget;
  119297. }
  119298. }
  119299. for(i=iEq;i<pLoop->nLTerm; i++){
  119300. if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  119301. }
  119302. if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
  119303. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
  119304. }else{
  119305. Select *pSelect = pX->x.pSelect;
  119306. sqlite3 *db = pParse->db;
  119307. u16 savedDbOptFlags = db->dbOptFlags;
  119308. ExprList *pOrigRhs = pSelect->pEList;
  119309. ExprList *pOrigLhs = pX->pLeft->x.pList;
  119310. ExprList *pRhs = 0; /* New Select.pEList for RHS */
  119311. ExprList *pLhs = 0; /* New pX->pLeft vector */
  119312. for(i=iEq;i<pLoop->nLTerm; i++){
  119313. if( pLoop->aLTerm[i]->pExpr==pX ){
  119314. int iField = pLoop->aLTerm[i]->iField - 1;
  119315. Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
  119316. Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
  119317. pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
  119318. pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
  119319. }
  119320. }
  119321. if( !db->mallocFailed ){
  119322. Expr *pLeft = pX->pLeft;
  119323. if( pSelect->pOrderBy ){
  119324. /* If the SELECT statement has an ORDER BY clause, zero the
  119325. ** iOrderByCol variables. These are set to non-zero when an
  119326. ** ORDER BY term exactly matches one of the terms of the
  119327. ** result-set. Since the result-set of the SELECT statement may
  119328. ** have been modified or reordered, these variables are no longer
  119329. ** set correctly. Since setting them is just an optimization,
  119330. ** it's easiest just to zero them here. */
  119331. ExprList *pOrderBy = pSelect->pOrderBy;
  119332. for(i=0; i<pOrderBy->nExpr; i++){
  119333. pOrderBy->a[i].u.x.iOrderByCol = 0;
  119334. }
  119335. }
  119336. /* Take care here not to generate a TK_VECTOR containing only a
  119337. ** single value. Since the parser never creates such a vector, some
  119338. ** of the subroutines do not handle this case. */
  119339. if( pLhs->nExpr==1 ){
  119340. pX->pLeft = pLhs->a[0].pExpr;
  119341. }else{
  119342. pLeft->x.pList = pLhs;
  119343. aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
  119344. testcase( aiMap==0 );
  119345. }
  119346. pSelect->pEList = pRhs;
  119347. db->dbOptFlags |= SQLITE_QueryFlattener;
  119348. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
  119349. db->dbOptFlags = savedDbOptFlags;
  119350. testcase( aiMap!=0 && aiMap[0]!=0 );
  119351. pSelect->pEList = pOrigRhs;
  119352. pLeft->x.pList = pOrigLhs;
  119353. pX->pLeft = pLeft;
  119354. }
  119355. sqlite3ExprListDelete(pParse->db, pLhs);
  119356. sqlite3ExprListDelete(pParse->db, pRhs);
  119357. }
  119358. if( eType==IN_INDEX_INDEX_DESC ){
  119359. testcase( bRev );
  119360. bRev = !bRev;
  119361. }
  119362. iTab = pX->iTable;
  119363. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  119364. VdbeCoverageIf(v, bRev);
  119365. VdbeCoverageIf(v, !bRev);
  119366. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  119367. pLoop->wsFlags |= WHERE_IN_ABLE;
  119368. if( pLevel->u.in.nIn==0 ){
  119369. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  119370. }
  119371. i = pLevel->u.in.nIn;
  119372. pLevel->u.in.nIn += nEq;
  119373. pLevel->u.in.aInLoop =
  119374. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  119375. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  119376. pIn = pLevel->u.in.aInLoop;
  119377. if( pIn ){
  119378. int iMap = 0; /* Index in aiMap[] */
  119379. pIn += i;
  119380. for(i=iEq;i<pLoop->nLTerm; i++){
  119381. if( pLoop->aLTerm[i]->pExpr==pX ){
  119382. int iOut = iReg + i - iEq;
  119383. if( eType==IN_INDEX_ROWID ){
  119384. testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */
  119385. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
  119386. }else{
  119387. int iCol = aiMap ? aiMap[iMap++] : 0;
  119388. pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
  119389. }
  119390. sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
  119391. if( i==iEq ){
  119392. pIn->iCur = iTab;
  119393. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  119394. }else{
  119395. pIn->eEndLoopOp = OP_Noop;
  119396. }
  119397. pIn++;
  119398. }
  119399. }
  119400. }else{
  119401. pLevel->u.in.nIn = 0;
  119402. }
  119403. sqlite3DbFree(pParse->db, aiMap);
  119404. #endif
  119405. }
  119406. disableTerm(pLevel, pTerm);
  119407. return iReg;
  119408. }
  119409. /*
  119410. ** Generate code that will evaluate all == and IN constraints for an
  119411. ** index scan.
  119412. **
  119413. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  119414. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  119415. ** The index has as many as three equality constraints, but in this
  119416. ** example, the third "c" value is an inequality. So only two
  119417. ** constraints are coded. This routine will generate code to evaluate
  119418. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  119419. ** in consecutive registers and the index of the first register is returned.
  119420. **
  119421. ** In the example above nEq==2. But this subroutine works for any value
  119422. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  119423. ** The only thing it does is allocate the pLevel->iMem memory cell and
  119424. ** compute the affinity string.
  119425. **
  119426. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  119427. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  119428. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  119429. ** occurs after the nEq quality constraints.
  119430. **
  119431. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  119432. ** the index of the first memory cell in that range. The code that
  119433. ** calls this routine will use that memory range to store keys for
  119434. ** start and termination conditions of the loop.
  119435. ** key value of the loop. If one or more IN operators appear, then
  119436. ** this routine allocates an additional nEq memory cells for internal
  119437. ** use.
  119438. **
  119439. ** Before returning, *pzAff is set to point to a buffer containing a
  119440. ** copy of the column affinity string of the index allocated using
  119441. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  119442. ** with equality constraints that use BLOB or NONE affinity are set to
  119443. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  119444. **
  119445. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  119446. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  119447. **
  119448. ** In the example above, the index on t1(a) has TEXT affinity. But since
  119449. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  119450. ** no conversion should be attempted before using a t2.b value as part of
  119451. ** a key to search the index. Hence the first byte in the returned affinity
  119452. ** string in this example would be set to SQLITE_AFF_BLOB.
  119453. */
  119454. static int codeAllEqualityTerms(
  119455. Parse *pParse, /* Parsing context */
  119456. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  119457. int bRev, /* Reverse the order of IN operators */
  119458. int nExtraReg, /* Number of extra registers to allocate */
  119459. char **pzAff /* OUT: Set to point to affinity string */
  119460. ){
  119461. u16 nEq; /* The number of == or IN constraints to code */
  119462. u16 nSkip; /* Number of left-most columns to skip */
  119463. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  119464. Index *pIdx; /* The index being used for this loop */
  119465. WhereTerm *pTerm; /* A single constraint term */
  119466. WhereLoop *pLoop; /* The WhereLoop object */
  119467. int j; /* Loop counter */
  119468. int regBase; /* Base register */
  119469. int nReg; /* Number of registers to allocate */
  119470. char *zAff; /* Affinity string to return */
  119471. /* This module is only called on query plans that use an index. */
  119472. pLoop = pLevel->pWLoop;
  119473. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  119474. nEq = pLoop->u.btree.nEq;
  119475. nSkip = pLoop->nSkip;
  119476. pIdx = pLoop->u.btree.pIndex;
  119477. assert( pIdx!=0 );
  119478. /* Figure out how many memory cells we will need then allocate them.
  119479. */
  119480. regBase = pParse->nMem + 1;
  119481. nReg = pLoop->u.btree.nEq + nExtraReg;
  119482. pParse->nMem += nReg;
  119483. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  119484. assert( zAff!=0 || pParse->db->mallocFailed );
  119485. if( nSkip ){
  119486. int iIdxCur = pLevel->iIdxCur;
  119487. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  119488. VdbeCoverageIf(v, bRev==0);
  119489. VdbeCoverageIf(v, bRev!=0);
  119490. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  119491. j = sqlite3VdbeAddOp0(v, OP_Goto);
  119492. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  119493. iIdxCur, 0, regBase, nSkip);
  119494. VdbeCoverageIf(v, bRev==0);
  119495. VdbeCoverageIf(v, bRev!=0);
  119496. sqlite3VdbeJumpHere(v, j);
  119497. for(j=0; j<nSkip; j++){
  119498. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  119499. testcase( pIdx->aiColumn[j]==XN_EXPR );
  119500. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  119501. }
  119502. }
  119503. /* Evaluate the equality constraints
  119504. */
  119505. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  119506. for(j=nSkip; j<nEq; j++){
  119507. int r1;
  119508. pTerm = pLoop->aLTerm[j];
  119509. assert( pTerm!=0 );
  119510. /* The following testcase is true for indices with redundant columns.
  119511. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  119512. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  119513. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  119514. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  119515. if( r1!=regBase+j ){
  119516. if( nReg==1 ){
  119517. sqlite3ReleaseTempReg(pParse, regBase);
  119518. regBase = r1;
  119519. }else{
  119520. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  119521. }
  119522. }
  119523. if( pTerm->eOperator & WO_IN ){
  119524. if( pTerm->pExpr->flags & EP_xIsSelect ){
  119525. /* No affinity ever needs to be (or should be) applied to a value
  119526. ** from the RHS of an "? IN (SELECT ...)" expression. The
  119527. ** sqlite3FindInIndex() routine has already ensured that the
  119528. ** affinity of the comparison has been applied to the value. */
  119529. if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
  119530. }
  119531. }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
  119532. Expr *pRight = pTerm->pExpr->pRight;
  119533. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  119534. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  119535. VdbeCoverage(v);
  119536. }
  119537. if( zAff ){
  119538. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  119539. zAff[j] = SQLITE_AFF_BLOB;
  119540. }
  119541. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  119542. zAff[j] = SQLITE_AFF_BLOB;
  119543. }
  119544. }
  119545. }
  119546. }
  119547. *pzAff = zAff;
  119548. return regBase;
  119549. }
  119550. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  119551. /*
  119552. ** If the most recently coded instruction is a constant range constraint
  119553. ** (a string literal) that originated from the LIKE optimization, then
  119554. ** set P3 and P5 on the OP_String opcode so that the string will be cast
  119555. ** to a BLOB at appropriate times.
  119556. **
  119557. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  119558. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  119559. ** scan loop run twice, once for strings and a second time for BLOBs.
  119560. ** The OP_String opcodes on the second pass convert the upper and lower
  119561. ** bound string constants to blobs. This routine makes the necessary changes
  119562. ** to the OP_String opcodes for that to happen.
  119563. **
  119564. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  119565. ** only the one pass through the string space is required, so this routine
  119566. ** becomes a no-op.
  119567. */
  119568. static void whereLikeOptimizationStringFixup(
  119569. Vdbe *v, /* prepared statement under construction */
  119570. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  119571. WhereTerm *pTerm /* The upper or lower bound just coded */
  119572. ){
  119573. if( pTerm->wtFlags & TERM_LIKEOPT ){
  119574. VdbeOp *pOp;
  119575. assert( pLevel->iLikeRepCntr>0 );
  119576. pOp = sqlite3VdbeGetOp(v, -1);
  119577. assert( pOp!=0 );
  119578. assert( pOp->opcode==OP_String8
  119579. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  119580. pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
  119581. pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
  119582. }
  119583. }
  119584. #else
  119585. # define whereLikeOptimizationStringFixup(A,B,C)
  119586. #endif
  119587. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  119588. /*
  119589. ** Information is passed from codeCursorHint() down to individual nodes of
  119590. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  119591. ** structure.
  119592. */
  119593. struct CCurHint {
  119594. int iTabCur; /* Cursor for the main table */
  119595. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  119596. Index *pIdx; /* The index used to access the table */
  119597. };
  119598. /*
  119599. ** This function is called for every node of an expression that is a candidate
  119600. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  119601. ** the table CCurHint.iTabCur, verify that the same column can be
  119602. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  119603. */
  119604. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  119605. struct CCurHint *pHint = pWalker->u.pCCurHint;
  119606. assert( pHint->pIdx!=0 );
  119607. if( pExpr->op==TK_COLUMN
  119608. && pExpr->iTable==pHint->iTabCur
  119609. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  119610. ){
  119611. pWalker->eCode = 1;
  119612. }
  119613. return WRC_Continue;
  119614. }
  119615. /*
  119616. ** Test whether or not expression pExpr, which was part of a WHERE clause,
  119617. ** should be included in the cursor-hint for a table that is on the rhs
  119618. ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
  119619. ** expression is not suitable.
  119620. **
  119621. ** An expression is unsuitable if it might evaluate to non NULL even if
  119622. ** a TK_COLUMN node that does affect the value of the expression is set
  119623. ** to NULL. For example:
  119624. **
  119625. ** col IS NULL
  119626. ** col IS NOT NULL
  119627. ** coalesce(col, 1)
  119628. ** CASE WHEN col THEN 0 ELSE 1 END
  119629. */
  119630. static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
  119631. if( pExpr->op==TK_IS
  119632. || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
  119633. || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
  119634. ){
  119635. pWalker->eCode = 1;
  119636. }else if( pExpr->op==TK_FUNCTION ){
  119637. int d1;
  119638. char d2[3];
  119639. if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
  119640. pWalker->eCode = 1;
  119641. }
  119642. }
  119643. return WRC_Continue;
  119644. }
  119645. /*
  119646. ** This function is called on every node of an expression tree used as an
  119647. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  119648. ** that accesses any table other than the one identified by
  119649. ** CCurHint.iTabCur, then do the following:
  119650. **
  119651. ** 1) allocate a register and code an OP_Column instruction to read
  119652. ** the specified column into the new register, and
  119653. **
  119654. ** 2) transform the expression node to a TK_REGISTER node that reads
  119655. ** from the newly populated register.
  119656. **
  119657. ** Also, if the node is a TK_COLUMN that does access the table idenified
  119658. ** by pCCurHint.iTabCur, and an index is being used (which we will
  119659. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  119660. ** an access of the index rather than the original table.
  119661. */
  119662. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  119663. int rc = WRC_Continue;
  119664. struct CCurHint *pHint = pWalker->u.pCCurHint;
  119665. if( pExpr->op==TK_COLUMN ){
  119666. if( pExpr->iTable!=pHint->iTabCur ){
  119667. Vdbe *v = pWalker->pParse->pVdbe;
  119668. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  119669. sqlite3ExprCodeGetColumnOfTable(
  119670. v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
  119671. );
  119672. pExpr->op = TK_REGISTER;
  119673. pExpr->iTable = reg;
  119674. }else if( pHint->pIdx!=0 ){
  119675. pExpr->iTable = pHint->iIdxCur;
  119676. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  119677. assert( pExpr->iColumn>=0 );
  119678. }
  119679. }else if( pExpr->op==TK_AGG_FUNCTION ){
  119680. /* An aggregate function in the WHERE clause of a query means this must
  119681. ** be a correlated sub-query, and expression pExpr is an aggregate from
  119682. ** the parent context. Do not walk the function arguments in this case.
  119683. **
  119684. ** todo: It should be possible to replace this node with a TK_REGISTER
  119685. ** expression, as the result of the expression must be stored in a
  119686. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  119687. rc = WRC_Prune;
  119688. }
  119689. return rc;
  119690. }
  119691. /*
  119692. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  119693. */
  119694. static void codeCursorHint(
  119695. struct SrcList_item *pTabItem, /* FROM clause item */
  119696. WhereInfo *pWInfo, /* The where clause */
  119697. WhereLevel *pLevel, /* Which loop to provide hints for */
  119698. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  119699. ){
  119700. Parse *pParse = pWInfo->pParse;
  119701. sqlite3 *db = pParse->db;
  119702. Vdbe *v = pParse->pVdbe;
  119703. Expr *pExpr = 0;
  119704. WhereLoop *pLoop = pLevel->pWLoop;
  119705. int iCur;
  119706. WhereClause *pWC;
  119707. WhereTerm *pTerm;
  119708. int i, j;
  119709. struct CCurHint sHint;
  119710. Walker sWalker;
  119711. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  119712. iCur = pLevel->iTabCur;
  119713. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  119714. sHint.iTabCur = iCur;
  119715. sHint.iIdxCur = pLevel->iIdxCur;
  119716. sHint.pIdx = pLoop->u.btree.pIndex;
  119717. memset(&sWalker, 0, sizeof(sWalker));
  119718. sWalker.pParse = pParse;
  119719. sWalker.u.pCCurHint = &sHint;
  119720. pWC = &pWInfo->sWC;
  119721. for(i=0; i<pWC->nTerm; i++){
  119722. pTerm = &pWC->a[i];
  119723. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  119724. if( pTerm->prereqAll & pLevel->notReady ) continue;
  119725. /* Any terms specified as part of the ON(...) clause for any LEFT
  119726. ** JOIN for which the current table is not the rhs are omitted
  119727. ** from the cursor-hint.
  119728. **
  119729. ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
  119730. ** that were specified as part of the WHERE clause must be excluded.
  119731. ** This is to address the following:
  119732. **
  119733. ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
  119734. **
  119735. ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
  119736. ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
  119737. ** pushed down to the cursor, this row is filtered out, causing
  119738. ** SQLite to synthesize a row of NULL values. Which does match the
  119739. ** WHERE clause, and so the query returns a row. Which is incorrect.
  119740. **
  119741. ** For the same reason, WHERE terms such as:
  119742. **
  119743. ** WHERE 1 = (t2.c IS NULL)
  119744. **
  119745. ** are also excluded. See codeCursorHintIsOrFunction() for details.
  119746. */
  119747. if( pTabItem->fg.jointype & JT_LEFT ){
  119748. Expr *pExpr = pTerm->pExpr;
  119749. if( !ExprHasProperty(pExpr, EP_FromJoin)
  119750. || pExpr->iRightJoinTable!=pTabItem->iCursor
  119751. ){
  119752. sWalker.eCode = 0;
  119753. sWalker.xExprCallback = codeCursorHintIsOrFunction;
  119754. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  119755. if( sWalker.eCode ) continue;
  119756. }
  119757. }else{
  119758. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  119759. }
  119760. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  119761. ** the cursor. These terms are not needed as hints for a pure range
  119762. ** scan (that has no == terms) so omit them. */
  119763. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  119764. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  119765. if( j<pLoop->nLTerm ) continue;
  119766. }
  119767. /* No subqueries or non-deterministic functions allowed */
  119768. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  119769. /* For an index scan, make sure referenced columns are actually in
  119770. ** the index. */
  119771. if( sHint.pIdx!=0 ){
  119772. sWalker.eCode = 0;
  119773. sWalker.xExprCallback = codeCursorHintCheckExpr;
  119774. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  119775. if( sWalker.eCode ) continue;
  119776. }
  119777. /* If we survive all prior tests, that means this term is worth hinting */
  119778. pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  119779. }
  119780. if( pExpr!=0 ){
  119781. sWalker.xExprCallback = codeCursorHintFixExpr;
  119782. sqlite3WalkExpr(&sWalker, pExpr);
  119783. sqlite3VdbeAddOp4(v, OP_CursorHint,
  119784. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  119785. (const char*)pExpr, P4_EXPR);
  119786. }
  119787. }
  119788. #else
  119789. # define codeCursorHint(A,B,C,D) /* No-op */
  119790. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  119791. /*
  119792. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  119793. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  119794. ** function generates code to do a deferred seek of cursor iCur to the
  119795. ** rowid stored in register iRowid.
  119796. **
  119797. ** Normally, this is just:
  119798. **
  119799. ** OP_Seek $iCur $iRowid
  119800. **
  119801. ** However, if the scan currently being coded is a branch of an OR-loop and
  119802. ** the statement currently being coded is a SELECT, then P3 of the OP_Seek
  119803. ** is set to iIdxCur and P4 is set to point to an array of integers
  119804. ** containing one entry for each column of the table cursor iCur is open
  119805. ** on. For each table column, if the column is the i'th column of the
  119806. ** index, then the corresponding array entry is set to (i+1). If the column
  119807. ** does not appear in the index at all, the array entry is set to 0.
  119808. */
  119809. static void codeDeferredSeek(
  119810. WhereInfo *pWInfo, /* Where clause context */
  119811. Index *pIdx, /* Index scan is using */
  119812. int iCur, /* Cursor for IPK b-tree */
  119813. int iIdxCur /* Index cursor */
  119814. ){
  119815. Parse *pParse = pWInfo->pParse; /* Parse context */
  119816. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  119817. assert( iIdxCur>0 );
  119818. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  119819. sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
  119820. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  119821. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  119822. ){
  119823. int i;
  119824. Table *pTab = pIdx->pTable;
  119825. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  119826. if( ai ){
  119827. ai[0] = pTab->nCol;
  119828. for(i=0; i<pIdx->nColumn-1; i++){
  119829. assert( pIdx->aiColumn[i]<pTab->nCol );
  119830. if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
  119831. }
  119832. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  119833. }
  119834. }
  119835. }
  119836. /*
  119837. ** If the expression passed as the second argument is a vector, generate
  119838. ** code to write the first nReg elements of the vector into an array
  119839. ** of registers starting with iReg.
  119840. **
  119841. ** If the expression is not a vector, then nReg must be passed 1. In
  119842. ** this case, generate code to evaluate the expression and leave the
  119843. ** result in register iReg.
  119844. */
  119845. static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
  119846. assert( nReg>0 );
  119847. if( sqlite3ExprIsVector(p) ){
  119848. #ifndef SQLITE_OMIT_SUBQUERY
  119849. if( (p->flags & EP_xIsSelect) ){
  119850. Vdbe *v = pParse->pVdbe;
  119851. int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
  119852. sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
  119853. }else
  119854. #endif
  119855. {
  119856. int i;
  119857. ExprList *pList = p->x.pList;
  119858. assert( nReg<=pList->nExpr );
  119859. for(i=0; i<nReg; i++){
  119860. sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
  119861. }
  119862. }
  119863. }else{
  119864. assert( nReg==1 );
  119865. sqlite3ExprCode(pParse, p, iReg);
  119866. }
  119867. }
  119868. /* An instance of the IdxExprTrans object carries information about a
  119869. ** mapping from an expression on table columns into a column in an index
  119870. ** down through the Walker.
  119871. */
  119872. typedef struct IdxExprTrans {
  119873. Expr *pIdxExpr; /* The index expression */
  119874. int iTabCur; /* The cursor of the corresponding table */
  119875. int iIdxCur; /* The cursor for the index */
  119876. int iIdxCol; /* The column for the index */
  119877. } IdxExprTrans;
  119878. /* The walker node callback used to transform matching expressions into
  119879. ** a reference to an index column for an index on an expression.
  119880. **
  119881. ** If pExpr matches, then transform it into a reference to the index column
  119882. ** that contains the value of pExpr.
  119883. */
  119884. static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
  119885. IdxExprTrans *pX = p->u.pIdxTrans;
  119886. if( sqlite3ExprCompare(pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
  119887. pExpr->op = TK_COLUMN;
  119888. pExpr->iTable = pX->iIdxCur;
  119889. pExpr->iColumn = pX->iIdxCol;
  119890. pExpr->pTab = 0;
  119891. return WRC_Prune;
  119892. }else{
  119893. return WRC_Continue;
  119894. }
  119895. }
  119896. /*
  119897. ** For an indexes on expression X, locate every instance of expression X in pExpr
  119898. ** and change that subexpression into a reference to the appropriate column of
  119899. ** the index.
  119900. */
  119901. static void whereIndexExprTrans(
  119902. Index *pIdx, /* The Index */
  119903. int iTabCur, /* Cursor of the table that is being indexed */
  119904. int iIdxCur, /* Cursor of the index itself */
  119905. WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
  119906. ){
  119907. int iIdxCol; /* Column number of the index */
  119908. ExprList *aColExpr; /* Expressions that are indexed */
  119909. Walker w;
  119910. IdxExprTrans x;
  119911. aColExpr = pIdx->aColExpr;
  119912. if( aColExpr==0 ) return; /* Not an index on expressions */
  119913. memset(&w, 0, sizeof(w));
  119914. w.xExprCallback = whereIndexExprTransNode;
  119915. w.u.pIdxTrans = &x;
  119916. x.iTabCur = iTabCur;
  119917. x.iIdxCur = iIdxCur;
  119918. for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
  119919. if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
  119920. assert( aColExpr->a[iIdxCol].pExpr!=0 );
  119921. x.iIdxCol = iIdxCol;
  119922. x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
  119923. sqlite3WalkExpr(&w, pWInfo->pWhere);
  119924. sqlite3WalkExprList(&w, pWInfo->pOrderBy);
  119925. sqlite3WalkExprList(&w, pWInfo->pResultSet);
  119926. }
  119927. }
  119928. /*
  119929. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  119930. ** implementation described by pWInfo.
  119931. */
  119932. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  119933. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  119934. int iLevel, /* Which level of pWInfo->a[] should be coded */
  119935. Bitmask notReady /* Which tables are currently available */
  119936. ){
  119937. int j, k; /* Loop counters */
  119938. int iCur; /* The VDBE cursor for the table */
  119939. int addrNxt; /* Where to jump to continue with the next IN case */
  119940. int omitTable; /* True if we use the index only */
  119941. int bRev; /* True if we need to scan in reverse order */
  119942. WhereLevel *pLevel; /* The where level to be coded */
  119943. WhereLoop *pLoop; /* The WhereLoop object being coded */
  119944. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  119945. WhereTerm *pTerm; /* A WHERE clause term */
  119946. Parse *pParse; /* Parsing context */
  119947. sqlite3 *db; /* Database connection */
  119948. Vdbe *v; /* The prepared stmt under constructions */
  119949. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  119950. int addrBrk; /* Jump here to break out of the loop */
  119951. int addrHalt; /* addrBrk for the outermost loop */
  119952. int addrCont; /* Jump here to continue with next cycle */
  119953. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  119954. int iReleaseReg = 0; /* Temp register to free before returning */
  119955. Index *pIdx = 0; /* Index used by loop (if any) */
  119956. int loopAgain; /* True if constraint generator loop should repeat */
  119957. pParse = pWInfo->pParse;
  119958. v = pParse->pVdbe;
  119959. pWC = &pWInfo->sWC;
  119960. db = pParse->db;
  119961. pLevel = &pWInfo->a[iLevel];
  119962. pLoop = pLevel->pWLoop;
  119963. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  119964. iCur = pTabItem->iCursor;
  119965. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  119966. bRev = (pWInfo->revMask>>iLevel)&1;
  119967. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  119968. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
  119969. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  119970. /* Create labels for the "break" and "continue" instructions
  119971. ** for the current loop. Jump to addrBrk to break out of a loop.
  119972. ** Jump to cont to go immediately to the next iteration of the
  119973. ** loop.
  119974. **
  119975. ** When there is an IN operator, we also have a "addrNxt" label that
  119976. ** means to continue with the next IN value combination. When
  119977. ** there are no IN operators in the constraints, the "addrNxt" label
  119978. ** is the same as "addrBrk".
  119979. */
  119980. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  119981. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  119982. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  119983. ** initialize a memory cell that records if this table matches any
  119984. ** row of the left table of the join.
  119985. */
  119986. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  119987. pLevel->iLeftJoin = ++pParse->nMem;
  119988. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  119989. VdbeComment((v, "init LEFT JOIN no-match flag"));
  119990. }
  119991. /* Compute a safe address to jump to if we discover that the table for
  119992. ** this loop is empty and can never contribute content. */
  119993. for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
  119994. addrHalt = pWInfo->a[j].addrBrk;
  119995. /* Special case of a FROM clause subquery implemented as a co-routine */
  119996. if( pTabItem->fg.viaCoroutine ){
  119997. int regYield = pTabItem->regReturn;
  119998. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  119999. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  120000. VdbeCoverage(v);
  120001. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  120002. pLevel->op = OP_Goto;
  120003. }else
  120004. #ifndef SQLITE_OMIT_VIRTUALTABLE
  120005. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  120006. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  120007. ** to access the data.
  120008. */
  120009. int iReg; /* P3 Value for OP_VFilter */
  120010. int addrNotFound;
  120011. int nConstraint = pLoop->nLTerm;
  120012. int iIn; /* Counter for IN constraints */
  120013. sqlite3ExprCachePush(pParse);
  120014. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  120015. addrNotFound = pLevel->addrBrk;
  120016. for(j=0; j<nConstraint; j++){
  120017. int iTarget = iReg+j+2;
  120018. pTerm = pLoop->aLTerm[j];
  120019. if( NEVER(pTerm==0) ) continue;
  120020. if( pTerm->eOperator & WO_IN ){
  120021. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  120022. addrNotFound = pLevel->addrNxt;
  120023. }else{
  120024. Expr *pRight = pTerm->pExpr->pRight;
  120025. codeExprOrVector(pParse, pRight, iTarget, 1);
  120026. }
  120027. }
  120028. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  120029. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  120030. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  120031. pLoop->u.vtab.idxStr,
  120032. pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
  120033. VdbeCoverage(v);
  120034. pLoop->u.vtab.needFree = 0;
  120035. pLevel->p1 = iCur;
  120036. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  120037. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  120038. iIn = pLevel->u.in.nIn;
  120039. for(j=nConstraint-1; j>=0; j--){
  120040. pTerm = pLoop->aLTerm[j];
  120041. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  120042. disableTerm(pLevel, pTerm);
  120043. }else if( (pTerm->eOperator & WO_IN)!=0 ){
  120044. Expr *pCompare; /* The comparison operator */
  120045. Expr *pRight; /* RHS of the comparison */
  120046. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  120047. /* Reload the constraint value into reg[iReg+j+2]. The same value
  120048. ** was loaded into the same register prior to the OP_VFilter, but
  120049. ** the xFilter implementation might have changed the datatype or
  120050. ** encoding of the value in the register, so it *must* be reloaded. */
  120051. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  120052. if( !db->mallocFailed ){
  120053. assert( iIn>0 );
  120054. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
  120055. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  120056. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  120057. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  120058. testcase( pOp->opcode==OP_Rowid );
  120059. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  120060. }
  120061. /* Generate code that will continue to the next row if
  120062. ** the IN constraint is not satisfied */
  120063. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
  120064. assert( pCompare!=0 || db->mallocFailed );
  120065. if( pCompare ){
  120066. pCompare->pLeft = pTerm->pExpr->pLeft;
  120067. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  120068. if( pRight ){
  120069. pRight->iTable = iReg+j+2;
  120070. sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
  120071. }
  120072. pCompare->pLeft = 0;
  120073. sqlite3ExprDelete(db, pCompare);
  120074. }
  120075. }
  120076. }
  120077. /* These registers need to be preserved in case there is an IN operator
  120078. ** loop. So we could deallocate the registers here (and potentially
  120079. ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
  120080. ** simpler and safer to simply not reuse the registers.
  120081. **
  120082. ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  120083. */
  120084. sqlite3ExprCachePop(pParse);
  120085. }else
  120086. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  120087. if( (pLoop->wsFlags & WHERE_IPK)!=0
  120088. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  120089. ){
  120090. /* Case 2: We can directly reference a single row using an
  120091. ** equality comparison against the ROWID field. Or
  120092. ** we reference multiple rows using a "rowid IN (...)"
  120093. ** construct.
  120094. */
  120095. assert( pLoop->u.btree.nEq==1 );
  120096. pTerm = pLoop->aLTerm[0];
  120097. assert( pTerm!=0 );
  120098. assert( pTerm->pExpr!=0 );
  120099. assert( omitTable==0 );
  120100. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  120101. iReleaseReg = ++pParse->nMem;
  120102. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  120103. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  120104. addrNxt = pLevel->addrNxt;
  120105. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
  120106. VdbeCoverage(v);
  120107. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  120108. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  120109. VdbeComment((v, "pk"));
  120110. pLevel->op = OP_Noop;
  120111. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  120112. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  120113. ){
  120114. /* Case 3: We have an inequality comparison against the ROWID field.
  120115. */
  120116. int testOp = OP_Noop;
  120117. int start;
  120118. int memEndValue = 0;
  120119. WhereTerm *pStart, *pEnd;
  120120. assert( omitTable==0 );
  120121. j = 0;
  120122. pStart = pEnd = 0;
  120123. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  120124. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  120125. assert( pStart!=0 || pEnd!=0 );
  120126. if( bRev ){
  120127. pTerm = pStart;
  120128. pStart = pEnd;
  120129. pEnd = pTerm;
  120130. }
  120131. codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
  120132. if( pStart ){
  120133. Expr *pX; /* The expression that defines the start bound */
  120134. int r1, rTemp; /* Registers for holding the start boundary */
  120135. int op; /* Cursor seek operation */
  120136. /* The following constant maps TK_xx codes into corresponding
  120137. ** seek opcodes. It depends on a particular ordering of TK_xx
  120138. */
  120139. const u8 aMoveOp[] = {
  120140. /* TK_GT */ OP_SeekGT,
  120141. /* TK_LE */ OP_SeekLE,
  120142. /* TK_LT */ OP_SeekLT,
  120143. /* TK_GE */ OP_SeekGE
  120144. };
  120145. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  120146. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  120147. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  120148. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  120149. testcase( pStart->wtFlags & TERM_VIRTUAL );
  120150. pX = pStart->pExpr;
  120151. assert( pX!=0 );
  120152. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  120153. if( sqlite3ExprIsVector(pX->pRight) ){
  120154. r1 = rTemp = sqlite3GetTempReg(pParse);
  120155. codeExprOrVector(pParse, pX->pRight, r1, 1);
  120156. op = aMoveOp[(pX->op - TK_GT) | 0x0001];
  120157. }else{
  120158. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  120159. disableTerm(pLevel, pStart);
  120160. op = aMoveOp[(pX->op - TK_GT)];
  120161. }
  120162. sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
  120163. VdbeComment((v, "pk"));
  120164. VdbeCoverageIf(v, pX->op==TK_GT);
  120165. VdbeCoverageIf(v, pX->op==TK_LE);
  120166. VdbeCoverageIf(v, pX->op==TK_LT);
  120167. VdbeCoverageIf(v, pX->op==TK_GE);
  120168. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  120169. sqlite3ReleaseTempReg(pParse, rTemp);
  120170. }else{
  120171. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
  120172. VdbeCoverageIf(v, bRev==0);
  120173. VdbeCoverageIf(v, bRev!=0);
  120174. }
  120175. if( pEnd ){
  120176. Expr *pX;
  120177. pX = pEnd->pExpr;
  120178. assert( pX!=0 );
  120179. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  120180. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  120181. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  120182. memEndValue = ++pParse->nMem;
  120183. codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
  120184. if( 0==sqlite3ExprIsVector(pX->pRight)
  120185. && (pX->op==TK_LT || pX->op==TK_GT)
  120186. ){
  120187. testOp = bRev ? OP_Le : OP_Ge;
  120188. }else{
  120189. testOp = bRev ? OP_Lt : OP_Gt;
  120190. }
  120191. if( 0==sqlite3ExprIsVector(pX->pRight) ){
  120192. disableTerm(pLevel, pEnd);
  120193. }
  120194. }
  120195. start = sqlite3VdbeCurrentAddr(v);
  120196. pLevel->op = bRev ? OP_Prev : OP_Next;
  120197. pLevel->p1 = iCur;
  120198. pLevel->p2 = start;
  120199. assert( pLevel->p5==0 );
  120200. if( testOp!=OP_Noop ){
  120201. iRowidReg = ++pParse->nMem;
  120202. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  120203. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  120204. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  120205. VdbeCoverageIf(v, testOp==OP_Le);
  120206. VdbeCoverageIf(v, testOp==OP_Lt);
  120207. VdbeCoverageIf(v, testOp==OP_Ge);
  120208. VdbeCoverageIf(v, testOp==OP_Gt);
  120209. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  120210. }
  120211. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  120212. /* Case 4: A scan using an index.
  120213. **
  120214. ** The WHERE clause may contain zero or more equality
  120215. ** terms ("==" or "IN" operators) that refer to the N
  120216. ** left-most columns of the index. It may also contain
  120217. ** inequality constraints (>, <, >= or <=) on the indexed
  120218. ** column that immediately follows the N equalities. Only
  120219. ** the right-most column can be an inequality - the rest must
  120220. ** use the "==" and "IN" operators. For example, if the
  120221. ** index is on (x,y,z), then the following clauses are all
  120222. ** optimized:
  120223. **
  120224. ** x=5
  120225. ** x=5 AND y=10
  120226. ** x=5 AND y<10
  120227. ** x=5 AND y>5 AND y<10
  120228. ** x=5 AND y=5 AND z<=10
  120229. **
  120230. ** The z<10 term of the following cannot be used, only
  120231. ** the x=5 term:
  120232. **
  120233. ** x=5 AND z<10
  120234. **
  120235. ** N may be zero if there are inequality constraints.
  120236. ** If there are no inequality constraints, then N is at
  120237. ** least one.
  120238. **
  120239. ** This case is also used when there are no WHERE clause
  120240. ** constraints but an index is selected anyway, in order
  120241. ** to force the output order to conform to an ORDER BY.
  120242. */
  120243. static const u8 aStartOp[] = {
  120244. 0,
  120245. 0,
  120246. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  120247. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  120248. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  120249. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  120250. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  120251. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  120252. };
  120253. static const u8 aEndOp[] = {
  120254. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  120255. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  120256. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  120257. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  120258. };
  120259. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  120260. u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
  120261. u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
  120262. int regBase; /* Base register holding constraint values */
  120263. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  120264. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  120265. int startEq; /* True if range start uses ==, >= or <= */
  120266. int endEq; /* True if range end uses ==, >= or <= */
  120267. int start_constraints; /* Start of range is constrained */
  120268. int nConstraint; /* Number of constraint terms */
  120269. int iIdxCur; /* The VDBE cursor for the index */
  120270. int nExtraReg = 0; /* Number of extra registers needed */
  120271. int op; /* Instruction opcode */
  120272. char *zStartAff; /* Affinity for start of range constraint */
  120273. char *zEndAff = 0; /* Affinity for end of range constraint */
  120274. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  120275. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  120276. pIdx = pLoop->u.btree.pIndex;
  120277. iIdxCur = pLevel->iIdxCur;
  120278. assert( nEq>=pLoop->nSkip );
  120279. /* If this loop satisfies a sort order (pOrderBy) request that
  120280. ** was passed to this function to implement a "SELECT min(x) ..."
  120281. ** query, then the caller will only allow the loop to run for
  120282. ** a single iteration. This means that the first row returned
  120283. ** should not have a NULL value stored in 'x'. If column 'x' is
  120284. ** the first one after the nEq equality constraints in the index,
  120285. ** this requires some special handling.
  120286. */
  120287. assert( pWInfo->pOrderBy==0
  120288. || pWInfo->pOrderBy->nExpr==1
  120289. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  120290. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  120291. && pWInfo->nOBSat>0
  120292. && (pIdx->nKeyCol>nEq)
  120293. ){
  120294. assert( pLoop->nSkip==0 );
  120295. bSeekPastNull = 1;
  120296. nExtraReg = 1;
  120297. }
  120298. /* Find any inequality constraint terms for the start and end
  120299. ** of the range.
  120300. */
  120301. j = nEq;
  120302. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  120303. pRangeStart = pLoop->aLTerm[j++];
  120304. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
  120305. /* Like optimization range constraints always occur in pairs */
  120306. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  120307. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  120308. }
  120309. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  120310. pRangeEnd = pLoop->aLTerm[j++];
  120311. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
  120312. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  120313. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  120314. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  120315. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  120316. pLevel->iLikeRepCntr = (u32)++pParse->nMem;
  120317. sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
  120318. VdbeComment((v, "LIKE loop counter"));
  120319. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  120320. /* iLikeRepCntr actually stores 2x the counter register number. The
  120321. ** bottom bit indicates whether the search order is ASC or DESC. */
  120322. testcase( bRev );
  120323. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  120324. assert( (bRev & ~1)==0 );
  120325. pLevel->iLikeRepCntr <<=1;
  120326. pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
  120327. }
  120328. #endif
  120329. if( pRangeStart==0 ){
  120330. j = pIdx->aiColumn[nEq];
  120331. if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
  120332. bSeekPastNull = 1;
  120333. }
  120334. }
  120335. }
  120336. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  120337. /* If we are doing a reverse order scan on an ascending index, or
  120338. ** a forward order scan on a descending index, interchange the
  120339. ** start and end terms (pRangeStart and pRangeEnd).
  120340. */
  120341. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  120342. || (bRev && pIdx->nKeyCol==nEq)
  120343. ){
  120344. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  120345. SWAP(u8, bSeekPastNull, bStopAtNull);
  120346. SWAP(u8, nBtm, nTop);
  120347. }
  120348. /* Generate code to evaluate all constraint terms using == or IN
  120349. ** and store the values of those terms in an array of registers
  120350. ** starting at regBase.
  120351. */
  120352. codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
  120353. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  120354. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  120355. if( zStartAff && nTop ){
  120356. zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
  120357. }
  120358. addrNxt = pLevel->addrNxt;
  120359. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  120360. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  120361. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  120362. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  120363. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  120364. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  120365. start_constraints = pRangeStart || nEq>0;
  120366. /* Seek the index cursor to the start of the range. */
  120367. nConstraint = nEq;
  120368. if( pRangeStart ){
  120369. Expr *pRight = pRangeStart->pExpr->pRight;
  120370. codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
  120371. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  120372. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  120373. && sqlite3ExprCanBeNull(pRight)
  120374. ){
  120375. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  120376. VdbeCoverage(v);
  120377. }
  120378. if( zStartAff ){
  120379. updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
  120380. }
  120381. nConstraint += nBtm;
  120382. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  120383. if( sqlite3ExprIsVector(pRight)==0 ){
  120384. disableTerm(pLevel, pRangeStart);
  120385. }else{
  120386. startEq = 1;
  120387. }
  120388. bSeekPastNull = 0;
  120389. }else if( bSeekPastNull ){
  120390. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  120391. nConstraint++;
  120392. startEq = 0;
  120393. start_constraints = 1;
  120394. }
  120395. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  120396. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  120397. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  120398. ** above has already left the cursor sitting on the correct row,
  120399. ** so no further seeking is needed */
  120400. }else{
  120401. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  120402. assert( op!=0 );
  120403. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  120404. VdbeCoverage(v);
  120405. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  120406. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  120407. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  120408. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  120409. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  120410. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  120411. }
  120412. /* Load the value for the inequality constraint at the end of the
  120413. ** range (if any).
  120414. */
  120415. nConstraint = nEq;
  120416. if( pRangeEnd ){
  120417. Expr *pRight = pRangeEnd->pExpr->pRight;
  120418. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  120419. codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
  120420. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  120421. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  120422. && sqlite3ExprCanBeNull(pRight)
  120423. ){
  120424. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  120425. VdbeCoverage(v);
  120426. }
  120427. if( zEndAff ){
  120428. updateRangeAffinityStr(pRight, nTop, zEndAff);
  120429. codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
  120430. }else{
  120431. assert( pParse->db->mallocFailed );
  120432. }
  120433. nConstraint += nTop;
  120434. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  120435. if( sqlite3ExprIsVector(pRight)==0 ){
  120436. disableTerm(pLevel, pRangeEnd);
  120437. }else{
  120438. endEq = 1;
  120439. }
  120440. }else if( bStopAtNull ){
  120441. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  120442. endEq = 0;
  120443. nConstraint++;
  120444. }
  120445. sqlite3DbFree(db, zStartAff);
  120446. sqlite3DbFree(db, zEndAff);
  120447. /* Top of the loop body */
  120448. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  120449. /* Check if the index cursor is past the end of the range. */
  120450. if( nConstraint ){
  120451. op = aEndOp[bRev*2 + endEq];
  120452. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  120453. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  120454. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  120455. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  120456. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  120457. }
  120458. /* Seek the table cursor, if required */
  120459. if( omitTable ){
  120460. /* pIdx is a covering index. No need to access the main table. */
  120461. }else if( HasRowid(pIdx->pTable) ){
  120462. if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
  120463. (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
  120464. && (pWInfo->eOnePass==ONEPASS_SINGLE)
  120465. )){
  120466. iRowidReg = ++pParse->nMem;
  120467. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  120468. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  120469. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  120470. VdbeCoverage(v);
  120471. }else{
  120472. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  120473. }
  120474. }else if( iCur!=iIdxCur ){
  120475. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  120476. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  120477. for(j=0; j<pPk->nKeyCol; j++){
  120478. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  120479. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  120480. }
  120481. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  120482. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  120483. }
  120484. /* If pIdx is an index on one or more expressions, then look through
  120485. ** all the expressions in pWInfo and try to transform matching expressions
  120486. ** into reference to index columns.
  120487. */
  120488. whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
  120489. /* Record the instruction used to terminate the loop. */
  120490. if( pLoop->wsFlags & WHERE_ONEROW ){
  120491. pLevel->op = OP_Noop;
  120492. }else if( bRev ){
  120493. pLevel->op = OP_Prev;
  120494. }else{
  120495. pLevel->op = OP_Next;
  120496. }
  120497. pLevel->p1 = iIdxCur;
  120498. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  120499. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  120500. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  120501. }else{
  120502. assert( pLevel->p5==0 );
  120503. }
  120504. if( omitTable ) pIdx = 0;
  120505. }else
  120506. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  120507. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  120508. /* Case 5: Two or more separately indexed terms connected by OR
  120509. **
  120510. ** Example:
  120511. **
  120512. ** CREATE TABLE t1(a,b,c,d);
  120513. ** CREATE INDEX i1 ON t1(a);
  120514. ** CREATE INDEX i2 ON t1(b);
  120515. ** CREATE INDEX i3 ON t1(c);
  120516. **
  120517. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  120518. **
  120519. ** In the example, there are three indexed terms connected by OR.
  120520. ** The top of the loop looks like this:
  120521. **
  120522. ** Null 1 # Zero the rowset in reg 1
  120523. **
  120524. ** Then, for each indexed term, the following. The arguments to
  120525. ** RowSetTest are such that the rowid of the current row is inserted
  120526. ** into the RowSet. If it is already present, control skips the
  120527. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  120528. **
  120529. ** sqlite3WhereBegin(<term>)
  120530. ** RowSetTest # Insert rowid into rowset
  120531. ** Gosub 2 A
  120532. ** sqlite3WhereEnd()
  120533. **
  120534. ** Following the above, code to terminate the loop. Label A, the target
  120535. ** of the Gosub above, jumps to the instruction right after the Goto.
  120536. **
  120537. ** Null 1 # Zero the rowset in reg 1
  120538. ** Goto B # The loop is finished.
  120539. **
  120540. ** A: <loop body> # Return data, whatever.
  120541. **
  120542. ** Return 2 # Jump back to the Gosub
  120543. **
  120544. ** B: <after the loop>
  120545. **
  120546. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  120547. ** use an ephemeral index instead of a RowSet to record the primary
  120548. ** keys of the rows we have already seen.
  120549. **
  120550. */
  120551. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  120552. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  120553. Index *pCov = 0; /* Potential covering index (or NULL) */
  120554. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  120555. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  120556. int regRowset = 0; /* Register for RowSet object */
  120557. int regRowid = 0; /* Register holding rowid */
  120558. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  120559. int iRetInit; /* Address of regReturn init */
  120560. int untestedTerms = 0; /* Some terms not completely tested */
  120561. int ii; /* Loop counter */
  120562. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  120563. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  120564. Table *pTab = pTabItem->pTab;
  120565. pTerm = pLoop->aLTerm[0];
  120566. assert( pTerm!=0 );
  120567. assert( pTerm->eOperator & WO_OR );
  120568. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  120569. pOrWc = &pTerm->u.pOrInfo->wc;
  120570. pLevel->op = OP_Return;
  120571. pLevel->p1 = regReturn;
  120572. /* Set up a new SrcList in pOrTab containing the table being scanned
  120573. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  120574. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  120575. */
  120576. if( pWInfo->nLevel>1 ){
  120577. int nNotReady; /* The number of notReady tables */
  120578. struct SrcList_item *origSrc; /* Original list of tables */
  120579. nNotReady = pWInfo->nLevel - iLevel - 1;
  120580. pOrTab = sqlite3StackAllocRaw(db,
  120581. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  120582. if( pOrTab==0 ) return notReady;
  120583. pOrTab->nAlloc = (u8)(nNotReady + 1);
  120584. pOrTab->nSrc = pOrTab->nAlloc;
  120585. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  120586. origSrc = pWInfo->pTabList->a;
  120587. for(k=1; k<=nNotReady; k++){
  120588. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  120589. }
  120590. }else{
  120591. pOrTab = pWInfo->pTabList;
  120592. }
  120593. /* Initialize the rowset register to contain NULL. An SQL NULL is
  120594. ** equivalent to an empty rowset. Or, create an ephemeral index
  120595. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  120596. **
  120597. ** Also initialize regReturn to contain the address of the instruction
  120598. ** immediately following the OP_Return at the bottom of the loop. This
  120599. ** is required in a few obscure LEFT JOIN cases where control jumps
  120600. ** over the top of the loop into the body of it. In this case the
  120601. ** correct response for the end-of-loop code (the OP_Return) is to
  120602. ** fall through to the next instruction, just as an OP_Next does if
  120603. ** called on an uninitialized cursor.
  120604. */
  120605. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  120606. if( HasRowid(pTab) ){
  120607. regRowset = ++pParse->nMem;
  120608. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  120609. }else{
  120610. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  120611. regRowset = pParse->nTab++;
  120612. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  120613. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  120614. }
  120615. regRowid = ++pParse->nMem;
  120616. }
  120617. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  120618. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  120619. ** Then for every term xN, evaluate as the subexpression: xN AND z
  120620. ** That way, terms in y that are factored into the disjunction will
  120621. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  120622. **
  120623. ** Actually, each subexpression is converted to "xN AND w" where w is
  120624. ** the "interesting" terms of z - terms that did not originate in the
  120625. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  120626. ** indices.
  120627. **
  120628. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  120629. ** is not contained in the ON clause of a LEFT JOIN.
  120630. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  120631. */
  120632. if( pWC->nTerm>1 ){
  120633. int iTerm;
  120634. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  120635. Expr *pExpr = pWC->a[iTerm].pExpr;
  120636. if( &pWC->a[iTerm] == pTerm ) continue;
  120637. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  120638. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  120639. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  120640. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  120641. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  120642. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  120643. pExpr = sqlite3ExprDup(db, pExpr, 0);
  120644. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  120645. }
  120646. if( pAndExpr ){
  120647. pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
  120648. }
  120649. }
  120650. /* Run a separate WHERE clause for each term of the OR clause. After
  120651. ** eliminating duplicates from other WHERE clauses, the action for each
  120652. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  120653. */
  120654. wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
  120655. for(ii=0; ii<pOrWc->nTerm; ii++){
  120656. WhereTerm *pOrTerm = &pOrWc->a[ii];
  120657. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  120658. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  120659. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  120660. int jmp1 = 0; /* Address of jump operation */
  120661. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  120662. pAndExpr->pLeft = pOrExpr;
  120663. pOrExpr = pAndExpr;
  120664. }
  120665. /* Loop through table entries that match term pOrTerm. */
  120666. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  120667. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  120668. wctrlFlags, iCovCur);
  120669. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  120670. if( pSubWInfo ){
  120671. WhereLoop *pSubLoop;
  120672. int addrExplain = sqlite3WhereExplainOneScan(
  120673. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  120674. );
  120675. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  120676. /* This is the sub-WHERE clause body. First skip over
  120677. ** duplicate rows from prior sub-WHERE clauses, and record the
  120678. ** rowid (or PRIMARY KEY) for the current row so that the same
  120679. ** row will be skipped in subsequent sub-WHERE clauses.
  120680. */
  120681. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  120682. int r;
  120683. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  120684. if( HasRowid(pTab) ){
  120685. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  120686. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  120687. r,iSet);
  120688. VdbeCoverage(v);
  120689. }else{
  120690. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  120691. int nPk = pPk->nKeyCol;
  120692. int iPk;
  120693. /* Read the PK into an array of temp registers. */
  120694. r = sqlite3GetTempRange(pParse, nPk);
  120695. for(iPk=0; iPk<nPk; iPk++){
  120696. int iCol = pPk->aiColumn[iPk];
  120697. sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
  120698. }
  120699. /* Check if the temp table already contains this key. If so,
  120700. ** the row has already been included in the result set and
  120701. ** can be ignored (by jumping past the Gosub below). Otherwise,
  120702. ** insert the key into the temp table and proceed with processing
  120703. ** the row.
  120704. **
  120705. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  120706. ** is zero, assume that the key cannot already be present in
  120707. ** the temp table. And if iSet is -1, assume that there is no
  120708. ** need to insert the key into the temp table, as it will never
  120709. ** be tested for. */
  120710. if( iSet ){
  120711. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  120712. VdbeCoverage(v);
  120713. }
  120714. if( iSet>=0 ){
  120715. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  120716. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
  120717. r, nPk);
  120718. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  120719. }
  120720. /* Release the array of temp registers */
  120721. sqlite3ReleaseTempRange(pParse, r, nPk);
  120722. }
  120723. }
  120724. /* Invoke the main loop body as a subroutine */
  120725. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  120726. /* Jump here (skipping the main loop body subroutine) if the
  120727. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  120728. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  120729. /* The pSubWInfo->untestedTerms flag means that this OR term
  120730. ** contained one or more AND term from a notReady table. The
  120731. ** terms from the notReady table could not be tested and will
  120732. ** need to be tested later.
  120733. */
  120734. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  120735. /* If all of the OR-connected terms are optimized using the same
  120736. ** index, and the index is opened using the same cursor number
  120737. ** by each call to sqlite3WhereBegin() made by this loop, it may
  120738. ** be possible to use that index as a covering index.
  120739. **
  120740. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  120741. ** uses an index, and this is either the first OR-connected term
  120742. ** processed or the index is the same as that used by all previous
  120743. ** terms, set pCov to the candidate covering index. Otherwise, set
  120744. ** pCov to NULL to indicate that no candidate covering index will
  120745. ** be available.
  120746. */
  120747. pSubLoop = pSubWInfo->a[0].pWLoop;
  120748. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  120749. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  120750. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  120751. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  120752. ){
  120753. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  120754. pCov = pSubLoop->u.btree.pIndex;
  120755. }else{
  120756. pCov = 0;
  120757. }
  120758. /* Finish the loop through table entries that match term pOrTerm. */
  120759. sqlite3WhereEnd(pSubWInfo);
  120760. }
  120761. }
  120762. }
  120763. pLevel->u.pCovidx = pCov;
  120764. if( pCov ) pLevel->iIdxCur = iCovCur;
  120765. if( pAndExpr ){
  120766. pAndExpr->pLeft = 0;
  120767. sqlite3ExprDelete(db, pAndExpr);
  120768. }
  120769. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  120770. sqlite3VdbeGoto(v, pLevel->addrBrk);
  120771. sqlite3VdbeResolveLabel(v, iLoopBody);
  120772. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  120773. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  120774. }else
  120775. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  120776. {
  120777. /* Case 6: There is no usable index. We must do a complete
  120778. ** scan of the entire table.
  120779. */
  120780. static const u8 aStep[] = { OP_Next, OP_Prev };
  120781. static const u8 aStart[] = { OP_Rewind, OP_Last };
  120782. assert( bRev==0 || bRev==1 );
  120783. if( pTabItem->fg.isRecursive ){
  120784. /* Tables marked isRecursive have only a single row that is stored in
  120785. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  120786. pLevel->op = OP_Noop;
  120787. }else{
  120788. codeCursorHint(pTabItem, pWInfo, pLevel, 0);
  120789. pLevel->op = aStep[bRev];
  120790. pLevel->p1 = iCur;
  120791. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
  120792. VdbeCoverageIf(v, bRev==0);
  120793. VdbeCoverageIf(v, bRev!=0);
  120794. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  120795. }
  120796. }
  120797. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  120798. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  120799. #endif
  120800. /* Insert code to test every subexpression that can be completely
  120801. ** computed using the current set of tables.
  120802. **
  120803. ** This loop may run either once (pIdx==0) or twice (pIdx!=0). If
  120804. ** it is run twice, then the first iteration codes those sub-expressions
  120805. ** that can be computed using columns from pIdx only (without seeking
  120806. ** the main table cursor).
  120807. */
  120808. do{
  120809. loopAgain = 0;
  120810. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  120811. Expr *pE;
  120812. int skipLikeAddr = 0;
  120813. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  120814. testcase( pTerm->wtFlags & TERM_CODED );
  120815. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  120816. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  120817. testcase( pWInfo->untestedTerms==0
  120818. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
  120819. pWInfo->untestedTerms = 1;
  120820. continue;
  120821. }
  120822. pE = pTerm->pExpr;
  120823. assert( pE!=0 );
  120824. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  120825. continue;
  120826. }
  120827. if( pIdx && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
  120828. loopAgain = 1;
  120829. continue;
  120830. }
  120831. if( pTerm->wtFlags & TERM_LIKECOND ){
  120832. /* If the TERM_LIKECOND flag is set, that means that the range search
  120833. ** is sufficient to guarantee that the LIKE operator is true, so we
  120834. ** can skip the call to the like(A,B) function. But this only works
  120835. ** for strings. So do not skip the call to the function on the pass
  120836. ** that compares BLOBs. */
  120837. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  120838. continue;
  120839. #else
  120840. u32 x = pLevel->iLikeRepCntr;
  120841. assert( x>0 );
  120842. skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If, (int)(x>>1));
  120843. VdbeCoverage(v);
  120844. #endif
  120845. }
  120846. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  120847. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  120848. pTerm->wtFlags |= TERM_CODED;
  120849. }
  120850. pIdx = 0;
  120851. }while( loopAgain );
  120852. /* Insert code to test for implied constraints based on transitivity
  120853. ** of the "==" operator.
  120854. **
  120855. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  120856. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  120857. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  120858. ** the implied "t1.a=123" constraint.
  120859. */
  120860. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  120861. Expr *pE, sEAlt;
  120862. WhereTerm *pAlt;
  120863. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  120864. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  120865. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  120866. if( pTerm->leftCursor!=iCur ) continue;
  120867. if( pLevel->iLeftJoin ) continue;
  120868. pE = pTerm->pExpr;
  120869. assert( !ExprHasProperty(pE, EP_FromJoin) );
  120870. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  120871. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  120872. WO_EQ|WO_IN|WO_IS, 0);
  120873. if( pAlt==0 ) continue;
  120874. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  120875. testcase( pAlt->eOperator & WO_EQ );
  120876. testcase( pAlt->eOperator & WO_IS );
  120877. testcase( pAlt->eOperator & WO_IN );
  120878. VdbeModuleComment((v, "begin transitive constraint"));
  120879. sEAlt = *pAlt->pExpr;
  120880. sEAlt.pLeft = pE->pLeft;
  120881. sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
  120882. }
  120883. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  120884. ** at least one row of the right table has matched the left table.
  120885. */
  120886. if( pLevel->iLeftJoin ){
  120887. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  120888. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  120889. VdbeComment((v, "record LEFT JOIN hit"));
  120890. sqlite3ExprCacheClear(pParse);
  120891. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  120892. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  120893. testcase( pTerm->wtFlags & TERM_CODED );
  120894. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  120895. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  120896. assert( pWInfo->untestedTerms );
  120897. continue;
  120898. }
  120899. assert( pTerm->pExpr );
  120900. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  120901. pTerm->wtFlags |= TERM_CODED;
  120902. }
  120903. }
  120904. return pLevel->notReady;
  120905. }
  120906. /************** End of wherecode.c *******************************************/
  120907. /************** Begin file whereexpr.c ***************************************/
  120908. /*
  120909. ** 2015-06-08
  120910. **
  120911. ** The author disclaims copyright to this source code. In place of
  120912. ** a legal notice, here is a blessing:
  120913. **
  120914. ** May you do good and not evil.
  120915. ** May you find forgiveness for yourself and forgive others.
  120916. ** May you share freely, never taking more than you give.
  120917. **
  120918. *************************************************************************
  120919. ** This module contains C code that generates VDBE code used to process
  120920. ** the WHERE clause of SQL statements.
  120921. **
  120922. ** This file was originally part of where.c but was split out to improve
  120923. ** readability and editabiliity. This file contains utility routines for
  120924. ** analyzing Expr objects in the WHERE clause.
  120925. */
  120926. /* #include "sqliteInt.h" */
  120927. /* #include "whereInt.h" */
  120928. /* Forward declarations */
  120929. static void exprAnalyze(SrcList*, WhereClause*, int);
  120930. /*
  120931. ** Deallocate all memory associated with a WhereOrInfo object.
  120932. */
  120933. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  120934. sqlite3WhereClauseClear(&p->wc);
  120935. sqlite3DbFree(db, p);
  120936. }
  120937. /*
  120938. ** Deallocate all memory associated with a WhereAndInfo object.
  120939. */
  120940. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  120941. sqlite3WhereClauseClear(&p->wc);
  120942. sqlite3DbFree(db, p);
  120943. }
  120944. /*
  120945. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  120946. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  120947. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  120948. ** 0 is returned if the new WhereTerm could not be added due to a memory
  120949. ** allocation error. The memory allocation failure will be recorded in
  120950. ** the db->mallocFailed flag so that higher-level functions can detect it.
  120951. **
  120952. ** This routine will increase the size of the pWC->a[] array as necessary.
  120953. **
  120954. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  120955. ** for freeing the expression p is assumed by the WhereClause object pWC.
  120956. ** This is true even if this routine fails to allocate a new WhereTerm.
  120957. **
  120958. ** WARNING: This routine might reallocate the space used to store
  120959. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  120960. ** calling this routine. Such pointers may be reinitialized by referencing
  120961. ** the pWC->a[] array.
  120962. */
  120963. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  120964. WhereTerm *pTerm;
  120965. int idx;
  120966. testcase( wtFlags & TERM_VIRTUAL );
  120967. if( pWC->nTerm>=pWC->nSlot ){
  120968. WhereTerm *pOld = pWC->a;
  120969. sqlite3 *db = pWC->pWInfo->pParse->db;
  120970. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  120971. if( pWC->a==0 ){
  120972. if( wtFlags & TERM_DYNAMIC ){
  120973. sqlite3ExprDelete(db, p);
  120974. }
  120975. pWC->a = pOld;
  120976. return 0;
  120977. }
  120978. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  120979. if( pOld!=pWC->aStatic ){
  120980. sqlite3DbFree(db, pOld);
  120981. }
  120982. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  120983. }
  120984. pTerm = &pWC->a[idx = pWC->nTerm++];
  120985. if( p && ExprHasProperty(p, EP_Unlikely) ){
  120986. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  120987. }else{
  120988. pTerm->truthProb = 1;
  120989. }
  120990. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  120991. pTerm->wtFlags = wtFlags;
  120992. pTerm->pWC = pWC;
  120993. pTerm->iParent = -1;
  120994. memset(&pTerm->eOperator, 0,
  120995. sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
  120996. return idx;
  120997. }
  120998. /*
  120999. ** Return TRUE if the given operator is one of the operators that is
  121000. ** allowed for an indexable WHERE clause term. The allowed operators are
  121001. ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
  121002. */
  121003. static int allowedOp(int op){
  121004. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  121005. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  121006. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  121007. assert( TK_GE==TK_EQ+4 );
  121008. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  121009. }
  121010. /*
  121011. ** Commute a comparison operator. Expressions of the form "X op Y"
  121012. ** are converted into "Y op X".
  121013. **
  121014. ** If left/right precedence rules come into play when determining the
  121015. ** collating sequence, then COLLATE operators are adjusted to ensure
  121016. ** that the collating sequence does not change. For example:
  121017. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  121018. ** the left hand side of a comparison overrides any collation sequence
  121019. ** attached to the right. For the same reason the EP_Collate flag
  121020. ** is not commuted.
  121021. */
  121022. static void exprCommute(Parse *pParse, Expr *pExpr){
  121023. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  121024. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  121025. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  121026. if( expRight==expLeft ){
  121027. /* Either X and Y both have COLLATE operator or neither do */
  121028. if( expRight ){
  121029. /* Both X and Y have COLLATE operators. Make sure X is always
  121030. ** used by clearing the EP_Collate flag from Y. */
  121031. pExpr->pRight->flags &= ~EP_Collate;
  121032. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  121033. /* Neither X nor Y have COLLATE operators, but X has a non-default
  121034. ** collating sequence. So add the EP_Collate marker on X to cause
  121035. ** it to be searched first. */
  121036. pExpr->pLeft->flags |= EP_Collate;
  121037. }
  121038. }
  121039. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  121040. if( pExpr->op>=TK_GT ){
  121041. assert( TK_LT==TK_GT+2 );
  121042. assert( TK_GE==TK_LE+2 );
  121043. assert( TK_GT>TK_EQ );
  121044. assert( TK_GT<TK_LE );
  121045. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  121046. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  121047. }
  121048. }
  121049. /*
  121050. ** Translate from TK_xx operator to WO_xx bitmask.
  121051. */
  121052. static u16 operatorMask(int op){
  121053. u16 c;
  121054. assert( allowedOp(op) );
  121055. if( op==TK_IN ){
  121056. c = WO_IN;
  121057. }else if( op==TK_ISNULL ){
  121058. c = WO_ISNULL;
  121059. }else if( op==TK_IS ){
  121060. c = WO_IS;
  121061. }else{
  121062. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  121063. c = (u16)(WO_EQ<<(op-TK_EQ));
  121064. }
  121065. assert( op!=TK_ISNULL || c==WO_ISNULL );
  121066. assert( op!=TK_IN || c==WO_IN );
  121067. assert( op!=TK_EQ || c==WO_EQ );
  121068. assert( op!=TK_LT || c==WO_LT );
  121069. assert( op!=TK_LE || c==WO_LE );
  121070. assert( op!=TK_GT || c==WO_GT );
  121071. assert( op!=TK_GE || c==WO_GE );
  121072. assert( op!=TK_IS || c==WO_IS );
  121073. return c;
  121074. }
  121075. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  121076. /*
  121077. ** Check to see if the given expression is a LIKE or GLOB operator that
  121078. ** can be optimized using inequality constraints. Return TRUE if it is
  121079. ** so and false if not.
  121080. **
  121081. ** In order for the operator to be optimizible, the RHS must be a string
  121082. ** literal that does not begin with a wildcard. The LHS must be a column
  121083. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  121084. ** that virtual tables cannot participate in the LIKE optimization.) The
  121085. ** collating sequence for the column on the LHS must be appropriate for
  121086. ** the operator.
  121087. */
  121088. static int isLikeOrGlob(
  121089. Parse *pParse, /* Parsing and code generating context */
  121090. Expr *pExpr, /* Test this expression */
  121091. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  121092. int *pisComplete, /* True if the only wildcard is % in the last character */
  121093. int *pnoCase /* True if uppercase is equivalent to lowercase */
  121094. ){
  121095. const char *z = 0; /* String on RHS of LIKE operator */
  121096. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  121097. ExprList *pList; /* List of operands to the LIKE operator */
  121098. int c; /* One character in z[] */
  121099. int cnt; /* Number of non-wildcard prefix characters */
  121100. char wc[3]; /* Wildcard characters */
  121101. sqlite3 *db = pParse->db; /* Database connection */
  121102. sqlite3_value *pVal = 0;
  121103. int op; /* Opcode of pRight */
  121104. int rc; /* Result code to return */
  121105. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  121106. return 0;
  121107. }
  121108. #ifdef SQLITE_EBCDIC
  121109. if( *pnoCase ) return 0;
  121110. #endif
  121111. pList = pExpr->x.pList;
  121112. pLeft = pList->a[1].pExpr;
  121113. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  121114. op = pRight->op;
  121115. if( op==TK_VARIABLE ){
  121116. Vdbe *pReprepare = pParse->pReprepare;
  121117. int iCol = pRight->iColumn;
  121118. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  121119. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  121120. z = (char *)sqlite3_value_text(pVal);
  121121. }
  121122. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  121123. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  121124. }else if( op==TK_STRING ){
  121125. z = pRight->u.zToken;
  121126. }
  121127. if( z ){
  121128. /* If the RHS begins with a digit or a minus sign, then the LHS must
  121129. ** be an ordinary column (not a virtual table column) with TEXT affinity.
  121130. ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
  121131. ** even though "lhs LIKE rhs" is true. But if the RHS does not start
  121132. ** with a digit or '-', then "lhs LIKE rhs" will always be false if
  121133. ** the LHS is numeric and so the optimization still works.
  121134. */
  121135. if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
  121136. if( pLeft->op!=TK_COLUMN
  121137. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  121138. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  121139. ){
  121140. sqlite3ValueFree(pVal);
  121141. return 0;
  121142. }
  121143. }
  121144. cnt = 0;
  121145. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  121146. cnt++;
  121147. }
  121148. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  121149. Expr *pPrefix;
  121150. *pisComplete = c==wc[0] && z[cnt+1]==0;
  121151. pPrefix = sqlite3Expr(db, TK_STRING, z);
  121152. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  121153. *ppPrefix = pPrefix;
  121154. if( op==TK_VARIABLE ){
  121155. Vdbe *v = pParse->pVdbe;
  121156. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  121157. if( *pisComplete && pRight->u.zToken[1] ){
  121158. /* If the rhs of the LIKE expression is a variable, and the current
  121159. ** value of the variable means there is no need to invoke the LIKE
  121160. ** function, then no OP_Variable will be added to the program.
  121161. ** This causes problems for the sqlite3_bind_parameter_name()
  121162. ** API. To work around them, add a dummy OP_Variable here.
  121163. */
  121164. int r1 = sqlite3GetTempReg(pParse);
  121165. sqlite3ExprCodeTarget(pParse, pRight, r1);
  121166. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  121167. sqlite3ReleaseTempReg(pParse, r1);
  121168. }
  121169. }
  121170. }else{
  121171. z = 0;
  121172. }
  121173. }
  121174. rc = (z!=0);
  121175. sqlite3ValueFree(pVal);
  121176. return rc;
  121177. }
  121178. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  121179. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121180. /*
  121181. ** Check to see if the given expression is of the form
  121182. **
  121183. ** column OP expr
  121184. **
  121185. ** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
  121186. ** column of a virtual table.
  121187. **
  121188. ** If it is then return TRUE. If not, return FALSE.
  121189. */
  121190. static int isMatchOfColumn(
  121191. Expr *pExpr, /* Test this expression */
  121192. unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */
  121193. ){
  121194. static const struct Op2 {
  121195. const char *zOp;
  121196. unsigned char eOp2;
  121197. } aOp[] = {
  121198. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  121199. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  121200. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  121201. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  121202. };
  121203. ExprList *pList;
  121204. Expr *pCol; /* Column reference */
  121205. int i;
  121206. if( pExpr->op!=TK_FUNCTION ){
  121207. return 0;
  121208. }
  121209. pList = pExpr->x.pList;
  121210. if( pList==0 || pList->nExpr!=2 ){
  121211. return 0;
  121212. }
  121213. pCol = pList->a[1].pExpr;
  121214. if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
  121215. return 0;
  121216. }
  121217. for(i=0; i<ArraySize(aOp); i++){
  121218. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  121219. *peOp2 = aOp[i].eOp2;
  121220. return 1;
  121221. }
  121222. }
  121223. return 0;
  121224. }
  121225. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  121226. /*
  121227. ** If the pBase expression originated in the ON or USING clause of
  121228. ** a join, then transfer the appropriate markings over to derived.
  121229. */
  121230. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  121231. if( pDerived ){
  121232. pDerived->flags |= pBase->flags & EP_FromJoin;
  121233. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  121234. }
  121235. }
  121236. /*
  121237. ** Mark term iChild as being a child of term iParent
  121238. */
  121239. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  121240. pWC->a[iChild].iParent = iParent;
  121241. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  121242. pWC->a[iParent].nChild++;
  121243. }
  121244. /*
  121245. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  121246. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  121247. ** the number of available subterms, return NULL.
  121248. */
  121249. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  121250. if( pTerm->eOperator!=WO_AND ){
  121251. return N==0 ? pTerm : 0;
  121252. }
  121253. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  121254. return &pTerm->u.pAndInfo->wc.a[N];
  121255. }
  121256. return 0;
  121257. }
  121258. /*
  121259. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  121260. ** two subterms are in disjunction - they are OR-ed together.
  121261. **
  121262. ** If these two terms are both of the form: "A op B" with the same
  121263. ** A and B values but different operators and if the operators are
  121264. ** compatible (if one is = and the other is <, for example) then
  121265. ** add a new virtual AND term to pWC that is the combination of the
  121266. ** two.
  121267. **
  121268. ** Some examples:
  121269. **
  121270. ** x<y OR x=y --> x<=y
  121271. ** x=y OR x=y --> x=y
  121272. ** x<=y OR x<y --> x<=y
  121273. **
  121274. ** The following is NOT generated:
  121275. **
  121276. ** x<y OR x>y --> x!=y
  121277. */
  121278. static void whereCombineDisjuncts(
  121279. SrcList *pSrc, /* the FROM clause */
  121280. WhereClause *pWC, /* The complete WHERE clause */
  121281. WhereTerm *pOne, /* First disjunct */
  121282. WhereTerm *pTwo /* Second disjunct */
  121283. ){
  121284. u16 eOp = pOne->eOperator | pTwo->eOperator;
  121285. sqlite3 *db; /* Database connection (for malloc) */
  121286. Expr *pNew; /* New virtual expression */
  121287. int op; /* Operator for the combined expression */
  121288. int idxNew; /* Index in pWC of the next virtual term */
  121289. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  121290. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  121291. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  121292. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  121293. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  121294. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  121295. if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  121296. if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
  121297. /* If we reach this point, it means the two subterms can be combined */
  121298. if( (eOp & (eOp-1))!=0 ){
  121299. if( eOp & (WO_LT|WO_LE) ){
  121300. eOp = WO_LE;
  121301. }else{
  121302. assert( eOp & (WO_GT|WO_GE) );
  121303. eOp = WO_GE;
  121304. }
  121305. }
  121306. db = pWC->pWInfo->pParse->db;
  121307. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  121308. if( pNew==0 ) return;
  121309. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  121310. pNew->op = op;
  121311. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  121312. exprAnalyze(pSrc, pWC, idxNew);
  121313. }
  121314. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  121315. /*
  121316. ** Analyze a term that consists of two or more OR-connected
  121317. ** subterms. So in:
  121318. **
  121319. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  121320. ** ^^^^^^^^^^^^^^^^^^^^
  121321. **
  121322. ** This routine analyzes terms such as the middle term in the above example.
  121323. ** A WhereOrTerm object is computed and attached to the term under
  121324. ** analysis, regardless of the outcome of the analysis. Hence:
  121325. **
  121326. ** WhereTerm.wtFlags |= TERM_ORINFO
  121327. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  121328. **
  121329. ** The term being analyzed must have two or more of OR-connected subterms.
  121330. ** A single subterm might be a set of AND-connected sub-subterms.
  121331. ** Examples of terms under analysis:
  121332. **
  121333. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  121334. ** (B) x=expr1 OR expr2=x OR x=expr3
  121335. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  121336. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  121337. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  121338. ** (F) x>A OR (x=A AND y>=B)
  121339. **
  121340. ** CASE 1:
  121341. **
  121342. ** If all subterms are of the form T.C=expr for some single column of C and
  121343. ** a single table T (as shown in example B above) then create a new virtual
  121344. ** term that is an equivalent IN expression. In other words, if the term
  121345. ** being analyzed is:
  121346. **
  121347. ** x = expr1 OR expr2 = x OR x = expr3
  121348. **
  121349. ** then create a new virtual term like this:
  121350. **
  121351. ** x IN (expr1,expr2,expr3)
  121352. **
  121353. ** CASE 2:
  121354. **
  121355. ** If there are exactly two disjuncts and one side has x>A and the other side
  121356. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  121357. ** WHERE clause of the form "x>=A". Example:
  121358. **
  121359. ** x>A OR (x=A AND y>B) adds: x>=A
  121360. **
  121361. ** The added conjunct can sometimes be helpful in query planning.
  121362. **
  121363. ** CASE 3:
  121364. **
  121365. ** If all subterms are indexable by a single table T, then set
  121366. **
  121367. ** WhereTerm.eOperator = WO_OR
  121368. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  121369. **
  121370. ** A subterm is "indexable" if it is of the form
  121371. ** "T.C <op> <expr>" where C is any column of table T and
  121372. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  121373. ** A subterm is also indexable if it is an AND of two or more
  121374. ** subsubterms at least one of which is indexable. Indexable AND
  121375. ** subterms have their eOperator set to WO_AND and they have
  121376. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  121377. **
  121378. ** From another point of view, "indexable" means that the subterm could
  121379. ** potentially be used with an index if an appropriate index exists.
  121380. ** This analysis does not consider whether or not the index exists; that
  121381. ** is decided elsewhere. This analysis only looks at whether subterms
  121382. ** appropriate for indexing exist.
  121383. **
  121384. ** All examples A through E above satisfy case 3. But if a term
  121385. ** also satisfies case 1 (such as B) we know that the optimizer will
  121386. ** always prefer case 1, so in that case we pretend that case 3 is not
  121387. ** satisfied.
  121388. **
  121389. ** It might be the case that multiple tables are indexable. For example,
  121390. ** (E) above is indexable on tables P, Q, and R.
  121391. **
  121392. ** Terms that satisfy case 3 are candidates for lookup by using
  121393. ** separate indices to find rowids for each subterm and composing
  121394. ** the union of all rowids using a RowSet object. This is similar
  121395. ** to "bitmap indices" in other database engines.
  121396. **
  121397. ** OTHERWISE:
  121398. **
  121399. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  121400. ** zero. This term is not useful for search.
  121401. */
  121402. static void exprAnalyzeOrTerm(
  121403. SrcList *pSrc, /* the FROM clause */
  121404. WhereClause *pWC, /* the complete WHERE clause */
  121405. int idxTerm /* Index of the OR-term to be analyzed */
  121406. ){
  121407. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  121408. Parse *pParse = pWInfo->pParse; /* Parser context */
  121409. sqlite3 *db = pParse->db; /* Database connection */
  121410. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  121411. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  121412. int i; /* Loop counters */
  121413. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  121414. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  121415. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  121416. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  121417. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  121418. /*
  121419. ** Break the OR clause into its separate subterms. The subterms are
  121420. ** stored in a WhereClause structure containing within the WhereOrInfo
  121421. ** object that is attached to the original OR clause term.
  121422. */
  121423. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  121424. assert( pExpr->op==TK_OR );
  121425. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  121426. if( pOrInfo==0 ) return;
  121427. pTerm->wtFlags |= TERM_ORINFO;
  121428. pOrWc = &pOrInfo->wc;
  121429. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  121430. sqlite3WhereClauseInit(pOrWc, pWInfo);
  121431. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  121432. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  121433. if( db->mallocFailed ) return;
  121434. assert( pOrWc->nTerm>=2 );
  121435. /*
  121436. ** Compute the set of tables that might satisfy cases 1 or 3.
  121437. */
  121438. indexable = ~(Bitmask)0;
  121439. chngToIN = ~(Bitmask)0;
  121440. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  121441. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  121442. WhereAndInfo *pAndInfo;
  121443. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  121444. chngToIN = 0;
  121445. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  121446. if( pAndInfo ){
  121447. WhereClause *pAndWC;
  121448. WhereTerm *pAndTerm;
  121449. int j;
  121450. Bitmask b = 0;
  121451. pOrTerm->u.pAndInfo = pAndInfo;
  121452. pOrTerm->wtFlags |= TERM_ANDINFO;
  121453. pOrTerm->eOperator = WO_AND;
  121454. pAndWC = &pAndInfo->wc;
  121455. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  121456. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  121457. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  121458. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  121459. pAndWC->pOuter = pWC;
  121460. if( !db->mallocFailed ){
  121461. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  121462. assert( pAndTerm->pExpr );
  121463. if( allowedOp(pAndTerm->pExpr->op)
  121464. || pAndTerm->eOperator==WO_MATCH
  121465. ){
  121466. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  121467. }
  121468. }
  121469. }
  121470. indexable &= b;
  121471. }
  121472. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  121473. /* Skip this term for now. We revisit it when we process the
  121474. ** corresponding TERM_VIRTUAL term */
  121475. }else{
  121476. Bitmask b;
  121477. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  121478. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  121479. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  121480. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  121481. }
  121482. indexable &= b;
  121483. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  121484. chngToIN = 0;
  121485. }else{
  121486. chngToIN &= b;
  121487. }
  121488. }
  121489. }
  121490. /*
  121491. ** Record the set of tables that satisfy case 3. The set might be
  121492. ** empty.
  121493. */
  121494. pOrInfo->indexable = indexable;
  121495. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  121496. /* For a two-way OR, attempt to implementation case 2.
  121497. */
  121498. if( indexable && pOrWc->nTerm==2 ){
  121499. int iOne = 0;
  121500. WhereTerm *pOne;
  121501. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  121502. int iTwo = 0;
  121503. WhereTerm *pTwo;
  121504. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  121505. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  121506. }
  121507. }
  121508. }
  121509. /*
  121510. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  121511. ** we have to do some additional checking to see if case 1 really
  121512. ** is satisfied.
  121513. **
  121514. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  121515. ** that there is no possibility of transforming the OR clause into an
  121516. ** IN operator because one or more terms in the OR clause contain
  121517. ** something other than == on a column in the single table. The 1-bit
  121518. ** case means that every term of the OR clause is of the form
  121519. ** "table.column=expr" for some single table. The one bit that is set
  121520. ** will correspond to the common table. We still need to check to make
  121521. ** sure the same column is used on all terms. The 2-bit case is when
  121522. ** the all terms are of the form "table1.column=table2.column". It
  121523. ** might be possible to form an IN operator with either table1.column
  121524. ** or table2.column as the LHS if either is common to every term of
  121525. ** the OR clause.
  121526. **
  121527. ** Note that terms of the form "table.column1=table.column2" (the
  121528. ** same table on both sizes of the ==) cannot be optimized.
  121529. */
  121530. if( chngToIN ){
  121531. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  121532. int iColumn = -1; /* Column index on lhs of IN operator */
  121533. int iCursor = -1; /* Table cursor common to all terms */
  121534. int j = 0; /* Loop counter */
  121535. /* Search for a table and column that appears on one side or the
  121536. ** other of the == operator in every subterm. That table and column
  121537. ** will be recorded in iCursor and iColumn. There might not be any
  121538. ** such table and column. Set okToChngToIN if an appropriate table
  121539. ** and column is found but leave okToChngToIN false if not found.
  121540. */
  121541. for(j=0; j<2 && !okToChngToIN; j++){
  121542. pOrTerm = pOrWc->a;
  121543. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  121544. assert( pOrTerm->eOperator & WO_EQ );
  121545. pOrTerm->wtFlags &= ~TERM_OR_OK;
  121546. if( pOrTerm->leftCursor==iCursor ){
  121547. /* This is the 2-bit case and we are on the second iteration and
  121548. ** current term is from the first iteration. So skip this term. */
  121549. assert( j==1 );
  121550. continue;
  121551. }
  121552. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  121553. pOrTerm->leftCursor))==0 ){
  121554. /* This term must be of the form t1.a==t2.b where t2 is in the
  121555. ** chngToIN set but t1 is not. This term will be either preceded
  121556. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  121557. ** and use its inversion. */
  121558. testcase( pOrTerm->wtFlags & TERM_COPIED );
  121559. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  121560. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  121561. continue;
  121562. }
  121563. iColumn = pOrTerm->u.leftColumn;
  121564. iCursor = pOrTerm->leftCursor;
  121565. break;
  121566. }
  121567. if( i<0 ){
  121568. /* No candidate table+column was found. This can only occur
  121569. ** on the second iteration */
  121570. assert( j==1 );
  121571. assert( IsPowerOfTwo(chngToIN) );
  121572. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  121573. break;
  121574. }
  121575. testcase( j==1 );
  121576. /* We have found a candidate table and column. Check to see if that
  121577. ** table and column is common to every term in the OR clause */
  121578. okToChngToIN = 1;
  121579. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  121580. assert( pOrTerm->eOperator & WO_EQ );
  121581. if( pOrTerm->leftCursor!=iCursor ){
  121582. pOrTerm->wtFlags &= ~TERM_OR_OK;
  121583. }else if( pOrTerm->u.leftColumn!=iColumn ){
  121584. okToChngToIN = 0;
  121585. }else{
  121586. int affLeft, affRight;
  121587. /* If the right-hand side is also a column, then the affinities
  121588. ** of both right and left sides must be such that no type
  121589. ** conversions are required on the right. (Ticket #2249)
  121590. */
  121591. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  121592. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  121593. if( affRight!=0 && affRight!=affLeft ){
  121594. okToChngToIN = 0;
  121595. }else{
  121596. pOrTerm->wtFlags |= TERM_OR_OK;
  121597. }
  121598. }
  121599. }
  121600. }
  121601. /* At this point, okToChngToIN is true if original pTerm satisfies
  121602. ** case 1. In that case, construct a new virtual term that is
  121603. ** pTerm converted into an IN operator.
  121604. */
  121605. if( okToChngToIN ){
  121606. Expr *pDup; /* A transient duplicate expression */
  121607. ExprList *pList = 0; /* The RHS of the IN operator */
  121608. Expr *pLeft = 0; /* The LHS of the IN operator */
  121609. Expr *pNew; /* The complete IN operator */
  121610. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  121611. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  121612. assert( pOrTerm->eOperator & WO_EQ );
  121613. assert( pOrTerm->leftCursor==iCursor );
  121614. assert( pOrTerm->u.leftColumn==iColumn );
  121615. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  121616. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  121617. pLeft = pOrTerm->pExpr->pLeft;
  121618. }
  121619. assert( pLeft!=0 );
  121620. pDup = sqlite3ExprDup(db, pLeft, 0);
  121621. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
  121622. if( pNew ){
  121623. int idxNew;
  121624. transferJoinMarkings(pNew, pExpr);
  121625. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  121626. pNew->x.pList = pList;
  121627. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  121628. testcase( idxNew==0 );
  121629. exprAnalyze(pSrc, pWC, idxNew);
  121630. pTerm = &pWC->a[idxTerm];
  121631. markTermAsChild(pWC, idxNew, idxTerm);
  121632. }else{
  121633. sqlite3ExprListDelete(db, pList);
  121634. }
  121635. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
  121636. }
  121637. }
  121638. }
  121639. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  121640. /*
  121641. ** We already know that pExpr is a binary operator where both operands are
  121642. ** column references. This routine checks to see if pExpr is an equivalence
  121643. ** relation:
  121644. ** 1. The SQLITE_Transitive optimization must be enabled
  121645. ** 2. Must be either an == or an IS operator
  121646. ** 3. Not originating in the ON clause of an OUTER JOIN
  121647. ** 4. The affinities of A and B must be compatible
  121648. ** 5a. Both operands use the same collating sequence OR
  121649. ** 5b. The overall collating sequence is BINARY
  121650. ** If this routine returns TRUE, that means that the RHS can be substituted
  121651. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  121652. ** This is an optimization. No harm comes from returning 0. But if 1 is
  121653. ** returned when it should not be, then incorrect answers might result.
  121654. */
  121655. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  121656. char aff1, aff2;
  121657. CollSeq *pColl;
  121658. const char *zColl1, *zColl2;
  121659. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  121660. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  121661. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  121662. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  121663. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  121664. if( aff1!=aff2
  121665. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  121666. ){
  121667. return 0;
  121668. }
  121669. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  121670. if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
  121671. pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  121672. zColl1 = pColl ? pColl->zName : 0;
  121673. pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  121674. zColl2 = pColl ? pColl->zName : 0;
  121675. return sqlite3_stricmp(zColl1, zColl2)==0;
  121676. }
  121677. /*
  121678. ** Recursively walk the expressions of a SELECT statement and generate
  121679. ** a bitmask indicating which tables are used in that expression
  121680. ** tree.
  121681. */
  121682. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  121683. Bitmask mask = 0;
  121684. while( pS ){
  121685. SrcList *pSrc = pS->pSrc;
  121686. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  121687. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  121688. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  121689. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  121690. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  121691. if( ALWAYS(pSrc!=0) ){
  121692. int i;
  121693. for(i=0; i<pSrc->nSrc; i++){
  121694. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  121695. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  121696. }
  121697. }
  121698. pS = pS->pPrior;
  121699. }
  121700. return mask;
  121701. }
  121702. /*
  121703. ** Expression pExpr is one operand of a comparison operator that might
  121704. ** be useful for indexing. This routine checks to see if pExpr appears
  121705. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  121706. ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
  121707. ** number of the table that is indexed and aiCurCol[1] to the column number
  121708. ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
  121709. ** indexed.
  121710. **
  121711. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  121712. ** true even if that particular column is not indexed, because the column
  121713. ** might be added to an automatic index later.
  121714. */
  121715. static SQLITE_NOINLINE int exprMightBeIndexed2(
  121716. SrcList *pFrom, /* The FROM clause */
  121717. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  121718. int *aiCurCol, /* Write the referenced table cursor and column here */
  121719. Expr *pExpr /* An operand of a comparison operator */
  121720. ){
  121721. Index *pIdx;
  121722. int i;
  121723. int iCur;
  121724. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  121725. iCur = pFrom->a[i].iCursor;
  121726. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  121727. if( pIdx->aColExpr==0 ) continue;
  121728. for(i=0; i<pIdx->nKeyCol; i++){
  121729. if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
  121730. if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  121731. aiCurCol[0] = iCur;
  121732. aiCurCol[1] = XN_EXPR;
  121733. return 1;
  121734. }
  121735. }
  121736. }
  121737. return 0;
  121738. }
  121739. static int exprMightBeIndexed(
  121740. SrcList *pFrom, /* The FROM clause */
  121741. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  121742. int *aiCurCol, /* Write the referenced table cursor & column here */
  121743. Expr *pExpr, /* An operand of a comparison operator */
  121744. int op /* The specific comparison operator */
  121745. ){
  121746. /* If this expression is a vector to the left or right of a
  121747. ** inequality constraint (>, <, >= or <=), perform the processing
  121748. ** on the first element of the vector. */
  121749. assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
  121750. assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
  121751. assert( op<=TK_GE );
  121752. if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
  121753. pExpr = pExpr->x.pList->a[0].pExpr;
  121754. }
  121755. if( pExpr->op==TK_COLUMN ){
  121756. aiCurCol[0] = pExpr->iTable;
  121757. aiCurCol[1] = pExpr->iColumn;
  121758. return 1;
  121759. }
  121760. if( mPrereq==0 ) return 0; /* No table references */
  121761. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  121762. return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
  121763. }
  121764. /*
  121765. ** The input to this routine is an WhereTerm structure with only the
  121766. ** "pExpr" field filled in. The job of this routine is to analyze the
  121767. ** subexpression and populate all the other fields of the WhereTerm
  121768. ** structure.
  121769. **
  121770. ** If the expression is of the form "<expr> <op> X" it gets commuted
  121771. ** to the standard form of "X <op> <expr>".
  121772. **
  121773. ** If the expression is of the form "X <op> Y" where both X and Y are
  121774. ** columns, then the original expression is unchanged and a new virtual
  121775. ** term of the form "Y <op> X" is added to the WHERE clause and
  121776. ** analyzed separately. The original term is marked with TERM_COPIED
  121777. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  121778. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  121779. ** is a commuted copy of a prior term.) The original term has nChild=1
  121780. ** and the copy has idxParent set to the index of the original term.
  121781. */
  121782. static void exprAnalyze(
  121783. SrcList *pSrc, /* the FROM clause */
  121784. WhereClause *pWC, /* the WHERE clause */
  121785. int idxTerm /* Index of the term to be analyzed */
  121786. ){
  121787. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  121788. WhereTerm *pTerm; /* The term to be analyzed */
  121789. WhereMaskSet *pMaskSet; /* Set of table index masks */
  121790. Expr *pExpr; /* The expression to be analyzed */
  121791. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  121792. Bitmask prereqAll; /* Prerequesites of pExpr */
  121793. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  121794. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  121795. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  121796. int noCase = 0; /* uppercase equivalent to lowercase */
  121797. int op; /* Top-level operator. pExpr->op */
  121798. Parse *pParse = pWInfo->pParse; /* Parsing context */
  121799. sqlite3 *db = pParse->db; /* Database connection */
  121800. unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
  121801. int nLeft; /* Number of elements on left side vector */
  121802. if( db->mallocFailed ){
  121803. return;
  121804. }
  121805. pTerm = &pWC->a[idxTerm];
  121806. pMaskSet = &pWInfo->sMaskSet;
  121807. pExpr = pTerm->pExpr;
  121808. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  121809. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  121810. op = pExpr->op;
  121811. if( op==TK_IN ){
  121812. assert( pExpr->pRight==0 );
  121813. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  121814. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  121815. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  121816. }else{
  121817. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  121818. }
  121819. }else if( op==TK_ISNULL ){
  121820. pTerm->prereqRight = 0;
  121821. }else{
  121822. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  121823. }
  121824. prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
  121825. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  121826. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  121827. prereqAll |= x;
  121828. extraRight = x-1; /* ON clause terms may not be used with an index
  121829. ** on left table of a LEFT JOIN. Ticket #3015 */
  121830. if( (prereqAll>>1)>=x ){
  121831. sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
  121832. return;
  121833. }
  121834. }
  121835. pTerm->prereqAll = prereqAll;
  121836. pTerm->leftCursor = -1;
  121837. pTerm->iParent = -1;
  121838. pTerm->eOperator = 0;
  121839. if( allowedOp(op) ){
  121840. int aiCurCol[2];
  121841. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  121842. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  121843. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  121844. if( pTerm->iField>0 ){
  121845. assert( op==TK_IN );
  121846. assert( pLeft->op==TK_VECTOR );
  121847. pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
  121848. }
  121849. if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
  121850. pTerm->leftCursor = aiCurCol[0];
  121851. pTerm->u.leftColumn = aiCurCol[1];
  121852. pTerm->eOperator = operatorMask(op) & opMask;
  121853. }
  121854. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  121855. if( pRight
  121856. && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
  121857. ){
  121858. WhereTerm *pNew;
  121859. Expr *pDup;
  121860. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  121861. assert( pTerm->iField==0 );
  121862. if( pTerm->leftCursor>=0 ){
  121863. int idxNew;
  121864. pDup = sqlite3ExprDup(db, pExpr, 0);
  121865. if( db->mallocFailed ){
  121866. sqlite3ExprDelete(db, pDup);
  121867. return;
  121868. }
  121869. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  121870. if( idxNew==0 ) return;
  121871. pNew = &pWC->a[idxNew];
  121872. markTermAsChild(pWC, idxNew, idxTerm);
  121873. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  121874. pTerm = &pWC->a[idxTerm];
  121875. pTerm->wtFlags |= TERM_COPIED;
  121876. if( termIsEquivalence(pParse, pDup) ){
  121877. pTerm->eOperator |= WO_EQUIV;
  121878. eExtraOp = WO_EQUIV;
  121879. }
  121880. }else{
  121881. pDup = pExpr;
  121882. pNew = pTerm;
  121883. }
  121884. exprCommute(pParse, pDup);
  121885. pNew->leftCursor = aiCurCol[0];
  121886. pNew->u.leftColumn = aiCurCol[1];
  121887. testcase( (prereqLeft | extraRight) != prereqLeft );
  121888. pNew->prereqRight = prereqLeft | extraRight;
  121889. pNew->prereqAll = prereqAll;
  121890. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  121891. }
  121892. }
  121893. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  121894. /* If a term is the BETWEEN operator, create two new virtual terms
  121895. ** that define the range that the BETWEEN implements. For example:
  121896. **
  121897. ** a BETWEEN b AND c
  121898. **
  121899. ** is converted into:
  121900. **
  121901. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  121902. **
  121903. ** The two new terms are added onto the end of the WhereClause object.
  121904. ** The new terms are "dynamic" and are children of the original BETWEEN
  121905. ** term. That means that if the BETWEEN term is coded, the children are
  121906. ** skipped. Or, if the children are satisfied by an index, the original
  121907. ** BETWEEN term is skipped.
  121908. */
  121909. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  121910. ExprList *pList = pExpr->x.pList;
  121911. int i;
  121912. static const u8 ops[] = {TK_GE, TK_LE};
  121913. assert( pList!=0 );
  121914. assert( pList->nExpr==2 );
  121915. for(i=0; i<2; i++){
  121916. Expr *pNewExpr;
  121917. int idxNew;
  121918. pNewExpr = sqlite3PExpr(pParse, ops[i],
  121919. sqlite3ExprDup(db, pExpr->pLeft, 0),
  121920. sqlite3ExprDup(db, pList->a[i].pExpr, 0));
  121921. transferJoinMarkings(pNewExpr, pExpr);
  121922. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  121923. testcase( idxNew==0 );
  121924. exprAnalyze(pSrc, pWC, idxNew);
  121925. pTerm = &pWC->a[idxTerm];
  121926. markTermAsChild(pWC, idxNew, idxTerm);
  121927. }
  121928. }
  121929. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  121930. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  121931. /* Analyze a term that is composed of two or more subterms connected by
  121932. ** an OR operator.
  121933. */
  121934. else if( pExpr->op==TK_OR ){
  121935. assert( pWC->op==TK_AND );
  121936. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  121937. pTerm = &pWC->a[idxTerm];
  121938. }
  121939. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  121940. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  121941. /* Add constraints to reduce the search space on a LIKE or GLOB
  121942. ** operator.
  121943. **
  121944. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  121945. **
  121946. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  121947. **
  121948. ** The last character of the prefix "abc" is incremented to form the
  121949. ** termination condition "abd". If case is not significant (the default
  121950. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  121951. ** bound is made all lowercase so that the bounds also work when comparing
  121952. ** BLOBs.
  121953. */
  121954. if( pWC->op==TK_AND
  121955. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  121956. ){
  121957. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  121958. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  121959. Expr *pNewExpr1;
  121960. Expr *pNewExpr2;
  121961. int idxNew1;
  121962. int idxNew2;
  121963. const char *zCollSeqName; /* Name of collating sequence */
  121964. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  121965. pLeft = pExpr->x.pList->a[1].pExpr;
  121966. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  121967. /* Convert the lower bound to upper-case and the upper bound to
  121968. ** lower-case (upper-case is less than lower-case in ASCII) so that
  121969. ** the range constraints also work for BLOBs
  121970. */
  121971. if( noCase && !pParse->db->mallocFailed ){
  121972. int i;
  121973. char c;
  121974. pTerm->wtFlags |= TERM_LIKE;
  121975. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  121976. pStr1->u.zToken[i] = sqlite3Toupper(c);
  121977. pStr2->u.zToken[i] = sqlite3Tolower(c);
  121978. }
  121979. }
  121980. if( !db->mallocFailed ){
  121981. u8 c, *pC; /* Last character before the first wildcard */
  121982. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  121983. c = *pC;
  121984. if( noCase ){
  121985. /* The point is to increment the last character before the first
  121986. ** wildcard. But if we increment '@', that will push it into the
  121987. ** alphabetic range where case conversions will mess up the
  121988. ** inequality. To avoid this, make sure to also run the full
  121989. ** LIKE on all candidate expressions by clearing the isComplete flag
  121990. */
  121991. if( c=='A'-1 ) isComplete = 0;
  121992. c = sqlite3UpperToLower[c];
  121993. }
  121994. *pC = c + 1;
  121995. }
  121996. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  121997. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  121998. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  121999. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  122000. pStr1);
  122001. transferJoinMarkings(pNewExpr1, pExpr);
  122002. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  122003. testcase( idxNew1==0 );
  122004. exprAnalyze(pSrc, pWC, idxNew1);
  122005. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  122006. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  122007. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  122008. pStr2);
  122009. transferJoinMarkings(pNewExpr2, pExpr);
  122010. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  122011. testcase( idxNew2==0 );
  122012. exprAnalyze(pSrc, pWC, idxNew2);
  122013. pTerm = &pWC->a[idxTerm];
  122014. if( isComplete ){
  122015. markTermAsChild(pWC, idxNew1, idxTerm);
  122016. markTermAsChild(pWC, idxNew2, idxTerm);
  122017. }
  122018. }
  122019. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  122020. #ifndef SQLITE_OMIT_VIRTUALTABLE
  122021. /* Add a WO_MATCH auxiliary term to the constraint set if the
  122022. ** current expression is of the form: column MATCH expr.
  122023. ** This information is used by the xBestIndex methods of
  122024. ** virtual tables. The native query optimizer does not attempt
  122025. ** to do anything with MATCH functions.
  122026. */
  122027. if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
  122028. int idxNew;
  122029. Expr *pRight, *pLeft;
  122030. WhereTerm *pNewTerm;
  122031. Bitmask prereqColumn, prereqExpr;
  122032. pRight = pExpr->x.pList->a[0].pExpr;
  122033. pLeft = pExpr->x.pList->a[1].pExpr;
  122034. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  122035. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  122036. if( (prereqExpr & prereqColumn)==0 ){
  122037. Expr *pNewExpr;
  122038. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  122039. 0, sqlite3ExprDup(db, pRight, 0));
  122040. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  122041. testcase( idxNew==0 );
  122042. pNewTerm = &pWC->a[idxNew];
  122043. pNewTerm->prereqRight = prereqExpr;
  122044. pNewTerm->leftCursor = pLeft->iTable;
  122045. pNewTerm->u.leftColumn = pLeft->iColumn;
  122046. pNewTerm->eOperator = WO_MATCH;
  122047. pNewTerm->eMatchOp = eOp2;
  122048. markTermAsChild(pWC, idxNew, idxTerm);
  122049. pTerm = &pWC->a[idxTerm];
  122050. pTerm->wtFlags |= TERM_COPIED;
  122051. pNewTerm->prereqAll = pTerm->prereqAll;
  122052. }
  122053. }
  122054. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  122055. /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
  122056. ** new terms for each component comparison - "a = ?" and "b = ?". The
  122057. ** new terms completely replace the original vector comparison, which is
  122058. ** no longer used.
  122059. **
  122060. ** This is only required if at least one side of the comparison operation
  122061. ** is not a sub-select. */
  122062. if( pWC->op==TK_AND
  122063. && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
  122064. && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
  122065. && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
  122066. && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
  122067. || (pExpr->pRight->flags & EP_xIsSelect)==0)
  122068. ){
  122069. int i;
  122070. for(i=0; i<nLeft; i++){
  122071. int idxNew;
  122072. Expr *pNew;
  122073. Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
  122074. Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
  122075. pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
  122076. transferJoinMarkings(pNew, pExpr);
  122077. idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
  122078. exprAnalyze(pSrc, pWC, idxNew);
  122079. }
  122080. pTerm = &pWC->a[idxTerm];
  122081. pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */
  122082. pTerm->eOperator = 0;
  122083. }
  122084. /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
  122085. ** a virtual term for each vector component. The expression object
  122086. ** used by each such virtual term is pExpr (the full vector IN(...)
  122087. ** expression). The WhereTerm.iField variable identifies the index within
  122088. ** the vector on the LHS that the virtual term represents.
  122089. **
  122090. ** This only works if the RHS is a simple SELECT, not a compound
  122091. */
  122092. if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
  122093. && pExpr->pLeft->op==TK_VECTOR
  122094. && pExpr->x.pSelect->pPrior==0
  122095. ){
  122096. int i;
  122097. for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
  122098. int idxNew;
  122099. idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
  122100. pWC->a[idxNew].iField = i+1;
  122101. exprAnalyze(pSrc, pWC, idxNew);
  122102. markTermAsChild(pWC, idxNew, idxTerm);
  122103. }
  122104. }
  122105. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  122106. /* When sqlite_stat3 histogram data is available an operator of the
  122107. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  122108. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  122109. ** virtual term of that form.
  122110. **
  122111. ** Note that the virtual term must be tagged with TERM_VNULL.
  122112. */
  122113. if( pExpr->op==TK_NOTNULL
  122114. && pExpr->pLeft->op==TK_COLUMN
  122115. && pExpr->pLeft->iColumn>=0
  122116. && OptimizationEnabled(db, SQLITE_Stat34)
  122117. ){
  122118. Expr *pNewExpr;
  122119. Expr *pLeft = pExpr->pLeft;
  122120. int idxNew;
  122121. WhereTerm *pNewTerm;
  122122. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  122123. sqlite3ExprDup(db, pLeft, 0),
  122124. sqlite3ExprAlloc(db, TK_NULL, 0, 0));
  122125. idxNew = whereClauseInsert(pWC, pNewExpr,
  122126. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  122127. if( idxNew ){
  122128. pNewTerm = &pWC->a[idxNew];
  122129. pNewTerm->prereqRight = 0;
  122130. pNewTerm->leftCursor = pLeft->iTable;
  122131. pNewTerm->u.leftColumn = pLeft->iColumn;
  122132. pNewTerm->eOperator = WO_GT;
  122133. markTermAsChild(pWC, idxNew, idxTerm);
  122134. pTerm = &pWC->a[idxTerm];
  122135. pTerm->wtFlags |= TERM_COPIED;
  122136. pNewTerm->prereqAll = pTerm->prereqAll;
  122137. }
  122138. }
  122139. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  122140. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  122141. ** an index for tables to the left of the join.
  122142. */
  122143. testcase( pTerm!=&pWC->a[idxTerm] );
  122144. pTerm = &pWC->a[idxTerm];
  122145. pTerm->prereqRight |= extraRight;
  122146. }
  122147. /***************************************************************************
  122148. ** Routines with file scope above. Interface to the rest of the where.c
  122149. ** subsystem follows.
  122150. ***************************************************************************/
  122151. /*
  122152. ** This routine identifies subexpressions in the WHERE clause where
  122153. ** each subexpression is separated by the AND operator or some other
  122154. ** operator specified in the op parameter. The WhereClause structure
  122155. ** is filled with pointers to subexpressions. For example:
  122156. **
  122157. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  122158. ** \________/ \_______________/ \________________/
  122159. ** slot[0] slot[1] slot[2]
  122160. **
  122161. ** The original WHERE clause in pExpr is unaltered. All this routine
  122162. ** does is make slot[] entries point to substructure within pExpr.
  122163. **
  122164. ** In the previous sentence and in the diagram, "slot[]" refers to
  122165. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  122166. ** all terms of the WHERE clause.
  122167. */
  122168. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  122169. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  122170. pWC->op = op;
  122171. if( pE2==0 ) return;
  122172. if( pE2->op!=op ){
  122173. whereClauseInsert(pWC, pExpr, 0);
  122174. }else{
  122175. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  122176. sqlite3WhereSplit(pWC, pE2->pRight, op);
  122177. }
  122178. }
  122179. /*
  122180. ** Initialize a preallocated WhereClause structure.
  122181. */
  122182. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  122183. WhereClause *pWC, /* The WhereClause to be initialized */
  122184. WhereInfo *pWInfo /* The WHERE processing context */
  122185. ){
  122186. pWC->pWInfo = pWInfo;
  122187. pWC->pOuter = 0;
  122188. pWC->nTerm = 0;
  122189. pWC->nSlot = ArraySize(pWC->aStatic);
  122190. pWC->a = pWC->aStatic;
  122191. }
  122192. /*
  122193. ** Deallocate a WhereClause structure. The WhereClause structure
  122194. ** itself is not freed. This routine is the inverse of
  122195. ** sqlite3WhereClauseInit().
  122196. */
  122197. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  122198. int i;
  122199. WhereTerm *a;
  122200. sqlite3 *db = pWC->pWInfo->pParse->db;
  122201. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  122202. if( a->wtFlags & TERM_DYNAMIC ){
  122203. sqlite3ExprDelete(db, a->pExpr);
  122204. }
  122205. if( a->wtFlags & TERM_ORINFO ){
  122206. whereOrInfoDelete(db, a->u.pOrInfo);
  122207. }else if( a->wtFlags & TERM_ANDINFO ){
  122208. whereAndInfoDelete(db, a->u.pAndInfo);
  122209. }
  122210. }
  122211. if( pWC->a!=pWC->aStatic ){
  122212. sqlite3DbFree(db, pWC->a);
  122213. }
  122214. }
  122215. /*
  122216. ** These routines walk (recursively) an expression tree and generate
  122217. ** a bitmask indicating which tables are used in that expression
  122218. ** tree.
  122219. */
  122220. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  122221. Bitmask mask;
  122222. if( p==0 ) return 0;
  122223. if( p->op==TK_COLUMN ){
  122224. return sqlite3WhereGetMask(pMaskSet, p->iTable);
  122225. }
  122226. mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
  122227. assert( !ExprHasProperty(p, EP_TokenOnly) );
  122228. if( p->pRight ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
  122229. if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  122230. if( ExprHasProperty(p, EP_xIsSelect) ){
  122231. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  122232. }else if( p->x.pList ){
  122233. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  122234. }
  122235. return mask;
  122236. }
  122237. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  122238. int i;
  122239. Bitmask mask = 0;
  122240. if( pList ){
  122241. for(i=0; i<pList->nExpr; i++){
  122242. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  122243. }
  122244. }
  122245. return mask;
  122246. }
  122247. /*
  122248. ** Call exprAnalyze on all terms in a WHERE clause.
  122249. **
  122250. ** Note that exprAnalyze() might add new virtual terms onto the
  122251. ** end of the WHERE clause. We do not want to analyze these new
  122252. ** virtual terms, so start analyzing at the end and work forward
  122253. ** so that the added virtual terms are never processed.
  122254. */
  122255. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  122256. SrcList *pTabList, /* the FROM clause */
  122257. WhereClause *pWC /* the WHERE clause to be analyzed */
  122258. ){
  122259. int i;
  122260. for(i=pWC->nTerm-1; i>=0; i--){
  122261. exprAnalyze(pTabList, pWC, i);
  122262. }
  122263. }
  122264. /*
  122265. ** For table-valued-functions, transform the function arguments into
  122266. ** new WHERE clause terms.
  122267. **
  122268. ** Each function argument translates into an equality constraint against
  122269. ** a HIDDEN column in the table.
  122270. */
  122271. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  122272. Parse *pParse, /* Parsing context */
  122273. struct SrcList_item *pItem, /* The FROM clause term to process */
  122274. WhereClause *pWC /* Xfer function arguments to here */
  122275. ){
  122276. Table *pTab;
  122277. int j, k;
  122278. ExprList *pArgs;
  122279. Expr *pColRef;
  122280. Expr *pTerm;
  122281. if( pItem->fg.isTabFunc==0 ) return;
  122282. pTab = pItem->pTab;
  122283. assert( pTab!=0 );
  122284. pArgs = pItem->u1.pFuncArg;
  122285. if( pArgs==0 ) return;
  122286. for(j=k=0; j<pArgs->nExpr; j++){
  122287. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  122288. if( k>=pTab->nCol ){
  122289. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  122290. pTab->zName, j);
  122291. return;
  122292. }
  122293. pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
  122294. if( pColRef==0 ) return;
  122295. pColRef->iTable = pItem->iCursor;
  122296. pColRef->iColumn = k++;
  122297. pColRef->pTab = pTab;
  122298. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
  122299. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
  122300. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  122301. }
  122302. }
  122303. /************** End of whereexpr.c *******************************************/
  122304. /************** Begin file where.c *******************************************/
  122305. /*
  122306. ** 2001 September 15
  122307. **
  122308. ** The author disclaims copyright to this source code. In place of
  122309. ** a legal notice, here is a blessing:
  122310. **
  122311. ** May you do good and not evil.
  122312. ** May you find forgiveness for yourself and forgive others.
  122313. ** May you share freely, never taking more than you give.
  122314. **
  122315. *************************************************************************
  122316. ** This module contains C code that generates VDBE code used to process
  122317. ** the WHERE clause of SQL statements. This module is responsible for
  122318. ** generating the code that loops through a table looking for applicable
  122319. ** rows. Indices are selected and used to speed the search when doing
  122320. ** so is applicable. Because this module is responsible for selecting
  122321. ** indices, you might also think of this module as the "query optimizer".
  122322. */
  122323. /* #include "sqliteInt.h" */
  122324. /* #include "whereInt.h" */
  122325. /* Forward declaration of methods */
  122326. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  122327. /* Test variable that can be set to enable WHERE tracing */
  122328. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  122329. /***/ int sqlite3WhereTrace = 0;
  122330. #endif
  122331. /*
  122332. ** Return the estimated number of output rows from a WHERE clause
  122333. */
  122334. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  122335. return pWInfo->nRowOut;
  122336. }
  122337. /*
  122338. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  122339. ** WHERE clause returns outputs for DISTINCT processing.
  122340. */
  122341. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  122342. return pWInfo->eDistinct;
  122343. }
  122344. /*
  122345. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  122346. ** Return FALSE if the output needs to be sorted.
  122347. */
  122348. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  122349. return pWInfo->nOBSat;
  122350. }
  122351. /*
  122352. ** Return TRUE if the innermost loop of the WHERE clause implementation
  122353. ** returns rows in ORDER BY order for complete run of the inner loop.
  122354. **
  122355. ** Across multiple iterations of outer loops, the output rows need not be
  122356. ** sorted. As long as rows are sorted for just the innermost loop, this
  122357. ** routine can return TRUE.
  122358. */
  122359. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
  122360. return pWInfo->bOrderedInnerLoop;
  122361. }
  122362. /*
  122363. ** Return the VDBE address or label to jump to in order to continue
  122364. ** immediately with the next row of a WHERE clause.
  122365. */
  122366. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  122367. assert( pWInfo->iContinue!=0 );
  122368. return pWInfo->iContinue;
  122369. }
  122370. /*
  122371. ** Return the VDBE address or label to jump to in order to break
  122372. ** out of a WHERE loop.
  122373. */
  122374. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  122375. return pWInfo->iBreak;
  122376. }
  122377. /*
  122378. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  122379. ** operate directly on the rowis returned by a WHERE clause. Return
  122380. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  122381. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  122382. ** optimization can be used on multiple
  122383. **
  122384. ** If the ONEPASS optimization is used (if this routine returns true)
  122385. ** then also write the indices of open cursors used by ONEPASS
  122386. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  122387. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  122388. ** Either value may be -1, indicating that cursor is not used.
  122389. ** Any cursors returned will have been opened for writing.
  122390. **
  122391. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  122392. ** unable to use the ONEPASS optimization.
  122393. */
  122394. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  122395. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  122396. #ifdef WHERETRACE_ENABLED
  122397. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  122398. sqlite3DebugPrintf("%s cursors: %d %d\n",
  122399. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  122400. aiCur[0], aiCur[1]);
  122401. }
  122402. #endif
  122403. return pWInfo->eOnePass;
  122404. }
  122405. /*
  122406. ** Move the content of pSrc into pDest
  122407. */
  122408. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  122409. pDest->n = pSrc->n;
  122410. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  122411. }
  122412. /*
  122413. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  122414. **
  122415. ** The new entry might overwrite an existing entry, or it might be
  122416. ** appended, or it might be discarded. Do whatever is the right thing
  122417. ** so that pSet keeps the N_OR_COST best entries seen so far.
  122418. */
  122419. static int whereOrInsert(
  122420. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  122421. Bitmask prereq, /* Prerequisites of the new entry */
  122422. LogEst rRun, /* Run-cost of the new entry */
  122423. LogEst nOut /* Number of outputs for the new entry */
  122424. ){
  122425. u16 i;
  122426. WhereOrCost *p;
  122427. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  122428. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  122429. goto whereOrInsert_done;
  122430. }
  122431. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  122432. return 0;
  122433. }
  122434. }
  122435. if( pSet->n<N_OR_COST ){
  122436. p = &pSet->a[pSet->n++];
  122437. p->nOut = nOut;
  122438. }else{
  122439. p = pSet->a;
  122440. for(i=1; i<pSet->n; i++){
  122441. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  122442. }
  122443. if( p->rRun<=rRun ) return 0;
  122444. }
  122445. whereOrInsert_done:
  122446. p->prereq = prereq;
  122447. p->rRun = rRun;
  122448. if( p->nOut>nOut ) p->nOut = nOut;
  122449. return 1;
  122450. }
  122451. /*
  122452. ** Return the bitmask for the given cursor number. Return 0 if
  122453. ** iCursor is not in the set.
  122454. */
  122455. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  122456. int i;
  122457. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  122458. for(i=0; i<pMaskSet->n; i++){
  122459. if( pMaskSet->ix[i]==iCursor ){
  122460. return MASKBIT(i);
  122461. }
  122462. }
  122463. return 0;
  122464. }
  122465. /*
  122466. ** Create a new mask for cursor iCursor.
  122467. **
  122468. ** There is one cursor per table in the FROM clause. The number of
  122469. ** tables in the FROM clause is limited by a test early in the
  122470. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  122471. ** array will never overflow.
  122472. */
  122473. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  122474. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  122475. pMaskSet->ix[pMaskSet->n++] = iCursor;
  122476. }
  122477. /*
  122478. ** Advance to the next WhereTerm that matches according to the criteria
  122479. ** established when the pScan object was initialized by whereScanInit().
  122480. ** Return NULL if there are no more matching WhereTerms.
  122481. */
  122482. static WhereTerm *whereScanNext(WhereScan *pScan){
  122483. int iCur; /* The cursor on the LHS of the term */
  122484. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  122485. Expr *pX; /* An expression being tested */
  122486. WhereClause *pWC; /* Shorthand for pScan->pWC */
  122487. WhereTerm *pTerm; /* The term being tested */
  122488. int k = pScan->k; /* Where to start scanning */
  122489. assert( pScan->iEquiv<=pScan->nEquiv );
  122490. pWC = pScan->pWC;
  122491. while(1){
  122492. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  122493. iCur = pScan->aiCur[pScan->iEquiv-1];
  122494. assert( pWC!=0 );
  122495. do{
  122496. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  122497. if( pTerm->leftCursor==iCur
  122498. && pTerm->u.leftColumn==iColumn
  122499. && (iColumn!=XN_EXPR
  122500. || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
  122501. pScan->pIdxExpr,iCur)==0)
  122502. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  122503. ){
  122504. if( (pTerm->eOperator & WO_EQUIV)!=0
  122505. && pScan->nEquiv<ArraySize(pScan->aiCur)
  122506. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  122507. ){
  122508. int j;
  122509. for(j=0; j<pScan->nEquiv; j++){
  122510. if( pScan->aiCur[j]==pX->iTable
  122511. && pScan->aiColumn[j]==pX->iColumn ){
  122512. break;
  122513. }
  122514. }
  122515. if( j==pScan->nEquiv ){
  122516. pScan->aiCur[j] = pX->iTable;
  122517. pScan->aiColumn[j] = pX->iColumn;
  122518. pScan->nEquiv++;
  122519. }
  122520. }
  122521. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  122522. /* Verify the affinity and collating sequence match */
  122523. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  122524. CollSeq *pColl;
  122525. Parse *pParse = pWC->pWInfo->pParse;
  122526. pX = pTerm->pExpr;
  122527. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  122528. continue;
  122529. }
  122530. assert(pX->pLeft);
  122531. pColl = sqlite3BinaryCompareCollSeq(pParse,
  122532. pX->pLeft, pX->pRight);
  122533. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  122534. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  122535. continue;
  122536. }
  122537. }
  122538. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  122539. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  122540. && pX->iTable==pScan->aiCur[0]
  122541. && pX->iColumn==pScan->aiColumn[0]
  122542. ){
  122543. testcase( pTerm->eOperator & WO_IS );
  122544. continue;
  122545. }
  122546. pScan->pWC = pWC;
  122547. pScan->k = k+1;
  122548. return pTerm;
  122549. }
  122550. }
  122551. }
  122552. pWC = pWC->pOuter;
  122553. k = 0;
  122554. }while( pWC!=0 );
  122555. if( pScan->iEquiv>=pScan->nEquiv ) break;
  122556. pWC = pScan->pOrigWC;
  122557. k = 0;
  122558. pScan->iEquiv++;
  122559. }
  122560. return 0;
  122561. }
  122562. /*
  122563. ** Initialize a WHERE clause scanner object. Return a pointer to the
  122564. ** first match. Return NULL if there are no matches.
  122565. **
  122566. ** The scanner will be searching the WHERE clause pWC. It will look
  122567. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  122568. ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
  122569. ** must be one of the indexes of table iCur.
  122570. **
  122571. ** The <op> must be one of the operators described by opMask.
  122572. **
  122573. ** If the search is for X and the WHERE clause contains terms of the
  122574. ** form X=Y then this routine might also return terms of the form
  122575. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  122576. ** but is enough to handle most commonly occurring SQL statements.
  122577. **
  122578. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  122579. ** index pIdx.
  122580. */
  122581. static WhereTerm *whereScanInit(
  122582. WhereScan *pScan, /* The WhereScan object being initialized */
  122583. WhereClause *pWC, /* The WHERE clause to be scanned */
  122584. int iCur, /* Cursor to scan for */
  122585. int iColumn, /* Column to scan for */
  122586. u32 opMask, /* Operator(s) to scan for */
  122587. Index *pIdx /* Must be compatible with this index */
  122588. ){
  122589. pScan->pOrigWC = pWC;
  122590. pScan->pWC = pWC;
  122591. pScan->pIdxExpr = 0;
  122592. pScan->idxaff = 0;
  122593. pScan->zCollName = 0;
  122594. if( pIdx ){
  122595. int j = iColumn;
  122596. iColumn = pIdx->aiColumn[j];
  122597. if( iColumn==XN_EXPR ){
  122598. pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  122599. pScan->zCollName = pIdx->azColl[j];
  122600. }else if( iColumn==pIdx->pTable->iPKey ){
  122601. iColumn = XN_ROWID;
  122602. }else if( iColumn>=0 ){
  122603. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  122604. pScan->zCollName = pIdx->azColl[j];
  122605. }
  122606. }else if( iColumn==XN_EXPR ){
  122607. return 0;
  122608. }
  122609. pScan->opMask = opMask;
  122610. pScan->k = 0;
  122611. pScan->aiCur[0] = iCur;
  122612. pScan->aiColumn[0] = iColumn;
  122613. pScan->nEquiv = 1;
  122614. pScan->iEquiv = 1;
  122615. return whereScanNext(pScan);
  122616. }
  122617. /*
  122618. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  122619. ** where X is a reference to the iColumn of table iCur or of index pIdx
  122620. ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
  122621. ** the op parameter. Return a pointer to the term. Return 0 if not found.
  122622. **
  122623. ** If pIdx!=0 then it must be one of the indexes of table iCur.
  122624. ** Search for terms matching the iColumn-th column of pIdx
  122625. ** rather than the iColumn-th column of table iCur.
  122626. **
  122627. ** The term returned might by Y=<expr> if there is another constraint in
  122628. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  122629. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  122630. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  122631. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  122632. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  122633. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  122634. **
  122635. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  122636. ** then try for the one with no dependencies on <expr> - in other words where
  122637. ** <expr> is a constant expression of some kind. Only return entries of
  122638. ** the form "X <op> Y" where Y is a column in another table if no terms of
  122639. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  122640. ** exist, try to return a term that does not use WO_EQUIV.
  122641. */
  122642. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  122643. WhereClause *pWC, /* The WHERE clause to be searched */
  122644. int iCur, /* Cursor number of LHS */
  122645. int iColumn, /* Column number of LHS */
  122646. Bitmask notReady, /* RHS must not overlap with this mask */
  122647. u32 op, /* Mask of WO_xx values describing operator */
  122648. Index *pIdx /* Must be compatible with this index, if not NULL */
  122649. ){
  122650. WhereTerm *pResult = 0;
  122651. WhereTerm *p;
  122652. WhereScan scan;
  122653. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  122654. op &= WO_EQ|WO_IS;
  122655. while( p ){
  122656. if( (p->prereqRight & notReady)==0 ){
  122657. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  122658. testcase( p->eOperator & WO_IS );
  122659. return p;
  122660. }
  122661. if( pResult==0 ) pResult = p;
  122662. }
  122663. p = whereScanNext(&scan);
  122664. }
  122665. return pResult;
  122666. }
  122667. /*
  122668. ** This function searches pList for an entry that matches the iCol-th column
  122669. ** of index pIdx.
  122670. **
  122671. ** If such an expression is found, its index in pList->a[] is returned. If
  122672. ** no expression is found, -1 is returned.
  122673. */
  122674. static int findIndexCol(
  122675. Parse *pParse, /* Parse context */
  122676. ExprList *pList, /* Expression list to search */
  122677. int iBase, /* Cursor for table associated with pIdx */
  122678. Index *pIdx, /* Index to match column of */
  122679. int iCol /* Column of index to match */
  122680. ){
  122681. int i;
  122682. const char *zColl = pIdx->azColl[iCol];
  122683. for(i=0; i<pList->nExpr; i++){
  122684. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  122685. if( p->op==TK_COLUMN
  122686. && p->iColumn==pIdx->aiColumn[iCol]
  122687. && p->iTable==iBase
  122688. ){
  122689. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  122690. if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  122691. return i;
  122692. }
  122693. }
  122694. }
  122695. return -1;
  122696. }
  122697. /*
  122698. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  122699. */
  122700. static int indexColumnNotNull(Index *pIdx, int iCol){
  122701. int j;
  122702. assert( pIdx!=0 );
  122703. assert( iCol>=0 && iCol<pIdx->nColumn );
  122704. j = pIdx->aiColumn[iCol];
  122705. if( j>=0 ){
  122706. return pIdx->pTable->aCol[j].notNull;
  122707. }else if( j==(-1) ){
  122708. return 1;
  122709. }else{
  122710. assert( j==(-2) );
  122711. return 0; /* Assume an indexed expression can always yield a NULL */
  122712. }
  122713. }
  122714. /*
  122715. ** Return true if the DISTINCT expression-list passed as the third argument
  122716. ** is redundant.
  122717. **
  122718. ** A DISTINCT list is redundant if any subset of the columns in the
  122719. ** DISTINCT list are collectively unique and individually non-null.
  122720. */
  122721. static int isDistinctRedundant(
  122722. Parse *pParse, /* Parsing context */
  122723. SrcList *pTabList, /* The FROM clause */
  122724. WhereClause *pWC, /* The WHERE clause */
  122725. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  122726. ){
  122727. Table *pTab;
  122728. Index *pIdx;
  122729. int i;
  122730. int iBase;
  122731. /* If there is more than one table or sub-select in the FROM clause of
  122732. ** this query, then it will not be possible to show that the DISTINCT
  122733. ** clause is redundant. */
  122734. if( pTabList->nSrc!=1 ) return 0;
  122735. iBase = pTabList->a[0].iCursor;
  122736. pTab = pTabList->a[0].pTab;
  122737. /* If any of the expressions is an IPK column on table iBase, then return
  122738. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  122739. ** current SELECT is a correlated sub-query.
  122740. */
  122741. for(i=0; i<pDistinct->nExpr; i++){
  122742. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  122743. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  122744. }
  122745. /* Loop through all indices on the table, checking each to see if it makes
  122746. ** the DISTINCT qualifier redundant. It does so if:
  122747. **
  122748. ** 1. The index is itself UNIQUE, and
  122749. **
  122750. ** 2. All of the columns in the index are either part of the pDistinct
  122751. ** list, or else the WHERE clause contains a term of the form "col=X",
  122752. ** where X is a constant value. The collation sequences of the
  122753. ** comparison and select-list expressions must match those of the index.
  122754. **
  122755. ** 3. All of those index columns for which the WHERE clause does not
  122756. ** contain a "col=X" term are subject to a NOT NULL constraint.
  122757. */
  122758. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  122759. if( !IsUniqueIndex(pIdx) ) continue;
  122760. for(i=0; i<pIdx->nKeyCol; i++){
  122761. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  122762. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  122763. if( indexColumnNotNull(pIdx, i)==0 ) break;
  122764. }
  122765. }
  122766. if( i==pIdx->nKeyCol ){
  122767. /* This index implies that the DISTINCT qualifier is redundant. */
  122768. return 1;
  122769. }
  122770. }
  122771. return 0;
  122772. }
  122773. /*
  122774. ** Estimate the logarithm of the input value to base 2.
  122775. */
  122776. static LogEst estLog(LogEst N){
  122777. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  122778. }
  122779. /*
  122780. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  122781. **
  122782. ** This routine runs over generated VDBE code and translates OP_Column
  122783. ** opcodes into OP_Copy when the table is being accessed via co-routine
  122784. ** instead of via table lookup.
  122785. **
  122786. ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
  122787. ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
  122788. ** then each OP_Rowid is transformed into an instruction to increment the
  122789. ** value stored in its output register.
  122790. */
  122791. static void translateColumnToCopy(
  122792. Parse *pParse, /* Parsing context */
  122793. int iStart, /* Translate from this opcode to the end */
  122794. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  122795. int iRegister, /* The first column is in this register */
  122796. int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
  122797. ){
  122798. Vdbe *v = pParse->pVdbe;
  122799. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  122800. int iEnd = sqlite3VdbeCurrentAddr(v);
  122801. if( pParse->db->mallocFailed ) return;
  122802. for(; iStart<iEnd; iStart++, pOp++){
  122803. if( pOp->p1!=iTabCur ) continue;
  122804. if( pOp->opcode==OP_Column ){
  122805. pOp->opcode = OP_Copy;
  122806. pOp->p1 = pOp->p2 + iRegister;
  122807. pOp->p2 = pOp->p3;
  122808. pOp->p3 = 0;
  122809. }else if( pOp->opcode==OP_Rowid ){
  122810. if( bIncrRowid ){
  122811. /* Increment the value stored in the P2 operand of the OP_Rowid. */
  122812. pOp->opcode = OP_AddImm;
  122813. pOp->p1 = pOp->p2;
  122814. pOp->p2 = 1;
  122815. }else{
  122816. pOp->opcode = OP_Null;
  122817. pOp->p1 = 0;
  122818. pOp->p3 = 0;
  122819. }
  122820. }
  122821. }
  122822. }
  122823. /*
  122824. ** Two routines for printing the content of an sqlite3_index_info
  122825. ** structure. Used for testing and debugging only. If neither
  122826. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  122827. ** are no-ops.
  122828. */
  122829. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  122830. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  122831. int i;
  122832. if( !sqlite3WhereTrace ) return;
  122833. for(i=0; i<p->nConstraint; i++){
  122834. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  122835. i,
  122836. p->aConstraint[i].iColumn,
  122837. p->aConstraint[i].iTermOffset,
  122838. p->aConstraint[i].op,
  122839. p->aConstraint[i].usable);
  122840. }
  122841. for(i=0; i<p->nOrderBy; i++){
  122842. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  122843. i,
  122844. p->aOrderBy[i].iColumn,
  122845. p->aOrderBy[i].desc);
  122846. }
  122847. }
  122848. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  122849. int i;
  122850. if( !sqlite3WhereTrace ) return;
  122851. for(i=0; i<p->nConstraint; i++){
  122852. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  122853. i,
  122854. p->aConstraintUsage[i].argvIndex,
  122855. p->aConstraintUsage[i].omit);
  122856. }
  122857. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  122858. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  122859. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  122860. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  122861. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  122862. }
  122863. #else
  122864. #define TRACE_IDX_INPUTS(A)
  122865. #define TRACE_IDX_OUTPUTS(A)
  122866. #endif
  122867. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  122868. /*
  122869. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  122870. ** could be used with an index to access pSrc, assuming an appropriate
  122871. ** index existed.
  122872. */
  122873. static int termCanDriveIndex(
  122874. WhereTerm *pTerm, /* WHERE clause term to check */
  122875. struct SrcList_item *pSrc, /* Table we are trying to access */
  122876. Bitmask notReady /* Tables in outer loops of the join */
  122877. ){
  122878. char aff;
  122879. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  122880. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  122881. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  122882. if( pTerm->u.leftColumn<0 ) return 0;
  122883. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  122884. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  122885. testcase( pTerm->pExpr->op==TK_IS );
  122886. return 1;
  122887. }
  122888. #endif
  122889. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  122890. /*
  122891. ** Generate code to construct the Index object for an automatic index
  122892. ** and to set up the WhereLevel object pLevel so that the code generator
  122893. ** makes use of the automatic index.
  122894. */
  122895. static void constructAutomaticIndex(
  122896. Parse *pParse, /* The parsing context */
  122897. WhereClause *pWC, /* The WHERE clause */
  122898. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  122899. Bitmask notReady, /* Mask of cursors that are not available */
  122900. WhereLevel *pLevel /* Write new index here */
  122901. ){
  122902. int nKeyCol; /* Number of columns in the constructed index */
  122903. WhereTerm *pTerm; /* A single term of the WHERE clause */
  122904. WhereTerm *pWCEnd; /* End of pWC->a[] */
  122905. Index *pIdx; /* Object describing the transient index */
  122906. Vdbe *v; /* Prepared statement under construction */
  122907. int addrInit; /* Address of the initialization bypass jump */
  122908. Table *pTable; /* The table being indexed */
  122909. int addrTop; /* Top of the index fill loop */
  122910. int regRecord; /* Register holding an index record */
  122911. int n; /* Column counter */
  122912. int i; /* Loop counter */
  122913. int mxBitCol; /* Maximum column in pSrc->colUsed */
  122914. CollSeq *pColl; /* Collating sequence to on a column */
  122915. WhereLoop *pLoop; /* The Loop object */
  122916. char *zNotUsed; /* Extra space on the end of pIdx */
  122917. Bitmask idxCols; /* Bitmap of columns used for indexing */
  122918. Bitmask extraCols; /* Bitmap of additional columns */
  122919. u8 sentWarning = 0; /* True if a warnning has been issued */
  122920. Expr *pPartial = 0; /* Partial Index Expression */
  122921. int iContinue = 0; /* Jump here to skip excluded rows */
  122922. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  122923. int addrCounter = 0; /* Address where integer counter is initialized */
  122924. int regBase; /* Array of registers where record is assembled */
  122925. /* Generate code to skip over the creation and initialization of the
  122926. ** transient index on 2nd and subsequent iterations of the loop. */
  122927. v = pParse->pVdbe;
  122928. assert( v!=0 );
  122929. addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  122930. /* Count the number of columns that will be added to the index
  122931. ** and used to match WHERE clause constraints */
  122932. nKeyCol = 0;
  122933. pTable = pSrc->pTab;
  122934. pWCEnd = &pWC->a[pWC->nTerm];
  122935. pLoop = pLevel->pWLoop;
  122936. idxCols = 0;
  122937. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  122938. Expr *pExpr = pTerm->pExpr;
  122939. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  122940. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  122941. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  122942. if( pLoop->prereq==0
  122943. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  122944. && !ExprHasProperty(pExpr, EP_FromJoin)
  122945. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  122946. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  122947. sqlite3ExprDup(pParse->db, pExpr, 0));
  122948. }
  122949. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  122950. int iCol = pTerm->u.leftColumn;
  122951. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  122952. testcase( iCol==BMS );
  122953. testcase( iCol==BMS-1 );
  122954. if( !sentWarning ){
  122955. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  122956. "automatic index on %s(%s)", pTable->zName,
  122957. pTable->aCol[iCol].zName);
  122958. sentWarning = 1;
  122959. }
  122960. if( (idxCols & cMask)==0 ){
  122961. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  122962. goto end_auto_index_create;
  122963. }
  122964. pLoop->aLTerm[nKeyCol++] = pTerm;
  122965. idxCols |= cMask;
  122966. }
  122967. }
  122968. }
  122969. assert( nKeyCol>0 );
  122970. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  122971. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  122972. | WHERE_AUTO_INDEX;
  122973. /* Count the number of additional columns needed to create a
  122974. ** covering index. A "covering index" is an index that contains all
  122975. ** columns that are needed by the query. With a covering index, the
  122976. ** original table never needs to be accessed. Automatic indices must
  122977. ** be a covering index because the index will not be updated if the
  122978. ** original table changes and the index and table cannot both be used
  122979. ** if they go out of sync.
  122980. */
  122981. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  122982. mxBitCol = MIN(BMS-1,pTable->nCol);
  122983. testcase( pTable->nCol==BMS-1 );
  122984. testcase( pTable->nCol==BMS-2 );
  122985. for(i=0; i<mxBitCol; i++){
  122986. if( extraCols & MASKBIT(i) ) nKeyCol++;
  122987. }
  122988. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  122989. nKeyCol += pTable->nCol - BMS + 1;
  122990. }
  122991. /* Construct the Index object to describe this index */
  122992. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  122993. if( pIdx==0 ) goto end_auto_index_create;
  122994. pLoop->u.btree.pIndex = pIdx;
  122995. pIdx->zName = "auto-index";
  122996. pIdx->pTable = pTable;
  122997. n = 0;
  122998. idxCols = 0;
  122999. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  123000. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  123001. int iCol = pTerm->u.leftColumn;
  123002. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  123003. testcase( iCol==BMS-1 );
  123004. testcase( iCol==BMS );
  123005. if( (idxCols & cMask)==0 ){
  123006. Expr *pX = pTerm->pExpr;
  123007. idxCols |= cMask;
  123008. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  123009. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  123010. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  123011. n++;
  123012. }
  123013. }
  123014. }
  123015. assert( (u32)n==pLoop->u.btree.nEq );
  123016. /* Add additional columns needed to make the automatic index into
  123017. ** a covering index */
  123018. for(i=0; i<mxBitCol; i++){
  123019. if( extraCols & MASKBIT(i) ){
  123020. pIdx->aiColumn[n] = i;
  123021. pIdx->azColl[n] = sqlite3StrBINARY;
  123022. n++;
  123023. }
  123024. }
  123025. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  123026. for(i=BMS-1; i<pTable->nCol; i++){
  123027. pIdx->aiColumn[n] = i;
  123028. pIdx->azColl[n] = sqlite3StrBINARY;
  123029. n++;
  123030. }
  123031. }
  123032. assert( n==nKeyCol );
  123033. pIdx->aiColumn[n] = XN_ROWID;
  123034. pIdx->azColl[n] = sqlite3StrBINARY;
  123035. /* Create the automatic index */
  123036. assert( pLevel->iIdxCur>=0 );
  123037. pLevel->iIdxCur = pParse->nTab++;
  123038. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  123039. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  123040. VdbeComment((v, "for %s", pTable->zName));
  123041. /* Fill the automatic index with content */
  123042. sqlite3ExprCachePush(pParse);
  123043. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  123044. if( pTabItem->fg.viaCoroutine ){
  123045. int regYield = pTabItem->regReturn;
  123046. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  123047. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  123048. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  123049. VdbeCoverage(v);
  123050. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  123051. }else{
  123052. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  123053. }
  123054. if( pPartial ){
  123055. iContinue = sqlite3VdbeMakeLabel(v);
  123056. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  123057. pLoop->wsFlags |= WHERE_PARTIALIDX;
  123058. }
  123059. regRecord = sqlite3GetTempReg(pParse);
  123060. regBase = sqlite3GenerateIndexKey(
  123061. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  123062. );
  123063. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  123064. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  123065. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  123066. if( pTabItem->fg.viaCoroutine ){
  123067. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  123068. testcase( pParse->db->mallocFailed );
  123069. translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
  123070. pTabItem->regResult, 1);
  123071. sqlite3VdbeGoto(v, addrTop);
  123072. pTabItem->fg.viaCoroutine = 0;
  123073. }else{
  123074. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  123075. }
  123076. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  123077. sqlite3VdbeJumpHere(v, addrTop);
  123078. sqlite3ReleaseTempReg(pParse, regRecord);
  123079. sqlite3ExprCachePop(pParse);
  123080. /* Jump here when skipping the initialization */
  123081. sqlite3VdbeJumpHere(v, addrInit);
  123082. end_auto_index_create:
  123083. sqlite3ExprDelete(pParse->db, pPartial);
  123084. }
  123085. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  123086. #ifndef SQLITE_OMIT_VIRTUALTABLE
  123087. /*
  123088. ** Allocate and populate an sqlite3_index_info structure. It is the
  123089. ** responsibility of the caller to eventually release the structure
  123090. ** by passing the pointer returned by this function to sqlite3_free().
  123091. */
  123092. static sqlite3_index_info *allocateIndexInfo(
  123093. Parse *pParse,
  123094. WhereClause *pWC,
  123095. Bitmask mUnusable, /* Ignore terms with these prereqs */
  123096. struct SrcList_item *pSrc,
  123097. ExprList *pOrderBy,
  123098. u16 *pmNoOmit /* Mask of terms not to omit */
  123099. ){
  123100. int i, j;
  123101. int nTerm;
  123102. struct sqlite3_index_constraint *pIdxCons;
  123103. struct sqlite3_index_orderby *pIdxOrderBy;
  123104. struct sqlite3_index_constraint_usage *pUsage;
  123105. WhereTerm *pTerm;
  123106. int nOrderBy;
  123107. sqlite3_index_info *pIdxInfo;
  123108. u16 mNoOmit = 0;
  123109. /* Count the number of possible WHERE clause constraints referring
  123110. ** to this virtual table */
  123111. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  123112. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  123113. if( pTerm->prereqRight & mUnusable ) continue;
  123114. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  123115. testcase( pTerm->eOperator & WO_IN );
  123116. testcase( pTerm->eOperator & WO_ISNULL );
  123117. testcase( pTerm->eOperator & WO_IS );
  123118. testcase( pTerm->eOperator & WO_ALL );
  123119. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  123120. if( pTerm->wtFlags & TERM_VNULL ) continue;
  123121. assert( pTerm->u.leftColumn>=(-1) );
  123122. nTerm++;
  123123. }
  123124. /* If the ORDER BY clause contains only columns in the current
  123125. ** virtual table then allocate space for the aOrderBy part of
  123126. ** the sqlite3_index_info structure.
  123127. */
  123128. nOrderBy = 0;
  123129. if( pOrderBy ){
  123130. int n = pOrderBy->nExpr;
  123131. for(i=0; i<n; i++){
  123132. Expr *pExpr = pOrderBy->a[i].pExpr;
  123133. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  123134. }
  123135. if( i==n){
  123136. nOrderBy = n;
  123137. }
  123138. }
  123139. /* Allocate the sqlite3_index_info structure
  123140. */
  123141. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  123142. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  123143. + sizeof(*pIdxOrderBy)*nOrderBy );
  123144. if( pIdxInfo==0 ){
  123145. sqlite3ErrorMsg(pParse, "out of memory");
  123146. return 0;
  123147. }
  123148. /* Initialize the structure. The sqlite3_index_info structure contains
  123149. ** many fields that are declared "const" to prevent xBestIndex from
  123150. ** changing them. We have to do some funky casting in order to
  123151. ** initialize those fields.
  123152. */
  123153. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  123154. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  123155. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  123156. *(int*)&pIdxInfo->nConstraint = nTerm;
  123157. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  123158. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  123159. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  123160. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  123161. pUsage;
  123162. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  123163. u8 op;
  123164. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  123165. if( pTerm->prereqRight & mUnusable ) continue;
  123166. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  123167. testcase( pTerm->eOperator & WO_IN );
  123168. testcase( pTerm->eOperator & WO_IS );
  123169. testcase( pTerm->eOperator & WO_ISNULL );
  123170. testcase( pTerm->eOperator & WO_ALL );
  123171. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  123172. if( pTerm->wtFlags & TERM_VNULL ) continue;
  123173. assert( pTerm->u.leftColumn>=(-1) );
  123174. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  123175. pIdxCons[j].iTermOffset = i;
  123176. op = (u8)pTerm->eOperator & WO_ALL;
  123177. if( op==WO_IN ) op = WO_EQ;
  123178. if( op==WO_MATCH ){
  123179. op = pTerm->eMatchOp;
  123180. }
  123181. pIdxCons[j].op = op;
  123182. /* The direct assignment in the previous line is possible only because
  123183. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  123184. ** following asserts verify this fact. */
  123185. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  123186. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  123187. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  123188. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  123189. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  123190. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  123191. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  123192. if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
  123193. && sqlite3ExprIsVector(pTerm->pExpr->pRight)
  123194. ){
  123195. if( i<16 ) mNoOmit |= (1 << i);
  123196. if( op==WO_LT ) pIdxCons[j].op = WO_LE;
  123197. if( op==WO_GT ) pIdxCons[j].op = WO_GE;
  123198. }
  123199. j++;
  123200. }
  123201. for(i=0; i<nOrderBy; i++){
  123202. Expr *pExpr = pOrderBy->a[i].pExpr;
  123203. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  123204. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  123205. }
  123206. *pmNoOmit = mNoOmit;
  123207. return pIdxInfo;
  123208. }
  123209. /*
  123210. ** The table object reference passed as the second argument to this function
  123211. ** must represent a virtual table. This function invokes the xBestIndex()
  123212. ** method of the virtual table with the sqlite3_index_info object that
  123213. ** comes in as the 3rd argument to this function.
  123214. **
  123215. ** If an error occurs, pParse is populated with an error message and a
  123216. ** non-zero value is returned. Otherwise, 0 is returned and the output
  123217. ** part of the sqlite3_index_info structure is left populated.
  123218. **
  123219. ** Whether or not an error is returned, it is the responsibility of the
  123220. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  123221. ** that this is required.
  123222. */
  123223. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  123224. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  123225. int rc;
  123226. TRACE_IDX_INPUTS(p);
  123227. rc = pVtab->pModule->xBestIndex(pVtab, p);
  123228. TRACE_IDX_OUTPUTS(p);
  123229. if( rc!=SQLITE_OK ){
  123230. if( rc==SQLITE_NOMEM ){
  123231. sqlite3OomFault(pParse->db);
  123232. }else if( !pVtab->zErrMsg ){
  123233. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  123234. }else{
  123235. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  123236. }
  123237. }
  123238. sqlite3_free(pVtab->zErrMsg);
  123239. pVtab->zErrMsg = 0;
  123240. #if 0
  123241. /* This error is now caught by the caller.
  123242. ** Search for "xBestIndex malfunction" below */
  123243. for(i=0; i<p->nConstraint; i++){
  123244. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  123245. sqlite3ErrorMsg(pParse,
  123246. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  123247. }
  123248. }
  123249. #endif
  123250. return pParse->nErr;
  123251. }
  123252. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  123253. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123254. /*
  123255. ** Estimate the location of a particular key among all keys in an
  123256. ** index. Store the results in aStat as follows:
  123257. **
  123258. ** aStat[0] Est. number of rows less than pRec
  123259. ** aStat[1] Est. number of rows equal to pRec
  123260. **
  123261. ** Return the index of the sample that is the smallest sample that
  123262. ** is greater than or equal to pRec. Note that this index is not an index
  123263. ** into the aSample[] array - it is an index into a virtual set of samples
  123264. ** based on the contents of aSample[] and the number of fields in record
  123265. ** pRec.
  123266. */
  123267. static int whereKeyStats(
  123268. Parse *pParse, /* Database connection */
  123269. Index *pIdx, /* Index to consider domain of */
  123270. UnpackedRecord *pRec, /* Vector of values to consider */
  123271. int roundUp, /* Round up if true. Round down if false */
  123272. tRowcnt *aStat /* OUT: stats written here */
  123273. ){
  123274. IndexSample *aSample = pIdx->aSample;
  123275. int iCol; /* Index of required stats in anEq[] etc. */
  123276. int i; /* Index of first sample >= pRec */
  123277. int iSample; /* Smallest sample larger than or equal to pRec */
  123278. int iMin = 0; /* Smallest sample not yet tested */
  123279. int iTest; /* Next sample to test */
  123280. int res; /* Result of comparison operation */
  123281. int nField; /* Number of fields in pRec */
  123282. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  123283. #ifndef SQLITE_DEBUG
  123284. UNUSED_PARAMETER( pParse );
  123285. #endif
  123286. assert( pRec!=0 );
  123287. assert( pIdx->nSample>0 );
  123288. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  123289. /* Do a binary search to find the first sample greater than or equal
  123290. ** to pRec. If pRec contains a single field, the set of samples to search
  123291. ** is simply the aSample[] array. If the samples in aSample[] contain more
  123292. ** than one fields, all fields following the first are ignored.
  123293. **
  123294. ** If pRec contains N fields, where N is more than one, then as well as the
  123295. ** samples in aSample[] (truncated to N fields), the search also has to
  123296. ** consider prefixes of those samples. For example, if the set of samples
  123297. ** in aSample is:
  123298. **
  123299. ** aSample[0] = (a, 5)
  123300. ** aSample[1] = (a, 10)
  123301. ** aSample[2] = (b, 5)
  123302. ** aSample[3] = (c, 100)
  123303. ** aSample[4] = (c, 105)
  123304. **
  123305. ** Then the search space should ideally be the samples above and the
  123306. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  123307. ** the code actually searches this set:
  123308. **
  123309. ** 0: (a)
  123310. ** 1: (a, 5)
  123311. ** 2: (a, 10)
  123312. ** 3: (a, 10)
  123313. ** 4: (b)
  123314. ** 5: (b, 5)
  123315. ** 6: (c)
  123316. ** 7: (c, 100)
  123317. ** 8: (c, 105)
  123318. ** 9: (c, 105)
  123319. **
  123320. ** For each sample in the aSample[] array, N samples are present in the
  123321. ** effective sample array. In the above, samples 0 and 1 are based on
  123322. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  123323. **
  123324. ** Often, sample i of each block of N effective samples has (i+1) fields.
  123325. ** Except, each sample may be extended to ensure that it is greater than or
  123326. ** equal to the previous sample in the array. For example, in the above,
  123327. ** sample 2 is the first sample of a block of N samples, so at first it
  123328. ** appears that it should be 1 field in size. However, that would make it
  123329. ** smaller than sample 1, so the binary search would not work. As a result,
  123330. ** it is extended to two fields. The duplicates that this creates do not
  123331. ** cause any problems.
  123332. */
  123333. nField = pRec->nField;
  123334. iCol = 0;
  123335. iSample = pIdx->nSample * nField;
  123336. do{
  123337. int iSamp; /* Index in aSample[] of test sample */
  123338. int n; /* Number of fields in test sample */
  123339. iTest = (iMin+iSample)/2;
  123340. iSamp = iTest / nField;
  123341. if( iSamp>0 ){
  123342. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  123343. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  123344. ** fields that is greater than the previous effective sample. */
  123345. for(n=(iTest % nField) + 1; n<nField; n++){
  123346. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  123347. }
  123348. }else{
  123349. n = iTest + 1;
  123350. }
  123351. pRec->nField = n;
  123352. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  123353. if( res<0 ){
  123354. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  123355. iMin = iTest+1;
  123356. }else if( res==0 && n<nField ){
  123357. iLower = aSample[iSamp].anLt[n-1];
  123358. iMin = iTest+1;
  123359. res = -1;
  123360. }else{
  123361. iSample = iTest;
  123362. iCol = n-1;
  123363. }
  123364. }while( res && iMin<iSample );
  123365. i = iSample / nField;
  123366. #ifdef SQLITE_DEBUG
  123367. /* The following assert statements check that the binary search code
  123368. ** above found the right answer. This block serves no purpose other
  123369. ** than to invoke the asserts. */
  123370. if( pParse->db->mallocFailed==0 ){
  123371. if( res==0 ){
  123372. /* If (res==0) is true, then pRec must be equal to sample i. */
  123373. assert( i<pIdx->nSample );
  123374. assert( iCol==nField-1 );
  123375. pRec->nField = nField;
  123376. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  123377. || pParse->db->mallocFailed
  123378. );
  123379. }else{
  123380. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  123381. ** all samples in the aSample[] array, pRec must be smaller than the
  123382. ** (iCol+1) field prefix of sample i. */
  123383. assert( i<=pIdx->nSample && i>=0 );
  123384. pRec->nField = iCol+1;
  123385. assert( i==pIdx->nSample
  123386. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  123387. || pParse->db->mallocFailed );
  123388. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  123389. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  123390. ** be greater than or equal to the (iCol) field prefix of sample i.
  123391. ** If (i>0), then pRec must also be greater than sample (i-1). */
  123392. if( iCol>0 ){
  123393. pRec->nField = iCol;
  123394. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  123395. || pParse->db->mallocFailed );
  123396. }
  123397. if( i>0 ){
  123398. pRec->nField = nField;
  123399. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  123400. || pParse->db->mallocFailed );
  123401. }
  123402. }
  123403. }
  123404. #endif /* ifdef SQLITE_DEBUG */
  123405. if( res==0 ){
  123406. /* Record pRec is equal to sample i */
  123407. assert( iCol==nField-1 );
  123408. aStat[0] = aSample[i].anLt[iCol];
  123409. aStat[1] = aSample[i].anEq[iCol];
  123410. }else{
  123411. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  123412. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  123413. ** is larger than all samples in the array. */
  123414. tRowcnt iUpper, iGap;
  123415. if( i>=pIdx->nSample ){
  123416. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  123417. }else{
  123418. iUpper = aSample[i].anLt[iCol];
  123419. }
  123420. if( iLower>=iUpper ){
  123421. iGap = 0;
  123422. }else{
  123423. iGap = iUpper - iLower;
  123424. }
  123425. if( roundUp ){
  123426. iGap = (iGap*2)/3;
  123427. }else{
  123428. iGap = iGap/3;
  123429. }
  123430. aStat[0] = iLower + iGap;
  123431. aStat[1] = pIdx->aAvgEq[iCol];
  123432. }
  123433. /* Restore the pRec->nField value before returning. */
  123434. pRec->nField = nField;
  123435. return i;
  123436. }
  123437. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  123438. /*
  123439. ** If it is not NULL, pTerm is a term that provides an upper or lower
  123440. ** bound on a range scan. Without considering pTerm, it is estimated
  123441. ** that the scan will visit nNew rows. This function returns the number
  123442. ** estimated to be visited after taking pTerm into account.
  123443. **
  123444. ** If the user explicitly specified a likelihood() value for this term,
  123445. ** then the return value is the likelihood multiplied by the number of
  123446. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  123447. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  123448. */
  123449. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  123450. LogEst nRet = nNew;
  123451. if( pTerm ){
  123452. if( pTerm->truthProb<=0 ){
  123453. nRet += pTerm->truthProb;
  123454. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  123455. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  123456. }
  123457. }
  123458. return nRet;
  123459. }
  123460. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123461. /*
  123462. ** Return the affinity for a single column of an index.
  123463. */
  123464. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  123465. assert( iCol>=0 && iCol<pIdx->nColumn );
  123466. if( !pIdx->zColAff ){
  123467. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  123468. }
  123469. return pIdx->zColAff[iCol];
  123470. }
  123471. #endif
  123472. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123473. /*
  123474. ** This function is called to estimate the number of rows visited by a
  123475. ** range-scan on a skip-scan index. For example:
  123476. **
  123477. ** CREATE INDEX i1 ON t1(a, b, c);
  123478. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  123479. **
  123480. ** Value pLoop->nOut is currently set to the estimated number of rows
  123481. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  123482. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  123483. ** on the stat4 data for the index. this scan will be peformed multiple
  123484. ** times (once for each (a,b) combination that matches a=?) is dealt with
  123485. ** by the caller.
  123486. **
  123487. ** It does this by scanning through all stat4 samples, comparing values
  123488. ** extracted from pLower and pUpper with the corresponding column in each
  123489. ** sample. If L and U are the number of samples found to be less than or
  123490. ** equal to the values extracted from pLower and pUpper respectively, and
  123491. ** N is the total number of samples, the pLoop->nOut value is adjusted
  123492. ** as follows:
  123493. **
  123494. ** nOut = nOut * ( min(U - L, 1) / N )
  123495. **
  123496. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  123497. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  123498. ** U is set to N.
  123499. **
  123500. ** Normally, this function sets *pbDone to 1 before returning. However,
  123501. ** if no value can be extracted from either pLower or pUpper (and so the
  123502. ** estimate of the number of rows delivered remains unchanged), *pbDone
  123503. ** is left as is.
  123504. **
  123505. ** If an error occurs, an SQLite error code is returned. Otherwise,
  123506. ** SQLITE_OK.
  123507. */
  123508. static int whereRangeSkipScanEst(
  123509. Parse *pParse, /* Parsing & code generating context */
  123510. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  123511. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  123512. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  123513. int *pbDone /* Set to true if at least one expr. value extracted */
  123514. ){
  123515. Index *p = pLoop->u.btree.pIndex;
  123516. int nEq = pLoop->u.btree.nEq;
  123517. sqlite3 *db = pParse->db;
  123518. int nLower = -1;
  123519. int nUpper = p->nSample+1;
  123520. int rc = SQLITE_OK;
  123521. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  123522. CollSeq *pColl;
  123523. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  123524. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  123525. sqlite3_value *pVal = 0; /* Value extracted from record */
  123526. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  123527. if( pLower ){
  123528. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  123529. nLower = 0;
  123530. }
  123531. if( pUpper && rc==SQLITE_OK ){
  123532. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  123533. nUpper = p2 ? 0 : p->nSample;
  123534. }
  123535. if( p1 || p2 ){
  123536. int i;
  123537. int nDiff;
  123538. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  123539. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  123540. if( rc==SQLITE_OK && p1 ){
  123541. int res = sqlite3MemCompare(p1, pVal, pColl);
  123542. if( res>=0 ) nLower++;
  123543. }
  123544. if( rc==SQLITE_OK && p2 ){
  123545. int res = sqlite3MemCompare(p2, pVal, pColl);
  123546. if( res>=0 ) nUpper++;
  123547. }
  123548. }
  123549. nDiff = (nUpper - nLower);
  123550. if( nDiff<=0 ) nDiff = 1;
  123551. /* If there is both an upper and lower bound specified, and the
  123552. ** comparisons indicate that they are close together, use the fallback
  123553. ** method (assume that the scan visits 1/64 of the rows) for estimating
  123554. ** the number of rows visited. Otherwise, estimate the number of rows
  123555. ** using the method described in the header comment for this function. */
  123556. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  123557. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  123558. pLoop->nOut -= nAdjust;
  123559. *pbDone = 1;
  123560. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  123561. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  123562. }
  123563. }else{
  123564. assert( *pbDone==0 );
  123565. }
  123566. sqlite3ValueFree(p1);
  123567. sqlite3ValueFree(p2);
  123568. sqlite3ValueFree(pVal);
  123569. return rc;
  123570. }
  123571. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  123572. /*
  123573. ** This function is used to estimate the number of rows that will be visited
  123574. ** by scanning an index for a range of values. The range may have an upper
  123575. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  123576. ** and lower bounds are represented by pLower and pUpper respectively. For
  123577. ** example, assuming that index p is on t1(a):
  123578. **
  123579. ** ... FROM t1 WHERE a > ? AND a < ? ...
  123580. ** |_____| |_____|
  123581. ** | |
  123582. ** pLower pUpper
  123583. **
  123584. ** If either of the upper or lower bound is not present, then NULL is passed in
  123585. ** place of the corresponding WhereTerm.
  123586. **
  123587. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  123588. ** column subject to the range constraint. Or, equivalently, the number of
  123589. ** equality constraints optimized by the proposed index scan. For example,
  123590. ** assuming index p is on t1(a, b), and the SQL query is:
  123591. **
  123592. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  123593. **
  123594. ** then nEq is set to 1 (as the range restricted column, b, is the second
  123595. ** left-most column of the index). Or, if the query is:
  123596. **
  123597. ** ... FROM t1 WHERE a > ? AND a < ? ...
  123598. **
  123599. ** then nEq is set to 0.
  123600. **
  123601. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  123602. ** number of rows that the index scan is expected to visit without
  123603. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  123604. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  123605. ** to account for the range constraints pLower and pUpper.
  123606. **
  123607. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  123608. ** used, a single range inequality reduces the search space by a factor of 4.
  123609. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  123610. ** rows visited by a factor of 64.
  123611. */
  123612. static int whereRangeScanEst(
  123613. Parse *pParse, /* Parsing & code generating context */
  123614. WhereLoopBuilder *pBuilder,
  123615. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  123616. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  123617. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  123618. ){
  123619. int rc = SQLITE_OK;
  123620. int nOut = pLoop->nOut;
  123621. LogEst nNew;
  123622. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123623. Index *p = pLoop->u.btree.pIndex;
  123624. int nEq = pLoop->u.btree.nEq;
  123625. if( p->nSample>0 && nEq<p->nSampleCol ){
  123626. if( nEq==pBuilder->nRecValid ){
  123627. UnpackedRecord *pRec = pBuilder->pRec;
  123628. tRowcnt a[2];
  123629. int nBtm = pLoop->u.btree.nBtm;
  123630. int nTop = pLoop->u.btree.nTop;
  123631. /* Variable iLower will be set to the estimate of the number of rows in
  123632. ** the index that are less than the lower bound of the range query. The
  123633. ** lower bound being the concatenation of $P and $L, where $P is the
  123634. ** key-prefix formed by the nEq values matched against the nEq left-most
  123635. ** columns of the index, and $L is the value in pLower.
  123636. **
  123637. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  123638. ** is not a simple variable or literal value), the lower bound of the
  123639. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  123640. ** if $L is available, whereKeyStats() is called for both ($P) and
  123641. ** ($P:$L) and the larger of the two returned values is used.
  123642. **
  123643. ** Similarly, iUpper is to be set to the estimate of the number of rows
  123644. ** less than the upper bound of the range query. Where the upper bound
  123645. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  123646. ** of iUpper are requested of whereKeyStats() and the smaller used.
  123647. **
  123648. ** The number of rows between the two bounds is then just iUpper-iLower.
  123649. */
  123650. tRowcnt iLower; /* Rows less than the lower bound */
  123651. tRowcnt iUpper; /* Rows less than the upper bound */
  123652. int iLwrIdx = -2; /* aSample[] for the lower bound */
  123653. int iUprIdx = -1; /* aSample[] for the upper bound */
  123654. if( pRec ){
  123655. testcase( pRec->nField!=pBuilder->nRecValid );
  123656. pRec->nField = pBuilder->nRecValid;
  123657. }
  123658. /* Determine iLower and iUpper using ($P) only. */
  123659. if( nEq==0 ){
  123660. iLower = 0;
  123661. iUpper = p->nRowEst0;
  123662. }else{
  123663. /* Note: this call could be optimized away - since the same values must
  123664. ** have been requested when testing key $P in whereEqualScanEst(). */
  123665. whereKeyStats(pParse, p, pRec, 0, a);
  123666. iLower = a[0];
  123667. iUpper = a[0] + a[1];
  123668. }
  123669. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  123670. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  123671. assert( p->aSortOrder!=0 );
  123672. if( p->aSortOrder[nEq] ){
  123673. /* The roles of pLower and pUpper are swapped for a DESC index */
  123674. SWAP(WhereTerm*, pLower, pUpper);
  123675. SWAP(int, nBtm, nTop);
  123676. }
  123677. /* If possible, improve on the iLower estimate using ($P:$L). */
  123678. if( pLower ){
  123679. int n; /* Values extracted from pExpr */
  123680. Expr *pExpr = pLower->pExpr->pRight;
  123681. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
  123682. if( rc==SQLITE_OK && n ){
  123683. tRowcnt iNew;
  123684. u16 mask = WO_GT|WO_LE;
  123685. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  123686. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  123687. iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
  123688. if( iNew>iLower ) iLower = iNew;
  123689. nOut--;
  123690. pLower = 0;
  123691. }
  123692. }
  123693. /* If possible, improve on the iUpper estimate using ($P:$U). */
  123694. if( pUpper ){
  123695. int n; /* Values extracted from pExpr */
  123696. Expr *pExpr = pUpper->pExpr->pRight;
  123697. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
  123698. if( rc==SQLITE_OK && n ){
  123699. tRowcnt iNew;
  123700. u16 mask = WO_GT|WO_LE;
  123701. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  123702. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  123703. iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
  123704. if( iNew<iUpper ) iUpper = iNew;
  123705. nOut--;
  123706. pUpper = 0;
  123707. }
  123708. }
  123709. pBuilder->pRec = pRec;
  123710. if( rc==SQLITE_OK ){
  123711. if( iUpper>iLower ){
  123712. nNew = sqlite3LogEst(iUpper - iLower);
  123713. /* TUNING: If both iUpper and iLower are derived from the same
  123714. ** sample, then assume they are 4x more selective. This brings
  123715. ** the estimated selectivity more in line with what it would be
  123716. ** if estimated without the use of STAT3/4 tables. */
  123717. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  123718. }else{
  123719. nNew = 10; assert( 10==sqlite3LogEst(2) );
  123720. }
  123721. if( nNew<nOut ){
  123722. nOut = nNew;
  123723. }
  123724. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  123725. (u32)iLower, (u32)iUpper, nOut));
  123726. }
  123727. }else{
  123728. int bDone = 0;
  123729. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  123730. if( bDone ) return rc;
  123731. }
  123732. }
  123733. #else
  123734. UNUSED_PARAMETER(pParse);
  123735. UNUSED_PARAMETER(pBuilder);
  123736. assert( pLower || pUpper );
  123737. #endif
  123738. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  123739. nNew = whereRangeAdjust(pLower, nOut);
  123740. nNew = whereRangeAdjust(pUpper, nNew);
  123741. /* TUNING: If there is both an upper and lower limit and neither limit
  123742. ** has an application-defined likelihood(), assume the range is
  123743. ** reduced by an additional 75%. This means that, by default, an open-ended
  123744. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  123745. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  123746. ** match 1/64 of the index. */
  123747. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  123748. nNew -= 20;
  123749. }
  123750. nOut -= (pLower!=0) + (pUpper!=0);
  123751. if( nNew<10 ) nNew = 10;
  123752. if( nNew<nOut ) nOut = nNew;
  123753. #if defined(WHERETRACE_ENABLED)
  123754. if( pLoop->nOut>nOut ){
  123755. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  123756. pLoop->nOut, nOut));
  123757. }
  123758. #endif
  123759. pLoop->nOut = (LogEst)nOut;
  123760. return rc;
  123761. }
  123762. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123763. /*
  123764. ** Estimate the number of rows that will be returned based on
  123765. ** an equality constraint x=VALUE and where that VALUE occurs in
  123766. ** the histogram data. This only works when x is the left-most
  123767. ** column of an index and sqlite_stat3 histogram data is available
  123768. ** for that index. When pExpr==NULL that means the constraint is
  123769. ** "x IS NULL" instead of "x=VALUE".
  123770. **
  123771. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  123772. ** If unable to make an estimate, leave *pnRow unchanged and return
  123773. ** non-zero.
  123774. **
  123775. ** This routine can fail if it is unable to load a collating sequence
  123776. ** required for string comparison, or if unable to allocate memory
  123777. ** for a UTF conversion required for comparison. The error is stored
  123778. ** in the pParse structure.
  123779. */
  123780. static int whereEqualScanEst(
  123781. Parse *pParse, /* Parsing & code generating context */
  123782. WhereLoopBuilder *pBuilder,
  123783. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  123784. tRowcnt *pnRow /* Write the revised row estimate here */
  123785. ){
  123786. Index *p = pBuilder->pNew->u.btree.pIndex;
  123787. int nEq = pBuilder->pNew->u.btree.nEq;
  123788. UnpackedRecord *pRec = pBuilder->pRec;
  123789. int rc; /* Subfunction return code */
  123790. tRowcnt a[2]; /* Statistics */
  123791. int bOk;
  123792. assert( nEq>=1 );
  123793. assert( nEq<=p->nColumn );
  123794. assert( p->aSample!=0 );
  123795. assert( p->nSample>0 );
  123796. assert( pBuilder->nRecValid<nEq );
  123797. /* If values are not available for all fields of the index to the left
  123798. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  123799. if( pBuilder->nRecValid<(nEq-1) ){
  123800. return SQLITE_NOTFOUND;
  123801. }
  123802. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  123803. ** below would return the same value. */
  123804. if( nEq>=p->nColumn ){
  123805. *pnRow = 1;
  123806. return SQLITE_OK;
  123807. }
  123808. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
  123809. pBuilder->pRec = pRec;
  123810. if( rc!=SQLITE_OK ) return rc;
  123811. if( bOk==0 ) return SQLITE_NOTFOUND;
  123812. pBuilder->nRecValid = nEq;
  123813. whereKeyStats(pParse, p, pRec, 0, a);
  123814. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  123815. p->zName, nEq-1, (int)a[1]));
  123816. *pnRow = a[1];
  123817. return rc;
  123818. }
  123819. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  123820. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123821. /*
  123822. ** Estimate the number of rows that will be returned based on
  123823. ** an IN constraint where the right-hand side of the IN operator
  123824. ** is a list of values. Example:
  123825. **
  123826. ** WHERE x IN (1,2,3,4)
  123827. **
  123828. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  123829. ** If unable to make an estimate, leave *pnRow unchanged and return
  123830. ** non-zero.
  123831. **
  123832. ** This routine can fail if it is unable to load a collating sequence
  123833. ** required for string comparison, or if unable to allocate memory
  123834. ** for a UTF conversion required for comparison. The error is stored
  123835. ** in the pParse structure.
  123836. */
  123837. static int whereInScanEst(
  123838. Parse *pParse, /* Parsing & code generating context */
  123839. WhereLoopBuilder *pBuilder,
  123840. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  123841. tRowcnt *pnRow /* Write the revised row estimate here */
  123842. ){
  123843. Index *p = pBuilder->pNew->u.btree.pIndex;
  123844. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  123845. int nRecValid = pBuilder->nRecValid;
  123846. int rc = SQLITE_OK; /* Subfunction return code */
  123847. tRowcnt nEst; /* Number of rows for a single term */
  123848. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  123849. int i; /* Loop counter */
  123850. assert( p->aSample!=0 );
  123851. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  123852. nEst = nRow0;
  123853. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  123854. nRowEst += nEst;
  123855. pBuilder->nRecValid = nRecValid;
  123856. }
  123857. if( rc==SQLITE_OK ){
  123858. if( nRowEst > nRow0 ) nRowEst = nRow0;
  123859. *pnRow = nRowEst;
  123860. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  123861. }
  123862. assert( pBuilder->nRecValid==nRecValid );
  123863. return rc;
  123864. }
  123865. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  123866. #ifdef WHERETRACE_ENABLED
  123867. /*
  123868. ** Print the content of a WhereTerm object
  123869. */
  123870. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  123871. if( pTerm==0 ){
  123872. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  123873. }else{
  123874. char zType[4];
  123875. char zLeft[50];
  123876. memcpy(zType, "...", 4);
  123877. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  123878. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  123879. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  123880. if( pTerm->eOperator & WO_SINGLE ){
  123881. sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
  123882. pTerm->leftCursor, pTerm->u.leftColumn);
  123883. }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
  123884. sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
  123885. pTerm->u.pOrInfo->indexable);
  123886. }else{
  123887. sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
  123888. }
  123889. sqlite3DebugPrintf(
  123890. "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
  123891. iTerm, pTerm, zType, zLeft, pTerm->truthProb,
  123892. pTerm->eOperator, pTerm->wtFlags);
  123893. if( pTerm->iField ){
  123894. sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
  123895. }else{
  123896. sqlite3DebugPrintf("\n");
  123897. }
  123898. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  123899. }
  123900. }
  123901. #endif
  123902. #ifdef WHERETRACE_ENABLED
  123903. /*
  123904. ** Show the complete content of a WhereClause
  123905. */
  123906. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
  123907. int i;
  123908. for(i=0; i<pWC->nTerm; i++){
  123909. whereTermPrint(&pWC->a[i], i);
  123910. }
  123911. }
  123912. #endif
  123913. #ifdef WHERETRACE_ENABLED
  123914. /*
  123915. ** Print a WhereLoop object for debugging purposes
  123916. */
  123917. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  123918. WhereInfo *pWInfo = pWC->pWInfo;
  123919. int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
  123920. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  123921. Table *pTab = pItem->pTab;
  123922. Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
  123923. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  123924. p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
  123925. sqlite3DebugPrintf(" %12s",
  123926. pItem->zAlias ? pItem->zAlias : pTab->zName);
  123927. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  123928. const char *zName;
  123929. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  123930. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  123931. int i = sqlite3Strlen30(zName) - 1;
  123932. while( zName[i]!='_' ) i--;
  123933. zName += i;
  123934. }
  123935. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  123936. }else{
  123937. sqlite3DebugPrintf("%20s","");
  123938. }
  123939. }else{
  123940. char *z;
  123941. if( p->u.vtab.idxStr ){
  123942. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  123943. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  123944. }else{
  123945. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  123946. }
  123947. sqlite3DebugPrintf(" %-19s", z);
  123948. sqlite3_free(z);
  123949. }
  123950. if( p->wsFlags & WHERE_SKIPSCAN ){
  123951. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  123952. }else{
  123953. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  123954. }
  123955. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  123956. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  123957. int i;
  123958. for(i=0; i<p->nLTerm; i++){
  123959. whereTermPrint(p->aLTerm[i], i);
  123960. }
  123961. }
  123962. }
  123963. #endif
  123964. /*
  123965. ** Convert bulk memory into a valid WhereLoop that can be passed
  123966. ** to whereLoopClear harmlessly.
  123967. */
  123968. static void whereLoopInit(WhereLoop *p){
  123969. p->aLTerm = p->aLTermSpace;
  123970. p->nLTerm = 0;
  123971. p->nLSlot = ArraySize(p->aLTermSpace);
  123972. p->wsFlags = 0;
  123973. }
  123974. /*
  123975. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  123976. */
  123977. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  123978. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  123979. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  123980. sqlite3_free(p->u.vtab.idxStr);
  123981. p->u.vtab.needFree = 0;
  123982. p->u.vtab.idxStr = 0;
  123983. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  123984. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  123985. sqlite3DbFreeNN(db, p->u.btree.pIndex);
  123986. p->u.btree.pIndex = 0;
  123987. }
  123988. }
  123989. }
  123990. /*
  123991. ** Deallocate internal memory used by a WhereLoop object
  123992. */
  123993. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  123994. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  123995. whereLoopClearUnion(db, p);
  123996. whereLoopInit(p);
  123997. }
  123998. /*
  123999. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  124000. */
  124001. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  124002. WhereTerm **paNew;
  124003. if( p->nLSlot>=n ) return SQLITE_OK;
  124004. n = (n+7)&~7;
  124005. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  124006. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  124007. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  124008. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  124009. p->aLTerm = paNew;
  124010. p->nLSlot = n;
  124011. return SQLITE_OK;
  124012. }
  124013. /*
  124014. ** Transfer content from the second pLoop into the first.
  124015. */
  124016. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  124017. whereLoopClearUnion(db, pTo);
  124018. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  124019. memset(&pTo->u, 0, sizeof(pTo->u));
  124020. return SQLITE_NOMEM_BKPT;
  124021. }
  124022. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  124023. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  124024. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  124025. pFrom->u.vtab.needFree = 0;
  124026. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  124027. pFrom->u.btree.pIndex = 0;
  124028. }
  124029. return SQLITE_OK;
  124030. }
  124031. /*
  124032. ** Delete a WhereLoop object
  124033. */
  124034. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  124035. whereLoopClear(db, p);
  124036. sqlite3DbFreeNN(db, p);
  124037. }
  124038. /*
  124039. ** Free a WhereInfo structure
  124040. */
  124041. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  124042. if( ALWAYS(pWInfo) ){
  124043. int i;
  124044. for(i=0; i<pWInfo->nLevel; i++){
  124045. WhereLevel *pLevel = &pWInfo->a[i];
  124046. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  124047. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  124048. }
  124049. }
  124050. sqlite3WhereClauseClear(&pWInfo->sWC);
  124051. while( pWInfo->pLoops ){
  124052. WhereLoop *p = pWInfo->pLoops;
  124053. pWInfo->pLoops = p->pNextLoop;
  124054. whereLoopDelete(db, p);
  124055. }
  124056. sqlite3DbFreeNN(db, pWInfo);
  124057. }
  124058. }
  124059. /*
  124060. ** Return TRUE if all of the following are true:
  124061. **
  124062. ** (1) X has the same or lower cost that Y
  124063. ** (2) X is a proper subset of Y
  124064. ** (3) X skips at least as many columns as Y
  124065. **
  124066. ** By "proper subset" we mean that X uses fewer WHERE clause terms
  124067. ** than Y and that every WHERE clause term used by X is also used
  124068. ** by Y.
  124069. **
  124070. ** If X is a proper subset of Y then Y is a better choice and ought
  124071. ** to have a lower cost. This routine returns TRUE when that cost
  124072. ** relationship is inverted and needs to be adjusted. The third rule
  124073. ** was added because if X uses skip-scan less than Y it still might
  124074. ** deserve a lower cost even if it is a proper subset of Y.
  124075. */
  124076. static int whereLoopCheaperProperSubset(
  124077. const WhereLoop *pX, /* First WhereLoop to compare */
  124078. const WhereLoop *pY /* Compare against this WhereLoop */
  124079. ){
  124080. int i, j;
  124081. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  124082. return 0; /* X is not a subset of Y */
  124083. }
  124084. if( pY->nSkip > pX->nSkip ) return 0;
  124085. if( pX->rRun >= pY->rRun ){
  124086. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  124087. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  124088. }
  124089. for(i=pX->nLTerm-1; i>=0; i--){
  124090. if( pX->aLTerm[i]==0 ) continue;
  124091. for(j=pY->nLTerm-1; j>=0; j--){
  124092. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  124093. }
  124094. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  124095. }
  124096. return 1; /* All conditions meet */
  124097. }
  124098. /*
  124099. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  124100. ** that:
  124101. **
  124102. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  124103. ** subset of pTemplate
  124104. **
  124105. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  124106. ** is a proper subset.
  124107. **
  124108. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  124109. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  124110. ** also used by Y.
  124111. */
  124112. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  124113. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  124114. for(; p; p=p->pNextLoop){
  124115. if( p->iTab!=pTemplate->iTab ) continue;
  124116. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  124117. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  124118. /* Adjust pTemplate cost downward so that it is cheaper than its
  124119. ** subset p. */
  124120. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  124121. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  124122. pTemplate->rRun = p->rRun;
  124123. pTemplate->nOut = p->nOut - 1;
  124124. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  124125. /* Adjust pTemplate cost upward so that it is costlier than p since
  124126. ** pTemplate is a proper subset of p */
  124127. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  124128. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  124129. pTemplate->rRun = p->rRun;
  124130. pTemplate->nOut = p->nOut + 1;
  124131. }
  124132. }
  124133. }
  124134. /*
  124135. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  124136. ** supplanted by pTemplate.
  124137. **
  124138. ** Return NULL if the WhereLoop list contains an entry that can supplant
  124139. ** pTemplate, in other words if pTemplate does not belong on the list.
  124140. **
  124141. ** If pX is a WhereLoop that pTemplate can supplant, then return the
  124142. ** link that points to pX.
  124143. **
  124144. ** If pTemplate cannot supplant any existing element of the list but needs
  124145. ** to be added to the list, then return a pointer to the tail of the list.
  124146. */
  124147. static WhereLoop **whereLoopFindLesser(
  124148. WhereLoop **ppPrev,
  124149. const WhereLoop *pTemplate
  124150. ){
  124151. WhereLoop *p;
  124152. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  124153. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  124154. /* If either the iTab or iSortIdx values for two WhereLoop are different
  124155. ** then those WhereLoops need to be considered separately. Neither is
  124156. ** a candidate to replace the other. */
  124157. continue;
  124158. }
  124159. /* In the current implementation, the rSetup value is either zero
  124160. ** or the cost of building an automatic index (NlogN) and the NlogN
  124161. ** is the same for compatible WhereLoops. */
  124162. assert( p->rSetup==0 || pTemplate->rSetup==0
  124163. || p->rSetup==pTemplate->rSetup );
  124164. /* whereLoopAddBtree() always generates and inserts the automatic index
  124165. ** case first. Hence compatible candidate WhereLoops never have a larger
  124166. ** rSetup. Call this SETUP-INVARIANT */
  124167. assert( p->rSetup>=pTemplate->rSetup );
  124168. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  124169. ** UNIQUE constraint) with one or more == constraints is better
  124170. ** than an automatic index. Unless it is a skip-scan. */
  124171. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  124172. && (pTemplate->nSkip)==0
  124173. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  124174. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  124175. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  124176. ){
  124177. break;
  124178. }
  124179. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  124180. ** discarded. WhereLoop p is better if:
  124181. ** (1) p has no more dependencies than pTemplate, and
  124182. ** (2) p has an equal or lower cost than pTemplate
  124183. */
  124184. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  124185. && p->rSetup<=pTemplate->rSetup /* (2a) */
  124186. && p->rRun<=pTemplate->rRun /* (2b) */
  124187. && p->nOut<=pTemplate->nOut /* (2c) */
  124188. ){
  124189. return 0; /* Discard pTemplate */
  124190. }
  124191. /* If pTemplate is always better than p, then cause p to be overwritten
  124192. ** with pTemplate. pTemplate is better than p if:
  124193. ** (1) pTemplate has no more dependences than p, and
  124194. ** (2) pTemplate has an equal or lower cost than p.
  124195. */
  124196. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  124197. && p->rRun>=pTemplate->rRun /* (2a) */
  124198. && p->nOut>=pTemplate->nOut /* (2b) */
  124199. ){
  124200. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  124201. break; /* Cause p to be overwritten by pTemplate */
  124202. }
  124203. }
  124204. return ppPrev;
  124205. }
  124206. /*
  124207. ** Insert or replace a WhereLoop entry using the template supplied.
  124208. **
  124209. ** An existing WhereLoop entry might be overwritten if the new template
  124210. ** is better and has fewer dependencies. Or the template will be ignored
  124211. ** and no insert will occur if an existing WhereLoop is faster and has
  124212. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  124213. ** added based on the template.
  124214. **
  124215. ** If pBuilder->pOrSet is not NULL then we care about only the
  124216. ** prerequisites and rRun and nOut costs of the N best loops. That
  124217. ** information is gathered in the pBuilder->pOrSet object. This special
  124218. ** processing mode is used only for OR clause processing.
  124219. **
  124220. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  124221. ** still might overwrite similar loops with the new template if the
  124222. ** new template is better. Loops may be overwritten if the following
  124223. ** conditions are met:
  124224. **
  124225. ** (1) They have the same iTab.
  124226. ** (2) They have the same iSortIdx.
  124227. ** (3) The template has same or fewer dependencies than the current loop
  124228. ** (4) The template has the same or lower cost than the current loop
  124229. */
  124230. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  124231. WhereLoop **ppPrev, *p;
  124232. WhereInfo *pWInfo = pBuilder->pWInfo;
  124233. sqlite3 *db = pWInfo->pParse->db;
  124234. int rc;
  124235. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  124236. ** and prereqs.
  124237. */
  124238. if( pBuilder->pOrSet!=0 ){
  124239. if( pTemplate->nLTerm ){
  124240. #if WHERETRACE_ENABLED
  124241. u16 n = pBuilder->pOrSet->n;
  124242. int x =
  124243. #endif
  124244. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  124245. pTemplate->nOut);
  124246. #if WHERETRACE_ENABLED /* 0x8 */
  124247. if( sqlite3WhereTrace & 0x8 ){
  124248. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  124249. whereLoopPrint(pTemplate, pBuilder->pWC);
  124250. }
  124251. #endif
  124252. }
  124253. return SQLITE_OK;
  124254. }
  124255. /* Look for an existing WhereLoop to replace with pTemplate
  124256. */
  124257. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  124258. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  124259. if( ppPrev==0 ){
  124260. /* There already exists a WhereLoop on the list that is better
  124261. ** than pTemplate, so just ignore pTemplate */
  124262. #if WHERETRACE_ENABLED /* 0x8 */
  124263. if( sqlite3WhereTrace & 0x8 ){
  124264. sqlite3DebugPrintf(" skip: ");
  124265. whereLoopPrint(pTemplate, pBuilder->pWC);
  124266. }
  124267. #endif
  124268. return SQLITE_OK;
  124269. }else{
  124270. p = *ppPrev;
  124271. }
  124272. /* If we reach this point it means that either p[] should be overwritten
  124273. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  124274. ** WhereLoop and insert it.
  124275. */
  124276. #if WHERETRACE_ENABLED /* 0x8 */
  124277. if( sqlite3WhereTrace & 0x8 ){
  124278. if( p!=0 ){
  124279. sqlite3DebugPrintf("replace: ");
  124280. whereLoopPrint(p, pBuilder->pWC);
  124281. }
  124282. sqlite3DebugPrintf(" add: ");
  124283. whereLoopPrint(pTemplate, pBuilder->pWC);
  124284. }
  124285. #endif
  124286. if( p==0 ){
  124287. /* Allocate a new WhereLoop to add to the end of the list */
  124288. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  124289. if( p==0 ) return SQLITE_NOMEM_BKPT;
  124290. whereLoopInit(p);
  124291. p->pNextLoop = 0;
  124292. }else{
  124293. /* We will be overwriting WhereLoop p[]. But before we do, first
  124294. ** go through the rest of the list and delete any other entries besides
  124295. ** p[] that are also supplated by pTemplate */
  124296. WhereLoop **ppTail = &p->pNextLoop;
  124297. WhereLoop *pToDel;
  124298. while( *ppTail ){
  124299. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  124300. if( ppTail==0 ) break;
  124301. pToDel = *ppTail;
  124302. if( pToDel==0 ) break;
  124303. *ppTail = pToDel->pNextLoop;
  124304. #if WHERETRACE_ENABLED /* 0x8 */
  124305. if( sqlite3WhereTrace & 0x8 ){
  124306. sqlite3DebugPrintf(" delete: ");
  124307. whereLoopPrint(pToDel, pBuilder->pWC);
  124308. }
  124309. #endif
  124310. whereLoopDelete(db, pToDel);
  124311. }
  124312. }
  124313. rc = whereLoopXfer(db, p, pTemplate);
  124314. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  124315. Index *pIndex = p->u.btree.pIndex;
  124316. if( pIndex && pIndex->tnum==0 ){
  124317. p->u.btree.pIndex = 0;
  124318. }
  124319. }
  124320. return rc;
  124321. }
  124322. /*
  124323. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  124324. ** WHERE clause that reference the loop but which are not used by an
  124325. ** index.
  124326. *
  124327. ** For every WHERE clause term that is not used by the index
  124328. ** and which has a truth probability assigned by one of the likelihood(),
  124329. ** likely(), or unlikely() SQL functions, reduce the estimated number
  124330. ** of output rows by the probability specified.
  124331. **
  124332. ** TUNING: For every WHERE clause term that is not used by the index
  124333. ** and which does not have an assigned truth probability, heuristics
  124334. ** described below are used to try to estimate the truth probability.
  124335. ** TODO --> Perhaps this is something that could be improved by better
  124336. ** table statistics.
  124337. **
  124338. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  124339. ** value corresponds to -1 in LogEst notation, so this means decrement
  124340. ** the WhereLoop.nOut field for every such WHERE clause term.
  124341. **
  124342. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  124343. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  124344. ** final output row estimate is no greater than 1/4 of the total number
  124345. ** of rows in the table. In other words, assume that x==EXPR will filter
  124346. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  124347. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  124348. ** on the "x" column and so in that case only cap the output row estimate
  124349. ** at 1/2 instead of 1/4.
  124350. */
  124351. static void whereLoopOutputAdjust(
  124352. WhereClause *pWC, /* The WHERE clause */
  124353. WhereLoop *pLoop, /* The loop to adjust downward */
  124354. LogEst nRow /* Number of rows in the entire table */
  124355. ){
  124356. WhereTerm *pTerm, *pX;
  124357. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  124358. int i, j, k;
  124359. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  124360. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  124361. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  124362. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  124363. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  124364. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  124365. for(j=pLoop->nLTerm-1; j>=0; j--){
  124366. pX = pLoop->aLTerm[j];
  124367. if( pX==0 ) continue;
  124368. if( pX==pTerm ) break;
  124369. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  124370. }
  124371. if( j<0 ){
  124372. if( pTerm->truthProb<=0 ){
  124373. /* If a truth probability is specified using the likelihood() hints,
  124374. ** then use the probability provided by the application. */
  124375. pLoop->nOut += pTerm->truthProb;
  124376. }else{
  124377. /* In the absence of explicit truth probabilities, use heuristics to
  124378. ** guess a reasonable truth probability. */
  124379. pLoop->nOut--;
  124380. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  124381. Expr *pRight = pTerm->pExpr->pRight;
  124382. testcase( pTerm->pExpr->op==TK_IS );
  124383. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  124384. k = 10;
  124385. }else{
  124386. k = 20;
  124387. }
  124388. if( iReduce<k ) iReduce = k;
  124389. }
  124390. }
  124391. }
  124392. }
  124393. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  124394. }
  124395. /*
  124396. ** Term pTerm is a vector range comparison operation. The first comparison
  124397. ** in the vector can be optimized using column nEq of the index. This
  124398. ** function returns the total number of vector elements that can be used
  124399. ** as part of the range comparison.
  124400. **
  124401. ** For example, if the query is:
  124402. **
  124403. ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
  124404. **
  124405. ** and the index:
  124406. **
  124407. ** CREATE INDEX ... ON (a, b, c, d, e)
  124408. **
  124409. ** then this function would be invoked with nEq=1. The value returned in
  124410. ** this case is 3.
  124411. */
  124412. static int whereRangeVectorLen(
  124413. Parse *pParse, /* Parsing context */
  124414. int iCur, /* Cursor open on pIdx */
  124415. Index *pIdx, /* The index to be used for a inequality constraint */
  124416. int nEq, /* Number of prior equality constraints on same index */
  124417. WhereTerm *pTerm /* The vector inequality constraint */
  124418. ){
  124419. int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
  124420. int i;
  124421. nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
  124422. for(i=1; i<nCmp; i++){
  124423. /* Test if comparison i of pTerm is compatible with column (i+nEq)
  124424. ** of the index. If not, exit the loop. */
  124425. char aff; /* Comparison affinity */
  124426. char idxaff = 0; /* Indexed columns affinity */
  124427. CollSeq *pColl; /* Comparison collation sequence */
  124428. Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
  124429. Expr *pRhs = pTerm->pExpr->pRight;
  124430. if( pRhs->flags & EP_xIsSelect ){
  124431. pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
  124432. }else{
  124433. pRhs = pRhs->x.pList->a[i].pExpr;
  124434. }
  124435. /* Check that the LHS of the comparison is a column reference to
  124436. ** the right column of the right source table. And that the sort
  124437. ** order of the index column is the same as the sort order of the
  124438. ** leftmost index column. */
  124439. if( pLhs->op!=TK_COLUMN
  124440. || pLhs->iTable!=iCur
  124441. || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
  124442. || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
  124443. ){
  124444. break;
  124445. }
  124446. testcase( pLhs->iColumn==XN_ROWID );
  124447. aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
  124448. idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
  124449. if( aff!=idxaff ) break;
  124450. pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  124451. if( pColl==0 ) break;
  124452. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
  124453. }
  124454. return i;
  124455. }
  124456. /*
  124457. ** Adjust the cost C by the costMult facter T. This only occurs if
  124458. ** compiled with -DSQLITE_ENABLE_COSTMULT
  124459. */
  124460. #ifdef SQLITE_ENABLE_COSTMULT
  124461. # define ApplyCostMultiplier(C,T) C += T
  124462. #else
  124463. # define ApplyCostMultiplier(C,T)
  124464. #endif
  124465. /*
  124466. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  124467. ** index pIndex. Try to match one more.
  124468. **
  124469. ** When this function is called, pBuilder->pNew->nOut contains the
  124470. ** number of rows expected to be visited by filtering using the nEq
  124471. ** terms only. If it is modified, this value is restored before this
  124472. ** function returns.
  124473. **
  124474. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  124475. ** INTEGER PRIMARY KEY.
  124476. */
  124477. static int whereLoopAddBtreeIndex(
  124478. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  124479. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  124480. Index *pProbe, /* An index on pSrc */
  124481. LogEst nInMul /* log(Number of iterations due to IN) */
  124482. ){
  124483. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  124484. Parse *pParse = pWInfo->pParse; /* Parsing context */
  124485. sqlite3 *db = pParse->db; /* Database connection malloc context */
  124486. WhereLoop *pNew; /* Template WhereLoop under construction */
  124487. WhereTerm *pTerm; /* A WhereTerm under consideration */
  124488. int opMask; /* Valid operators for constraints */
  124489. WhereScan scan; /* Iterator for WHERE terms */
  124490. Bitmask saved_prereq; /* Original value of pNew->prereq */
  124491. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  124492. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  124493. u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
  124494. u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
  124495. u16 saved_nSkip; /* Original value of pNew->nSkip */
  124496. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  124497. LogEst saved_nOut; /* Original value of pNew->nOut */
  124498. int rc = SQLITE_OK; /* Return code */
  124499. LogEst rSize; /* Number of rows in the table */
  124500. LogEst rLogSize; /* Logarithm of table size */
  124501. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  124502. pNew = pBuilder->pNew;
  124503. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  124504. WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
  124505. pProbe->zName, pNew->u.btree.nEq));
  124506. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  124507. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  124508. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  124509. opMask = WO_LT|WO_LE;
  124510. }else{
  124511. assert( pNew->u.btree.nBtm==0 );
  124512. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  124513. }
  124514. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  124515. assert( pNew->u.btree.nEq<pProbe->nColumn );
  124516. saved_nEq = pNew->u.btree.nEq;
  124517. saved_nBtm = pNew->u.btree.nBtm;
  124518. saved_nTop = pNew->u.btree.nTop;
  124519. saved_nSkip = pNew->nSkip;
  124520. saved_nLTerm = pNew->nLTerm;
  124521. saved_wsFlags = pNew->wsFlags;
  124522. saved_prereq = pNew->prereq;
  124523. saved_nOut = pNew->nOut;
  124524. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  124525. opMask, pProbe);
  124526. pNew->rSetup = 0;
  124527. rSize = pProbe->aiRowLogEst[0];
  124528. rLogSize = estLog(rSize);
  124529. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  124530. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  124531. LogEst rCostIdx;
  124532. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  124533. int nIn = 0;
  124534. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124535. int nRecValid = pBuilder->nRecValid;
  124536. #endif
  124537. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  124538. && indexColumnNotNull(pProbe, saved_nEq)
  124539. ){
  124540. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  124541. }
  124542. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  124543. /* Do not allow the upper bound of a LIKE optimization range constraint
  124544. ** to mix with a lower range bound from some other source */
  124545. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  124546. /* Do not allow IS constraints from the WHERE clause to be used by the
  124547. ** right table of a LEFT JOIN. Only constraints in the ON clause are
  124548. ** allowed */
  124549. if( (pSrc->fg.jointype & JT_LEFT)!=0
  124550. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  124551. && (eOp & (WO_IS|WO_ISNULL))!=0
  124552. ){
  124553. testcase( eOp & WO_IS );
  124554. testcase( eOp & WO_ISNULL );
  124555. continue;
  124556. }
  124557. if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
  124558. pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
  124559. }else{
  124560. pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
  124561. }
  124562. pNew->wsFlags = saved_wsFlags;
  124563. pNew->u.btree.nEq = saved_nEq;
  124564. pNew->u.btree.nBtm = saved_nBtm;
  124565. pNew->u.btree.nTop = saved_nTop;
  124566. pNew->nLTerm = saved_nLTerm;
  124567. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  124568. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  124569. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  124570. assert( nInMul==0
  124571. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  124572. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  124573. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  124574. );
  124575. if( eOp & WO_IN ){
  124576. Expr *pExpr = pTerm->pExpr;
  124577. pNew->wsFlags |= WHERE_COLUMN_IN;
  124578. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  124579. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  124580. int i;
  124581. nIn = 46; assert( 46==sqlite3LogEst(25) );
  124582. /* The expression may actually be of the form (x, y) IN (SELECT...).
  124583. ** In this case there is a separate term for each of (x) and (y).
  124584. ** However, the nIn multiplier should only be applied once, not once
  124585. ** for each such term. The following loop checks that pTerm is the
  124586. ** first such term in use, and sets nIn back to 0 if it is not. */
  124587. for(i=0; i<pNew->nLTerm-1; i++){
  124588. if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
  124589. }
  124590. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  124591. /* "x IN (value, value, ...)" */
  124592. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  124593. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  124594. ** changes "x IN (?)" into "x=?". */
  124595. }
  124596. }else if( eOp & (WO_EQ|WO_IS) ){
  124597. int iCol = pProbe->aiColumn[saved_nEq];
  124598. pNew->wsFlags |= WHERE_COLUMN_EQ;
  124599. assert( saved_nEq==pNew->u.btree.nEq );
  124600. if( iCol==XN_ROWID
  124601. || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  124602. ){
  124603. if( iCol>=0 && pProbe->uniqNotNull==0 ){
  124604. pNew->wsFlags |= WHERE_UNQ_WANTED;
  124605. }else{
  124606. pNew->wsFlags |= WHERE_ONEROW;
  124607. }
  124608. }
  124609. }else if( eOp & WO_ISNULL ){
  124610. pNew->wsFlags |= WHERE_COLUMN_NULL;
  124611. }else if( eOp & (WO_GT|WO_GE) ){
  124612. testcase( eOp & WO_GT );
  124613. testcase( eOp & WO_GE );
  124614. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  124615. pNew->u.btree.nBtm = whereRangeVectorLen(
  124616. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  124617. );
  124618. pBtm = pTerm;
  124619. pTop = 0;
  124620. if( pTerm->wtFlags & TERM_LIKEOPT ){
  124621. /* Range contraints that come from the LIKE optimization are
  124622. ** always used in pairs. */
  124623. pTop = &pTerm[1];
  124624. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  124625. assert( pTop->wtFlags & TERM_LIKEOPT );
  124626. assert( pTop->eOperator==WO_LT );
  124627. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  124628. pNew->aLTerm[pNew->nLTerm++] = pTop;
  124629. pNew->wsFlags |= WHERE_TOP_LIMIT;
  124630. pNew->u.btree.nTop = 1;
  124631. }
  124632. }else{
  124633. assert( eOp & (WO_LT|WO_LE) );
  124634. testcase( eOp & WO_LT );
  124635. testcase( eOp & WO_LE );
  124636. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  124637. pNew->u.btree.nTop = whereRangeVectorLen(
  124638. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  124639. );
  124640. pTop = pTerm;
  124641. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  124642. pNew->aLTerm[pNew->nLTerm-2] : 0;
  124643. }
  124644. /* At this point pNew->nOut is set to the number of rows expected to
  124645. ** be visited by the index scan before considering term pTerm, or the
  124646. ** values of nIn and nInMul. In other words, assuming that all
  124647. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  124648. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  124649. assert( pNew->nOut==saved_nOut );
  124650. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  124651. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  124652. ** data, using some other estimate. */
  124653. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  124654. }else{
  124655. int nEq = ++pNew->u.btree.nEq;
  124656. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  124657. assert( pNew->nOut==saved_nOut );
  124658. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  124659. assert( (eOp & WO_IN) || nIn==0 );
  124660. testcase( eOp & WO_IN );
  124661. pNew->nOut += pTerm->truthProb;
  124662. pNew->nOut -= nIn;
  124663. }else{
  124664. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124665. tRowcnt nOut = 0;
  124666. if( nInMul==0
  124667. && pProbe->nSample
  124668. && pNew->u.btree.nEq<=pProbe->nSampleCol
  124669. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  124670. ){
  124671. Expr *pExpr = pTerm->pExpr;
  124672. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  124673. testcase( eOp & WO_EQ );
  124674. testcase( eOp & WO_IS );
  124675. testcase( eOp & WO_ISNULL );
  124676. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  124677. }else{
  124678. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  124679. }
  124680. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  124681. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  124682. if( nOut ){
  124683. pNew->nOut = sqlite3LogEst(nOut);
  124684. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  124685. pNew->nOut -= nIn;
  124686. }
  124687. }
  124688. if( nOut==0 )
  124689. #endif
  124690. {
  124691. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  124692. if( eOp & WO_ISNULL ){
  124693. /* TUNING: If there is no likelihood() value, assume that a
  124694. ** "col IS NULL" expression matches twice as many rows
  124695. ** as (col=?). */
  124696. pNew->nOut += 10;
  124697. }
  124698. }
  124699. }
  124700. }
  124701. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  124702. ** it to pNew->rRun, which is currently set to the cost of the index
  124703. ** seek only. Then, if this is a non-covering index, add the cost of
  124704. ** visiting the rows in the main table. */
  124705. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  124706. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  124707. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  124708. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  124709. }
  124710. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  124711. nOutUnadjusted = pNew->nOut;
  124712. pNew->rRun += nInMul + nIn;
  124713. pNew->nOut += nInMul + nIn;
  124714. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  124715. rc = whereLoopInsert(pBuilder, pNew);
  124716. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  124717. pNew->nOut = saved_nOut;
  124718. }else{
  124719. pNew->nOut = nOutUnadjusted;
  124720. }
  124721. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  124722. && pNew->u.btree.nEq<pProbe->nColumn
  124723. ){
  124724. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  124725. }
  124726. pNew->nOut = saved_nOut;
  124727. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124728. pBuilder->nRecValid = nRecValid;
  124729. #endif
  124730. }
  124731. pNew->prereq = saved_prereq;
  124732. pNew->u.btree.nEq = saved_nEq;
  124733. pNew->u.btree.nBtm = saved_nBtm;
  124734. pNew->u.btree.nTop = saved_nTop;
  124735. pNew->nSkip = saved_nSkip;
  124736. pNew->wsFlags = saved_wsFlags;
  124737. pNew->nOut = saved_nOut;
  124738. pNew->nLTerm = saved_nLTerm;
  124739. /* Consider using a skip-scan if there are no WHERE clause constraints
  124740. ** available for the left-most terms of the index, and if the average
  124741. ** number of repeats in the left-most terms is at least 18.
  124742. **
  124743. ** The magic number 18 is selected on the basis that scanning 17 rows
  124744. ** is almost always quicker than an index seek (even though if the index
  124745. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  124746. ** the code). And, even if it is not, it should not be too much slower.
  124747. ** On the other hand, the extra seeks could end up being significantly
  124748. ** more expensive. */
  124749. assert( 42==sqlite3LogEst(18) );
  124750. if( saved_nEq==saved_nSkip
  124751. && saved_nEq+1<pProbe->nKeyCol
  124752. && pProbe->noSkipScan==0
  124753. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  124754. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  124755. ){
  124756. LogEst nIter;
  124757. pNew->u.btree.nEq++;
  124758. pNew->nSkip++;
  124759. pNew->aLTerm[pNew->nLTerm++] = 0;
  124760. pNew->wsFlags |= WHERE_SKIPSCAN;
  124761. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  124762. pNew->nOut -= nIter;
  124763. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  124764. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  124765. nIter += 5;
  124766. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  124767. pNew->nOut = saved_nOut;
  124768. pNew->u.btree.nEq = saved_nEq;
  124769. pNew->nSkip = saved_nSkip;
  124770. pNew->wsFlags = saved_wsFlags;
  124771. }
  124772. WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
  124773. pProbe->zName, saved_nEq, rc));
  124774. return rc;
  124775. }
  124776. /*
  124777. ** Return True if it is possible that pIndex might be useful in
  124778. ** implementing the ORDER BY clause in pBuilder.
  124779. **
  124780. ** Return False if pBuilder does not contain an ORDER BY clause or
  124781. ** if there is no way for pIndex to be useful in implementing that
  124782. ** ORDER BY clause.
  124783. */
  124784. static int indexMightHelpWithOrderBy(
  124785. WhereLoopBuilder *pBuilder,
  124786. Index *pIndex,
  124787. int iCursor
  124788. ){
  124789. ExprList *pOB;
  124790. ExprList *aColExpr;
  124791. int ii, jj;
  124792. if( pIndex->bUnordered ) return 0;
  124793. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  124794. for(ii=0; ii<pOB->nExpr; ii++){
  124795. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  124796. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  124797. if( pExpr->iColumn<0 ) return 1;
  124798. for(jj=0; jj<pIndex->nKeyCol; jj++){
  124799. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  124800. }
  124801. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  124802. for(jj=0; jj<pIndex->nKeyCol; jj++){
  124803. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  124804. if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  124805. return 1;
  124806. }
  124807. }
  124808. }
  124809. }
  124810. return 0;
  124811. }
  124812. /*
  124813. ** Return a bitmask where 1s indicate that the corresponding column of
  124814. ** the table is used by an index. Only the first 63 columns are considered.
  124815. */
  124816. static Bitmask columnsInIndex(Index *pIdx){
  124817. Bitmask m = 0;
  124818. int j;
  124819. for(j=pIdx->nColumn-1; j>=0; j--){
  124820. int x = pIdx->aiColumn[j];
  124821. if( x>=0 ){
  124822. testcase( x==BMS-1 );
  124823. testcase( x==BMS-2 );
  124824. if( x<BMS-1 ) m |= MASKBIT(x);
  124825. }
  124826. }
  124827. return m;
  124828. }
  124829. /* Check to see if a partial index with pPartIndexWhere can be used
  124830. ** in the current query. Return true if it can be and false if not.
  124831. */
  124832. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  124833. int i;
  124834. WhereTerm *pTerm;
  124835. while( pWhere->op==TK_AND ){
  124836. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  124837. pWhere = pWhere->pRight;
  124838. }
  124839. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  124840. Expr *pExpr = pTerm->pExpr;
  124841. if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
  124842. && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  124843. ){
  124844. return 1;
  124845. }
  124846. }
  124847. return 0;
  124848. }
  124849. /*
  124850. ** Add all WhereLoop objects for a single table of the join where the table
  124851. ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
  124852. ** a b-tree table, not a virtual table.
  124853. **
  124854. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  124855. ** are calculated as follows:
  124856. **
  124857. ** For a full scan, assuming the table (or index) contains nRow rows:
  124858. **
  124859. ** cost = nRow * 3.0 // full-table scan
  124860. ** cost = nRow * K // scan of covering index
  124861. ** cost = nRow * (K+3.0) // scan of non-covering index
  124862. **
  124863. ** where K is a value between 1.1 and 3.0 set based on the relative
  124864. ** estimated average size of the index and table records.
  124865. **
  124866. ** For an index scan, where nVisit is the number of index rows visited
  124867. ** by the scan, and nSeek is the number of seek operations required on
  124868. ** the index b-tree:
  124869. **
  124870. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  124871. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  124872. **
  124873. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  124874. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  124875. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  124876. **
  124877. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  124878. ** of uncertainty. For this reason, scoring is designed to pick plans that
  124879. ** "do the least harm" if the estimates are inaccurate. For example, a
  124880. ** log(nRow) factor is omitted from a non-covering index scan in order to
  124881. ** bias the scoring in favor of using an index, since the worst-case
  124882. ** performance of using an index is far better than the worst-case performance
  124883. ** of a full table scan.
  124884. */
  124885. static int whereLoopAddBtree(
  124886. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  124887. Bitmask mPrereq /* Extra prerequesites for using this table */
  124888. ){
  124889. WhereInfo *pWInfo; /* WHERE analysis context */
  124890. Index *pProbe; /* An index we are evaluating */
  124891. Index sPk; /* A fake index object for the primary key */
  124892. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  124893. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  124894. SrcList *pTabList; /* The FROM clause */
  124895. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  124896. WhereLoop *pNew; /* Template WhereLoop object */
  124897. int rc = SQLITE_OK; /* Return code */
  124898. int iSortIdx = 1; /* Index number */
  124899. int b; /* A boolean value */
  124900. LogEst rSize; /* number of rows in the table */
  124901. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  124902. WhereClause *pWC; /* The parsed WHERE clause */
  124903. Table *pTab; /* Table being queried */
  124904. pNew = pBuilder->pNew;
  124905. pWInfo = pBuilder->pWInfo;
  124906. pTabList = pWInfo->pTabList;
  124907. pSrc = pTabList->a + pNew->iTab;
  124908. pTab = pSrc->pTab;
  124909. pWC = pBuilder->pWC;
  124910. assert( !IsVirtual(pSrc->pTab) );
  124911. if( pSrc->pIBIndex ){
  124912. /* An INDEXED BY clause specifies a particular index to use */
  124913. pProbe = pSrc->pIBIndex;
  124914. }else if( !HasRowid(pTab) ){
  124915. pProbe = pTab->pIndex;
  124916. }else{
  124917. /* There is no INDEXED BY clause. Create a fake Index object in local
  124918. ** variable sPk to represent the rowid primary key index. Make this
  124919. ** fake index the first in a chain of Index objects with all of the real
  124920. ** indices to follow */
  124921. Index *pFirst; /* First of real indices on the table */
  124922. memset(&sPk, 0, sizeof(Index));
  124923. sPk.nKeyCol = 1;
  124924. sPk.nColumn = 1;
  124925. sPk.aiColumn = &aiColumnPk;
  124926. sPk.aiRowLogEst = aiRowEstPk;
  124927. sPk.onError = OE_Replace;
  124928. sPk.pTable = pTab;
  124929. sPk.szIdxRow = pTab->szTabRow;
  124930. aiRowEstPk[0] = pTab->nRowLogEst;
  124931. aiRowEstPk[1] = 0;
  124932. pFirst = pSrc->pTab->pIndex;
  124933. if( pSrc->fg.notIndexed==0 ){
  124934. /* The real indices of the table are only considered if the
  124935. ** NOT INDEXED qualifier is omitted from the FROM clause */
  124936. sPk.pNext = pFirst;
  124937. }
  124938. pProbe = &sPk;
  124939. }
  124940. rSize = pTab->nRowLogEst;
  124941. rLogSize = estLog(rSize);
  124942. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  124943. /* Automatic indexes */
  124944. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  124945. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  124946. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  124947. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  124948. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  124949. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  124950. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  124951. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  124952. ){
  124953. /* Generate auto-index WhereLoops */
  124954. WhereTerm *pTerm;
  124955. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  124956. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  124957. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  124958. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  124959. pNew->u.btree.nEq = 1;
  124960. pNew->nSkip = 0;
  124961. pNew->u.btree.pIndex = 0;
  124962. pNew->nLTerm = 1;
  124963. pNew->aLTerm[0] = pTerm;
  124964. /* TUNING: One-time cost for computing the automatic index is
  124965. ** estimated to be X*N*log2(N) where N is the number of rows in
  124966. ** the table being indexed and where X is 7 (LogEst=28) for normal
  124967. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  124968. ** of X is smaller for views and subqueries so that the query planner
  124969. ** will be more aggressive about generating automatic indexes for
  124970. ** those objects, since there is no opportunity to add schema
  124971. ** indexes on subqueries and views. */
  124972. pNew->rSetup = rLogSize + rSize + 4;
  124973. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  124974. pNew->rSetup += 24;
  124975. }
  124976. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  124977. if( pNew->rSetup<0 ) pNew->rSetup = 0;
  124978. /* TUNING: Each index lookup yields 20 rows in the table. This
  124979. ** is more than the usual guess of 10 rows, since we have no way
  124980. ** of knowing how selective the index will ultimately be. It would
  124981. ** not be unreasonable to make this value much larger. */
  124982. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  124983. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  124984. pNew->wsFlags = WHERE_AUTO_INDEX;
  124985. pNew->prereq = mPrereq | pTerm->prereqRight;
  124986. rc = whereLoopInsert(pBuilder, pNew);
  124987. }
  124988. }
  124989. }
  124990. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  124991. /* Loop over all indices
  124992. */
  124993. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  124994. if( pProbe->pPartIdxWhere!=0
  124995. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  124996. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  124997. continue; /* Partial index inappropriate for this query */
  124998. }
  124999. rSize = pProbe->aiRowLogEst[0];
  125000. pNew->u.btree.nEq = 0;
  125001. pNew->u.btree.nBtm = 0;
  125002. pNew->u.btree.nTop = 0;
  125003. pNew->nSkip = 0;
  125004. pNew->nLTerm = 0;
  125005. pNew->iSortIdx = 0;
  125006. pNew->rSetup = 0;
  125007. pNew->prereq = mPrereq;
  125008. pNew->nOut = rSize;
  125009. pNew->u.btree.pIndex = pProbe;
  125010. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  125011. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  125012. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  125013. if( pProbe->tnum<=0 ){
  125014. /* Integer primary key index */
  125015. pNew->wsFlags = WHERE_IPK;
  125016. /* Full table scan */
  125017. pNew->iSortIdx = b ? iSortIdx : 0;
  125018. /* TUNING: Cost of full table scan is (N*3.0). */
  125019. pNew->rRun = rSize + 16;
  125020. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  125021. whereLoopOutputAdjust(pWC, pNew, rSize);
  125022. rc = whereLoopInsert(pBuilder, pNew);
  125023. pNew->nOut = rSize;
  125024. if( rc ) break;
  125025. }else{
  125026. Bitmask m;
  125027. if( pProbe->isCovering ){
  125028. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  125029. m = 0;
  125030. }else{
  125031. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  125032. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  125033. }
  125034. /* Full scan via index */
  125035. if( b
  125036. || !HasRowid(pTab)
  125037. || pProbe->pPartIdxWhere!=0
  125038. || ( m==0
  125039. && pProbe->bUnordered==0
  125040. && (pProbe->szIdxRow<pTab->szTabRow)
  125041. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  125042. && sqlite3GlobalConfig.bUseCis
  125043. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  125044. )
  125045. ){
  125046. pNew->iSortIdx = b ? iSortIdx : 0;
  125047. /* The cost of visiting the index rows is N*K, where K is
  125048. ** between 1.1 and 3.0, depending on the relative sizes of the
  125049. ** index and table rows. */
  125050. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  125051. if( m!=0 ){
  125052. /* If this is a non-covering index scan, add in the cost of
  125053. ** doing table lookups. The cost will be 3x the number of
  125054. ** lookups. Take into account WHERE clause terms that can be
  125055. ** satisfied using just the index, and that do not require a
  125056. ** table lookup. */
  125057. LogEst nLookup = rSize + 16; /* Base cost: N*3 */
  125058. int ii;
  125059. int iCur = pSrc->iCursor;
  125060. WhereClause *pWC2 = &pWInfo->sWC;
  125061. for(ii=0; ii<pWC2->nTerm; ii++){
  125062. WhereTerm *pTerm = &pWC2->a[ii];
  125063. if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
  125064. break;
  125065. }
  125066. /* pTerm can be evaluated using just the index. So reduce
  125067. ** the expected number of table lookups accordingly */
  125068. if( pTerm->truthProb<=0 ){
  125069. nLookup += pTerm->truthProb;
  125070. }else{
  125071. nLookup--;
  125072. if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
  125073. }
  125074. }
  125075. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
  125076. }
  125077. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  125078. whereLoopOutputAdjust(pWC, pNew, rSize);
  125079. rc = whereLoopInsert(pBuilder, pNew);
  125080. pNew->nOut = rSize;
  125081. if( rc ) break;
  125082. }
  125083. }
  125084. pBuilder->bldFlags = 0;
  125085. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  125086. if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
  125087. /* If a non-unique index is used, or if a prefix of the key for
  125088. ** unique index is used (making the index functionally non-unique)
  125089. ** then the sqlite_stat1 data becomes important for scoring the
  125090. ** plan */
  125091. pTab->tabFlags |= TF_StatsUsed;
  125092. }
  125093. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  125094. sqlite3Stat4ProbeFree(pBuilder->pRec);
  125095. pBuilder->nRecValid = 0;
  125096. pBuilder->pRec = 0;
  125097. #endif
  125098. /* If there was an INDEXED BY clause, then only that one index is
  125099. ** considered. */
  125100. if( pSrc->pIBIndex ) break;
  125101. }
  125102. return rc;
  125103. }
  125104. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125105. /*
  125106. ** Argument pIdxInfo is already populated with all constraints that may
  125107. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  125108. ** function marks a subset of those constraints usable, invokes the
  125109. ** xBestIndex method and adds the returned plan to pBuilder.
  125110. **
  125111. ** A constraint is marked usable if:
  125112. **
  125113. ** * Argument mUsable indicates that its prerequisites are available, and
  125114. **
  125115. ** * It is not one of the operators specified in the mExclude mask passed
  125116. ** as the fourth argument (which in practice is either WO_IN or 0).
  125117. **
  125118. ** Argument mPrereq is a mask of tables that must be scanned before the
  125119. ** virtual table in question. These are added to the plans prerequisites
  125120. ** before it is added to pBuilder.
  125121. **
  125122. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  125123. ** uses one or more WO_IN terms, or false otherwise.
  125124. */
  125125. static int whereLoopAddVirtualOne(
  125126. WhereLoopBuilder *pBuilder,
  125127. Bitmask mPrereq, /* Mask of tables that must be used. */
  125128. Bitmask mUsable, /* Mask of usable tables */
  125129. u16 mExclude, /* Exclude terms using these operators */
  125130. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  125131. u16 mNoOmit, /* Do not omit these constraints */
  125132. int *pbIn /* OUT: True if plan uses an IN(...) op */
  125133. ){
  125134. WhereClause *pWC = pBuilder->pWC;
  125135. struct sqlite3_index_constraint *pIdxCons;
  125136. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  125137. int i;
  125138. int mxTerm;
  125139. int rc = SQLITE_OK;
  125140. WhereLoop *pNew = pBuilder->pNew;
  125141. Parse *pParse = pBuilder->pWInfo->pParse;
  125142. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  125143. int nConstraint = pIdxInfo->nConstraint;
  125144. assert( (mUsable & mPrereq)==mPrereq );
  125145. *pbIn = 0;
  125146. pNew->prereq = mPrereq;
  125147. /* Set the usable flag on the subset of constraints identified by
  125148. ** arguments mUsable and mExclude. */
  125149. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  125150. for(i=0; i<nConstraint; i++, pIdxCons++){
  125151. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  125152. pIdxCons->usable = 0;
  125153. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  125154. && (pTerm->eOperator & mExclude)==0
  125155. ){
  125156. pIdxCons->usable = 1;
  125157. }
  125158. }
  125159. /* Initialize the output fields of the sqlite3_index_info structure */
  125160. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  125161. assert( pIdxInfo->needToFreeIdxStr==0 );
  125162. pIdxInfo->idxStr = 0;
  125163. pIdxInfo->idxNum = 0;
  125164. pIdxInfo->orderByConsumed = 0;
  125165. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  125166. pIdxInfo->estimatedRows = 25;
  125167. pIdxInfo->idxFlags = 0;
  125168. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  125169. /* Invoke the virtual table xBestIndex() method */
  125170. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  125171. if( rc ) return rc;
  125172. mxTerm = -1;
  125173. assert( pNew->nLSlot>=nConstraint );
  125174. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  125175. pNew->u.vtab.omitMask = 0;
  125176. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  125177. for(i=0; i<nConstraint; i++, pIdxCons++){
  125178. int iTerm;
  125179. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  125180. WhereTerm *pTerm;
  125181. int j = pIdxCons->iTermOffset;
  125182. if( iTerm>=nConstraint
  125183. || j<0
  125184. || j>=pWC->nTerm
  125185. || pNew->aLTerm[iTerm]!=0
  125186. || pIdxCons->usable==0
  125187. ){
  125188. rc = SQLITE_ERROR;
  125189. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  125190. return rc;
  125191. }
  125192. testcase( iTerm==nConstraint-1 );
  125193. testcase( j==0 );
  125194. testcase( j==pWC->nTerm-1 );
  125195. pTerm = &pWC->a[j];
  125196. pNew->prereq |= pTerm->prereqRight;
  125197. assert( iTerm<pNew->nLSlot );
  125198. pNew->aLTerm[iTerm] = pTerm;
  125199. if( iTerm>mxTerm ) mxTerm = iTerm;
  125200. testcase( iTerm==15 );
  125201. testcase( iTerm==16 );
  125202. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  125203. if( (pTerm->eOperator & WO_IN)!=0 ){
  125204. /* A virtual table that is constrained by an IN clause may not
  125205. ** consume the ORDER BY clause because (1) the order of IN terms
  125206. ** is not necessarily related to the order of output terms and
  125207. ** (2) Multiple outputs from a single IN value will not merge
  125208. ** together. */
  125209. pIdxInfo->orderByConsumed = 0;
  125210. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  125211. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  125212. }
  125213. }
  125214. }
  125215. pNew->u.vtab.omitMask &= ~mNoOmit;
  125216. pNew->nLTerm = mxTerm+1;
  125217. assert( pNew->nLTerm<=pNew->nLSlot );
  125218. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  125219. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  125220. pIdxInfo->needToFreeIdxStr = 0;
  125221. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  125222. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  125223. pIdxInfo->nOrderBy : 0);
  125224. pNew->rSetup = 0;
  125225. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  125226. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  125227. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  125228. ** that the scan will visit at most one row. Clear it otherwise. */
  125229. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  125230. pNew->wsFlags |= WHERE_ONEROW;
  125231. }else{
  125232. pNew->wsFlags &= ~WHERE_ONEROW;
  125233. }
  125234. rc = whereLoopInsert(pBuilder, pNew);
  125235. if( pNew->u.vtab.needFree ){
  125236. sqlite3_free(pNew->u.vtab.idxStr);
  125237. pNew->u.vtab.needFree = 0;
  125238. }
  125239. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  125240. *pbIn, (sqlite3_uint64)mPrereq,
  125241. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  125242. return rc;
  125243. }
  125244. /*
  125245. ** Add all WhereLoop objects for a table of the join identified by
  125246. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  125247. **
  125248. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  125249. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  125250. ** entries that occur before the virtual table in the FROM clause and are
  125251. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  125252. ** mUnusable mask contains all FROM clause entries that occur after the
  125253. ** virtual table and are separated from it by at least one LEFT or
  125254. ** CROSS JOIN.
  125255. **
  125256. ** For example, if the query were:
  125257. **
  125258. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  125259. **
  125260. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  125261. **
  125262. ** All the tables in mPrereq must be scanned before the current virtual
  125263. ** table. So any terms for which all prerequisites are satisfied by
  125264. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  125265. ** Conversely, all tables in mUnusable must be scanned after the current
  125266. ** virtual table, so any terms for which the prerequisites overlap with
  125267. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  125268. */
  125269. static int whereLoopAddVirtual(
  125270. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  125271. Bitmask mPrereq, /* Tables that must be scanned before this one */
  125272. Bitmask mUnusable /* Tables that must be scanned after this one */
  125273. ){
  125274. int rc = SQLITE_OK; /* Return code */
  125275. WhereInfo *pWInfo; /* WHERE analysis context */
  125276. Parse *pParse; /* The parsing context */
  125277. WhereClause *pWC; /* The WHERE clause */
  125278. struct SrcList_item *pSrc; /* The FROM clause term to search */
  125279. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  125280. int nConstraint; /* Number of constraints in p */
  125281. int bIn; /* True if plan uses IN(...) operator */
  125282. WhereLoop *pNew;
  125283. Bitmask mBest; /* Tables used by best possible plan */
  125284. u16 mNoOmit;
  125285. assert( (mPrereq & mUnusable)==0 );
  125286. pWInfo = pBuilder->pWInfo;
  125287. pParse = pWInfo->pParse;
  125288. pWC = pBuilder->pWC;
  125289. pNew = pBuilder->pNew;
  125290. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  125291. assert( IsVirtual(pSrc->pTab) );
  125292. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
  125293. &mNoOmit);
  125294. if( p==0 ) return SQLITE_NOMEM_BKPT;
  125295. pNew->rSetup = 0;
  125296. pNew->wsFlags = WHERE_VIRTUALTABLE;
  125297. pNew->nLTerm = 0;
  125298. pNew->u.vtab.needFree = 0;
  125299. nConstraint = p->nConstraint;
  125300. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  125301. sqlite3DbFree(pParse->db, p);
  125302. return SQLITE_NOMEM_BKPT;
  125303. }
  125304. /* First call xBestIndex() with all constraints usable. */
  125305. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  125306. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
  125307. /* If the call to xBestIndex() with all terms enabled produced a plan
  125308. ** that does not require any source tables (IOW: a plan with mBest==0),
  125309. ** then there is no point in making any further calls to xBestIndex()
  125310. ** since they will all return the same result (if the xBestIndex()
  125311. ** implementation is sane). */
  125312. if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
  125313. int seenZero = 0; /* True if a plan with no prereqs seen */
  125314. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  125315. Bitmask mPrev = 0;
  125316. Bitmask mBestNoIn = 0;
  125317. /* If the plan produced by the earlier call uses an IN(...) term, call
  125318. ** xBestIndex again, this time with IN(...) terms disabled. */
  125319. if( bIn ){
  125320. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  125321. rc = whereLoopAddVirtualOne(
  125322. pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
  125323. assert( bIn==0 );
  125324. mBestNoIn = pNew->prereq & ~mPrereq;
  125325. if( mBestNoIn==0 ){
  125326. seenZero = 1;
  125327. seenZeroNoIN = 1;
  125328. }
  125329. }
  125330. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  125331. ** in the set of terms that apply to the current virtual table. */
  125332. while( rc==SQLITE_OK ){
  125333. int i;
  125334. Bitmask mNext = ALLBITS;
  125335. assert( mNext>0 );
  125336. for(i=0; i<nConstraint; i++){
  125337. Bitmask mThis = (
  125338. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  125339. );
  125340. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  125341. }
  125342. mPrev = mNext;
  125343. if( mNext==ALLBITS ) break;
  125344. if( mNext==mBest || mNext==mBestNoIn ) continue;
  125345. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  125346. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  125347. rc = whereLoopAddVirtualOne(
  125348. pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
  125349. if( pNew->prereq==mPrereq ){
  125350. seenZero = 1;
  125351. if( bIn==0 ) seenZeroNoIN = 1;
  125352. }
  125353. }
  125354. /* If the calls to xBestIndex() in the above loop did not find a plan
  125355. ** that requires no source tables at all (i.e. one guaranteed to be
  125356. ** usable), make a call here with all source tables disabled */
  125357. if( rc==SQLITE_OK && seenZero==0 ){
  125358. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  125359. rc = whereLoopAddVirtualOne(
  125360. pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
  125361. if( bIn==0 ) seenZeroNoIN = 1;
  125362. }
  125363. /* If the calls to xBestIndex() have so far failed to find a plan
  125364. ** that requires no source tables at all and does not use an IN(...)
  125365. ** operator, make a final call to obtain one here. */
  125366. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  125367. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  125368. rc = whereLoopAddVirtualOne(
  125369. pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
  125370. }
  125371. }
  125372. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  125373. sqlite3DbFreeNN(pParse->db, p);
  125374. return rc;
  125375. }
  125376. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  125377. /*
  125378. ** Add WhereLoop entries to handle OR terms. This works for either
  125379. ** btrees or virtual tables.
  125380. */
  125381. static int whereLoopAddOr(
  125382. WhereLoopBuilder *pBuilder,
  125383. Bitmask mPrereq,
  125384. Bitmask mUnusable
  125385. ){
  125386. WhereInfo *pWInfo = pBuilder->pWInfo;
  125387. WhereClause *pWC;
  125388. WhereLoop *pNew;
  125389. WhereTerm *pTerm, *pWCEnd;
  125390. int rc = SQLITE_OK;
  125391. int iCur;
  125392. WhereClause tempWC;
  125393. WhereLoopBuilder sSubBuild;
  125394. WhereOrSet sSum, sCur;
  125395. struct SrcList_item *pItem;
  125396. pWC = pBuilder->pWC;
  125397. pWCEnd = pWC->a + pWC->nTerm;
  125398. pNew = pBuilder->pNew;
  125399. memset(&sSum, 0, sizeof(sSum));
  125400. pItem = pWInfo->pTabList->a + pNew->iTab;
  125401. iCur = pItem->iCursor;
  125402. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  125403. if( (pTerm->eOperator & WO_OR)!=0
  125404. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  125405. ){
  125406. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  125407. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  125408. WhereTerm *pOrTerm;
  125409. int once = 1;
  125410. int i, j;
  125411. sSubBuild = *pBuilder;
  125412. sSubBuild.pOrderBy = 0;
  125413. sSubBuild.pOrSet = &sCur;
  125414. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  125415. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  125416. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  125417. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  125418. }else if( pOrTerm->leftCursor==iCur ){
  125419. tempWC.pWInfo = pWC->pWInfo;
  125420. tempWC.pOuter = pWC;
  125421. tempWC.op = TK_AND;
  125422. tempWC.nTerm = 1;
  125423. tempWC.a = pOrTerm;
  125424. sSubBuild.pWC = &tempWC;
  125425. }else{
  125426. continue;
  125427. }
  125428. sCur.n = 0;
  125429. #ifdef WHERETRACE_ENABLED
  125430. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  125431. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  125432. if( sqlite3WhereTrace & 0x400 ){
  125433. sqlite3WhereClausePrint(sSubBuild.pWC);
  125434. }
  125435. #endif
  125436. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125437. if( IsVirtual(pItem->pTab) ){
  125438. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  125439. }else
  125440. #endif
  125441. {
  125442. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  125443. }
  125444. if( rc==SQLITE_OK ){
  125445. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  125446. }
  125447. assert( rc==SQLITE_OK || sCur.n==0 );
  125448. if( sCur.n==0 ){
  125449. sSum.n = 0;
  125450. break;
  125451. }else if( once ){
  125452. whereOrMove(&sSum, &sCur);
  125453. once = 0;
  125454. }else{
  125455. WhereOrSet sPrev;
  125456. whereOrMove(&sPrev, &sSum);
  125457. sSum.n = 0;
  125458. for(i=0; i<sPrev.n; i++){
  125459. for(j=0; j<sCur.n; j++){
  125460. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  125461. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  125462. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  125463. }
  125464. }
  125465. }
  125466. }
  125467. pNew->nLTerm = 1;
  125468. pNew->aLTerm[0] = pTerm;
  125469. pNew->wsFlags = WHERE_MULTI_OR;
  125470. pNew->rSetup = 0;
  125471. pNew->iSortIdx = 0;
  125472. memset(&pNew->u, 0, sizeof(pNew->u));
  125473. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  125474. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  125475. ** of all sub-scans required by the OR-scan. However, due to rounding
  125476. ** errors, it may be that the cost of the OR-scan is equal to its
  125477. ** most expensive sub-scan. Add the smallest possible penalty
  125478. ** (equivalent to multiplying the cost by 1.07) to ensure that
  125479. ** this does not happen. Otherwise, for WHERE clauses such as the
  125480. ** following where there is an index on "y":
  125481. **
  125482. ** WHERE likelihood(x=?, 0.99) OR y=?
  125483. **
  125484. ** the planner may elect to "OR" together a full-table scan and an
  125485. ** index lookup. And other similarly odd results. */
  125486. pNew->rRun = sSum.a[i].rRun + 1;
  125487. pNew->nOut = sSum.a[i].nOut;
  125488. pNew->prereq = sSum.a[i].prereq;
  125489. rc = whereLoopInsert(pBuilder, pNew);
  125490. }
  125491. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  125492. }
  125493. }
  125494. return rc;
  125495. }
  125496. /*
  125497. ** Add all WhereLoop objects for all tables
  125498. */
  125499. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  125500. WhereInfo *pWInfo = pBuilder->pWInfo;
  125501. Bitmask mPrereq = 0;
  125502. Bitmask mPrior = 0;
  125503. int iTab;
  125504. SrcList *pTabList = pWInfo->pTabList;
  125505. struct SrcList_item *pItem;
  125506. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  125507. sqlite3 *db = pWInfo->pParse->db;
  125508. int rc = SQLITE_OK;
  125509. WhereLoop *pNew;
  125510. u8 priorJointype = 0;
  125511. /* Loop over the tables in the join, from left to right */
  125512. pNew = pBuilder->pNew;
  125513. whereLoopInit(pNew);
  125514. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  125515. Bitmask mUnusable = 0;
  125516. pNew->iTab = iTab;
  125517. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  125518. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  125519. /* This condition is true when pItem is the FROM clause term on the
  125520. ** right-hand-side of a LEFT or CROSS JOIN. */
  125521. mPrereq = mPrior;
  125522. }
  125523. priorJointype = pItem->fg.jointype;
  125524. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125525. if( IsVirtual(pItem->pTab) ){
  125526. struct SrcList_item *p;
  125527. for(p=&pItem[1]; p<pEnd; p++){
  125528. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  125529. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  125530. }
  125531. }
  125532. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  125533. }else
  125534. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  125535. {
  125536. rc = whereLoopAddBtree(pBuilder, mPrereq);
  125537. }
  125538. if( rc==SQLITE_OK ){
  125539. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  125540. }
  125541. mPrior |= pNew->maskSelf;
  125542. if( rc || db->mallocFailed ) break;
  125543. }
  125544. whereLoopClear(db, pNew);
  125545. return rc;
  125546. }
  125547. /*
  125548. ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
  125549. ** parameters) to see if it outputs rows in the requested ORDER BY
  125550. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  125551. **
  125552. ** N>0: N terms of the ORDER BY clause are satisfied
  125553. ** N==0: No terms of the ORDER BY clause are satisfied
  125554. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  125555. **
  125556. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  125557. ** strict. With GROUP BY and DISTINCT the only requirement is that
  125558. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  125559. ** and DISTINCT do not require rows to appear in any particular order as long
  125560. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  125561. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  125562. ** pOrderBy terms must be matched in strict left-to-right order.
  125563. */
  125564. static i8 wherePathSatisfiesOrderBy(
  125565. WhereInfo *pWInfo, /* The WHERE clause */
  125566. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  125567. WherePath *pPath, /* The WherePath to check */
  125568. u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
  125569. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  125570. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  125571. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  125572. ){
  125573. u8 revSet; /* True if rev is known */
  125574. u8 rev; /* Composite sort order */
  125575. u8 revIdx; /* Index sort order */
  125576. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  125577. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  125578. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  125579. u16 eqOpMask; /* Allowed equality operators */
  125580. u16 nKeyCol; /* Number of key columns in pIndex */
  125581. u16 nColumn; /* Total number of ordered columns in the index */
  125582. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  125583. int iLoop; /* Index of WhereLoop in pPath being processed */
  125584. int i, j; /* Loop counters */
  125585. int iCur; /* Cursor number for current WhereLoop */
  125586. int iColumn; /* A column number within table iCur */
  125587. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  125588. WhereTerm *pTerm; /* A single term of the WHERE clause */
  125589. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  125590. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  125591. Index *pIndex; /* The index associated with pLoop */
  125592. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  125593. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  125594. Bitmask obDone; /* Mask of all ORDER BY terms */
  125595. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  125596. Bitmask ready; /* Mask of inner loops */
  125597. /*
  125598. ** We say the WhereLoop is "one-row" if it generates no more than one
  125599. ** row of output. A WhereLoop is one-row if all of the following are true:
  125600. ** (a) All index columns match with WHERE_COLUMN_EQ.
  125601. ** (b) The index is unique
  125602. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  125603. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  125604. **
  125605. ** We say the WhereLoop is "order-distinct" if the set of columns from
  125606. ** that WhereLoop that are in the ORDER BY clause are different for every
  125607. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  125608. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  125609. ** is not order-distinct. To be order-distinct is not quite the same as being
  125610. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  125611. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  125612. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  125613. **
  125614. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  125615. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  125616. ** automatically order-distinct.
  125617. */
  125618. assert( pOrderBy!=0 );
  125619. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  125620. nOrderBy = pOrderBy->nExpr;
  125621. testcase( nOrderBy==BMS-1 );
  125622. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  125623. isOrderDistinct = 1;
  125624. obDone = MASKBIT(nOrderBy)-1;
  125625. orderDistinctMask = 0;
  125626. ready = 0;
  125627. eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
  125628. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
  125629. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  125630. if( iLoop>0 ) ready |= pLoop->maskSelf;
  125631. if( iLoop<nLoop ){
  125632. pLoop = pPath->aLoop[iLoop];
  125633. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
  125634. }else{
  125635. pLoop = pLast;
  125636. }
  125637. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  125638. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  125639. break;
  125640. }else{
  125641. pLoop->u.btree.nIdxCol = 0;
  125642. }
  125643. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  125644. /* Mark off any ORDER BY term X that is a column in the table of
  125645. ** the current loop for which there is term in the WHERE
  125646. ** clause of the form X IS NULL or X=? that reference only outer
  125647. ** loops.
  125648. */
  125649. for(i=0; i<nOrderBy; i++){
  125650. if( MASKBIT(i) & obSat ) continue;
  125651. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  125652. if( pOBExpr->op!=TK_COLUMN ) continue;
  125653. if( pOBExpr->iTable!=iCur ) continue;
  125654. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  125655. ~ready, eqOpMask, 0);
  125656. if( pTerm==0 ) continue;
  125657. if( pTerm->eOperator==WO_IN ){
  125658. /* IN terms are only valid for sorting in the ORDER BY LIMIT
  125659. ** optimization, and then only if they are actually used
  125660. ** by the query plan */
  125661. assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
  125662. for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
  125663. if( j>=pLoop->nLTerm ) continue;
  125664. }
  125665. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  125666. const char *z1, *z2;
  125667. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  125668. if( !pColl ) pColl = db->pDfltColl;
  125669. z1 = pColl->zName;
  125670. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  125671. if( !pColl ) pColl = db->pDfltColl;
  125672. z2 = pColl->zName;
  125673. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  125674. testcase( pTerm->pExpr->op==TK_IS );
  125675. }
  125676. obSat |= MASKBIT(i);
  125677. }
  125678. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  125679. if( pLoop->wsFlags & WHERE_IPK ){
  125680. pIndex = 0;
  125681. nKeyCol = 0;
  125682. nColumn = 1;
  125683. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  125684. return 0;
  125685. }else{
  125686. nKeyCol = pIndex->nKeyCol;
  125687. nColumn = pIndex->nColumn;
  125688. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  125689. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  125690. || !HasRowid(pIndex->pTable));
  125691. isOrderDistinct = IsUniqueIndex(pIndex);
  125692. }
  125693. /* Loop through all columns of the index and deal with the ones
  125694. ** that are not constrained by == or IN.
  125695. */
  125696. rev = revSet = 0;
  125697. distinctColumns = 0;
  125698. for(j=0; j<nColumn; j++){
  125699. u8 bOnce = 1; /* True to run the ORDER BY search loop */
  125700. assert( j>=pLoop->u.btree.nEq
  125701. || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
  125702. );
  125703. if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
  125704. u16 eOp = pLoop->aLTerm[j]->eOperator;
  125705. /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
  125706. ** doing WHERE_ORDERBY_LIMIT processing).
  125707. **
  125708. ** If the current term is a column of an ((?,?) IN (SELECT...))
  125709. ** expression for which the SELECT returns more than one column,
  125710. ** check that it is the only column used by this loop. Otherwise,
  125711. ** if it is one of two or more, none of the columns can be
  125712. ** considered to match an ORDER BY term. */
  125713. if( (eOp & eqOpMask)!=0 ){
  125714. if( eOp & WO_ISNULL ){
  125715. testcase( isOrderDistinct );
  125716. isOrderDistinct = 0;
  125717. }
  125718. continue;
  125719. }else if( ALWAYS(eOp & WO_IN) ){
  125720. /* ALWAYS() justification: eOp is an equality operator due to the
  125721. ** j<pLoop->u.btree.nEq constraint above. Any equality other
  125722. ** than WO_IN is captured by the previous "if". So this one
  125723. ** always has to be WO_IN. */
  125724. Expr *pX = pLoop->aLTerm[j]->pExpr;
  125725. for(i=j+1; i<pLoop->u.btree.nEq; i++){
  125726. if( pLoop->aLTerm[i]->pExpr==pX ){
  125727. assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
  125728. bOnce = 0;
  125729. break;
  125730. }
  125731. }
  125732. }
  125733. }
  125734. /* Get the column number in the table (iColumn) and sort order
  125735. ** (revIdx) for the j-th column of the index.
  125736. */
  125737. if( pIndex ){
  125738. iColumn = pIndex->aiColumn[j];
  125739. revIdx = pIndex->aSortOrder[j];
  125740. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  125741. }else{
  125742. iColumn = XN_ROWID;
  125743. revIdx = 0;
  125744. }
  125745. /* An unconstrained column that might be NULL means that this
  125746. ** WhereLoop is not well-ordered
  125747. */
  125748. if( isOrderDistinct
  125749. && iColumn>=0
  125750. && j>=pLoop->u.btree.nEq
  125751. && pIndex->pTable->aCol[iColumn].notNull==0
  125752. ){
  125753. isOrderDistinct = 0;
  125754. }
  125755. /* Find the ORDER BY term that corresponds to the j-th column
  125756. ** of the index and mark that ORDER BY term off
  125757. */
  125758. isMatch = 0;
  125759. for(i=0; bOnce && i<nOrderBy; i++){
  125760. if( MASKBIT(i) & obSat ) continue;
  125761. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  125762. testcase( wctrlFlags & WHERE_GROUPBY );
  125763. testcase( wctrlFlags & WHERE_DISTINCTBY );
  125764. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  125765. if( iColumn>=(-1) ){
  125766. if( pOBExpr->op!=TK_COLUMN ) continue;
  125767. if( pOBExpr->iTable!=iCur ) continue;
  125768. if( pOBExpr->iColumn!=iColumn ) continue;
  125769. }else{
  125770. if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
  125771. continue;
  125772. }
  125773. }
  125774. if( iColumn>=0 ){
  125775. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  125776. if( !pColl ) pColl = db->pDfltColl;
  125777. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  125778. }
  125779. pLoop->u.btree.nIdxCol = j+1;
  125780. isMatch = 1;
  125781. break;
  125782. }
  125783. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  125784. /* Make sure the sort order is compatible in an ORDER BY clause.
  125785. ** Sort order is irrelevant for a GROUP BY clause. */
  125786. if( revSet ){
  125787. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  125788. }else{
  125789. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  125790. if( rev ) *pRevMask |= MASKBIT(iLoop);
  125791. revSet = 1;
  125792. }
  125793. }
  125794. if( isMatch ){
  125795. if( iColumn==XN_ROWID ){
  125796. testcase( distinctColumns==0 );
  125797. distinctColumns = 1;
  125798. }
  125799. obSat |= MASKBIT(i);
  125800. }else{
  125801. /* No match found */
  125802. if( j==0 || j<nKeyCol ){
  125803. testcase( isOrderDistinct!=0 );
  125804. isOrderDistinct = 0;
  125805. }
  125806. break;
  125807. }
  125808. } /* end Loop over all index columns */
  125809. if( distinctColumns ){
  125810. testcase( isOrderDistinct==0 );
  125811. isOrderDistinct = 1;
  125812. }
  125813. } /* end-if not one-row */
  125814. /* Mark off any other ORDER BY terms that reference pLoop */
  125815. if( isOrderDistinct ){
  125816. orderDistinctMask |= pLoop->maskSelf;
  125817. for(i=0; i<nOrderBy; i++){
  125818. Expr *p;
  125819. Bitmask mTerm;
  125820. if( MASKBIT(i) & obSat ) continue;
  125821. p = pOrderBy->a[i].pExpr;
  125822. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  125823. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  125824. if( (mTerm&~orderDistinctMask)==0 ){
  125825. obSat |= MASKBIT(i);
  125826. }
  125827. }
  125828. }
  125829. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  125830. if( obSat==obDone ) return (i8)nOrderBy;
  125831. if( !isOrderDistinct ){
  125832. for(i=nOrderBy-1; i>0; i--){
  125833. Bitmask m = MASKBIT(i) - 1;
  125834. if( (obSat&m)==m ) return i;
  125835. }
  125836. return 0;
  125837. }
  125838. return -1;
  125839. }
  125840. /*
  125841. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  125842. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  125843. ** BY clause - and so any order that groups rows as required satisfies the
  125844. ** request.
  125845. **
  125846. ** Normally, in this case it is not possible for the caller to determine
  125847. ** whether or not the rows are really being delivered in sorted order, or
  125848. ** just in some other order that provides the required grouping. However,
  125849. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  125850. ** this function may be called on the returned WhereInfo object. It returns
  125851. ** true if the rows really will be sorted in the specified order, or false
  125852. ** otherwise.
  125853. **
  125854. ** For example, assuming:
  125855. **
  125856. ** CREATE INDEX i1 ON t1(x, Y);
  125857. **
  125858. ** then
  125859. **
  125860. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  125861. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  125862. */
  125863. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  125864. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  125865. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  125866. return pWInfo->sorted;
  125867. }
  125868. #ifdef WHERETRACE_ENABLED
  125869. /* For debugging use only: */
  125870. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  125871. static char zName[65];
  125872. int i;
  125873. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  125874. if( pLast ) zName[i++] = pLast->cId;
  125875. zName[i] = 0;
  125876. return zName;
  125877. }
  125878. #endif
  125879. /*
  125880. ** Return the cost of sorting nRow rows, assuming that the keys have
  125881. ** nOrderby columns and that the first nSorted columns are already in
  125882. ** order.
  125883. */
  125884. static LogEst whereSortingCost(
  125885. WhereInfo *pWInfo,
  125886. LogEst nRow,
  125887. int nOrderBy,
  125888. int nSorted
  125889. ){
  125890. /* TUNING: Estimated cost of a full external sort, where N is
  125891. ** the number of rows to sort is:
  125892. **
  125893. ** cost = (3.0 * N * log(N)).
  125894. **
  125895. ** Or, if the order-by clause has X terms but only the last Y
  125896. ** terms are out of order, then block-sorting will reduce the
  125897. ** sorting cost to:
  125898. **
  125899. ** cost = (3.0 * N * log(N)) * (Y/X)
  125900. **
  125901. ** The (Y/X) term is implemented using stack variable rScale
  125902. ** below. */
  125903. LogEst rScale, rSortCost;
  125904. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  125905. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  125906. rSortCost = nRow + rScale + 16;
  125907. /* Multiple by log(M) where M is the number of output rows.
  125908. ** Use the LIMIT for M if it is smaller */
  125909. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  125910. nRow = pWInfo->iLimit;
  125911. }
  125912. rSortCost += estLog(nRow);
  125913. return rSortCost;
  125914. }
  125915. /*
  125916. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  125917. ** attempts to find the lowest cost path that visits each WhereLoop
  125918. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  125919. **
  125920. ** Assume that the total number of output rows that will need to be sorted
  125921. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  125922. ** costs if nRowEst==0.
  125923. **
  125924. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  125925. ** error occurs.
  125926. */
  125927. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  125928. int mxChoice; /* Maximum number of simultaneous paths tracked */
  125929. int nLoop; /* Number of terms in the join */
  125930. Parse *pParse; /* Parsing context */
  125931. sqlite3 *db; /* The database connection */
  125932. int iLoop; /* Loop counter over the terms of the join */
  125933. int ii, jj; /* Loop counters */
  125934. int mxI = 0; /* Index of next entry to replace */
  125935. int nOrderBy; /* Number of ORDER BY clause terms */
  125936. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  125937. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  125938. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  125939. WherePath *aFrom; /* All nFrom paths at the previous level */
  125940. WherePath *aTo; /* The nTo best paths at the current level */
  125941. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  125942. WherePath *pTo; /* An element of aTo[] that we are working on */
  125943. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  125944. WhereLoop **pX; /* Used to divy up the pSpace memory */
  125945. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  125946. char *pSpace; /* Temporary memory used by this routine */
  125947. int nSpace; /* Bytes of space allocated at pSpace */
  125948. pParse = pWInfo->pParse;
  125949. db = pParse->db;
  125950. nLoop = pWInfo->nLevel;
  125951. /* TUNING: For simple queries, only the best path is tracked.
  125952. ** For 2-way joins, the 5 best paths are followed.
  125953. ** For joins of 3 or more tables, track the 10 best paths */
  125954. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  125955. assert( nLoop<=pWInfo->pTabList->nSrc );
  125956. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  125957. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  125958. ** case the purpose of this call is to estimate the number of rows returned
  125959. ** by the overall query. Once this estimate has been obtained, the caller
  125960. ** will invoke this function a second time, passing the estimate as the
  125961. ** nRowEst parameter. */
  125962. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  125963. nOrderBy = 0;
  125964. }else{
  125965. nOrderBy = pWInfo->pOrderBy->nExpr;
  125966. }
  125967. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  125968. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  125969. nSpace += sizeof(LogEst) * nOrderBy;
  125970. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  125971. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  125972. aTo = (WherePath*)pSpace;
  125973. aFrom = aTo+mxChoice;
  125974. memset(aFrom, 0, sizeof(aFrom[0]));
  125975. pX = (WhereLoop**)(aFrom+mxChoice);
  125976. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  125977. pFrom->aLoop = pX;
  125978. }
  125979. if( nOrderBy ){
  125980. /* If there is an ORDER BY clause and it is not being ignored, set up
  125981. ** space for the aSortCost[] array. Each element of the aSortCost array
  125982. ** is either zero - meaning it has not yet been initialized - or the
  125983. ** cost of sorting nRowEst rows of data where the first X terms of
  125984. ** the ORDER BY clause are already in order, where X is the array
  125985. ** index. */
  125986. aSortCost = (LogEst*)pX;
  125987. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  125988. }
  125989. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  125990. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  125991. /* Seed the search with a single WherePath containing zero WhereLoops.
  125992. **
  125993. ** TUNING: Do not let the number of iterations go above 28. If the cost
  125994. ** of computing an automatic index is not paid back within the first 28
  125995. ** rows, then do not use the automatic index. */
  125996. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  125997. nFrom = 1;
  125998. assert( aFrom[0].isOrdered==0 );
  125999. if( nOrderBy ){
  126000. /* If nLoop is zero, then there are no FROM terms in the query. Since
  126001. ** in this case the query may return a maximum of one row, the results
  126002. ** are already in the requested order. Set isOrdered to nOrderBy to
  126003. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  126004. ** -1, indicating that the result set may or may not be ordered,
  126005. ** depending on the loops added to the current plan. */
  126006. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  126007. }
  126008. /* Compute successively longer WherePaths using the previous generation
  126009. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  126010. ** best paths at each generation */
  126011. for(iLoop=0; iLoop<nLoop; iLoop++){
  126012. nTo = 0;
  126013. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  126014. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  126015. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  126016. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  126017. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  126018. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  126019. Bitmask maskNew; /* Mask of src visited by (..) */
  126020. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  126021. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  126022. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  126023. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
  126024. /* Do not use an automatic index if the this loop is expected
  126025. ** to run less than 2 times. */
  126026. assert( 10==sqlite3LogEst(2) );
  126027. continue;
  126028. }
  126029. /* At this point, pWLoop is a candidate to be the next loop.
  126030. ** Compute its cost */
  126031. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  126032. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  126033. nOut = pFrom->nRow + pWLoop->nOut;
  126034. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  126035. if( isOrdered<0 ){
  126036. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  126037. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  126038. iLoop, pWLoop, &revMask);
  126039. }else{
  126040. revMask = pFrom->revLoop;
  126041. }
  126042. if( isOrdered>=0 && isOrdered<nOrderBy ){
  126043. if( aSortCost[isOrdered]==0 ){
  126044. aSortCost[isOrdered] = whereSortingCost(
  126045. pWInfo, nRowEst, nOrderBy, isOrdered
  126046. );
  126047. }
  126048. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  126049. WHERETRACE(0x002,
  126050. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  126051. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  126052. rUnsorted, rCost));
  126053. }else{
  126054. rCost = rUnsorted;
  126055. }
  126056. /* Check to see if pWLoop should be added to the set of
  126057. ** mxChoice best-so-far paths.
  126058. **
  126059. ** First look for an existing path among best-so-far paths
  126060. ** that covers the same set of loops and has the same isOrdered
  126061. ** setting as the current path candidate.
  126062. **
  126063. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  126064. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  126065. ** of legal values for isOrdered, -1..64.
  126066. */
  126067. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  126068. if( pTo->maskLoop==maskNew
  126069. && ((pTo->isOrdered^isOrdered)&0x80)==0
  126070. ){
  126071. testcase( jj==nTo-1 );
  126072. break;
  126073. }
  126074. }
  126075. if( jj>=nTo ){
  126076. /* None of the existing best-so-far paths match the candidate. */
  126077. if( nTo>=mxChoice
  126078. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  126079. ){
  126080. /* The current candidate is no better than any of the mxChoice
  126081. ** paths currently in the best-so-far buffer. So discard
  126082. ** this candidate as not viable. */
  126083. #ifdef WHERETRACE_ENABLED /* 0x4 */
  126084. if( sqlite3WhereTrace&0x4 ){
  126085. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  126086. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  126087. isOrdered>=0 ? isOrdered+'0' : '?');
  126088. }
  126089. #endif
  126090. continue;
  126091. }
  126092. /* If we reach this points it means that the new candidate path
  126093. ** needs to be added to the set of best-so-far paths. */
  126094. if( nTo<mxChoice ){
  126095. /* Increase the size of the aTo set by one */
  126096. jj = nTo++;
  126097. }else{
  126098. /* New path replaces the prior worst to keep count below mxChoice */
  126099. jj = mxI;
  126100. }
  126101. pTo = &aTo[jj];
  126102. #ifdef WHERETRACE_ENABLED /* 0x4 */
  126103. if( sqlite3WhereTrace&0x4 ){
  126104. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  126105. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  126106. isOrdered>=0 ? isOrdered+'0' : '?');
  126107. }
  126108. #endif
  126109. }else{
  126110. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  126111. ** same set of loops and has the sam isOrdered setting as the
  126112. ** candidate path. Check to see if the candidate should replace
  126113. ** pTo or if the candidate should be skipped */
  126114. if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  126115. #ifdef WHERETRACE_ENABLED /* 0x4 */
  126116. if( sqlite3WhereTrace&0x4 ){
  126117. sqlite3DebugPrintf(
  126118. "Skip %s cost=%-3d,%3d order=%c",
  126119. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  126120. isOrdered>=0 ? isOrdered+'0' : '?');
  126121. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  126122. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  126123. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  126124. }
  126125. #endif
  126126. /* Discard the candidate path from further consideration */
  126127. testcase( pTo->rCost==rCost );
  126128. continue;
  126129. }
  126130. testcase( pTo->rCost==rCost+1 );
  126131. /* Control reaches here if the candidate path is better than the
  126132. ** pTo path. Replace pTo with the candidate. */
  126133. #ifdef WHERETRACE_ENABLED /* 0x4 */
  126134. if( sqlite3WhereTrace&0x4 ){
  126135. sqlite3DebugPrintf(
  126136. "Update %s cost=%-3d,%3d order=%c",
  126137. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  126138. isOrdered>=0 ? isOrdered+'0' : '?');
  126139. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  126140. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  126141. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  126142. }
  126143. #endif
  126144. }
  126145. /* pWLoop is a winner. Add it to the set of best so far */
  126146. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  126147. pTo->revLoop = revMask;
  126148. pTo->nRow = nOut;
  126149. pTo->rCost = rCost;
  126150. pTo->rUnsorted = rUnsorted;
  126151. pTo->isOrdered = isOrdered;
  126152. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  126153. pTo->aLoop[iLoop] = pWLoop;
  126154. if( nTo>=mxChoice ){
  126155. mxI = 0;
  126156. mxCost = aTo[0].rCost;
  126157. mxUnsorted = aTo[0].nRow;
  126158. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  126159. if( pTo->rCost>mxCost
  126160. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  126161. ){
  126162. mxCost = pTo->rCost;
  126163. mxUnsorted = pTo->rUnsorted;
  126164. mxI = jj;
  126165. }
  126166. }
  126167. }
  126168. }
  126169. }
  126170. #ifdef WHERETRACE_ENABLED /* >=2 */
  126171. if( sqlite3WhereTrace & 0x02 ){
  126172. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  126173. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  126174. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  126175. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  126176. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  126177. if( pTo->isOrdered>0 ){
  126178. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  126179. }else{
  126180. sqlite3DebugPrintf("\n");
  126181. }
  126182. }
  126183. }
  126184. #endif
  126185. /* Swap the roles of aFrom and aTo for the next generation */
  126186. pFrom = aTo;
  126187. aTo = aFrom;
  126188. aFrom = pFrom;
  126189. nFrom = nTo;
  126190. }
  126191. if( nFrom==0 ){
  126192. sqlite3ErrorMsg(pParse, "no query solution");
  126193. sqlite3DbFreeNN(db, pSpace);
  126194. return SQLITE_ERROR;
  126195. }
  126196. /* Find the lowest cost path. pFrom will be left pointing to that path */
  126197. pFrom = aFrom;
  126198. for(ii=1; ii<nFrom; ii++){
  126199. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  126200. }
  126201. assert( pWInfo->nLevel==nLoop );
  126202. /* Load the lowest cost path into pWInfo */
  126203. for(iLoop=0; iLoop<nLoop; iLoop++){
  126204. WhereLevel *pLevel = pWInfo->a + iLoop;
  126205. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  126206. pLevel->iFrom = pWLoop->iTab;
  126207. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  126208. }
  126209. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  126210. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  126211. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  126212. && nRowEst
  126213. ){
  126214. Bitmask notUsed;
  126215. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  126216. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  126217. if( rc==pWInfo->pResultSet->nExpr ){
  126218. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  126219. }
  126220. }
  126221. if( pWInfo->pOrderBy ){
  126222. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  126223. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  126224. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  126225. }
  126226. }else{
  126227. pWInfo->nOBSat = pFrom->isOrdered;
  126228. pWInfo->revMask = pFrom->revLoop;
  126229. if( pWInfo->nOBSat<=0 ){
  126230. pWInfo->nOBSat = 0;
  126231. if( nLoop>0 ){
  126232. u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
  126233. if( (wsFlags & WHERE_ONEROW)==0
  126234. && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
  126235. ){
  126236. Bitmask m = 0;
  126237. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
  126238. WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
  126239. testcase( wsFlags & WHERE_IPK );
  126240. testcase( wsFlags & WHERE_COLUMN_IN );
  126241. if( rc==pWInfo->pOrderBy->nExpr ){
  126242. pWInfo->bOrderedInnerLoop = 1;
  126243. pWInfo->revMask = m;
  126244. }
  126245. }
  126246. }
  126247. }
  126248. }
  126249. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  126250. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  126251. ){
  126252. Bitmask revMask = 0;
  126253. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  126254. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  126255. );
  126256. assert( pWInfo->sorted==0 );
  126257. if( nOrder==pWInfo->pOrderBy->nExpr ){
  126258. pWInfo->sorted = 1;
  126259. pWInfo->revMask = revMask;
  126260. }
  126261. }
  126262. }
  126263. pWInfo->nRowOut = pFrom->nRow;
  126264. /* Free temporary memory and return success */
  126265. sqlite3DbFreeNN(db, pSpace);
  126266. return SQLITE_OK;
  126267. }
  126268. /*
  126269. ** Most queries use only a single table (they are not joins) and have
  126270. ** simple == constraints against indexed fields. This routine attempts
  126271. ** to plan those simple cases using much less ceremony than the
  126272. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  126273. ** times for the common case.
  126274. **
  126275. ** Return non-zero on success, if this query can be handled by this
  126276. ** no-frills query planner. Return zero if this query needs the
  126277. ** general-purpose query planner.
  126278. */
  126279. static int whereShortCut(WhereLoopBuilder *pBuilder){
  126280. WhereInfo *pWInfo;
  126281. struct SrcList_item *pItem;
  126282. WhereClause *pWC;
  126283. WhereTerm *pTerm;
  126284. WhereLoop *pLoop;
  126285. int iCur;
  126286. int j;
  126287. Table *pTab;
  126288. Index *pIdx;
  126289. pWInfo = pBuilder->pWInfo;
  126290. if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
  126291. assert( pWInfo->pTabList->nSrc>=1 );
  126292. pItem = pWInfo->pTabList->a;
  126293. pTab = pItem->pTab;
  126294. if( IsVirtual(pTab) ) return 0;
  126295. if( pItem->fg.isIndexedBy ) return 0;
  126296. iCur = pItem->iCursor;
  126297. pWC = &pWInfo->sWC;
  126298. pLoop = pBuilder->pNew;
  126299. pLoop->wsFlags = 0;
  126300. pLoop->nSkip = 0;
  126301. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  126302. if( pTerm ){
  126303. testcase( pTerm->eOperator & WO_IS );
  126304. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  126305. pLoop->aLTerm[0] = pTerm;
  126306. pLoop->nLTerm = 1;
  126307. pLoop->u.btree.nEq = 1;
  126308. /* TUNING: Cost of a rowid lookup is 10 */
  126309. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  126310. }else{
  126311. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  126312. int opMask;
  126313. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  126314. if( !IsUniqueIndex(pIdx)
  126315. || pIdx->pPartIdxWhere!=0
  126316. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  126317. ) continue;
  126318. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  126319. for(j=0; j<pIdx->nKeyCol; j++){
  126320. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  126321. if( pTerm==0 ) break;
  126322. testcase( pTerm->eOperator & WO_IS );
  126323. pLoop->aLTerm[j] = pTerm;
  126324. }
  126325. if( j!=pIdx->nKeyCol ) continue;
  126326. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  126327. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  126328. pLoop->wsFlags |= WHERE_IDX_ONLY;
  126329. }
  126330. pLoop->nLTerm = j;
  126331. pLoop->u.btree.nEq = j;
  126332. pLoop->u.btree.pIndex = pIdx;
  126333. /* TUNING: Cost of a unique index lookup is 15 */
  126334. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  126335. break;
  126336. }
  126337. }
  126338. if( pLoop->wsFlags ){
  126339. pLoop->nOut = (LogEst)1;
  126340. pWInfo->a[0].pWLoop = pLoop;
  126341. assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
  126342. pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
  126343. pWInfo->a[0].iTabCur = iCur;
  126344. pWInfo->nRowOut = 1;
  126345. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  126346. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  126347. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  126348. }
  126349. #ifdef SQLITE_DEBUG
  126350. pLoop->cId = '0';
  126351. #endif
  126352. return 1;
  126353. }
  126354. return 0;
  126355. }
  126356. /*
  126357. ** Generate the beginning of the loop used for WHERE clause processing.
  126358. ** The return value is a pointer to an opaque structure that contains
  126359. ** information needed to terminate the loop. Later, the calling routine
  126360. ** should invoke sqlite3WhereEnd() with the return value of this function
  126361. ** in order to complete the WHERE clause processing.
  126362. **
  126363. ** If an error occurs, this routine returns NULL.
  126364. **
  126365. ** The basic idea is to do a nested loop, one loop for each table in
  126366. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  126367. ** same as a SELECT with only a single table in the FROM clause.) For
  126368. ** example, if the SQL is this:
  126369. **
  126370. ** SELECT * FROM t1, t2, t3 WHERE ...;
  126371. **
  126372. ** Then the code generated is conceptually like the following:
  126373. **
  126374. ** foreach row1 in t1 do \ Code generated
  126375. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  126376. ** foreach row3 in t3 do /
  126377. ** ...
  126378. ** end \ Code generated
  126379. ** end |-- by sqlite3WhereEnd()
  126380. ** end /
  126381. **
  126382. ** Note that the loops might not be nested in the order in which they
  126383. ** appear in the FROM clause if a different order is better able to make
  126384. ** use of indices. Note also that when the IN operator appears in
  126385. ** the WHERE clause, it might result in additional nested loops for
  126386. ** scanning through all values on the right-hand side of the IN.
  126387. **
  126388. ** There are Btree cursors associated with each table. t1 uses cursor
  126389. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  126390. ** And so forth. This routine generates code to open those VDBE cursors
  126391. ** and sqlite3WhereEnd() generates the code to close them.
  126392. **
  126393. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  126394. ** in pTabList pointing at their appropriate entries. The [...] code
  126395. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  126396. ** data from the various tables of the loop.
  126397. **
  126398. ** If the WHERE clause is empty, the foreach loops must each scan their
  126399. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  126400. ** the tables have indices and there are terms in the WHERE clause that
  126401. ** refer to those indices, a complete table scan can be avoided and the
  126402. ** code will run much faster. Most of the work of this routine is checking
  126403. ** to see if there are indices that can be used to speed up the loop.
  126404. **
  126405. ** Terms of the WHERE clause are also used to limit which rows actually
  126406. ** make it to the "..." in the middle of the loop. After each "foreach",
  126407. ** terms of the WHERE clause that use only terms in that loop and outer
  126408. ** loops are evaluated and if false a jump is made around all subsequent
  126409. ** inner loops (or around the "..." if the test occurs within the inner-
  126410. ** most loop)
  126411. **
  126412. ** OUTER JOINS
  126413. **
  126414. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  126415. **
  126416. ** foreach row1 in t1 do
  126417. ** flag = 0
  126418. ** foreach row2 in t2 do
  126419. ** start:
  126420. ** ...
  126421. ** flag = 1
  126422. ** end
  126423. ** if flag==0 then
  126424. ** move the row2 cursor to a null row
  126425. ** goto start
  126426. ** fi
  126427. ** end
  126428. **
  126429. ** ORDER BY CLAUSE PROCESSING
  126430. **
  126431. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  126432. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  126433. ** if there is one. If there is no ORDER BY clause or if this routine
  126434. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  126435. **
  126436. ** The iIdxCur parameter is the cursor number of an index. If
  126437. ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
  126438. ** to use for OR clause processing. The WHERE clause should use this
  126439. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  126440. ** the first cursor in an array of cursors for all indices. iIdxCur should
  126441. ** be used to compute the appropriate cursor depending on which index is
  126442. ** used.
  126443. */
  126444. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  126445. Parse *pParse, /* The parser context */
  126446. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  126447. Expr *pWhere, /* The WHERE clause */
  126448. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  126449. ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
  126450. u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
  126451. int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
  126452. ** If WHERE_USE_LIMIT, then the limit amount */
  126453. ){
  126454. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  126455. int nTabList; /* Number of elements in pTabList */
  126456. WhereInfo *pWInfo; /* Will become the return value of this function */
  126457. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  126458. Bitmask notReady; /* Cursors that are not yet positioned */
  126459. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  126460. WhereMaskSet *pMaskSet; /* The expression mask set */
  126461. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  126462. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  126463. int ii; /* Loop counter */
  126464. sqlite3 *db; /* Database connection */
  126465. int rc; /* Return code */
  126466. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  126467. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  126468. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  126469. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  126470. ));
  126471. /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
  126472. assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  126473. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  126474. /* Variable initialization */
  126475. db = pParse->db;
  126476. memset(&sWLB, 0, sizeof(sWLB));
  126477. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  126478. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  126479. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  126480. sWLB.pOrderBy = pOrderBy;
  126481. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  126482. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  126483. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  126484. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  126485. }
  126486. /* The number of tables in the FROM clause is limited by the number of
  126487. ** bits in a Bitmask
  126488. */
  126489. testcase( pTabList->nSrc==BMS );
  126490. if( pTabList->nSrc>BMS ){
  126491. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  126492. return 0;
  126493. }
  126494. /* This function normally generates a nested loop for all tables in
  126495. ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
  126496. ** only generate code for the first table in pTabList and assume that
  126497. ** any cursors associated with subsequent tables are uninitialized.
  126498. */
  126499. nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
  126500. /* Allocate and initialize the WhereInfo structure that will become the
  126501. ** return value. A single allocation is used to store the WhereInfo
  126502. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  126503. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  126504. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  126505. ** some architectures. Hence the ROUND8() below.
  126506. */
  126507. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  126508. pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
  126509. if( db->mallocFailed ){
  126510. sqlite3DbFree(db, pWInfo);
  126511. pWInfo = 0;
  126512. goto whereBeginError;
  126513. }
  126514. pWInfo->pParse = pParse;
  126515. pWInfo->pTabList = pTabList;
  126516. pWInfo->pOrderBy = pOrderBy;
  126517. pWInfo->pWhere = pWhere;
  126518. pWInfo->pResultSet = pResultSet;
  126519. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  126520. pWInfo->nLevel = nTabList;
  126521. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  126522. pWInfo->wctrlFlags = wctrlFlags;
  126523. pWInfo->iLimit = iAuxArg;
  126524. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  126525. memset(&pWInfo->nOBSat, 0,
  126526. offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
  126527. memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
  126528. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  126529. pMaskSet = &pWInfo->sMaskSet;
  126530. sWLB.pWInfo = pWInfo;
  126531. sWLB.pWC = &pWInfo->sWC;
  126532. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  126533. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  126534. whereLoopInit(sWLB.pNew);
  126535. #ifdef SQLITE_DEBUG
  126536. sWLB.pNew->cId = '*';
  126537. #endif
  126538. /* Split the WHERE clause into separate subexpressions where each
  126539. ** subexpression is separated by an AND operator.
  126540. */
  126541. initMaskSet(pMaskSet);
  126542. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  126543. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  126544. /* Special case: a WHERE clause that is constant. Evaluate the
  126545. ** expression and either jump over all of the code or fall thru.
  126546. */
  126547. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  126548. if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
  126549. sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
  126550. SQLITE_JUMPIFNULL);
  126551. sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
  126552. }
  126553. }
  126554. /* Special case: No FROM clause
  126555. */
  126556. if( nTabList==0 ){
  126557. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  126558. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  126559. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  126560. }
  126561. }
  126562. /* Assign a bit from the bitmask to every term in the FROM clause.
  126563. **
  126564. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  126565. **
  126566. ** The rule of the previous sentence ensures thta if X is the bitmask for
  126567. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  126568. ** Knowing the bitmask for all tables to the left of a left join is
  126569. ** important. Ticket #3015.
  126570. **
  126571. ** Note that bitmasks are created for all pTabList->nSrc tables in
  126572. ** pTabList, not just the first nTabList tables. nTabList is normally
  126573. ** equal to pTabList->nSrc but might be shortened to 1 if the
  126574. ** WHERE_OR_SUBCLAUSE flag is set.
  126575. */
  126576. for(ii=0; ii<pTabList->nSrc; ii++){
  126577. createMask(pMaskSet, pTabList->a[ii].iCursor);
  126578. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  126579. }
  126580. #ifdef SQLITE_DEBUG
  126581. for(ii=0; ii<pTabList->nSrc; ii++){
  126582. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  126583. assert( m==MASKBIT(ii) );
  126584. }
  126585. #endif
  126586. /* Analyze all of the subexpressions. */
  126587. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  126588. if( db->mallocFailed ) goto whereBeginError;
  126589. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  126590. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  126591. /* The DISTINCT marking is pointless. Ignore it. */
  126592. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  126593. }else if( pOrderBy==0 ){
  126594. /* Try to ORDER BY the result set to make distinct processing easier */
  126595. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  126596. pWInfo->pOrderBy = pResultSet;
  126597. }
  126598. }
  126599. /* Construct the WhereLoop objects */
  126600. #if defined(WHERETRACE_ENABLED)
  126601. if( sqlite3WhereTrace & 0xffff ){
  126602. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  126603. if( wctrlFlags & WHERE_USE_LIMIT ){
  126604. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  126605. }
  126606. sqlite3DebugPrintf(")\n");
  126607. }
  126608. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  126609. sqlite3WhereClausePrint(sWLB.pWC);
  126610. }
  126611. #endif
  126612. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  126613. rc = whereLoopAddAll(&sWLB);
  126614. if( rc ) goto whereBeginError;
  126615. #ifdef WHERETRACE_ENABLED
  126616. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  126617. WhereLoop *p;
  126618. int i;
  126619. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  126620. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  126621. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  126622. p->cId = zLabel[i%sizeof(zLabel)];
  126623. whereLoopPrint(p, sWLB.pWC);
  126624. }
  126625. }
  126626. #endif
  126627. wherePathSolver(pWInfo, 0);
  126628. if( db->mallocFailed ) goto whereBeginError;
  126629. if( pWInfo->pOrderBy ){
  126630. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  126631. if( db->mallocFailed ) goto whereBeginError;
  126632. }
  126633. }
  126634. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  126635. pWInfo->revMask = ALLBITS;
  126636. }
  126637. if( pParse->nErr || NEVER(db->mallocFailed) ){
  126638. goto whereBeginError;
  126639. }
  126640. #ifdef WHERETRACE_ENABLED
  126641. if( sqlite3WhereTrace ){
  126642. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  126643. if( pWInfo->nOBSat>0 ){
  126644. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  126645. }
  126646. switch( pWInfo->eDistinct ){
  126647. case WHERE_DISTINCT_UNIQUE: {
  126648. sqlite3DebugPrintf(" DISTINCT=unique");
  126649. break;
  126650. }
  126651. case WHERE_DISTINCT_ORDERED: {
  126652. sqlite3DebugPrintf(" DISTINCT=ordered");
  126653. break;
  126654. }
  126655. case WHERE_DISTINCT_UNORDERED: {
  126656. sqlite3DebugPrintf(" DISTINCT=unordered");
  126657. break;
  126658. }
  126659. }
  126660. sqlite3DebugPrintf("\n");
  126661. for(ii=0; ii<pWInfo->nLevel; ii++){
  126662. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  126663. }
  126664. }
  126665. #endif
  126666. /* Attempt to omit tables from the join that do not effect the result */
  126667. if( pWInfo->nLevel>=2
  126668. && pResultSet!=0
  126669. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  126670. ){
  126671. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  126672. if( sWLB.pOrderBy ){
  126673. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  126674. }
  126675. while( pWInfo->nLevel>=2 ){
  126676. WhereTerm *pTerm, *pEnd;
  126677. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  126678. if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
  126679. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  126680. && (pLoop->wsFlags & WHERE_ONEROW)==0
  126681. ){
  126682. break;
  126683. }
  126684. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  126685. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  126686. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  126687. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  126688. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  126689. ){
  126690. break;
  126691. }
  126692. }
  126693. if( pTerm<pEnd ) break;
  126694. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  126695. pWInfo->nLevel--;
  126696. nTabList--;
  126697. }
  126698. }
  126699. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  126700. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  126701. /* If the caller is an UPDATE or DELETE statement that is requesting
  126702. ** to use a one-pass algorithm, determine if this is appropriate.
  126703. */
  126704. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  126705. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  126706. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  126707. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  126708. if( bOnerow
  126709. || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
  126710. && 0==(wsFlags & WHERE_VIRTUALTABLE))
  126711. ){
  126712. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  126713. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  126714. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  126715. bFordelete = OPFLAG_FORDELETE;
  126716. }
  126717. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  126718. }
  126719. }
  126720. }
  126721. /* Open all tables in the pTabList and any indices selected for
  126722. ** searching those tables.
  126723. */
  126724. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  126725. Table *pTab; /* Table to open */
  126726. int iDb; /* Index of database containing table/index */
  126727. struct SrcList_item *pTabItem;
  126728. pTabItem = &pTabList->a[pLevel->iFrom];
  126729. pTab = pTabItem->pTab;
  126730. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  126731. pLoop = pLevel->pWLoop;
  126732. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  126733. /* Do nothing */
  126734. }else
  126735. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126736. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  126737. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  126738. int iCur = pTabItem->iCursor;
  126739. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  126740. }else if( IsVirtual(pTab) ){
  126741. /* noop */
  126742. }else
  126743. #endif
  126744. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  126745. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  126746. int op = OP_OpenRead;
  126747. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  126748. op = OP_OpenWrite;
  126749. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  126750. };
  126751. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  126752. assert( pTabItem->iCursor==pLevel->iTabCur );
  126753. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  126754. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  126755. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  126756. Bitmask b = pTabItem->colUsed;
  126757. int n = 0;
  126758. for(; b; b=b>>1, n++){}
  126759. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  126760. assert( n<=pTab->nCol );
  126761. }
  126762. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  126763. if( pLoop->u.btree.pIndex!=0 ){
  126764. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  126765. }else
  126766. #endif
  126767. {
  126768. sqlite3VdbeChangeP5(v, bFordelete);
  126769. }
  126770. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  126771. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  126772. (const u8*)&pTabItem->colUsed, P4_INT64);
  126773. #endif
  126774. }else{
  126775. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  126776. }
  126777. if( pLoop->wsFlags & WHERE_INDEXED ){
  126778. Index *pIx = pLoop->u.btree.pIndex;
  126779. int iIndexCur;
  126780. int op = OP_OpenRead;
  126781. /* iAuxArg is always set if to a positive value if ONEPASS is possible */
  126782. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  126783. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  126784. && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
  126785. ){
  126786. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  126787. ** WITHOUT ROWID table. No need for a separate index */
  126788. iIndexCur = pLevel->iTabCur;
  126789. op = 0;
  126790. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  126791. Index *pJ = pTabItem->pTab->pIndex;
  126792. iIndexCur = iAuxArg;
  126793. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  126794. while( ALWAYS(pJ) && pJ!=pIx ){
  126795. iIndexCur++;
  126796. pJ = pJ->pNext;
  126797. }
  126798. op = OP_OpenWrite;
  126799. pWInfo->aiCurOnePass[1] = iIndexCur;
  126800. }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
  126801. iIndexCur = iAuxArg;
  126802. op = OP_ReopenIdx;
  126803. }else{
  126804. iIndexCur = pParse->nTab++;
  126805. }
  126806. pLevel->iIdxCur = iIndexCur;
  126807. assert( pIx->pSchema==pTab->pSchema );
  126808. assert( iIndexCur>=0 );
  126809. if( op ){
  126810. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  126811. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  126812. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  126813. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  126814. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  126815. && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
  126816. ){
  126817. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  126818. }
  126819. VdbeComment((v, "%s", pIx->zName));
  126820. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  126821. {
  126822. u64 colUsed = 0;
  126823. int ii, jj;
  126824. for(ii=0; ii<pIx->nColumn; ii++){
  126825. jj = pIx->aiColumn[ii];
  126826. if( jj<0 ) continue;
  126827. if( jj>63 ) jj = 63;
  126828. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  126829. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  126830. }
  126831. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  126832. (u8*)&colUsed, P4_INT64);
  126833. }
  126834. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  126835. }
  126836. }
  126837. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  126838. }
  126839. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  126840. if( db->mallocFailed ) goto whereBeginError;
  126841. /* Generate the code to do the search. Each iteration of the for
  126842. ** loop below generates code for a single nested loop of the VM
  126843. ** program.
  126844. */
  126845. notReady = ~(Bitmask)0;
  126846. for(ii=0; ii<nTabList; ii++){
  126847. int addrExplain;
  126848. int wsFlags;
  126849. pLevel = &pWInfo->a[ii];
  126850. wsFlags = pLevel->pWLoop->wsFlags;
  126851. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  126852. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  126853. constructAutomaticIndex(pParse, &pWInfo->sWC,
  126854. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  126855. if( db->mallocFailed ) goto whereBeginError;
  126856. }
  126857. #endif
  126858. addrExplain = sqlite3WhereExplainOneScan(
  126859. pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
  126860. );
  126861. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  126862. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  126863. pWInfo->iContinue = pLevel->addrCont;
  126864. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
  126865. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  126866. }
  126867. }
  126868. /* Done. */
  126869. VdbeModuleComment((v, "Begin WHERE-core"));
  126870. return pWInfo;
  126871. /* Jump here if malloc fails */
  126872. whereBeginError:
  126873. if( pWInfo ){
  126874. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  126875. whereInfoFree(db, pWInfo);
  126876. }
  126877. return 0;
  126878. }
  126879. /*
  126880. ** Generate the end of the WHERE loop. See comments on
  126881. ** sqlite3WhereBegin() for additional information.
  126882. */
  126883. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  126884. Parse *pParse = pWInfo->pParse;
  126885. Vdbe *v = pParse->pVdbe;
  126886. int i;
  126887. WhereLevel *pLevel;
  126888. WhereLoop *pLoop;
  126889. SrcList *pTabList = pWInfo->pTabList;
  126890. sqlite3 *db = pParse->db;
  126891. /* Generate loop termination code.
  126892. */
  126893. VdbeModuleComment((v, "End WHERE-core"));
  126894. sqlite3ExprCacheClear(pParse);
  126895. for(i=pWInfo->nLevel-1; i>=0; i--){
  126896. int addr;
  126897. pLevel = &pWInfo->a[i];
  126898. pLoop = pLevel->pWLoop;
  126899. if( pLevel->op!=OP_Noop ){
  126900. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  126901. int addrSeek = 0;
  126902. Index *pIdx;
  126903. int n;
  126904. if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
  126905. && (pLoop->wsFlags & WHERE_INDEXED)!=0
  126906. && (pIdx = pLoop->u.btree.pIndex)->hasStat1
  126907. && (n = pLoop->u.btree.nIdxCol)>0
  126908. && pIdx->aiRowLogEst[n]>=36
  126909. ){
  126910. int r1 = pParse->nMem+1;
  126911. int j, op;
  126912. for(j=0; j<n; j++){
  126913. sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
  126914. }
  126915. pParse->nMem += n+1;
  126916. op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
  126917. addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
  126918. VdbeCoverageIf(v, op==OP_SeekLT);
  126919. VdbeCoverageIf(v, op==OP_SeekGT);
  126920. sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
  126921. }
  126922. #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
  126923. /* The common case: Advance to the next row */
  126924. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  126925. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  126926. sqlite3VdbeChangeP5(v, pLevel->p5);
  126927. VdbeCoverage(v);
  126928. VdbeCoverageIf(v, pLevel->op==OP_Next);
  126929. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  126930. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  126931. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  126932. if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
  126933. #endif
  126934. }else{
  126935. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  126936. }
  126937. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  126938. struct InLoop *pIn;
  126939. int j;
  126940. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  126941. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  126942. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  126943. if( pIn->eEndLoopOp!=OP_Noop ){
  126944. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  126945. VdbeCoverage(v);
  126946. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  126947. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  126948. }
  126949. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  126950. }
  126951. }
  126952. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  126953. if( pLevel->addrSkip ){
  126954. sqlite3VdbeGoto(v, pLevel->addrSkip);
  126955. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  126956. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  126957. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  126958. }
  126959. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  126960. if( pLevel->addrLikeRep ){
  126961. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
  126962. pLevel->addrLikeRep);
  126963. VdbeCoverage(v);
  126964. }
  126965. #endif
  126966. if( pLevel->iLeftJoin ){
  126967. int ws = pLoop->wsFlags;
  126968. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  126969. assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
  126970. if( (ws & WHERE_IDX_ONLY)==0 ){
  126971. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  126972. }
  126973. if( (ws & WHERE_INDEXED)
  126974. || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
  126975. ){
  126976. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  126977. }
  126978. if( pLevel->op==OP_Return ){
  126979. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  126980. }else{
  126981. sqlite3VdbeGoto(v, pLevel->addrFirst);
  126982. }
  126983. sqlite3VdbeJumpHere(v, addr);
  126984. }
  126985. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  126986. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  126987. }
  126988. /* The "break" point is here, just past the end of the outer loop.
  126989. ** Set it.
  126990. */
  126991. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  126992. assert( pWInfo->nLevel<=pTabList->nSrc );
  126993. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  126994. int k, last;
  126995. VdbeOp *pOp;
  126996. Index *pIdx = 0;
  126997. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  126998. Table *pTab = pTabItem->pTab;
  126999. assert( pTab!=0 );
  127000. pLoop = pLevel->pWLoop;
  127001. /* For a co-routine, change all OP_Column references to the table of
  127002. ** the co-routine into OP_Copy of result contained in a register.
  127003. ** OP_Rowid becomes OP_Null.
  127004. */
  127005. if( pTabItem->fg.viaCoroutine ){
  127006. testcase( pParse->db->mallocFailed );
  127007. translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
  127008. pTabItem->regResult, 0);
  127009. continue;
  127010. }
  127011. /* If this scan uses an index, make VDBE code substitutions to read data
  127012. ** from the index instead of from the table where possible. In some cases
  127013. ** this optimization prevents the table from ever being read, which can
  127014. ** yield a significant performance boost.
  127015. **
  127016. ** Calls to the code generator in between sqlite3WhereBegin and
  127017. ** sqlite3WhereEnd will have created code that references the table
  127018. ** directly. This loop scans all that code looking for opcodes
  127019. ** that reference the table and converts them into opcodes that
  127020. ** reference the index.
  127021. */
  127022. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  127023. pIdx = pLoop->u.btree.pIndex;
  127024. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  127025. pIdx = pLevel->u.pCovidx;
  127026. }
  127027. if( pIdx
  127028. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  127029. && !db->mallocFailed
  127030. ){
  127031. last = sqlite3VdbeCurrentAddr(v);
  127032. k = pLevel->addrBody;
  127033. pOp = sqlite3VdbeGetOp(v, k);
  127034. for(; k<last; k++, pOp++){
  127035. if( pOp->p1!=pLevel->iTabCur ) continue;
  127036. if( pOp->opcode==OP_Column ){
  127037. int x = pOp->p2;
  127038. assert( pIdx->pTable==pTab );
  127039. if( !HasRowid(pTab) ){
  127040. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  127041. x = pPk->aiColumn[x];
  127042. assert( x>=0 );
  127043. }
  127044. x = sqlite3ColumnOfIndex(pIdx, x);
  127045. if( x>=0 ){
  127046. pOp->p2 = x;
  127047. pOp->p1 = pLevel->iIdxCur;
  127048. }
  127049. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
  127050. || pWInfo->eOnePass );
  127051. }else if( pOp->opcode==OP_Rowid ){
  127052. pOp->p1 = pLevel->iIdxCur;
  127053. pOp->opcode = OP_IdxRowid;
  127054. }else if( pOp->opcode==OP_IfNullRow ){
  127055. pOp->p1 = pLevel->iIdxCur;
  127056. }
  127057. }
  127058. }
  127059. }
  127060. /* Final cleanup
  127061. */
  127062. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  127063. whereInfoFree(db, pWInfo);
  127064. return;
  127065. }
  127066. /************** End of where.c ***********************************************/
  127067. /************** Begin file parse.c *******************************************/
  127068. /*
  127069. ** 2000-05-29
  127070. **
  127071. ** The author disclaims copyright to this source code. In place of
  127072. ** a legal notice, here is a blessing:
  127073. **
  127074. ** May you do good and not evil.
  127075. ** May you find forgiveness for yourself and forgive others.
  127076. ** May you share freely, never taking more than you give.
  127077. **
  127078. *************************************************************************
  127079. ** Driver template for the LEMON parser generator.
  127080. **
  127081. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  127082. ** this template to construct a parser. The "lemon" program inserts text
  127083. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  127084. ** interstitial "-" characters) contained in this template is changed into
  127085. ** the value of the %name directive from the grammar. Otherwise, the content
  127086. ** of this template is copied straight through into the generate parser
  127087. ** source file.
  127088. **
  127089. ** The following is the concatenation of all %include directives from the
  127090. ** input grammar file:
  127091. */
  127092. /* #include <stdio.h> */
  127093. /************ Begin %include sections from the grammar ************************/
  127094. /* #include "sqliteInt.h" */
  127095. /*
  127096. ** Disable all error recovery processing in the parser push-down
  127097. ** automaton.
  127098. */
  127099. #define YYNOERRORRECOVERY 1
  127100. /*
  127101. ** Make yytestcase() the same as testcase()
  127102. */
  127103. #define yytestcase(X) testcase(X)
  127104. /*
  127105. ** Indicate that sqlite3ParserFree() will never be called with a null
  127106. ** pointer.
  127107. */
  127108. #define YYPARSEFREENEVERNULL 1
  127109. /*
  127110. ** In the amalgamation, the parse.c file generated by lemon and the
  127111. ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
  127112. ** has access to the the size of the yyParser object and so the parser
  127113. ** engine can be allocated from stack. In that case, only the
  127114. ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
  127115. ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
  127116. ** omitted.
  127117. */
  127118. #ifdef SQLITE_AMALGAMATION
  127119. # define sqlite3Parser_ENGINEALWAYSONSTACK 1
  127120. #endif
  127121. /*
  127122. ** Alternative datatype for the argument to the malloc() routine passed
  127123. ** into sqlite3ParserAlloc(). The default is size_t.
  127124. */
  127125. #define YYMALLOCARGTYPE u64
  127126. /*
  127127. ** An instance of this structure holds information about the
  127128. ** LIMIT clause of a SELECT statement.
  127129. */
  127130. struct LimitVal {
  127131. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  127132. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  127133. };
  127134. /*
  127135. ** An instance of the following structure describes the event of a
  127136. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  127137. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  127138. **
  127139. ** UPDATE ON (a,b,c)
  127140. **
  127141. ** Then the "b" IdList records the list "a,b,c".
  127142. */
  127143. struct TrigEvent { int a; IdList * b; };
  127144. /*
  127145. ** Disable lookaside memory allocation for objects that might be
  127146. ** shared across database connections.
  127147. */
  127148. static void disableLookaside(Parse *pParse){
  127149. pParse->disableLookaside++;
  127150. pParse->db->lookaside.bDisable++;
  127151. }
  127152. /*
  127153. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  127154. ** all elements in the list. And make sure list length does not exceed
  127155. ** SQLITE_LIMIT_COMPOUND_SELECT.
  127156. */
  127157. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  127158. if( p->pPrior ){
  127159. Select *pNext = 0, *pLoop;
  127160. int mxSelect, cnt = 0;
  127161. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  127162. pLoop->pNext = pNext;
  127163. pLoop->selFlags |= SF_Compound;
  127164. }
  127165. if( (p->selFlags & SF_MultiValue)==0 &&
  127166. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  127167. cnt>mxSelect
  127168. ){
  127169. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  127170. }
  127171. }
  127172. }
  127173. /* This is a utility routine used to set the ExprSpan.zStart and
  127174. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  127175. ** range of text beginning with pStart and going to the end of pEnd.
  127176. */
  127177. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  127178. pOut->zStart = pStart->z;
  127179. pOut->zEnd = &pEnd->z[pEnd->n];
  127180. }
  127181. /* Construct a new Expr object from a single identifier. Use the
  127182. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  127183. ** that created the expression.
  127184. */
  127185. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
  127186. Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
  127187. if( p ){
  127188. memset(p, 0, sizeof(Expr));
  127189. p->op = (u8)op;
  127190. p->flags = EP_Leaf;
  127191. p->iAgg = -1;
  127192. p->u.zToken = (char*)&p[1];
  127193. memcpy(p->u.zToken, t.z, t.n);
  127194. p->u.zToken[t.n] = 0;
  127195. if( sqlite3Isquote(p->u.zToken[0]) ){
  127196. if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
  127197. sqlite3Dequote(p->u.zToken);
  127198. }
  127199. #if SQLITE_MAX_EXPR_DEPTH>0
  127200. p->nHeight = 1;
  127201. #endif
  127202. }
  127203. pOut->pExpr = p;
  127204. pOut->zStart = t.z;
  127205. pOut->zEnd = &t.z[t.n];
  127206. }
  127207. /* This routine constructs a binary expression node out of two ExprSpan
  127208. ** objects and uses the result to populate a new ExprSpan object.
  127209. */
  127210. static void spanBinaryExpr(
  127211. Parse *pParse, /* The parsing context. Errors accumulate here */
  127212. int op, /* The binary operation */
  127213. ExprSpan *pLeft, /* The left operand, and output */
  127214. ExprSpan *pRight /* The right operand */
  127215. ){
  127216. pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr);
  127217. pLeft->zEnd = pRight->zEnd;
  127218. }
  127219. /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
  127220. ** outside of *ppExpr.
  127221. */
  127222. static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
  127223. if( doNot ){
  127224. pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0);
  127225. }
  127226. }
  127227. /* Construct an expression node for a unary postfix operator
  127228. */
  127229. static void spanUnaryPostfix(
  127230. Parse *pParse, /* Parsing context to record errors */
  127231. int op, /* The operator */
  127232. ExprSpan *pOperand, /* The operand, and output */
  127233. Token *pPostOp /* The operand token for setting the span */
  127234. ){
  127235. pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
  127236. pOperand->zEnd = &pPostOp->z[pPostOp->n];
  127237. }
  127238. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  127239. ** unary TK_ISNULL or TK_NOTNULL expression. */
  127240. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  127241. sqlite3 *db = pParse->db;
  127242. if( pA && pY && pY->op==TK_NULL ){
  127243. pA->op = (u8)op;
  127244. sqlite3ExprDelete(db, pA->pRight);
  127245. pA->pRight = 0;
  127246. }
  127247. }
  127248. /* Construct an expression node for a unary prefix operator
  127249. */
  127250. static void spanUnaryPrefix(
  127251. ExprSpan *pOut, /* Write the new expression node here */
  127252. Parse *pParse, /* Parsing context to record errors */
  127253. int op, /* The operator */
  127254. ExprSpan *pOperand, /* The operand */
  127255. Token *pPreOp /* The operand token for setting the span */
  127256. ){
  127257. pOut->zStart = pPreOp->z;
  127258. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
  127259. pOut->zEnd = pOperand->zEnd;
  127260. }
  127261. /* Add a single new term to an ExprList that is used to store a
  127262. ** list of identifiers. Report an error if the ID list contains
  127263. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  127264. ** error while parsing a legacy schema.
  127265. */
  127266. static ExprList *parserAddExprIdListTerm(
  127267. Parse *pParse,
  127268. ExprList *pPrior,
  127269. Token *pIdToken,
  127270. int hasCollate,
  127271. int sortOrder
  127272. ){
  127273. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  127274. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  127275. && pParse->db->init.busy==0
  127276. ){
  127277. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  127278. pIdToken->n, pIdToken->z);
  127279. }
  127280. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  127281. return p;
  127282. }
  127283. /**************** End of %include directives **********************************/
  127284. /* These constants specify the various numeric values for terminal symbols
  127285. ** in a format understandable to "makeheaders". This section is blank unless
  127286. ** "lemon" is run with the "-m" command-line option.
  127287. ***************** Begin makeheaders token definitions *************************/
  127288. /**************** End makeheaders token definitions ***************************/
  127289. /* The next sections is a series of control #defines.
  127290. ** various aspects of the generated parser.
  127291. ** YYCODETYPE is the data type used to store the integer codes
  127292. ** that represent terminal and non-terminal symbols.
  127293. ** "unsigned char" is used if there are fewer than
  127294. ** 256 symbols. Larger types otherwise.
  127295. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  127296. ** any terminal or nonterminal symbol.
  127297. ** YYFALLBACK If defined, this indicates that one or more tokens
  127298. ** (also known as: "terminal symbols") have fall-back
  127299. ** values which should be used if the original symbol
  127300. ** would not parse. This permits keywords to sometimes
  127301. ** be used as identifiers, for example.
  127302. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  127303. ** that indicate what to do in response to the next
  127304. ** token.
  127305. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  127306. ** symbols. Background: A "minor type" is a semantic
  127307. ** value associated with a terminal or non-terminal
  127308. ** symbols. For example, for an "ID" terminal symbol,
  127309. ** the minor type might be the name of the identifier.
  127310. ** Each non-terminal can have a different minor type.
  127311. ** Terminal symbols all have the same minor type, though.
  127312. ** This macros defines the minor type for terminal
  127313. ** symbols.
  127314. ** YYMINORTYPE is the data type used for all minor types.
  127315. ** This is typically a union of many types, one of
  127316. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  127317. ** for terminal symbols is called "yy0".
  127318. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  127319. ** zero the stack is dynamically sized using realloc()
  127320. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  127321. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  127322. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  127323. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  127324. ** YYERRORSYMBOL is the code number of the error symbol. If not
  127325. ** defined, then do no error processing.
  127326. ** YYNSTATE the combined number of states.
  127327. ** YYNRULE the number of rules in the grammar
  127328. ** YY_MAX_SHIFT Maximum value for shift actions
  127329. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  127330. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  127331. ** YY_MIN_REDUCE Maximum value for reduce actions
  127332. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  127333. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  127334. ** YY_NO_ACTION The yy_action[] code for no-op
  127335. */
  127336. #ifndef INTERFACE
  127337. # define INTERFACE 1
  127338. #endif
  127339. /************* Begin control #defines *****************************************/
  127340. #define YYCODETYPE unsigned char
  127341. #define YYNOCODE 252
  127342. #define YYACTIONTYPE unsigned short int
  127343. #define YYWILDCARD 69
  127344. #define sqlite3ParserTOKENTYPE Token
  127345. typedef union {
  127346. int yyinit;
  127347. sqlite3ParserTOKENTYPE yy0;
  127348. Expr* yy72;
  127349. TriggerStep* yy145;
  127350. ExprList* yy148;
  127351. SrcList* yy185;
  127352. ExprSpan yy190;
  127353. int yy194;
  127354. Select* yy243;
  127355. IdList* yy254;
  127356. With* yy285;
  127357. struct TrigEvent yy332;
  127358. struct LimitVal yy354;
  127359. struct {int value; int mask;} yy497;
  127360. } YYMINORTYPE;
  127361. #ifndef YYSTACKDEPTH
  127362. #define YYSTACKDEPTH 100
  127363. #endif
  127364. #define sqlite3ParserARG_SDECL Parse *pParse;
  127365. #define sqlite3ParserARG_PDECL ,Parse *pParse
  127366. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  127367. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  127368. #define YYFALLBACK 1
  127369. #define YYNSTATE 456
  127370. #define YYNRULE 332
  127371. #define YY_MAX_SHIFT 455
  127372. #define YY_MIN_SHIFTREDUCE 668
  127373. #define YY_MAX_SHIFTREDUCE 999
  127374. #define YY_MIN_REDUCE 1000
  127375. #define YY_MAX_REDUCE 1331
  127376. #define YY_ERROR_ACTION 1332
  127377. #define YY_ACCEPT_ACTION 1333
  127378. #define YY_NO_ACTION 1334
  127379. /************* End control #defines *******************************************/
  127380. /* Define the yytestcase() macro to be a no-op if is not already defined
  127381. ** otherwise.
  127382. **
  127383. ** Applications can choose to define yytestcase() in the %include section
  127384. ** to a macro that can assist in verifying code coverage. For production
  127385. ** code the yytestcase() macro should be turned off. But it is useful
  127386. ** for testing.
  127387. */
  127388. #ifndef yytestcase
  127389. # define yytestcase(X)
  127390. #endif
  127391. /* Next are the tables used to determine what action to take based on the
  127392. ** current state and lookahead token. These tables are used to implement
  127393. ** functions that take a state number and lookahead value and return an
  127394. ** action integer.
  127395. **
  127396. ** Suppose the action integer is N. Then the action is determined as
  127397. ** follows
  127398. **
  127399. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  127400. ** token onto the stack and goto state N.
  127401. **
  127402. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  127403. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  127404. **
  127405. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  127406. ** and YY_MAX_REDUCE
  127407. **
  127408. ** N == YY_ERROR_ACTION A syntax error has occurred.
  127409. **
  127410. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  127411. **
  127412. ** N == YY_NO_ACTION No such action. Denotes unused
  127413. ** slots in the yy_action[] table.
  127414. **
  127415. ** The action table is constructed as a single large table named yy_action[].
  127416. ** Given state S and lookahead X, the action is computed as either:
  127417. **
  127418. ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
  127419. ** (B) N = yy_default[S]
  127420. **
  127421. ** The (A) formula is preferred. The B formula is used instead if:
  127422. ** (1) The yy_shift_ofst[S]+X value is out of range, or
  127423. ** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
  127424. ** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
  127425. ** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
  127426. ** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
  127427. ** Hence only tests (1) and (2) need to be evaluated.)
  127428. **
  127429. ** The formulas above are for computing the action when the lookahead is
  127430. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  127431. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  127432. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  127433. ** YY_SHIFT_USE_DFLT.
  127434. **
  127435. ** The following are the tables generated in this section:
  127436. **
  127437. ** yy_action[] A single table containing all actions.
  127438. ** yy_lookahead[] A table containing the lookahead for each entry in
  127439. ** yy_action. Used to detect hash collisions.
  127440. ** yy_shift_ofst[] For each state, the offset into yy_action for
  127441. ** shifting terminals.
  127442. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  127443. ** shifting non-terminals after a reduce.
  127444. ** yy_default[] Default action for each state.
  127445. **
  127446. *********** Begin parsing tables **********************************************/
  127447. #define YY_ACTTAB_COUNT (1566)
  127448. static const YYACTIONTYPE yy_action[] = {
  127449. /* 0 */ 325, 411, 343, 752, 752, 203, 946, 354, 976, 98,
  127450. /* 10 */ 98, 98, 98, 91, 96, 96, 96, 96, 95, 95,
  127451. /* 20 */ 94, 94, 94, 93, 351, 1333, 155, 155, 2, 813,
  127452. /* 30 */ 978, 978, 98, 98, 98, 98, 20, 96, 96, 96,
  127453. /* 40 */ 96, 95, 95, 94, 94, 94, 93, 351, 92, 89,
  127454. /* 50 */ 178, 99, 100, 90, 853, 856, 845, 845, 97, 97,
  127455. /* 60 */ 98, 98, 98, 98, 351, 96, 96, 96, 96, 95,
  127456. /* 70 */ 95, 94, 94, 94, 93, 351, 325, 340, 976, 262,
  127457. /* 80 */ 365, 251, 212, 169, 287, 405, 282, 404, 199, 791,
  127458. /* 90 */ 242, 412, 21, 957, 379, 280, 93, 351, 792, 95,
  127459. /* 100 */ 95, 94, 94, 94, 93, 351, 978, 978, 96, 96,
  127460. /* 110 */ 96, 96, 95, 95, 94, 94, 94, 93, 351, 813,
  127461. /* 120 */ 329, 242, 412, 913, 832, 913, 132, 99, 100, 90,
  127462. /* 130 */ 853, 856, 845, 845, 97, 97, 98, 98, 98, 98,
  127463. /* 140 */ 450, 96, 96, 96, 96, 95, 95, 94, 94, 94,
  127464. /* 150 */ 93, 351, 325, 825, 349, 348, 120, 819, 120, 75,
  127465. /* 160 */ 52, 52, 957, 958, 959, 760, 984, 146, 361, 262,
  127466. /* 170 */ 370, 261, 957, 982, 961, 983, 92, 89, 178, 371,
  127467. /* 180 */ 230, 371, 978, 978, 817, 361, 360, 101, 824, 824,
  127468. /* 190 */ 826, 384, 24, 964, 381, 428, 413, 369, 985, 380,
  127469. /* 200 */ 985, 708, 325, 99, 100, 90, 853, 856, 845, 845,
  127470. /* 210 */ 97, 97, 98, 98, 98, 98, 373, 96, 96, 96,
  127471. /* 220 */ 96, 95, 95, 94, 94, 94, 93, 351, 957, 132,
  127472. /* 230 */ 897, 450, 978, 978, 896, 60, 94, 94, 94, 93,
  127473. /* 240 */ 351, 957, 958, 959, 961, 103, 361, 957, 385, 334,
  127474. /* 250 */ 702, 52, 52, 99, 100, 90, 853, 856, 845, 845,
  127475. /* 260 */ 97, 97, 98, 98, 98, 98, 698, 96, 96, 96,
  127476. /* 270 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 455,
  127477. /* 280 */ 670, 450, 227, 61, 157, 243, 344, 114, 701, 888,
  127478. /* 290 */ 147, 832, 957, 373, 747, 957, 320, 957, 958, 959,
  127479. /* 300 */ 194, 10, 10, 402, 399, 398, 888, 890, 978, 978,
  127480. /* 310 */ 762, 171, 170, 157, 397, 337, 957, 958, 959, 702,
  127481. /* 320 */ 825, 310, 153, 957, 819, 321, 82, 23, 80, 99,
  127482. /* 330 */ 100, 90, 853, 856, 845, 845, 97, 97, 98, 98,
  127483. /* 340 */ 98, 98, 894, 96, 96, 96, 96, 95, 95, 94,
  127484. /* 350 */ 94, 94, 93, 351, 325, 824, 824, 826, 277, 231,
  127485. /* 360 */ 300, 957, 958, 959, 957, 958, 959, 888, 194, 25,
  127486. /* 370 */ 450, 402, 399, 398, 957, 355, 300, 450, 957, 74,
  127487. /* 380 */ 450, 1, 397, 132, 978, 978, 957, 224, 224, 813,
  127488. /* 390 */ 10, 10, 957, 958, 959, 968, 132, 52, 52, 415,
  127489. /* 400 */ 52, 52, 739, 739, 339, 99, 100, 90, 853, 856,
  127490. /* 410 */ 845, 845, 97, 97, 98, 98, 98, 98, 790, 96,
  127491. /* 420 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351,
  127492. /* 430 */ 325, 789, 428, 418, 706, 428, 427, 1270, 1270, 262,
  127493. /* 440 */ 370, 261, 957, 957, 958, 959, 757, 957, 958, 959,
  127494. /* 450 */ 450, 756, 450, 734, 713, 957, 958, 959, 443, 711,
  127495. /* 460 */ 978, 978, 734, 394, 92, 89, 178, 447, 447, 447,
  127496. /* 470 */ 51, 51, 52, 52, 439, 778, 700, 92, 89, 178,
  127497. /* 480 */ 172, 99, 100, 90, 853, 856, 845, 845, 97, 97,
  127498. /* 490 */ 98, 98, 98, 98, 198, 96, 96, 96, 96, 95,
  127499. /* 500 */ 95, 94, 94, 94, 93, 351, 325, 428, 408, 916,
  127500. /* 510 */ 699, 957, 958, 959, 92, 89, 178, 224, 224, 157,
  127501. /* 520 */ 241, 221, 419, 299, 776, 917, 416, 375, 450, 415,
  127502. /* 530 */ 58, 324, 737, 737, 920, 379, 978, 978, 379, 777,
  127503. /* 540 */ 449, 918, 363, 740, 296, 686, 9, 9, 52, 52,
  127504. /* 550 */ 234, 330, 234, 256, 417, 741, 280, 99, 100, 90,
  127505. /* 560 */ 853, 856, 845, 845, 97, 97, 98, 98, 98, 98,
  127506. /* 570 */ 450, 96, 96, 96, 96, 95, 95, 94, 94, 94,
  127507. /* 580 */ 93, 351, 325, 423, 72, 450, 833, 120, 368, 450,
  127508. /* 590 */ 10, 10, 5, 301, 203, 450, 177, 976, 253, 420,
  127509. /* 600 */ 255, 776, 200, 175, 233, 10, 10, 842, 842, 36,
  127510. /* 610 */ 36, 1299, 978, 978, 729, 37, 37, 349, 348, 425,
  127511. /* 620 */ 203, 260, 776, 976, 232, 937, 1326, 876, 338, 1326,
  127512. /* 630 */ 422, 854, 857, 99, 100, 90, 853, 856, 845, 845,
  127513. /* 640 */ 97, 97, 98, 98, 98, 98, 268, 96, 96, 96,
  127514. /* 650 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 846,
  127515. /* 660 */ 450, 985, 818, 985, 1209, 450, 916, 976, 720, 350,
  127516. /* 670 */ 350, 350, 935, 177, 450, 937, 1327, 254, 198, 1327,
  127517. /* 680 */ 12, 12, 917, 403, 450, 27, 27, 250, 978, 978,
  127518. /* 690 */ 118, 721, 162, 976, 38, 38, 268, 176, 918, 776,
  127519. /* 700 */ 433, 1275, 946, 354, 39, 39, 317, 998, 325, 99,
  127520. /* 710 */ 100, 90, 853, 856, 845, 845, 97, 97, 98, 98,
  127521. /* 720 */ 98, 98, 935, 96, 96, 96, 96, 95, 95, 94,
  127522. /* 730 */ 94, 94, 93, 351, 450, 330, 450, 358, 978, 978,
  127523. /* 740 */ 717, 317, 936, 341, 900, 900, 387, 673, 674, 675,
  127524. /* 750 */ 275, 996, 318, 999, 40, 40, 41, 41, 268, 99,
  127525. /* 760 */ 100, 90, 853, 856, 845, 845, 97, 97, 98, 98,
  127526. /* 770 */ 98, 98, 450, 96, 96, 96, 96, 95, 95, 94,
  127527. /* 780 */ 94, 94, 93, 351, 325, 450, 356, 450, 999, 450,
  127528. /* 790 */ 692, 331, 42, 42, 791, 270, 450, 273, 450, 228,
  127529. /* 800 */ 450, 298, 450, 792, 450, 28, 28, 29, 29, 31,
  127530. /* 810 */ 31, 450, 817, 450, 978, 978, 43, 43, 44, 44,
  127531. /* 820 */ 45, 45, 11, 11, 46, 46, 893, 78, 893, 268,
  127532. /* 830 */ 268, 105, 105, 47, 47, 99, 100, 90, 853, 856,
  127533. /* 840 */ 845, 845, 97, 97, 98, 98, 98, 98, 450, 96,
  127534. /* 850 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351,
  127535. /* 860 */ 325, 450, 117, 450, 749, 158, 450, 696, 48, 48,
  127536. /* 870 */ 229, 919, 450, 928, 450, 415, 450, 335, 450, 245,
  127537. /* 880 */ 450, 33, 33, 49, 49, 450, 50, 50, 246, 817,
  127538. /* 890 */ 978, 978, 34, 34, 122, 122, 123, 123, 124, 124,
  127539. /* 900 */ 56, 56, 268, 81, 249, 35, 35, 197, 196, 195,
  127540. /* 910 */ 325, 99, 100, 90, 853, 856, 845, 845, 97, 97,
  127541. /* 920 */ 98, 98, 98, 98, 450, 96, 96, 96, 96, 95,
  127542. /* 930 */ 95, 94, 94, 94, 93, 351, 450, 696, 450, 817,
  127543. /* 940 */ 978, 978, 975, 884, 106, 106, 268, 886, 268, 944,
  127544. /* 950 */ 2, 892, 268, 892, 336, 716, 53, 53, 107, 107,
  127545. /* 960 */ 325, 99, 100, 90, 853, 856, 845, 845, 97, 97,
  127546. /* 970 */ 98, 98, 98, 98, 450, 96, 96, 96, 96, 95,
  127547. /* 980 */ 95, 94, 94, 94, 93, 351, 450, 746, 450, 742,
  127548. /* 990 */ 978, 978, 715, 267, 108, 108, 446, 331, 332, 133,
  127549. /* 1000 */ 223, 175, 301, 225, 386, 933, 104, 104, 121, 121,
  127550. /* 1010 */ 325, 99, 88, 90, 853, 856, 845, 845, 97, 97,
  127551. /* 1020 */ 98, 98, 98, 98, 817, 96, 96, 96, 96, 95,
  127552. /* 1030 */ 95, 94, 94, 94, 93, 351, 450, 347, 450, 167,
  127553. /* 1040 */ 978, 978, 932, 815, 372, 319, 202, 202, 374, 263,
  127554. /* 1050 */ 395, 202, 74, 208, 726, 727, 119, 119, 112, 112,
  127555. /* 1060 */ 325, 407, 100, 90, 853, 856, 845, 845, 97, 97,
  127556. /* 1070 */ 98, 98, 98, 98, 450, 96, 96, 96, 96, 95,
  127557. /* 1080 */ 95, 94, 94, 94, 93, 351, 450, 757, 450, 345,
  127558. /* 1090 */ 978, 978, 756, 278, 111, 111, 74, 719, 718, 709,
  127559. /* 1100 */ 286, 883, 754, 1289, 257, 77, 109, 109, 110, 110,
  127560. /* 1110 */ 908, 285, 810, 90, 853, 856, 845, 845, 97, 97,
  127561. /* 1120 */ 98, 98, 98, 98, 911, 96, 96, 96, 96, 95,
  127562. /* 1130 */ 95, 94, 94, 94, 93, 351, 86, 445, 450, 3,
  127563. /* 1140 */ 1202, 450, 745, 132, 352, 120, 689, 86, 445, 785,
  127564. /* 1150 */ 3, 767, 202, 377, 448, 352, 907, 120, 55, 55,
  127565. /* 1160 */ 450, 57, 57, 828, 879, 448, 450, 208, 450, 709,
  127566. /* 1170 */ 450, 883, 237, 434, 436, 120, 440, 429, 362, 120,
  127567. /* 1180 */ 54, 54, 132, 450, 434, 832, 52, 52, 26, 26,
  127568. /* 1190 */ 30, 30, 382, 132, 409, 444, 832, 694, 264, 390,
  127569. /* 1200 */ 116, 269, 272, 32, 32, 83, 84, 120, 274, 120,
  127570. /* 1210 */ 120, 276, 85, 352, 452, 451, 83, 84, 819, 730,
  127571. /* 1220 */ 714, 428, 430, 85, 352, 452, 451, 120, 120, 819,
  127572. /* 1230 */ 378, 218, 281, 828, 783, 816, 86, 445, 410, 3,
  127573. /* 1240 */ 763, 774, 431, 432, 352, 302, 303, 823, 697, 824,
  127574. /* 1250 */ 824, 826, 827, 19, 448, 691, 680, 679, 681, 951,
  127575. /* 1260 */ 824, 824, 826, 827, 19, 289, 159, 291, 293, 7,
  127576. /* 1270 */ 316, 173, 259, 434, 805, 364, 252, 910, 376, 713,
  127577. /* 1280 */ 295, 435, 168, 993, 400, 832, 284, 881, 880, 205,
  127578. /* 1290 */ 954, 308, 927, 86, 445, 990, 3, 925, 333, 144,
  127579. /* 1300 */ 130, 352, 72, 135, 59, 83, 84, 761, 137, 366,
  127580. /* 1310 */ 802, 448, 85, 352, 452, 451, 139, 226, 819, 140,
  127581. /* 1320 */ 156, 62, 315, 314, 313, 215, 311, 367, 393, 683,
  127582. /* 1330 */ 434, 185, 141, 912, 142, 160, 148, 812, 875, 383,
  127583. /* 1340 */ 189, 67, 832, 180, 389, 248, 895, 775, 219, 824,
  127584. /* 1350 */ 824, 826, 827, 19, 247, 190, 266, 154, 391, 271,
  127585. /* 1360 */ 191, 192, 83, 84, 682, 406, 733, 182, 322, 85,
  127586. /* 1370 */ 352, 452, 451, 732, 183, 819, 342, 132, 181, 711,
  127587. /* 1380 */ 731, 421, 76, 445, 705, 3, 323, 704, 283, 724,
  127588. /* 1390 */ 352, 771, 703, 966, 723, 71, 204, 6, 288, 290,
  127589. /* 1400 */ 448, 772, 770, 769, 79, 292, 824, 824, 826, 827,
  127590. /* 1410 */ 19, 294, 297, 438, 346, 442, 102, 861, 753, 434,
  127591. /* 1420 */ 238, 426, 73, 305, 239, 304, 326, 240, 424, 306,
  127592. /* 1430 */ 307, 832, 213, 688, 22, 952, 453, 214, 216, 217,
  127593. /* 1440 */ 454, 677, 115, 676, 671, 125, 126, 235, 127, 669,
  127594. /* 1450 */ 327, 83, 84, 359, 353, 244, 166, 328, 85, 352,
  127595. /* 1460 */ 452, 451, 134, 179, 819, 357, 113, 891, 811, 889,
  127596. /* 1470 */ 136, 128, 138, 743, 258, 184, 906, 143, 145, 63,
  127597. /* 1480 */ 64, 65, 66, 129, 909, 905, 187, 186, 8, 13,
  127598. /* 1490 */ 188, 265, 898, 149, 202, 824, 824, 826, 827, 19,
  127599. /* 1500 */ 388, 987, 150, 161, 285, 685, 392, 396, 151, 722,
  127600. /* 1510 */ 193, 68, 14, 401, 279, 15, 69, 236, 831, 830,
  127601. /* 1520 */ 131, 859, 751, 70, 16, 414, 755, 4, 784, 220,
  127602. /* 1530 */ 222, 174, 152, 437, 779, 201, 17, 77, 74, 18,
  127603. /* 1540 */ 874, 860, 858, 915, 863, 914, 207, 206, 941, 163,
  127604. /* 1550 */ 210, 942, 209, 164, 441, 862, 165, 211, 829, 695,
  127605. /* 1560 */ 87, 312, 309, 947, 1291, 1290,
  127606. };
  127607. static const YYCODETYPE yy_lookahead[] = {
  127608. /* 0 */ 19, 115, 19, 117, 118, 24, 1, 2, 27, 79,
  127609. /* 10 */ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
  127610. /* 20 */ 90, 91, 92, 93, 94, 144, 145, 146, 147, 58,
  127611. /* 30 */ 49, 50, 79, 80, 81, 82, 22, 84, 85, 86,
  127612. /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 221, 222,
  127613. /* 50 */ 223, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127614. /* 60 */ 79, 80, 81, 82, 94, 84, 85, 86, 87, 88,
  127615. /* 70 */ 89, 90, 91, 92, 93, 94, 19, 94, 97, 108,
  127616. /* 80 */ 109, 110, 99, 100, 101, 102, 103, 104, 105, 32,
  127617. /* 90 */ 119, 120, 78, 27, 152, 112, 93, 94, 41, 88,
  127618. /* 100 */ 89, 90, 91, 92, 93, 94, 49, 50, 84, 85,
  127619. /* 110 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 58,
  127620. /* 120 */ 157, 119, 120, 163, 68, 163, 65, 70, 71, 72,
  127621. /* 130 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  127622. /* 140 */ 152, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  127623. /* 150 */ 93, 94, 19, 97, 88, 89, 196, 101, 196, 26,
  127624. /* 160 */ 172, 173, 96, 97, 98, 210, 100, 22, 152, 108,
  127625. /* 170 */ 109, 110, 27, 107, 27, 109, 221, 222, 223, 219,
  127626. /* 180 */ 238, 219, 49, 50, 152, 169, 170, 54, 132, 133,
  127627. /* 190 */ 134, 228, 232, 171, 231, 207, 208, 237, 132, 237,
  127628. /* 200 */ 134, 179, 19, 70, 71, 72, 73, 74, 75, 76,
  127629. /* 210 */ 77, 78, 79, 80, 81, 82, 152, 84, 85, 86,
  127630. /* 220 */ 87, 88, 89, 90, 91, 92, 93, 94, 27, 65,
  127631. /* 230 */ 30, 152, 49, 50, 34, 52, 90, 91, 92, 93,
  127632. /* 240 */ 94, 96, 97, 98, 97, 22, 230, 27, 48, 217,
  127633. /* 250 */ 27, 172, 173, 70, 71, 72, 73, 74, 75, 76,
  127634. /* 260 */ 77, 78, 79, 80, 81, 82, 172, 84, 85, 86,
  127635. /* 270 */ 87, 88, 89, 90, 91, 92, 93, 94, 19, 148,
  127636. /* 280 */ 149, 152, 218, 24, 152, 154, 207, 156, 172, 152,
  127637. /* 290 */ 22, 68, 27, 152, 163, 27, 164, 96, 97, 98,
  127638. /* 300 */ 99, 172, 173, 102, 103, 104, 169, 170, 49, 50,
  127639. /* 310 */ 90, 88, 89, 152, 113, 186, 96, 97, 98, 96,
  127640. /* 320 */ 97, 160, 57, 27, 101, 164, 137, 196, 139, 70,
  127641. /* 330 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  127642. /* 340 */ 81, 82, 11, 84, 85, 86, 87, 88, 89, 90,
  127643. /* 350 */ 91, 92, 93, 94, 19, 132, 133, 134, 23, 218,
  127644. /* 360 */ 152, 96, 97, 98, 96, 97, 98, 230, 99, 22,
  127645. /* 370 */ 152, 102, 103, 104, 27, 244, 152, 152, 27, 26,
  127646. /* 380 */ 152, 22, 113, 65, 49, 50, 27, 194, 195, 58,
  127647. /* 390 */ 172, 173, 96, 97, 98, 185, 65, 172, 173, 206,
  127648. /* 400 */ 172, 173, 190, 191, 186, 70, 71, 72, 73, 74,
  127649. /* 410 */ 75, 76, 77, 78, 79, 80, 81, 82, 175, 84,
  127650. /* 420 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  127651. /* 430 */ 19, 175, 207, 208, 23, 207, 208, 119, 120, 108,
  127652. /* 440 */ 109, 110, 27, 96, 97, 98, 116, 96, 97, 98,
  127653. /* 450 */ 152, 121, 152, 179, 180, 96, 97, 98, 250, 106,
  127654. /* 460 */ 49, 50, 188, 19, 221, 222, 223, 168, 169, 170,
  127655. /* 470 */ 172, 173, 172, 173, 250, 124, 172, 221, 222, 223,
  127656. /* 480 */ 26, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127657. /* 490 */ 79, 80, 81, 82, 50, 84, 85, 86, 87, 88,
  127658. /* 500 */ 89, 90, 91, 92, 93, 94, 19, 207, 208, 12,
  127659. /* 510 */ 23, 96, 97, 98, 221, 222, 223, 194, 195, 152,
  127660. /* 520 */ 199, 23, 19, 225, 26, 28, 152, 152, 152, 206,
  127661. /* 530 */ 209, 164, 190, 191, 241, 152, 49, 50, 152, 124,
  127662. /* 540 */ 152, 44, 219, 46, 152, 21, 172, 173, 172, 173,
  127663. /* 550 */ 183, 107, 185, 16, 163, 58, 112, 70, 71, 72,
  127664. /* 560 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  127665. /* 570 */ 152, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  127666. /* 580 */ 93, 94, 19, 207, 130, 152, 23, 196, 64, 152,
  127667. /* 590 */ 172, 173, 22, 152, 24, 152, 98, 27, 61, 96,
  127668. /* 600 */ 63, 26, 211, 212, 186, 172, 173, 49, 50, 172,
  127669. /* 610 */ 173, 23, 49, 50, 26, 172, 173, 88, 89, 186,
  127670. /* 620 */ 24, 238, 124, 27, 238, 22, 23, 103, 187, 26,
  127671. /* 630 */ 152, 73, 74, 70, 71, 72, 73, 74, 75, 76,
  127672. /* 640 */ 77, 78, 79, 80, 81, 82, 152, 84, 85, 86,
  127673. /* 650 */ 87, 88, 89, 90, 91, 92, 93, 94, 19, 101,
  127674. /* 660 */ 152, 132, 23, 134, 140, 152, 12, 97, 36, 168,
  127675. /* 670 */ 169, 170, 69, 98, 152, 22, 23, 140, 50, 26,
  127676. /* 680 */ 172, 173, 28, 51, 152, 172, 173, 193, 49, 50,
  127677. /* 690 */ 22, 59, 24, 97, 172, 173, 152, 152, 44, 124,
  127678. /* 700 */ 46, 0, 1, 2, 172, 173, 22, 23, 19, 70,
  127679. /* 710 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  127680. /* 720 */ 81, 82, 69, 84, 85, 86, 87, 88, 89, 90,
  127681. /* 730 */ 91, 92, 93, 94, 152, 107, 152, 193, 49, 50,
  127682. /* 740 */ 181, 22, 23, 111, 108, 109, 110, 7, 8, 9,
  127683. /* 750 */ 16, 247, 248, 69, 172, 173, 172, 173, 152, 70,
  127684. /* 760 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  127685. /* 770 */ 81, 82, 152, 84, 85, 86, 87, 88, 89, 90,
  127686. /* 780 */ 91, 92, 93, 94, 19, 152, 242, 152, 69, 152,
  127687. /* 790 */ 166, 167, 172, 173, 32, 61, 152, 63, 152, 193,
  127688. /* 800 */ 152, 152, 152, 41, 152, 172, 173, 172, 173, 172,
  127689. /* 810 */ 173, 152, 152, 152, 49, 50, 172, 173, 172, 173,
  127690. /* 820 */ 172, 173, 172, 173, 172, 173, 132, 138, 134, 152,
  127691. /* 830 */ 152, 172, 173, 172, 173, 70, 71, 72, 73, 74,
  127692. /* 840 */ 75, 76, 77, 78, 79, 80, 81, 82, 152, 84,
  127693. /* 850 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  127694. /* 860 */ 19, 152, 22, 152, 195, 24, 152, 27, 172, 173,
  127695. /* 870 */ 193, 193, 152, 152, 152, 206, 152, 217, 152, 152,
  127696. /* 880 */ 152, 172, 173, 172, 173, 152, 172, 173, 152, 152,
  127697. /* 890 */ 49, 50, 172, 173, 172, 173, 172, 173, 172, 173,
  127698. /* 900 */ 172, 173, 152, 138, 152, 172, 173, 108, 109, 110,
  127699. /* 910 */ 19, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127700. /* 920 */ 79, 80, 81, 82, 152, 84, 85, 86, 87, 88,
  127701. /* 930 */ 89, 90, 91, 92, 93, 94, 152, 97, 152, 152,
  127702. /* 940 */ 49, 50, 26, 193, 172, 173, 152, 152, 152, 146,
  127703. /* 950 */ 147, 132, 152, 134, 217, 181, 172, 173, 172, 173,
  127704. /* 960 */ 19, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127705. /* 970 */ 79, 80, 81, 82, 152, 84, 85, 86, 87, 88,
  127706. /* 980 */ 89, 90, 91, 92, 93, 94, 152, 193, 152, 193,
  127707. /* 990 */ 49, 50, 181, 193, 172, 173, 166, 167, 245, 246,
  127708. /* 1000 */ 211, 212, 152, 22, 217, 152, 172, 173, 172, 173,
  127709. /* 1010 */ 19, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127710. /* 1020 */ 79, 80, 81, 82, 152, 84, 85, 86, 87, 88,
  127711. /* 1030 */ 89, 90, 91, 92, 93, 94, 152, 187, 152, 123,
  127712. /* 1040 */ 49, 50, 23, 23, 23, 26, 26, 26, 23, 23,
  127713. /* 1050 */ 23, 26, 26, 26, 7, 8, 172, 173, 172, 173,
  127714. /* 1060 */ 19, 90, 71, 72, 73, 74, 75, 76, 77, 78,
  127715. /* 1070 */ 79, 80, 81, 82, 152, 84, 85, 86, 87, 88,
  127716. /* 1080 */ 89, 90, 91, 92, 93, 94, 152, 116, 152, 217,
  127717. /* 1090 */ 49, 50, 121, 23, 172, 173, 26, 100, 101, 27,
  127718. /* 1100 */ 101, 27, 23, 122, 152, 26, 172, 173, 172, 173,
  127719. /* 1110 */ 152, 112, 163, 72, 73, 74, 75, 76, 77, 78,
  127720. /* 1120 */ 79, 80, 81, 82, 163, 84, 85, 86, 87, 88,
  127721. /* 1130 */ 89, 90, 91, 92, 93, 94, 19, 20, 152, 22,
  127722. /* 1140 */ 23, 152, 163, 65, 27, 196, 163, 19, 20, 23,
  127723. /* 1150 */ 22, 213, 26, 19, 37, 27, 152, 196, 172, 173,
  127724. /* 1160 */ 152, 172, 173, 27, 23, 37, 152, 26, 152, 97,
  127725. /* 1170 */ 152, 97, 210, 56, 163, 196, 163, 163, 100, 196,
  127726. /* 1180 */ 172, 173, 65, 152, 56, 68, 172, 173, 172, 173,
  127727. /* 1190 */ 172, 173, 152, 65, 163, 163, 68, 23, 152, 234,
  127728. /* 1200 */ 26, 152, 152, 172, 173, 88, 89, 196, 152, 196,
  127729. /* 1210 */ 196, 152, 95, 96, 97, 98, 88, 89, 101, 152,
  127730. /* 1220 */ 152, 207, 208, 95, 96, 97, 98, 196, 196, 101,
  127731. /* 1230 */ 96, 233, 152, 97, 152, 152, 19, 20, 207, 22,
  127732. /* 1240 */ 152, 152, 152, 191, 27, 152, 152, 152, 152, 132,
  127733. /* 1250 */ 133, 134, 135, 136, 37, 152, 152, 152, 152, 152,
  127734. /* 1260 */ 132, 133, 134, 135, 136, 210, 197, 210, 210, 198,
  127735. /* 1270 */ 150, 184, 239, 56, 201, 214, 214, 201, 239, 180,
  127736. /* 1280 */ 214, 227, 198, 38, 176, 68, 175, 175, 175, 122,
  127737. /* 1290 */ 155, 200, 159, 19, 20, 40, 22, 159, 159, 22,
  127738. /* 1300 */ 70, 27, 130, 243, 240, 88, 89, 90, 189, 18,
  127739. /* 1310 */ 201, 37, 95, 96, 97, 98, 192, 5, 101, 192,
  127740. /* 1320 */ 220, 240, 10, 11, 12, 13, 14, 159, 18, 17,
  127741. /* 1330 */ 56, 158, 192, 201, 192, 220, 189, 189, 201, 159,
  127742. /* 1340 */ 158, 137, 68, 31, 45, 33, 236, 159, 159, 132,
  127743. /* 1350 */ 133, 134, 135, 136, 42, 158, 235, 22, 177, 159,
  127744. /* 1360 */ 158, 158, 88, 89, 159, 107, 174, 55, 177, 95,
  127745. /* 1370 */ 96, 97, 98, 174, 62, 101, 47, 65, 66, 106,
  127746. /* 1380 */ 174, 125, 19, 20, 174, 22, 177, 176, 174, 182,
  127747. /* 1390 */ 27, 216, 174, 174, 182, 107, 159, 22, 215, 215,
  127748. /* 1400 */ 37, 216, 216, 216, 137, 215, 132, 133, 134, 135,
  127749. /* 1410 */ 136, 215, 159, 177, 94, 177, 129, 224, 205, 56,
  127750. /* 1420 */ 226, 126, 128, 203, 229, 204, 114, 229, 127, 202,
  127751. /* 1430 */ 201, 68, 25, 162, 26, 13, 161, 153, 153, 6,
  127752. /* 1440 */ 151, 151, 178, 151, 151, 165, 165, 178, 165, 4,
  127753. /* 1450 */ 249, 88, 89, 141, 3, 142, 22, 249, 95, 96,
  127754. /* 1460 */ 97, 98, 246, 15, 101, 67, 16, 23, 120, 23,
  127755. /* 1470 */ 131, 111, 123, 20, 16, 125, 1, 123, 131, 78,
  127756. /* 1480 */ 78, 78, 78, 111, 96, 1, 122, 35, 5, 22,
  127757. /* 1490 */ 107, 140, 53, 53, 26, 132, 133, 134, 135, 136,
  127758. /* 1500 */ 43, 60, 107, 24, 112, 20, 19, 52, 22, 29,
  127759. /* 1510 */ 105, 22, 22, 52, 23, 22, 22, 52, 23, 23,
  127760. /* 1520 */ 39, 23, 116, 26, 22, 26, 23, 22, 96, 23,
  127761. /* 1530 */ 23, 122, 22, 24, 124, 35, 35, 26, 26, 35,
  127762. /* 1540 */ 23, 23, 23, 23, 11, 23, 22, 26, 23, 22,
  127763. /* 1550 */ 122, 23, 26, 22, 24, 23, 22, 122, 23, 23,
  127764. /* 1560 */ 22, 15, 23, 1, 122, 122,
  127765. };
  127766. #define YY_SHIFT_USE_DFLT (1566)
  127767. #define YY_SHIFT_COUNT (455)
  127768. #define YY_SHIFT_MIN (-114)
  127769. #define YY_SHIFT_MAX (1562)
  127770. static const short yy_shift_ofst[] = {
  127771. /* 0 */ 5, 1117, 1312, 1128, 1274, 1274, 1274, 1274, 61, -19,
  127772. /* 10 */ 57, 57, 183, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127773. /* 20 */ 66, 66, 201, -29, 331, 318, 133, 259, 335, 411,
  127774. /* 30 */ 487, 563, 639, 689, 765, 841, 891, 891, 891, 891,
  127775. /* 40 */ 891, 891, 891, 891, 891, 891, 891, 891, 891, 891,
  127776. /* 50 */ 891, 891, 891, 941, 891, 991, 1041, 1041, 1217, 1274,
  127777. /* 60 */ 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127778. /* 70 */ 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127779. /* 80 */ 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127780. /* 90 */ 1363, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127781. /* 100 */ 1274, 1274, 1274, 1274, -70, -47, -47, -47, -47, -47,
  127782. /* 110 */ 24, 11, 146, 296, 524, 444, 529, 529, 296, 3,
  127783. /* 120 */ 2, -30, 1566, 1566, 1566, -17, -17, -17, 145, 145,
  127784. /* 130 */ 497, 497, 265, 603, 653, 296, 296, 296, 296, 296,
  127785. /* 140 */ 296, 296, 296, 296, 296, 296, 296, 296, 296, 296,
  127786. /* 150 */ 296, 296, 296, 296, 296, 701, 1078, 147, 147, 2,
  127787. /* 160 */ 164, 164, 164, 164, 164, 164, 1566, 1566, 1566, 223,
  127788. /* 170 */ 56, 56, 268, 269, 220, 347, 351, 415, 359, 296,
  127789. /* 180 */ 296, 296, 296, 296, 296, 296, 296, 296, 296, 296,
  127790. /* 190 */ 296, 296, 296, 296, 296, 632, 632, 632, 296, 296,
  127791. /* 200 */ 498, 296, 296, 296, 570, 296, 296, 654, 296, 296,
  127792. /* 210 */ 296, 296, 296, 296, 296, 296, 296, 296, 636, 200,
  127793. /* 220 */ 596, 596, 596, 575, -114, 971, 740, 454, 503, 503,
  127794. /* 230 */ 1134, 454, 1134, 353, 588, 628, 762, 503, 189, 762,
  127795. /* 240 */ 762, 916, 330, 668, 1245, 1167, 1167, 1255, 1255, 1167,
  127796. /* 250 */ 1277, 1230, 1172, 1291, 1291, 1291, 1291, 1167, 1310, 1172,
  127797. /* 260 */ 1277, 1230, 1230, 1172, 1167, 1310, 1204, 1299, 1167, 1167,
  127798. /* 270 */ 1310, 1335, 1167, 1310, 1167, 1310, 1335, 1258, 1258, 1258,
  127799. /* 280 */ 1329, 1335, 1258, 1273, 1258, 1329, 1258, 1258, 1256, 1288,
  127800. /* 290 */ 1256, 1288, 1256, 1288, 1256, 1288, 1167, 1375, 1167, 1267,
  127801. /* 300 */ 1335, 1320, 1320, 1335, 1287, 1295, 1294, 1301, 1172, 1407,
  127802. /* 310 */ 1408, 1422, 1422, 1433, 1433, 1433, 1433, 1566, 1566, 1566,
  127803. /* 320 */ 1566, 1566, 1566, 1566, 1566, 558, 537, 684, 719, 734,
  127804. /* 330 */ 799, 840, 1019, 14, 1020, 1021, 1025, 1026, 1027, 1070,
  127805. /* 340 */ 1072, 997, 1047, 999, 1079, 1126, 1074, 1141, 694, 819,
  127806. /* 350 */ 1174, 1136, 981, 1445, 1451, 1434, 1313, 1448, 1398, 1450,
  127807. /* 360 */ 1444, 1446, 1348, 1339, 1360, 1349, 1453, 1350, 1458, 1475,
  127808. /* 370 */ 1354, 1347, 1401, 1402, 1403, 1404, 1372, 1388, 1452, 1364,
  127809. /* 380 */ 1484, 1483, 1467, 1383, 1351, 1439, 1468, 1440, 1441, 1457,
  127810. /* 390 */ 1395, 1479, 1485, 1487, 1392, 1405, 1486, 1455, 1489, 1490,
  127811. /* 400 */ 1491, 1493, 1461, 1480, 1494, 1465, 1481, 1495, 1496, 1498,
  127812. /* 410 */ 1497, 1406, 1502, 1503, 1505, 1499, 1409, 1506, 1507, 1432,
  127813. /* 420 */ 1500, 1510, 1410, 1511, 1501, 1512, 1504, 1517, 1511, 1518,
  127814. /* 430 */ 1519, 1520, 1521, 1522, 1524, 1533, 1525, 1527, 1509, 1526,
  127815. /* 440 */ 1528, 1531, 1530, 1526, 1532, 1534, 1535, 1536, 1538, 1428,
  127816. /* 450 */ 1435, 1442, 1443, 1539, 1546, 1562,
  127817. };
  127818. #define YY_REDUCE_USE_DFLT (-174)
  127819. #define YY_REDUCE_COUNT (324)
  127820. #define YY_REDUCE_MIN (-173)
  127821. #define YY_REDUCE_MAX (1293)
  127822. static const short yy_reduce_ofst[] = {
  127823. /* 0 */ -119, 1014, 131, 1031, -12, 225, 228, 300, -40, -45,
  127824. /* 10 */ 243, 256, 293, 129, 218, 418, 79, 376, 433, 298,
  127825. /* 20 */ 16, 137, 367, 323, -38, 391, -173, -173, -173, -173,
  127826. /* 30 */ -173, -173, -173, -173, -173, -173, -173, -173, -173, -173,
  127827. /* 40 */ -173, -173, -173, -173, -173, -173, -173, -173, -173, -173,
  127828. /* 50 */ -173, -173, -173, -173, -173, -173, -173, -173, 374, 437,
  127829. /* 60 */ 443, 508, 513, 522, 532, 582, 584, 620, 633, 635,
  127830. /* 70 */ 637, 644, 646, 648, 650, 652, 659, 661, 696, 709,
  127831. /* 80 */ 711, 714, 720, 722, 724, 726, 728, 733, 772, 784,
  127832. /* 90 */ 786, 822, 834, 836, 884, 886, 922, 934, 936, 986,
  127833. /* 100 */ 989, 1008, 1016, 1018, -173, -173, -173, -173, -173, -173,
  127834. /* 110 */ -173, -173, -173, 544, -37, 274, 299, 501, 161, -173,
  127835. /* 120 */ 193, -173, -173, -173, -173, 22, 22, 22, 64, 141,
  127836. /* 130 */ 212, 342, 208, 504, 504, 132, 494, 606, 677, 678,
  127837. /* 140 */ 750, 794, 796, -58, 32, 383, 660, 737, 386, 787,
  127838. /* 150 */ 800, 441, 872, 224, 850, 803, 949, 624, 830, 669,
  127839. /* 160 */ 961, 979, 983, 1011, 1013, 1032, 753, 789, 321, 94,
  127840. /* 170 */ 116, 304, 375, 210, 388, 392, 478, 545, 649, 721,
  127841. /* 180 */ 727, 736, 752, 795, 853, 952, 958, 1004, 1040, 1046,
  127842. /* 190 */ 1049, 1050, 1056, 1059, 1067, 559, 774, 811, 1068, 1080,
  127843. /* 200 */ 938, 1082, 1083, 1088, 962, 1089, 1090, 1052, 1093, 1094,
  127844. /* 210 */ 1095, 388, 1096, 1103, 1104, 1105, 1106, 1107, 965, 998,
  127845. /* 220 */ 1055, 1057, 1058, 938, 1069, 1071, 1120, 1073, 1061, 1062,
  127846. /* 230 */ 1033, 1076, 1039, 1108, 1087, 1099, 1111, 1066, 1054, 1112,
  127847. /* 240 */ 1113, 1091, 1084, 1135, 1060, 1133, 1138, 1064, 1081, 1139,
  127848. /* 250 */ 1100, 1119, 1109, 1124, 1127, 1140, 1142, 1168, 1173, 1132,
  127849. /* 260 */ 1115, 1147, 1148, 1137, 1180, 1182, 1110, 1121, 1188, 1189,
  127850. /* 270 */ 1197, 1181, 1200, 1202, 1205, 1203, 1191, 1192, 1199, 1206,
  127851. /* 280 */ 1207, 1209, 1210, 1211, 1214, 1212, 1218, 1219, 1175, 1183,
  127852. /* 290 */ 1185, 1184, 1186, 1190, 1187, 1196, 1237, 1193, 1253, 1194,
  127853. /* 300 */ 1236, 1195, 1198, 1238, 1213, 1221, 1220, 1227, 1229, 1271,
  127854. /* 310 */ 1275, 1284, 1285, 1289, 1290, 1292, 1293, 1201, 1208, 1216,
  127855. /* 320 */ 1280, 1281, 1264, 1269, 1283,
  127856. };
  127857. static const YYACTIONTYPE yy_default[] = {
  127858. /* 0 */ 1280, 1270, 1270, 1270, 1202, 1202, 1202, 1202, 1270, 1096,
  127859. /* 10 */ 1125, 1125, 1254, 1332, 1332, 1332, 1332, 1332, 1332, 1201,
  127860. /* 20 */ 1332, 1332, 1332, 1332, 1270, 1100, 1131, 1332, 1332, 1332,
  127861. /* 30 */ 1332, 1203, 1204, 1332, 1332, 1332, 1253, 1255, 1141, 1140,
  127862. /* 40 */ 1139, 1138, 1236, 1112, 1136, 1129, 1133, 1203, 1197, 1198,
  127863. /* 50 */ 1196, 1200, 1204, 1332, 1132, 1167, 1181, 1166, 1332, 1332,
  127864. /* 60 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127865. /* 70 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127866. /* 80 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127867. /* 90 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127868. /* 100 */ 1332, 1332, 1332, 1332, 1175, 1180, 1187, 1179, 1176, 1169,
  127869. /* 110 */ 1168, 1170, 1171, 1332, 1019, 1067, 1332, 1332, 1332, 1172,
  127870. /* 120 */ 1332, 1173, 1184, 1183, 1182, 1261, 1288, 1287, 1332, 1332,
  127871. /* 130 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127872. /* 140 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127873. /* 150 */ 1332, 1332, 1332, 1332, 1332, 1280, 1270, 1025, 1025, 1332,
  127874. /* 160 */ 1270, 1270, 1270, 1270, 1270, 1270, 1266, 1100, 1091, 1332,
  127875. /* 170 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127876. /* 180 */ 1258, 1256, 1332, 1217, 1332, 1332, 1332, 1332, 1332, 1332,
  127877. /* 190 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127878. /* 200 */ 1332, 1332, 1332, 1332, 1096, 1332, 1332, 1332, 1332, 1332,
  127879. /* 210 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1282, 1332, 1231,
  127880. /* 220 */ 1096, 1096, 1096, 1098, 1080, 1090, 1004, 1135, 1114, 1114,
  127881. /* 230 */ 1321, 1135, 1321, 1042, 1302, 1039, 1125, 1114, 1199, 1125,
  127882. /* 240 */ 1125, 1097, 1090, 1332, 1324, 1105, 1105, 1323, 1323, 1105,
  127883. /* 250 */ 1146, 1070, 1135, 1076, 1076, 1076, 1076, 1105, 1016, 1135,
  127884. /* 260 */ 1146, 1070, 1070, 1135, 1105, 1016, 1235, 1318, 1105, 1105,
  127885. /* 270 */ 1016, 1210, 1105, 1016, 1105, 1016, 1210, 1068, 1068, 1068,
  127886. /* 280 */ 1057, 1210, 1068, 1042, 1068, 1057, 1068, 1068, 1118, 1113,
  127887. /* 290 */ 1118, 1113, 1118, 1113, 1118, 1113, 1105, 1205, 1105, 1332,
  127888. /* 300 */ 1210, 1214, 1214, 1210, 1130, 1119, 1128, 1126, 1135, 1022,
  127889. /* 310 */ 1060, 1285, 1285, 1281, 1281, 1281, 1281, 1329, 1329, 1266,
  127890. /* 320 */ 1297, 1297, 1044, 1044, 1297, 1332, 1332, 1332, 1332, 1332,
  127891. /* 330 */ 1332, 1292, 1332, 1219, 1332, 1332, 1332, 1332, 1332, 1332,
  127892. /* 340 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127893. /* 350 */ 1332, 1332, 1152, 1332, 1000, 1263, 1332, 1332, 1262, 1332,
  127894. /* 360 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127895. /* 370 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1320,
  127896. /* 380 */ 1332, 1332, 1332, 1332, 1332, 1332, 1234, 1233, 1332, 1332,
  127897. /* 390 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127898. /* 400 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127899. /* 410 */ 1332, 1082, 1332, 1332, 1332, 1306, 1332, 1332, 1332, 1332,
  127900. /* 420 */ 1332, 1332, 1332, 1127, 1332, 1120, 1332, 1332, 1311, 1332,
  127901. /* 430 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1272,
  127902. /* 440 */ 1332, 1332, 1332, 1271, 1332, 1332, 1332, 1332, 1332, 1154,
  127903. /* 450 */ 1332, 1153, 1157, 1332, 1010, 1332,
  127904. };
  127905. /********** End of lemon-generated parsing tables *****************************/
  127906. /* The next table maps tokens (terminal symbols) into fallback tokens.
  127907. ** If a construct like the following:
  127908. **
  127909. ** %fallback ID X Y Z.
  127910. **
  127911. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  127912. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  127913. ** but it does not parse, the type of the token is changed to ID and
  127914. ** the parse is retried before an error is thrown.
  127915. **
  127916. ** This feature can be used, for example, to cause some keywords in a language
  127917. ** to revert to identifiers if they keyword does not apply in the context where
  127918. ** it appears.
  127919. */
  127920. #ifdef YYFALLBACK
  127921. static const YYCODETYPE yyFallback[] = {
  127922. 0, /* $ => nothing */
  127923. 0, /* SEMI => nothing */
  127924. 27, /* EXPLAIN => ID */
  127925. 27, /* QUERY => ID */
  127926. 27, /* PLAN => ID */
  127927. 27, /* BEGIN => ID */
  127928. 0, /* TRANSACTION => nothing */
  127929. 27, /* DEFERRED => ID */
  127930. 27, /* IMMEDIATE => ID */
  127931. 27, /* EXCLUSIVE => ID */
  127932. 0, /* COMMIT => nothing */
  127933. 27, /* END => ID */
  127934. 27, /* ROLLBACK => ID */
  127935. 27, /* SAVEPOINT => ID */
  127936. 27, /* RELEASE => ID */
  127937. 0, /* TO => nothing */
  127938. 0, /* TABLE => nothing */
  127939. 0, /* CREATE => nothing */
  127940. 27, /* IF => ID */
  127941. 0, /* NOT => nothing */
  127942. 0, /* EXISTS => nothing */
  127943. 27, /* TEMP => ID */
  127944. 0, /* LP => nothing */
  127945. 0, /* RP => nothing */
  127946. 0, /* AS => nothing */
  127947. 27, /* WITHOUT => ID */
  127948. 0, /* COMMA => nothing */
  127949. 0, /* ID => nothing */
  127950. 27, /* ABORT => ID */
  127951. 27, /* ACTION => ID */
  127952. 27, /* AFTER => ID */
  127953. 27, /* ANALYZE => ID */
  127954. 27, /* ASC => ID */
  127955. 27, /* ATTACH => ID */
  127956. 27, /* BEFORE => ID */
  127957. 27, /* BY => ID */
  127958. 27, /* CASCADE => ID */
  127959. 27, /* CAST => ID */
  127960. 27, /* COLUMNKW => ID */
  127961. 27, /* CONFLICT => ID */
  127962. 27, /* DATABASE => ID */
  127963. 27, /* DESC => ID */
  127964. 27, /* DETACH => ID */
  127965. 27, /* EACH => ID */
  127966. 27, /* FAIL => ID */
  127967. 27, /* FOR => ID */
  127968. 27, /* IGNORE => ID */
  127969. 27, /* INITIALLY => ID */
  127970. 27, /* INSTEAD => ID */
  127971. 27, /* LIKE_KW => ID */
  127972. 27, /* MATCH => ID */
  127973. 27, /* NO => ID */
  127974. 27, /* KEY => ID */
  127975. 27, /* OF => ID */
  127976. 27, /* OFFSET => ID */
  127977. 27, /* PRAGMA => ID */
  127978. 27, /* RAISE => ID */
  127979. 27, /* RECURSIVE => ID */
  127980. 27, /* REPLACE => ID */
  127981. 27, /* RESTRICT => ID */
  127982. 27, /* ROW => ID */
  127983. 27, /* TRIGGER => ID */
  127984. 27, /* VACUUM => ID */
  127985. 27, /* VIEW => ID */
  127986. 27, /* VIRTUAL => ID */
  127987. 27, /* WITH => ID */
  127988. 27, /* REINDEX => ID */
  127989. 27, /* RENAME => ID */
  127990. 27, /* CTIME_KW => ID */
  127991. };
  127992. #endif /* YYFALLBACK */
  127993. /* The following structure represents a single element of the
  127994. ** parser's stack. Information stored includes:
  127995. **
  127996. ** + The state number for the parser at this level of the stack.
  127997. **
  127998. ** + The value of the token stored at this level of the stack.
  127999. ** (In other words, the "major" token.)
  128000. **
  128001. ** + The semantic value stored at this level of the stack. This is
  128002. ** the information used by the action routines in the grammar.
  128003. ** It is sometimes called the "minor" token.
  128004. **
  128005. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  128006. ** actually contains the reduce action for the second half of the
  128007. ** SHIFTREDUCE.
  128008. */
  128009. struct yyStackEntry {
  128010. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  128011. YYCODETYPE major; /* The major token value. This is the code
  128012. ** number for the token at this stack level */
  128013. YYMINORTYPE minor; /* The user-supplied minor token value. This
  128014. ** is the value of the token */
  128015. };
  128016. typedef struct yyStackEntry yyStackEntry;
  128017. /* The state of the parser is completely contained in an instance of
  128018. ** the following structure */
  128019. struct yyParser {
  128020. yyStackEntry *yytos; /* Pointer to top element of the stack */
  128021. #ifdef YYTRACKMAXSTACKDEPTH
  128022. int yyhwm; /* High-water mark of the stack */
  128023. #endif
  128024. #ifndef YYNOERRORRECOVERY
  128025. int yyerrcnt; /* Shifts left before out of the error */
  128026. #endif
  128027. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  128028. #if YYSTACKDEPTH<=0
  128029. int yystksz; /* Current side of the stack */
  128030. yyStackEntry *yystack; /* The parser's stack */
  128031. yyStackEntry yystk0; /* First stack entry */
  128032. #else
  128033. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  128034. #endif
  128035. };
  128036. typedef struct yyParser yyParser;
  128037. #ifndef NDEBUG
  128038. /* #include <stdio.h> */
  128039. static FILE *yyTraceFILE = 0;
  128040. static char *yyTracePrompt = 0;
  128041. #endif /* NDEBUG */
  128042. #ifndef NDEBUG
  128043. /*
  128044. ** Turn parser tracing on by giving a stream to which to write the trace
  128045. ** and a prompt to preface each trace message. Tracing is turned off
  128046. ** by making either argument NULL
  128047. **
  128048. ** Inputs:
  128049. ** <ul>
  128050. ** <li> A FILE* to which trace output should be written.
  128051. ** If NULL, then tracing is turned off.
  128052. ** <li> A prefix string written at the beginning of every
  128053. ** line of trace output. If NULL, then tracing is
  128054. ** turned off.
  128055. ** </ul>
  128056. **
  128057. ** Outputs:
  128058. ** None.
  128059. */
  128060. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  128061. yyTraceFILE = TraceFILE;
  128062. yyTracePrompt = zTracePrompt;
  128063. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  128064. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  128065. }
  128066. #endif /* NDEBUG */
  128067. #ifndef NDEBUG
  128068. /* For tracing shifts, the names of all terminals and nonterminals
  128069. ** are required. The following table supplies these names */
  128070. static const char *const yyTokenName[] = {
  128071. "$", "SEMI", "EXPLAIN", "QUERY",
  128072. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  128073. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  128074. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  128075. "TABLE", "CREATE", "IF", "NOT",
  128076. "EXISTS", "TEMP", "LP", "RP",
  128077. "AS", "WITHOUT", "COMMA", "ID",
  128078. "ABORT", "ACTION", "AFTER", "ANALYZE",
  128079. "ASC", "ATTACH", "BEFORE", "BY",
  128080. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  128081. "DATABASE", "DESC", "DETACH", "EACH",
  128082. "FAIL", "FOR", "IGNORE", "INITIALLY",
  128083. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  128084. "KEY", "OF", "OFFSET", "PRAGMA",
  128085. "RAISE", "RECURSIVE", "REPLACE", "RESTRICT",
  128086. "ROW", "TRIGGER", "VACUUM", "VIEW",
  128087. "VIRTUAL", "WITH", "REINDEX", "RENAME",
  128088. "CTIME_KW", "ANY", "OR", "AND",
  128089. "IS", "BETWEEN", "IN", "ISNULL",
  128090. "NOTNULL", "NE", "EQ", "GT",
  128091. "LE", "LT", "GE", "ESCAPE",
  128092. "BITAND", "BITOR", "LSHIFT", "RSHIFT",
  128093. "PLUS", "MINUS", "STAR", "SLASH",
  128094. "REM", "CONCAT", "COLLATE", "BITNOT",
  128095. "INDEXED", "STRING", "JOIN_KW", "CONSTRAINT",
  128096. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  128097. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  128098. "INSERT", "DELETE", "UPDATE", "SET",
  128099. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  128100. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  128101. "VALUES", "DISTINCT", "DOT", "FROM",
  128102. "JOIN", "USING", "ORDER", "GROUP",
  128103. "HAVING", "LIMIT", "WHERE", "INTO",
  128104. "FLOAT", "BLOB", "INTEGER", "VARIABLE",
  128105. "CASE", "WHEN", "THEN", "ELSE",
  128106. "INDEX", "ALTER", "ADD", "error",
  128107. "input", "cmdlist", "ecmd", "explain",
  128108. "cmdx", "cmd", "transtype", "trans_opt",
  128109. "nm", "savepoint_opt", "create_table", "create_table_args",
  128110. "createkw", "temp", "ifnotexists", "dbnm",
  128111. "columnlist", "conslist_opt", "table_options", "select",
  128112. "columnname", "carglist", "typetoken", "typename",
  128113. "signed", "plus_num", "minus_num", "ccons",
  128114. "term", "expr", "onconf", "sortorder",
  128115. "autoinc", "eidlist_opt", "refargs", "defer_subclause",
  128116. "refarg", "refact", "init_deferred_pred_opt", "conslist",
  128117. "tconscomma", "tcons", "sortlist", "eidlist",
  128118. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  128119. "ifexists", "fullname", "selectnowith", "oneselect",
  128120. "with", "multiselect_op", "distinct", "selcollist",
  128121. "from", "where_opt", "groupby_opt", "having_opt",
  128122. "orderby_opt", "limit_opt", "values", "nexprlist",
  128123. "exprlist", "sclp", "as", "seltablist",
  128124. "stl_prefix", "joinop", "indexed_opt", "on_opt",
  128125. "using_opt", "idlist", "setlist", "insert_cmd",
  128126. "idlist_opt", "likeop", "between_op", "in_op",
  128127. "paren_exprlist", "case_operand", "case_exprlist", "case_else",
  128128. "uniqueflag", "collate", "nmnum", "trigger_decl",
  128129. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  128130. "when_clause", "trigger_cmd", "trnm", "tridxby",
  128131. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  128132. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  128133. "lp", "anylist", "wqlist",
  128134. };
  128135. #endif /* NDEBUG */
  128136. #ifndef NDEBUG
  128137. /* For tracing reduce actions, the names of all rules are required.
  128138. */
  128139. static const char *const yyRuleName[] = {
  128140. /* 0 */ "explain ::= EXPLAIN",
  128141. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  128142. /* 2 */ "cmdx ::= cmd",
  128143. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  128144. /* 4 */ "transtype ::=",
  128145. /* 5 */ "transtype ::= DEFERRED",
  128146. /* 6 */ "transtype ::= IMMEDIATE",
  128147. /* 7 */ "transtype ::= EXCLUSIVE",
  128148. /* 8 */ "cmd ::= COMMIT trans_opt",
  128149. /* 9 */ "cmd ::= END trans_opt",
  128150. /* 10 */ "cmd ::= ROLLBACK trans_opt",
  128151. /* 11 */ "cmd ::= SAVEPOINT nm",
  128152. /* 12 */ "cmd ::= RELEASE savepoint_opt nm",
  128153. /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  128154. /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  128155. /* 15 */ "createkw ::= CREATE",
  128156. /* 16 */ "ifnotexists ::=",
  128157. /* 17 */ "ifnotexists ::= IF NOT EXISTS",
  128158. /* 18 */ "temp ::= TEMP",
  128159. /* 19 */ "temp ::=",
  128160. /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  128161. /* 21 */ "create_table_args ::= AS select",
  128162. /* 22 */ "table_options ::=",
  128163. /* 23 */ "table_options ::= WITHOUT nm",
  128164. /* 24 */ "columnname ::= nm typetoken",
  128165. /* 25 */ "typetoken ::=",
  128166. /* 26 */ "typetoken ::= typename LP signed RP",
  128167. /* 27 */ "typetoken ::= typename LP signed COMMA signed RP",
  128168. /* 28 */ "typename ::= typename ID|STRING",
  128169. /* 29 */ "ccons ::= CONSTRAINT nm",
  128170. /* 30 */ "ccons ::= DEFAULT term",
  128171. /* 31 */ "ccons ::= DEFAULT LP expr RP",
  128172. /* 32 */ "ccons ::= DEFAULT PLUS term",
  128173. /* 33 */ "ccons ::= DEFAULT MINUS term",
  128174. /* 34 */ "ccons ::= DEFAULT ID|INDEXED",
  128175. /* 35 */ "ccons ::= NOT NULL onconf",
  128176. /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  128177. /* 37 */ "ccons ::= UNIQUE onconf",
  128178. /* 38 */ "ccons ::= CHECK LP expr RP",
  128179. /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  128180. /* 40 */ "ccons ::= defer_subclause",
  128181. /* 41 */ "ccons ::= COLLATE ID|STRING",
  128182. /* 42 */ "autoinc ::=",
  128183. /* 43 */ "autoinc ::= AUTOINCR",
  128184. /* 44 */ "refargs ::=",
  128185. /* 45 */ "refargs ::= refargs refarg",
  128186. /* 46 */ "refarg ::= MATCH nm",
  128187. /* 47 */ "refarg ::= ON INSERT refact",
  128188. /* 48 */ "refarg ::= ON DELETE refact",
  128189. /* 49 */ "refarg ::= ON UPDATE refact",
  128190. /* 50 */ "refact ::= SET NULL",
  128191. /* 51 */ "refact ::= SET DEFAULT",
  128192. /* 52 */ "refact ::= CASCADE",
  128193. /* 53 */ "refact ::= RESTRICT",
  128194. /* 54 */ "refact ::= NO ACTION",
  128195. /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  128196. /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  128197. /* 57 */ "init_deferred_pred_opt ::=",
  128198. /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  128199. /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  128200. /* 60 */ "conslist_opt ::=",
  128201. /* 61 */ "tconscomma ::= COMMA",
  128202. /* 62 */ "tcons ::= CONSTRAINT nm",
  128203. /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  128204. /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  128205. /* 65 */ "tcons ::= CHECK LP expr RP onconf",
  128206. /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  128207. /* 67 */ "defer_subclause_opt ::=",
  128208. /* 68 */ "onconf ::=",
  128209. /* 69 */ "onconf ::= ON CONFLICT resolvetype",
  128210. /* 70 */ "orconf ::=",
  128211. /* 71 */ "orconf ::= OR resolvetype",
  128212. /* 72 */ "resolvetype ::= IGNORE",
  128213. /* 73 */ "resolvetype ::= REPLACE",
  128214. /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
  128215. /* 75 */ "ifexists ::= IF EXISTS",
  128216. /* 76 */ "ifexists ::=",
  128217. /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  128218. /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
  128219. /* 79 */ "cmd ::= select",
  128220. /* 80 */ "select ::= with selectnowith",
  128221. /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  128222. /* 82 */ "multiselect_op ::= UNION",
  128223. /* 83 */ "multiselect_op ::= UNION ALL",
  128224. /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT",
  128225. /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  128226. /* 86 */ "values ::= VALUES LP nexprlist RP",
  128227. /* 87 */ "values ::= values COMMA LP exprlist RP",
  128228. /* 88 */ "distinct ::= DISTINCT",
  128229. /* 89 */ "distinct ::= ALL",
  128230. /* 90 */ "distinct ::=",
  128231. /* 91 */ "sclp ::=",
  128232. /* 92 */ "selcollist ::= sclp expr as",
  128233. /* 93 */ "selcollist ::= sclp STAR",
  128234. /* 94 */ "selcollist ::= sclp nm DOT STAR",
  128235. /* 95 */ "as ::= AS nm",
  128236. /* 96 */ "as ::=",
  128237. /* 97 */ "from ::=",
  128238. /* 98 */ "from ::= FROM seltablist",
  128239. /* 99 */ "stl_prefix ::= seltablist joinop",
  128240. /* 100 */ "stl_prefix ::=",
  128241. /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  128242. /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  128243. /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  128244. /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  128245. /* 105 */ "dbnm ::=",
  128246. /* 106 */ "dbnm ::= DOT nm",
  128247. /* 107 */ "fullname ::= nm dbnm",
  128248. /* 108 */ "joinop ::= COMMA|JOIN",
  128249. /* 109 */ "joinop ::= JOIN_KW JOIN",
  128250. /* 110 */ "joinop ::= JOIN_KW nm JOIN",
  128251. /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
  128252. /* 112 */ "on_opt ::= ON expr",
  128253. /* 113 */ "on_opt ::=",
  128254. /* 114 */ "indexed_opt ::=",
  128255. /* 115 */ "indexed_opt ::= INDEXED BY nm",
  128256. /* 116 */ "indexed_opt ::= NOT INDEXED",
  128257. /* 117 */ "using_opt ::= USING LP idlist RP",
  128258. /* 118 */ "using_opt ::=",
  128259. /* 119 */ "orderby_opt ::=",
  128260. /* 120 */ "orderby_opt ::= ORDER BY sortlist",
  128261. /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
  128262. /* 122 */ "sortlist ::= expr sortorder",
  128263. /* 123 */ "sortorder ::= ASC",
  128264. /* 124 */ "sortorder ::= DESC",
  128265. /* 125 */ "sortorder ::=",
  128266. /* 126 */ "groupby_opt ::=",
  128267. /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
  128268. /* 128 */ "having_opt ::=",
  128269. /* 129 */ "having_opt ::= HAVING expr",
  128270. /* 130 */ "limit_opt ::=",
  128271. /* 131 */ "limit_opt ::= LIMIT expr",
  128272. /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
  128273. /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
  128274. /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  128275. /* 135 */ "where_opt ::=",
  128276. /* 136 */ "where_opt ::= WHERE expr",
  128277. /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  128278. /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
  128279. /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
  128280. /* 140 */ "setlist ::= nm EQ expr",
  128281. /* 141 */ "setlist ::= LP idlist RP EQ expr",
  128282. /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
  128283. /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
  128284. /* 144 */ "insert_cmd ::= INSERT orconf",
  128285. /* 145 */ "insert_cmd ::= REPLACE",
  128286. /* 146 */ "idlist_opt ::=",
  128287. /* 147 */ "idlist_opt ::= LP idlist RP",
  128288. /* 148 */ "idlist ::= idlist COMMA nm",
  128289. /* 149 */ "idlist ::= nm",
  128290. /* 150 */ "expr ::= LP expr RP",
  128291. /* 151 */ "term ::= NULL",
  128292. /* 152 */ "expr ::= ID|INDEXED",
  128293. /* 153 */ "expr ::= JOIN_KW",
  128294. /* 154 */ "expr ::= nm DOT nm",
  128295. /* 155 */ "expr ::= nm DOT nm DOT nm",
  128296. /* 156 */ "term ::= FLOAT|BLOB",
  128297. /* 157 */ "term ::= STRING",
  128298. /* 158 */ "term ::= INTEGER",
  128299. /* 159 */ "expr ::= VARIABLE",
  128300. /* 160 */ "expr ::= expr COLLATE ID|STRING",
  128301. /* 161 */ "expr ::= CAST LP expr AS typetoken RP",
  128302. /* 162 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  128303. /* 163 */ "expr ::= ID|INDEXED LP STAR RP",
  128304. /* 164 */ "term ::= CTIME_KW",
  128305. /* 165 */ "expr ::= LP nexprlist COMMA expr RP",
  128306. /* 166 */ "expr ::= expr AND expr",
  128307. /* 167 */ "expr ::= expr OR expr",
  128308. /* 168 */ "expr ::= expr LT|GT|GE|LE expr",
  128309. /* 169 */ "expr ::= expr EQ|NE expr",
  128310. /* 170 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  128311. /* 171 */ "expr ::= expr PLUS|MINUS expr",
  128312. /* 172 */ "expr ::= expr STAR|SLASH|REM expr",
  128313. /* 173 */ "expr ::= expr CONCAT expr",
  128314. /* 174 */ "likeop ::= NOT LIKE_KW|MATCH",
  128315. /* 175 */ "expr ::= expr likeop expr",
  128316. /* 176 */ "expr ::= expr likeop expr ESCAPE expr",
  128317. /* 177 */ "expr ::= expr ISNULL|NOTNULL",
  128318. /* 178 */ "expr ::= expr NOT NULL",
  128319. /* 179 */ "expr ::= expr IS expr",
  128320. /* 180 */ "expr ::= expr IS NOT expr",
  128321. /* 181 */ "expr ::= NOT expr",
  128322. /* 182 */ "expr ::= BITNOT expr",
  128323. /* 183 */ "expr ::= MINUS expr",
  128324. /* 184 */ "expr ::= PLUS expr",
  128325. /* 185 */ "between_op ::= BETWEEN",
  128326. /* 186 */ "between_op ::= NOT BETWEEN",
  128327. /* 187 */ "expr ::= expr between_op expr AND expr",
  128328. /* 188 */ "in_op ::= IN",
  128329. /* 189 */ "in_op ::= NOT IN",
  128330. /* 190 */ "expr ::= expr in_op LP exprlist RP",
  128331. /* 191 */ "expr ::= LP select RP",
  128332. /* 192 */ "expr ::= expr in_op LP select RP",
  128333. /* 193 */ "expr ::= expr in_op nm dbnm paren_exprlist",
  128334. /* 194 */ "expr ::= EXISTS LP select RP",
  128335. /* 195 */ "expr ::= CASE case_operand case_exprlist case_else END",
  128336. /* 196 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  128337. /* 197 */ "case_exprlist ::= WHEN expr THEN expr",
  128338. /* 198 */ "case_else ::= ELSE expr",
  128339. /* 199 */ "case_else ::=",
  128340. /* 200 */ "case_operand ::= expr",
  128341. /* 201 */ "case_operand ::=",
  128342. /* 202 */ "exprlist ::=",
  128343. /* 203 */ "nexprlist ::= nexprlist COMMA expr",
  128344. /* 204 */ "nexprlist ::= expr",
  128345. /* 205 */ "paren_exprlist ::=",
  128346. /* 206 */ "paren_exprlist ::= LP exprlist RP",
  128347. /* 207 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  128348. /* 208 */ "uniqueflag ::= UNIQUE",
  128349. /* 209 */ "uniqueflag ::=",
  128350. /* 210 */ "eidlist_opt ::=",
  128351. /* 211 */ "eidlist_opt ::= LP eidlist RP",
  128352. /* 212 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  128353. /* 213 */ "eidlist ::= nm collate sortorder",
  128354. /* 214 */ "collate ::=",
  128355. /* 215 */ "collate ::= COLLATE ID|STRING",
  128356. /* 216 */ "cmd ::= DROP INDEX ifexists fullname",
  128357. /* 217 */ "cmd ::= VACUUM",
  128358. /* 218 */ "cmd ::= VACUUM nm",
  128359. /* 219 */ "cmd ::= PRAGMA nm dbnm",
  128360. /* 220 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  128361. /* 221 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  128362. /* 222 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  128363. /* 223 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  128364. /* 224 */ "plus_num ::= PLUS INTEGER|FLOAT",
  128365. /* 225 */ "minus_num ::= MINUS INTEGER|FLOAT",
  128366. /* 226 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  128367. /* 227 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  128368. /* 228 */ "trigger_time ::= BEFORE",
  128369. /* 229 */ "trigger_time ::= AFTER",
  128370. /* 230 */ "trigger_time ::= INSTEAD OF",
  128371. /* 231 */ "trigger_time ::=",
  128372. /* 232 */ "trigger_event ::= DELETE|INSERT",
  128373. /* 233 */ "trigger_event ::= UPDATE",
  128374. /* 234 */ "trigger_event ::= UPDATE OF idlist",
  128375. /* 235 */ "when_clause ::=",
  128376. /* 236 */ "when_clause ::= WHEN expr",
  128377. /* 237 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  128378. /* 238 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  128379. /* 239 */ "trnm ::= nm DOT nm",
  128380. /* 240 */ "tridxby ::= INDEXED BY nm",
  128381. /* 241 */ "tridxby ::= NOT INDEXED",
  128382. /* 242 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  128383. /* 243 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
  128384. /* 244 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  128385. /* 245 */ "trigger_cmd ::= select",
  128386. /* 246 */ "expr ::= RAISE LP IGNORE RP",
  128387. /* 247 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  128388. /* 248 */ "raisetype ::= ROLLBACK",
  128389. /* 249 */ "raisetype ::= ABORT",
  128390. /* 250 */ "raisetype ::= FAIL",
  128391. /* 251 */ "cmd ::= DROP TRIGGER ifexists fullname",
  128392. /* 252 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  128393. /* 253 */ "cmd ::= DETACH database_kw_opt expr",
  128394. /* 254 */ "key_opt ::=",
  128395. /* 255 */ "key_opt ::= KEY expr",
  128396. /* 256 */ "cmd ::= REINDEX",
  128397. /* 257 */ "cmd ::= REINDEX nm dbnm",
  128398. /* 258 */ "cmd ::= ANALYZE",
  128399. /* 259 */ "cmd ::= ANALYZE nm dbnm",
  128400. /* 260 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  128401. /* 261 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  128402. /* 262 */ "add_column_fullname ::= fullname",
  128403. /* 263 */ "cmd ::= create_vtab",
  128404. /* 264 */ "cmd ::= create_vtab LP vtabarglist RP",
  128405. /* 265 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  128406. /* 266 */ "vtabarg ::=",
  128407. /* 267 */ "vtabargtoken ::= ANY",
  128408. /* 268 */ "vtabargtoken ::= lp anylist RP",
  128409. /* 269 */ "lp ::= LP",
  128410. /* 270 */ "with ::=",
  128411. /* 271 */ "with ::= WITH wqlist",
  128412. /* 272 */ "with ::= WITH RECURSIVE wqlist",
  128413. /* 273 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  128414. /* 274 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  128415. /* 275 */ "input ::= cmdlist",
  128416. /* 276 */ "cmdlist ::= cmdlist ecmd",
  128417. /* 277 */ "cmdlist ::= ecmd",
  128418. /* 278 */ "ecmd ::= SEMI",
  128419. /* 279 */ "ecmd ::= explain cmdx SEMI",
  128420. /* 280 */ "explain ::=",
  128421. /* 281 */ "trans_opt ::=",
  128422. /* 282 */ "trans_opt ::= TRANSACTION",
  128423. /* 283 */ "trans_opt ::= TRANSACTION nm",
  128424. /* 284 */ "savepoint_opt ::= SAVEPOINT",
  128425. /* 285 */ "savepoint_opt ::=",
  128426. /* 286 */ "cmd ::= create_table create_table_args",
  128427. /* 287 */ "columnlist ::= columnlist COMMA columnname carglist",
  128428. /* 288 */ "columnlist ::= columnname carglist",
  128429. /* 289 */ "nm ::= ID|INDEXED",
  128430. /* 290 */ "nm ::= STRING",
  128431. /* 291 */ "nm ::= JOIN_KW",
  128432. /* 292 */ "typetoken ::= typename",
  128433. /* 293 */ "typename ::= ID|STRING",
  128434. /* 294 */ "signed ::= plus_num",
  128435. /* 295 */ "signed ::= minus_num",
  128436. /* 296 */ "carglist ::= carglist ccons",
  128437. /* 297 */ "carglist ::=",
  128438. /* 298 */ "ccons ::= NULL onconf",
  128439. /* 299 */ "conslist_opt ::= COMMA conslist",
  128440. /* 300 */ "conslist ::= conslist tconscomma tcons",
  128441. /* 301 */ "conslist ::= tcons",
  128442. /* 302 */ "tconscomma ::=",
  128443. /* 303 */ "defer_subclause_opt ::= defer_subclause",
  128444. /* 304 */ "resolvetype ::= raisetype",
  128445. /* 305 */ "selectnowith ::= oneselect",
  128446. /* 306 */ "oneselect ::= values",
  128447. /* 307 */ "sclp ::= selcollist COMMA",
  128448. /* 308 */ "as ::= ID|STRING",
  128449. /* 309 */ "expr ::= term",
  128450. /* 310 */ "likeop ::= LIKE_KW|MATCH",
  128451. /* 311 */ "exprlist ::= nexprlist",
  128452. /* 312 */ "nmnum ::= plus_num",
  128453. /* 313 */ "nmnum ::= nm",
  128454. /* 314 */ "nmnum ::= ON",
  128455. /* 315 */ "nmnum ::= DELETE",
  128456. /* 316 */ "nmnum ::= DEFAULT",
  128457. /* 317 */ "plus_num ::= INTEGER|FLOAT",
  128458. /* 318 */ "foreach_clause ::=",
  128459. /* 319 */ "foreach_clause ::= FOR EACH ROW",
  128460. /* 320 */ "trnm ::= nm",
  128461. /* 321 */ "tridxby ::=",
  128462. /* 322 */ "database_kw_opt ::= DATABASE",
  128463. /* 323 */ "database_kw_opt ::=",
  128464. /* 324 */ "kwcolumn_opt ::=",
  128465. /* 325 */ "kwcolumn_opt ::= COLUMNKW",
  128466. /* 326 */ "vtabarglist ::= vtabarg",
  128467. /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  128468. /* 328 */ "vtabarg ::= vtabarg vtabargtoken",
  128469. /* 329 */ "anylist ::=",
  128470. /* 330 */ "anylist ::= anylist LP anylist RP",
  128471. /* 331 */ "anylist ::= anylist ANY",
  128472. };
  128473. #endif /* NDEBUG */
  128474. #if YYSTACKDEPTH<=0
  128475. /*
  128476. ** Try to increase the size of the parser stack. Return the number
  128477. ** of errors. Return 0 on success.
  128478. */
  128479. static int yyGrowStack(yyParser *p){
  128480. int newSize;
  128481. int idx;
  128482. yyStackEntry *pNew;
  128483. newSize = p->yystksz*2 + 100;
  128484. idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
  128485. if( p->yystack==&p->yystk0 ){
  128486. pNew = malloc(newSize*sizeof(pNew[0]));
  128487. if( pNew ) pNew[0] = p->yystk0;
  128488. }else{
  128489. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  128490. }
  128491. if( pNew ){
  128492. p->yystack = pNew;
  128493. p->yytos = &p->yystack[idx];
  128494. #ifndef NDEBUG
  128495. if( yyTraceFILE ){
  128496. fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  128497. yyTracePrompt, p->yystksz, newSize);
  128498. }
  128499. #endif
  128500. p->yystksz = newSize;
  128501. }
  128502. return pNew==0;
  128503. }
  128504. #endif
  128505. /* Datatype of the argument to the memory allocated passed as the
  128506. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  128507. ** putting an appropriate #define in the %include section of the input
  128508. ** grammar.
  128509. */
  128510. #ifndef YYMALLOCARGTYPE
  128511. # define YYMALLOCARGTYPE size_t
  128512. #endif
  128513. /* Initialize a new parser that has already been allocated.
  128514. */
  128515. SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){
  128516. yyParser *pParser = (yyParser*)yypParser;
  128517. #ifdef YYTRACKMAXSTACKDEPTH
  128518. pParser->yyhwm = 0;
  128519. #endif
  128520. #if YYSTACKDEPTH<=0
  128521. pParser->yytos = NULL;
  128522. pParser->yystack = NULL;
  128523. pParser->yystksz = 0;
  128524. if( yyGrowStack(pParser) ){
  128525. pParser->yystack = &pParser->yystk0;
  128526. pParser->yystksz = 1;
  128527. }
  128528. #endif
  128529. #ifndef YYNOERRORRECOVERY
  128530. pParser->yyerrcnt = -1;
  128531. #endif
  128532. pParser->yytos = pParser->yystack;
  128533. pParser->yystack[0].stateno = 0;
  128534. pParser->yystack[0].major = 0;
  128535. }
  128536. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  128537. /*
  128538. ** This function allocates a new parser.
  128539. ** The only argument is a pointer to a function which works like
  128540. ** malloc.
  128541. **
  128542. ** Inputs:
  128543. ** A pointer to the function used to allocate memory.
  128544. **
  128545. ** Outputs:
  128546. ** A pointer to a parser. This pointer is used in subsequent calls
  128547. ** to sqlite3Parser and sqlite3ParserFree.
  128548. */
  128549. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
  128550. yyParser *pParser;
  128551. pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  128552. if( pParser ) sqlite3ParserInit(pParser);
  128553. return pParser;
  128554. }
  128555. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  128556. /* The following function deletes the "minor type" or semantic value
  128557. ** associated with a symbol. The symbol can be either a terminal
  128558. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  128559. ** a pointer to the value to be deleted. The code used to do the
  128560. ** deletions is derived from the %destructor and/or %token_destructor
  128561. ** directives of the input grammar.
  128562. */
  128563. static void yy_destructor(
  128564. yyParser *yypParser, /* The parser */
  128565. YYCODETYPE yymajor, /* Type code for object to destroy */
  128566. YYMINORTYPE *yypminor /* The object to be destroyed */
  128567. ){
  128568. sqlite3ParserARG_FETCH;
  128569. switch( yymajor ){
  128570. /* Here is inserted the actions which take place when a
  128571. ** terminal or non-terminal is destroyed. This can happen
  128572. ** when the symbol is popped from the stack during a
  128573. ** reduce or during error processing or when a parser is
  128574. ** being destroyed before it is finished parsing.
  128575. **
  128576. ** Note: during a reduce, the only symbols destroyed are those
  128577. ** which appear on the RHS of the rule, but which are *not* used
  128578. ** inside the C code.
  128579. */
  128580. /********* Begin destructor definitions ***************************************/
  128581. case 163: /* select */
  128582. case 194: /* selectnowith */
  128583. case 195: /* oneselect */
  128584. case 206: /* values */
  128585. {
  128586. sqlite3SelectDelete(pParse->db, (yypminor->yy243));
  128587. }
  128588. break;
  128589. case 172: /* term */
  128590. case 173: /* expr */
  128591. {
  128592. sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
  128593. }
  128594. break;
  128595. case 177: /* eidlist_opt */
  128596. case 186: /* sortlist */
  128597. case 187: /* eidlist */
  128598. case 199: /* selcollist */
  128599. case 202: /* groupby_opt */
  128600. case 204: /* orderby_opt */
  128601. case 207: /* nexprlist */
  128602. case 208: /* exprlist */
  128603. case 209: /* sclp */
  128604. case 218: /* setlist */
  128605. case 224: /* paren_exprlist */
  128606. case 226: /* case_exprlist */
  128607. {
  128608. sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
  128609. }
  128610. break;
  128611. case 193: /* fullname */
  128612. case 200: /* from */
  128613. case 211: /* seltablist */
  128614. case 212: /* stl_prefix */
  128615. {
  128616. sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
  128617. }
  128618. break;
  128619. case 196: /* with */
  128620. case 250: /* wqlist */
  128621. {
  128622. sqlite3WithDelete(pParse->db, (yypminor->yy285));
  128623. }
  128624. break;
  128625. case 201: /* where_opt */
  128626. case 203: /* having_opt */
  128627. case 215: /* on_opt */
  128628. case 225: /* case_operand */
  128629. case 227: /* case_else */
  128630. case 236: /* when_clause */
  128631. case 241: /* key_opt */
  128632. {
  128633. sqlite3ExprDelete(pParse->db, (yypminor->yy72));
  128634. }
  128635. break;
  128636. case 216: /* using_opt */
  128637. case 217: /* idlist */
  128638. case 220: /* idlist_opt */
  128639. {
  128640. sqlite3IdListDelete(pParse->db, (yypminor->yy254));
  128641. }
  128642. break;
  128643. case 232: /* trigger_cmd_list */
  128644. case 237: /* trigger_cmd */
  128645. {
  128646. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
  128647. }
  128648. break;
  128649. case 234: /* trigger_event */
  128650. {
  128651. sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
  128652. }
  128653. break;
  128654. /********* End destructor definitions *****************************************/
  128655. default: break; /* If no destructor action specified: do nothing */
  128656. }
  128657. }
  128658. /*
  128659. ** Pop the parser's stack once.
  128660. **
  128661. ** If there is a destructor routine associated with the token which
  128662. ** is popped from the stack, then call it.
  128663. */
  128664. static void yy_pop_parser_stack(yyParser *pParser){
  128665. yyStackEntry *yytos;
  128666. assert( pParser->yytos!=0 );
  128667. assert( pParser->yytos > pParser->yystack );
  128668. yytos = pParser->yytos--;
  128669. #ifndef NDEBUG
  128670. if( yyTraceFILE ){
  128671. fprintf(yyTraceFILE,"%sPopping %s\n",
  128672. yyTracePrompt,
  128673. yyTokenName[yytos->major]);
  128674. }
  128675. #endif
  128676. yy_destructor(pParser, yytos->major, &yytos->minor);
  128677. }
  128678. /*
  128679. ** Clear all secondary memory allocations from the parser
  128680. */
  128681. SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
  128682. yyParser *pParser = (yyParser*)p;
  128683. while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
  128684. #if YYSTACKDEPTH<=0
  128685. if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
  128686. #endif
  128687. }
  128688. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  128689. /*
  128690. ** Deallocate and destroy a parser. Destructors are called for
  128691. ** all stack elements before shutting the parser down.
  128692. **
  128693. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  128694. ** is defined in a %include section of the input grammar) then it is
  128695. ** assumed that the input pointer is never NULL.
  128696. */
  128697. SQLITE_PRIVATE void sqlite3ParserFree(
  128698. void *p, /* The parser to be deleted */
  128699. void (*freeProc)(void*) /* Function used to reclaim memory */
  128700. ){
  128701. #ifndef YYPARSEFREENEVERNULL
  128702. if( p==0 ) return;
  128703. #endif
  128704. sqlite3ParserFinalize(p);
  128705. (*freeProc)(p);
  128706. }
  128707. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  128708. /*
  128709. ** Return the peak depth of the stack for a parser.
  128710. */
  128711. #ifdef YYTRACKMAXSTACKDEPTH
  128712. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  128713. yyParser *pParser = (yyParser*)p;
  128714. return pParser->yyhwm;
  128715. }
  128716. #endif
  128717. /*
  128718. ** Find the appropriate action for a parser given the terminal
  128719. ** look-ahead token iLookAhead.
  128720. */
  128721. static unsigned int yy_find_shift_action(
  128722. yyParser *pParser, /* The parser */
  128723. YYCODETYPE iLookAhead /* The look-ahead token */
  128724. ){
  128725. int i;
  128726. int stateno = pParser->yytos->stateno;
  128727. if( stateno>=YY_MIN_REDUCE ) return stateno;
  128728. assert( stateno <= YY_SHIFT_COUNT );
  128729. do{
  128730. i = yy_shift_ofst[stateno];
  128731. assert( iLookAhead!=YYNOCODE );
  128732. i += iLookAhead;
  128733. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  128734. #ifdef YYFALLBACK
  128735. YYCODETYPE iFallback; /* Fallback token */
  128736. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  128737. && (iFallback = yyFallback[iLookAhead])!=0 ){
  128738. #ifndef NDEBUG
  128739. if( yyTraceFILE ){
  128740. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  128741. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  128742. }
  128743. #endif
  128744. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  128745. iLookAhead = iFallback;
  128746. continue;
  128747. }
  128748. #endif
  128749. #ifdef YYWILDCARD
  128750. {
  128751. int j = i - iLookAhead + YYWILDCARD;
  128752. if(
  128753. #if YY_SHIFT_MIN+YYWILDCARD<0
  128754. j>=0 &&
  128755. #endif
  128756. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  128757. j<YY_ACTTAB_COUNT &&
  128758. #endif
  128759. yy_lookahead[j]==YYWILDCARD && iLookAhead>0
  128760. ){
  128761. #ifndef NDEBUG
  128762. if( yyTraceFILE ){
  128763. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  128764. yyTracePrompt, yyTokenName[iLookAhead],
  128765. yyTokenName[YYWILDCARD]);
  128766. }
  128767. #endif /* NDEBUG */
  128768. return yy_action[j];
  128769. }
  128770. }
  128771. #endif /* YYWILDCARD */
  128772. return yy_default[stateno];
  128773. }else{
  128774. return yy_action[i];
  128775. }
  128776. }while(1);
  128777. }
  128778. /*
  128779. ** Find the appropriate action for a parser given the non-terminal
  128780. ** look-ahead token iLookAhead.
  128781. */
  128782. static int yy_find_reduce_action(
  128783. int stateno, /* Current state number */
  128784. YYCODETYPE iLookAhead /* The look-ahead token */
  128785. ){
  128786. int i;
  128787. #ifdef YYERRORSYMBOL
  128788. if( stateno>YY_REDUCE_COUNT ){
  128789. return yy_default[stateno];
  128790. }
  128791. #else
  128792. assert( stateno<=YY_REDUCE_COUNT );
  128793. #endif
  128794. i = yy_reduce_ofst[stateno];
  128795. assert( i!=YY_REDUCE_USE_DFLT );
  128796. assert( iLookAhead!=YYNOCODE );
  128797. i += iLookAhead;
  128798. #ifdef YYERRORSYMBOL
  128799. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  128800. return yy_default[stateno];
  128801. }
  128802. #else
  128803. assert( i>=0 && i<YY_ACTTAB_COUNT );
  128804. assert( yy_lookahead[i]==iLookAhead );
  128805. #endif
  128806. return yy_action[i];
  128807. }
  128808. /*
  128809. ** The following routine is called if the stack overflows.
  128810. */
  128811. static void yyStackOverflow(yyParser *yypParser){
  128812. sqlite3ParserARG_FETCH;
  128813. #ifndef NDEBUG
  128814. if( yyTraceFILE ){
  128815. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  128816. }
  128817. #endif
  128818. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  128819. /* Here code is inserted which will execute if the parser
  128820. ** stack every overflows */
  128821. /******** Begin %stack_overflow code ******************************************/
  128822. sqlite3ErrorMsg(pParse, "parser stack overflow");
  128823. /******** End %stack_overflow code ********************************************/
  128824. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  128825. }
  128826. /*
  128827. ** Print tracing information for a SHIFT action
  128828. */
  128829. #ifndef NDEBUG
  128830. static void yyTraceShift(yyParser *yypParser, int yyNewState){
  128831. if( yyTraceFILE ){
  128832. if( yyNewState<YYNSTATE ){
  128833. fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
  128834. yyTracePrompt,yyTokenName[yypParser->yytos->major],
  128835. yyNewState);
  128836. }else{
  128837. fprintf(yyTraceFILE,"%sShift '%s'\n",
  128838. yyTracePrompt,yyTokenName[yypParser->yytos->major]);
  128839. }
  128840. }
  128841. }
  128842. #else
  128843. # define yyTraceShift(X,Y)
  128844. #endif
  128845. /*
  128846. ** Perform a shift action.
  128847. */
  128848. static void yy_shift(
  128849. yyParser *yypParser, /* The parser to be shifted */
  128850. int yyNewState, /* The new state to shift in */
  128851. int yyMajor, /* The major token to shift in */
  128852. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  128853. ){
  128854. yyStackEntry *yytos;
  128855. yypParser->yytos++;
  128856. #ifdef YYTRACKMAXSTACKDEPTH
  128857. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  128858. yypParser->yyhwm++;
  128859. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
  128860. }
  128861. #endif
  128862. #if YYSTACKDEPTH>0
  128863. if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){
  128864. yypParser->yytos--;
  128865. yyStackOverflow(yypParser);
  128866. return;
  128867. }
  128868. #else
  128869. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
  128870. if( yyGrowStack(yypParser) ){
  128871. yypParser->yytos--;
  128872. yyStackOverflow(yypParser);
  128873. return;
  128874. }
  128875. }
  128876. #endif
  128877. if( yyNewState > YY_MAX_SHIFT ){
  128878. yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  128879. }
  128880. yytos = yypParser->yytos;
  128881. yytos->stateno = (YYACTIONTYPE)yyNewState;
  128882. yytos->major = (YYCODETYPE)yyMajor;
  128883. yytos->minor.yy0 = yyMinor;
  128884. yyTraceShift(yypParser, yyNewState);
  128885. }
  128886. /* The following table contains information about every rule that
  128887. ** is used during the reduce.
  128888. */
  128889. static const struct {
  128890. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  128891. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  128892. } yyRuleInfo[] = {
  128893. { 147, 1 },
  128894. { 147, 3 },
  128895. { 148, 1 },
  128896. { 149, 3 },
  128897. { 150, 0 },
  128898. { 150, 1 },
  128899. { 150, 1 },
  128900. { 150, 1 },
  128901. { 149, 2 },
  128902. { 149, 2 },
  128903. { 149, 2 },
  128904. { 149, 2 },
  128905. { 149, 3 },
  128906. { 149, 5 },
  128907. { 154, 6 },
  128908. { 156, 1 },
  128909. { 158, 0 },
  128910. { 158, 3 },
  128911. { 157, 1 },
  128912. { 157, 0 },
  128913. { 155, 5 },
  128914. { 155, 2 },
  128915. { 162, 0 },
  128916. { 162, 2 },
  128917. { 164, 2 },
  128918. { 166, 0 },
  128919. { 166, 4 },
  128920. { 166, 6 },
  128921. { 167, 2 },
  128922. { 171, 2 },
  128923. { 171, 2 },
  128924. { 171, 4 },
  128925. { 171, 3 },
  128926. { 171, 3 },
  128927. { 171, 2 },
  128928. { 171, 3 },
  128929. { 171, 5 },
  128930. { 171, 2 },
  128931. { 171, 4 },
  128932. { 171, 4 },
  128933. { 171, 1 },
  128934. { 171, 2 },
  128935. { 176, 0 },
  128936. { 176, 1 },
  128937. { 178, 0 },
  128938. { 178, 2 },
  128939. { 180, 2 },
  128940. { 180, 3 },
  128941. { 180, 3 },
  128942. { 180, 3 },
  128943. { 181, 2 },
  128944. { 181, 2 },
  128945. { 181, 1 },
  128946. { 181, 1 },
  128947. { 181, 2 },
  128948. { 179, 3 },
  128949. { 179, 2 },
  128950. { 182, 0 },
  128951. { 182, 2 },
  128952. { 182, 2 },
  128953. { 161, 0 },
  128954. { 184, 1 },
  128955. { 185, 2 },
  128956. { 185, 7 },
  128957. { 185, 5 },
  128958. { 185, 5 },
  128959. { 185, 10 },
  128960. { 188, 0 },
  128961. { 174, 0 },
  128962. { 174, 3 },
  128963. { 189, 0 },
  128964. { 189, 2 },
  128965. { 190, 1 },
  128966. { 190, 1 },
  128967. { 149, 4 },
  128968. { 192, 2 },
  128969. { 192, 0 },
  128970. { 149, 9 },
  128971. { 149, 4 },
  128972. { 149, 1 },
  128973. { 163, 2 },
  128974. { 194, 3 },
  128975. { 197, 1 },
  128976. { 197, 2 },
  128977. { 197, 1 },
  128978. { 195, 9 },
  128979. { 206, 4 },
  128980. { 206, 5 },
  128981. { 198, 1 },
  128982. { 198, 1 },
  128983. { 198, 0 },
  128984. { 209, 0 },
  128985. { 199, 3 },
  128986. { 199, 2 },
  128987. { 199, 4 },
  128988. { 210, 2 },
  128989. { 210, 0 },
  128990. { 200, 0 },
  128991. { 200, 2 },
  128992. { 212, 2 },
  128993. { 212, 0 },
  128994. { 211, 7 },
  128995. { 211, 9 },
  128996. { 211, 7 },
  128997. { 211, 7 },
  128998. { 159, 0 },
  128999. { 159, 2 },
  129000. { 193, 2 },
  129001. { 213, 1 },
  129002. { 213, 2 },
  129003. { 213, 3 },
  129004. { 213, 4 },
  129005. { 215, 2 },
  129006. { 215, 0 },
  129007. { 214, 0 },
  129008. { 214, 3 },
  129009. { 214, 2 },
  129010. { 216, 4 },
  129011. { 216, 0 },
  129012. { 204, 0 },
  129013. { 204, 3 },
  129014. { 186, 4 },
  129015. { 186, 2 },
  129016. { 175, 1 },
  129017. { 175, 1 },
  129018. { 175, 0 },
  129019. { 202, 0 },
  129020. { 202, 3 },
  129021. { 203, 0 },
  129022. { 203, 2 },
  129023. { 205, 0 },
  129024. { 205, 2 },
  129025. { 205, 4 },
  129026. { 205, 4 },
  129027. { 149, 6 },
  129028. { 201, 0 },
  129029. { 201, 2 },
  129030. { 149, 8 },
  129031. { 218, 5 },
  129032. { 218, 7 },
  129033. { 218, 3 },
  129034. { 218, 5 },
  129035. { 149, 6 },
  129036. { 149, 7 },
  129037. { 219, 2 },
  129038. { 219, 1 },
  129039. { 220, 0 },
  129040. { 220, 3 },
  129041. { 217, 3 },
  129042. { 217, 1 },
  129043. { 173, 3 },
  129044. { 172, 1 },
  129045. { 173, 1 },
  129046. { 173, 1 },
  129047. { 173, 3 },
  129048. { 173, 5 },
  129049. { 172, 1 },
  129050. { 172, 1 },
  129051. { 172, 1 },
  129052. { 173, 1 },
  129053. { 173, 3 },
  129054. { 173, 6 },
  129055. { 173, 5 },
  129056. { 173, 4 },
  129057. { 172, 1 },
  129058. { 173, 5 },
  129059. { 173, 3 },
  129060. { 173, 3 },
  129061. { 173, 3 },
  129062. { 173, 3 },
  129063. { 173, 3 },
  129064. { 173, 3 },
  129065. { 173, 3 },
  129066. { 173, 3 },
  129067. { 221, 2 },
  129068. { 173, 3 },
  129069. { 173, 5 },
  129070. { 173, 2 },
  129071. { 173, 3 },
  129072. { 173, 3 },
  129073. { 173, 4 },
  129074. { 173, 2 },
  129075. { 173, 2 },
  129076. { 173, 2 },
  129077. { 173, 2 },
  129078. { 222, 1 },
  129079. { 222, 2 },
  129080. { 173, 5 },
  129081. { 223, 1 },
  129082. { 223, 2 },
  129083. { 173, 5 },
  129084. { 173, 3 },
  129085. { 173, 5 },
  129086. { 173, 5 },
  129087. { 173, 4 },
  129088. { 173, 5 },
  129089. { 226, 5 },
  129090. { 226, 4 },
  129091. { 227, 2 },
  129092. { 227, 0 },
  129093. { 225, 1 },
  129094. { 225, 0 },
  129095. { 208, 0 },
  129096. { 207, 3 },
  129097. { 207, 1 },
  129098. { 224, 0 },
  129099. { 224, 3 },
  129100. { 149, 12 },
  129101. { 228, 1 },
  129102. { 228, 0 },
  129103. { 177, 0 },
  129104. { 177, 3 },
  129105. { 187, 5 },
  129106. { 187, 3 },
  129107. { 229, 0 },
  129108. { 229, 2 },
  129109. { 149, 4 },
  129110. { 149, 1 },
  129111. { 149, 2 },
  129112. { 149, 3 },
  129113. { 149, 5 },
  129114. { 149, 6 },
  129115. { 149, 5 },
  129116. { 149, 6 },
  129117. { 169, 2 },
  129118. { 170, 2 },
  129119. { 149, 5 },
  129120. { 231, 11 },
  129121. { 233, 1 },
  129122. { 233, 1 },
  129123. { 233, 2 },
  129124. { 233, 0 },
  129125. { 234, 1 },
  129126. { 234, 1 },
  129127. { 234, 3 },
  129128. { 236, 0 },
  129129. { 236, 2 },
  129130. { 232, 3 },
  129131. { 232, 2 },
  129132. { 238, 3 },
  129133. { 239, 3 },
  129134. { 239, 2 },
  129135. { 237, 7 },
  129136. { 237, 5 },
  129137. { 237, 5 },
  129138. { 237, 1 },
  129139. { 173, 4 },
  129140. { 173, 6 },
  129141. { 191, 1 },
  129142. { 191, 1 },
  129143. { 191, 1 },
  129144. { 149, 4 },
  129145. { 149, 6 },
  129146. { 149, 3 },
  129147. { 241, 0 },
  129148. { 241, 2 },
  129149. { 149, 1 },
  129150. { 149, 3 },
  129151. { 149, 1 },
  129152. { 149, 3 },
  129153. { 149, 6 },
  129154. { 149, 7 },
  129155. { 242, 1 },
  129156. { 149, 1 },
  129157. { 149, 4 },
  129158. { 244, 8 },
  129159. { 246, 0 },
  129160. { 247, 1 },
  129161. { 247, 3 },
  129162. { 248, 1 },
  129163. { 196, 0 },
  129164. { 196, 2 },
  129165. { 196, 3 },
  129166. { 250, 6 },
  129167. { 250, 8 },
  129168. { 144, 1 },
  129169. { 145, 2 },
  129170. { 145, 1 },
  129171. { 146, 1 },
  129172. { 146, 3 },
  129173. { 147, 0 },
  129174. { 151, 0 },
  129175. { 151, 1 },
  129176. { 151, 2 },
  129177. { 153, 1 },
  129178. { 153, 0 },
  129179. { 149, 2 },
  129180. { 160, 4 },
  129181. { 160, 2 },
  129182. { 152, 1 },
  129183. { 152, 1 },
  129184. { 152, 1 },
  129185. { 166, 1 },
  129186. { 167, 1 },
  129187. { 168, 1 },
  129188. { 168, 1 },
  129189. { 165, 2 },
  129190. { 165, 0 },
  129191. { 171, 2 },
  129192. { 161, 2 },
  129193. { 183, 3 },
  129194. { 183, 1 },
  129195. { 184, 0 },
  129196. { 188, 1 },
  129197. { 190, 1 },
  129198. { 194, 1 },
  129199. { 195, 1 },
  129200. { 209, 2 },
  129201. { 210, 1 },
  129202. { 173, 1 },
  129203. { 221, 1 },
  129204. { 208, 1 },
  129205. { 230, 1 },
  129206. { 230, 1 },
  129207. { 230, 1 },
  129208. { 230, 1 },
  129209. { 230, 1 },
  129210. { 169, 1 },
  129211. { 235, 0 },
  129212. { 235, 3 },
  129213. { 238, 1 },
  129214. { 239, 0 },
  129215. { 240, 1 },
  129216. { 240, 0 },
  129217. { 243, 0 },
  129218. { 243, 1 },
  129219. { 245, 1 },
  129220. { 245, 3 },
  129221. { 246, 2 },
  129222. { 249, 0 },
  129223. { 249, 4 },
  129224. { 249, 2 },
  129225. };
  129226. static void yy_accept(yyParser*); /* Forward Declaration */
  129227. /*
  129228. ** Perform a reduce action and the shift that must immediately
  129229. ** follow the reduce.
  129230. */
  129231. static void yy_reduce(
  129232. yyParser *yypParser, /* The parser */
  129233. unsigned int yyruleno /* Number of the rule by which to reduce */
  129234. ){
  129235. int yygoto; /* The next state */
  129236. int yyact; /* The next action */
  129237. yyStackEntry *yymsp; /* The top of the parser's stack */
  129238. int yysize; /* Amount to pop the stack */
  129239. sqlite3ParserARG_FETCH;
  129240. yymsp = yypParser->yytos;
  129241. #ifndef NDEBUG
  129242. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  129243. yysize = yyRuleInfo[yyruleno].nrhs;
  129244. fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
  129245. yyRuleName[yyruleno], yymsp[-yysize].stateno);
  129246. }
  129247. #endif /* NDEBUG */
  129248. /* Check that the stack is large enough to grow by a single entry
  129249. ** if the RHS of the rule is empty. This ensures that there is room
  129250. ** enough on the stack to push the LHS value */
  129251. if( yyRuleInfo[yyruleno].nrhs==0 ){
  129252. #ifdef YYTRACKMAXSTACKDEPTH
  129253. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  129254. yypParser->yyhwm++;
  129255. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
  129256. }
  129257. #endif
  129258. #if YYSTACKDEPTH>0
  129259. if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){
  129260. yyStackOverflow(yypParser);
  129261. return;
  129262. }
  129263. #else
  129264. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
  129265. if( yyGrowStack(yypParser) ){
  129266. yyStackOverflow(yypParser);
  129267. return;
  129268. }
  129269. yymsp = yypParser->yytos;
  129270. }
  129271. #endif
  129272. }
  129273. switch( yyruleno ){
  129274. /* Beginning here are the reduction cases. A typical example
  129275. ** follows:
  129276. ** case 0:
  129277. ** #line <lineno> <grammarfile>
  129278. ** { ... } // User supplied code
  129279. ** #line <lineno> <thisfile>
  129280. ** break;
  129281. */
  129282. /********** Begin reduce actions **********************************************/
  129283. YYMINORTYPE yylhsminor;
  129284. case 0: /* explain ::= EXPLAIN */
  129285. { pParse->explain = 1; }
  129286. break;
  129287. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  129288. { pParse->explain = 2; }
  129289. break;
  129290. case 2: /* cmdx ::= cmd */
  129291. { sqlite3FinishCoding(pParse); }
  129292. break;
  129293. case 3: /* cmd ::= BEGIN transtype trans_opt */
  129294. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
  129295. break;
  129296. case 4: /* transtype ::= */
  129297. {yymsp[1].minor.yy194 = TK_DEFERRED;}
  129298. break;
  129299. case 5: /* transtype ::= DEFERRED */
  129300. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  129301. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  129302. {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
  129303. break;
  129304. case 8: /* cmd ::= COMMIT trans_opt */
  129305. case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
  129306. {sqlite3CommitTransaction(pParse);}
  129307. break;
  129308. case 10: /* cmd ::= ROLLBACK trans_opt */
  129309. {sqlite3RollbackTransaction(pParse);}
  129310. break;
  129311. case 11: /* cmd ::= SAVEPOINT nm */
  129312. {
  129313. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  129314. }
  129315. break;
  129316. case 12: /* cmd ::= RELEASE savepoint_opt nm */
  129317. {
  129318. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  129319. }
  129320. break;
  129321. case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  129322. {
  129323. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  129324. }
  129325. break;
  129326. case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  129327. {
  129328. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
  129329. }
  129330. break;
  129331. case 15: /* createkw ::= CREATE */
  129332. {disableLookaside(pParse);}
  129333. break;
  129334. case 16: /* ifnotexists ::= */
  129335. case 19: /* temp ::= */ yytestcase(yyruleno==19);
  129336. case 22: /* table_options ::= */ yytestcase(yyruleno==22);
  129337. case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
  129338. case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
  129339. case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
  129340. case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
  129341. case 90: /* distinct ::= */ yytestcase(yyruleno==90);
  129342. case 214: /* collate ::= */ yytestcase(yyruleno==214);
  129343. {yymsp[1].minor.yy194 = 0;}
  129344. break;
  129345. case 17: /* ifnotexists ::= IF NOT EXISTS */
  129346. {yymsp[-2].minor.yy194 = 1;}
  129347. break;
  129348. case 18: /* temp ::= TEMP */
  129349. case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
  129350. {yymsp[0].minor.yy194 = 1;}
  129351. break;
  129352. case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  129353. {
  129354. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
  129355. }
  129356. break;
  129357. case 21: /* create_table_args ::= AS select */
  129358. {
  129359. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
  129360. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
  129361. }
  129362. break;
  129363. case 23: /* table_options ::= WITHOUT nm */
  129364. {
  129365. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  129366. yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
  129367. }else{
  129368. yymsp[-1].minor.yy194 = 0;
  129369. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  129370. }
  129371. }
  129372. break;
  129373. case 24: /* columnname ::= nm typetoken */
  129374. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  129375. break;
  129376. case 25: /* typetoken ::= */
  129377. case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
  129378. case 96: /* as ::= */ yytestcase(yyruleno==96);
  129379. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  129380. break;
  129381. case 26: /* typetoken ::= typename LP signed RP */
  129382. {
  129383. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  129384. }
  129385. break;
  129386. case 27: /* typetoken ::= typename LP signed COMMA signed RP */
  129387. {
  129388. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  129389. }
  129390. break;
  129391. case 28: /* typename ::= typename ID|STRING */
  129392. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  129393. break;
  129394. case 29: /* ccons ::= CONSTRAINT nm */
  129395. case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
  129396. {pParse->constraintName = yymsp[0].minor.yy0;}
  129397. break;
  129398. case 30: /* ccons ::= DEFAULT term */
  129399. case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
  129400. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
  129401. break;
  129402. case 31: /* ccons ::= DEFAULT LP expr RP */
  129403. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
  129404. break;
  129405. case 33: /* ccons ::= DEFAULT MINUS term */
  129406. {
  129407. ExprSpan v;
  129408. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0);
  129409. v.zStart = yymsp[-1].minor.yy0.z;
  129410. v.zEnd = yymsp[0].minor.yy190.zEnd;
  129411. sqlite3AddDefaultValue(pParse,&v);
  129412. }
  129413. break;
  129414. case 34: /* ccons ::= DEFAULT ID|INDEXED */
  129415. {
  129416. ExprSpan v;
  129417. spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
  129418. sqlite3AddDefaultValue(pParse,&v);
  129419. }
  129420. break;
  129421. case 35: /* ccons ::= NOT NULL onconf */
  129422. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
  129423. break;
  129424. case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  129425. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
  129426. break;
  129427. case 37: /* ccons ::= UNIQUE onconf */
  129428. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
  129429. SQLITE_IDXTYPE_UNIQUE);}
  129430. break;
  129431. case 38: /* ccons ::= CHECK LP expr RP */
  129432. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
  129433. break;
  129434. case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  129435. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
  129436. break;
  129437. case 40: /* ccons ::= defer_subclause */
  129438. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
  129439. break;
  129440. case 41: /* ccons ::= COLLATE ID|STRING */
  129441. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  129442. break;
  129443. case 44: /* refargs ::= */
  129444. { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
  129445. break;
  129446. case 45: /* refargs ::= refargs refarg */
  129447. { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
  129448. break;
  129449. case 46: /* refarg ::= MATCH nm */
  129450. { yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; }
  129451. break;
  129452. case 47: /* refarg ::= ON INSERT refact */
  129453. { yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; }
  129454. break;
  129455. case 48: /* refarg ::= ON DELETE refact */
  129456. { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; }
  129457. break;
  129458. case 49: /* refarg ::= ON UPDATE refact */
  129459. { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; }
  129460. break;
  129461. case 50: /* refact ::= SET NULL */
  129462. { yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */}
  129463. break;
  129464. case 51: /* refact ::= SET DEFAULT */
  129465. { yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */}
  129466. break;
  129467. case 52: /* refact ::= CASCADE */
  129468. { yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */}
  129469. break;
  129470. case 53: /* refact ::= RESTRICT */
  129471. { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
  129472. break;
  129473. case 54: /* refact ::= NO ACTION */
  129474. { yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */}
  129475. break;
  129476. case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  129477. {yymsp[-2].minor.yy194 = 0;}
  129478. break;
  129479. case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  129480. case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
  129481. case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144);
  129482. {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
  129483. break;
  129484. case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  129485. case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
  129486. case 186: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==186);
  129487. case 189: /* in_op ::= NOT IN */ yytestcase(yyruleno==189);
  129488. case 215: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==215);
  129489. {yymsp[-1].minor.yy194 = 1;}
  129490. break;
  129491. case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  129492. {yymsp[-1].minor.yy194 = 0;}
  129493. break;
  129494. case 61: /* tconscomma ::= COMMA */
  129495. {pParse->constraintName.n = 0;}
  129496. break;
  129497. case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  129498. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
  129499. break;
  129500. case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
  129501. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
  129502. SQLITE_IDXTYPE_UNIQUE);}
  129503. break;
  129504. case 65: /* tcons ::= CHECK LP expr RP onconf */
  129505. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
  129506. break;
  129507. case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  129508. {
  129509. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
  129510. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
  129511. }
  129512. break;
  129513. case 68: /* onconf ::= */
  129514. case 70: /* orconf ::= */ yytestcase(yyruleno==70);
  129515. {yymsp[1].minor.yy194 = OE_Default;}
  129516. break;
  129517. case 69: /* onconf ::= ON CONFLICT resolvetype */
  129518. {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
  129519. break;
  129520. case 72: /* resolvetype ::= IGNORE */
  129521. {yymsp[0].minor.yy194 = OE_Ignore;}
  129522. break;
  129523. case 73: /* resolvetype ::= REPLACE */
  129524. case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145);
  129525. {yymsp[0].minor.yy194 = OE_Replace;}
  129526. break;
  129527. case 74: /* cmd ::= DROP TABLE ifexists fullname */
  129528. {
  129529. sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
  129530. }
  129531. break;
  129532. case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  129533. {
  129534. 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);
  129535. }
  129536. break;
  129537. case 78: /* cmd ::= DROP VIEW ifexists fullname */
  129538. {
  129539. sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
  129540. }
  129541. break;
  129542. case 79: /* cmd ::= select */
  129543. {
  129544. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  129545. sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
  129546. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
  129547. }
  129548. break;
  129549. case 80: /* select ::= with selectnowith */
  129550. {
  129551. Select *p = yymsp[0].minor.yy243;
  129552. if( p ){
  129553. p->pWith = yymsp[-1].minor.yy285;
  129554. parserDoubleLinkSelect(pParse, p);
  129555. }else{
  129556. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
  129557. }
  129558. yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
  129559. }
  129560. break;
  129561. case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
  129562. {
  129563. Select *pRhs = yymsp[0].minor.yy243;
  129564. Select *pLhs = yymsp[-2].minor.yy243;
  129565. if( pRhs && pRhs->pPrior ){
  129566. SrcList *pFrom;
  129567. Token x;
  129568. x.n = 0;
  129569. parserDoubleLinkSelect(pParse, pRhs);
  129570. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  129571. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  129572. }
  129573. if( pRhs ){
  129574. pRhs->op = (u8)yymsp[-1].minor.yy194;
  129575. pRhs->pPrior = pLhs;
  129576. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  129577. pRhs->selFlags &= ~SF_MultiValue;
  129578. if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
  129579. }else{
  129580. sqlite3SelectDelete(pParse->db, pLhs);
  129581. }
  129582. yymsp[-2].minor.yy243 = pRhs;
  129583. }
  129584. break;
  129585. case 82: /* multiselect_op ::= UNION */
  129586. case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
  129587. {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
  129588. break;
  129589. case 83: /* multiselect_op ::= UNION ALL */
  129590. {yymsp[-1].minor.yy194 = TK_ALL;}
  129591. break;
  129592. case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  129593. {
  129594. #if SELECTTRACE_ENABLED
  129595. Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
  129596. #endif
  129597. 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);
  129598. #if SELECTTRACE_ENABLED
  129599. /* Populate the Select.zSelName[] string that is used to help with
  129600. ** query planner debugging, to differentiate between multiple Select
  129601. ** objects in a complex query.
  129602. **
  129603. ** If the SELECT keyword is immediately followed by a C-style comment
  129604. ** then extract the first few alphanumeric characters from within that
  129605. ** comment to be the zSelName value. Otherwise, the label is #N where
  129606. ** is an integer that is incremented with each SELECT statement seen.
  129607. */
  129608. if( yymsp[-8].minor.yy243!=0 ){
  129609. const char *z = s.z+6;
  129610. int i;
  129611. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
  129612. ++pParse->nSelect);
  129613. while( z[0]==' ' ) z++;
  129614. if( z[0]=='/' && z[1]=='*' ){
  129615. z += 2;
  129616. while( z[0]==' ' ) z++;
  129617. for(i=0; sqlite3Isalnum(z[i]); i++){}
  129618. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
  129619. }
  129620. }
  129621. #endif /* SELECTRACE_ENABLED */
  129622. }
  129623. break;
  129624. case 86: /* values ::= VALUES LP nexprlist RP */
  129625. {
  129626. yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
  129627. }
  129628. break;
  129629. case 87: /* values ::= values COMMA LP exprlist RP */
  129630. {
  129631. Select *pRight, *pLeft = yymsp[-4].minor.yy243;
  129632. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
  129633. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  129634. if( pRight ){
  129635. pRight->op = TK_ALL;
  129636. pRight->pPrior = pLeft;
  129637. yymsp[-4].minor.yy243 = pRight;
  129638. }else{
  129639. yymsp[-4].minor.yy243 = pLeft;
  129640. }
  129641. }
  129642. break;
  129643. case 88: /* distinct ::= DISTINCT */
  129644. {yymsp[0].minor.yy194 = SF_Distinct;}
  129645. break;
  129646. case 89: /* distinct ::= ALL */
  129647. {yymsp[0].minor.yy194 = SF_All;}
  129648. break;
  129649. case 91: /* sclp ::= */
  129650. case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
  129651. case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
  129652. case 202: /* exprlist ::= */ yytestcase(yyruleno==202);
  129653. case 205: /* paren_exprlist ::= */ yytestcase(yyruleno==205);
  129654. case 210: /* eidlist_opt ::= */ yytestcase(yyruleno==210);
  129655. {yymsp[1].minor.yy148 = 0;}
  129656. break;
  129657. case 92: /* selcollist ::= sclp expr as */
  129658. {
  129659. yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
  129660. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
  129661. sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
  129662. }
  129663. break;
  129664. case 93: /* selcollist ::= sclp STAR */
  129665. {
  129666. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  129667. yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
  129668. }
  129669. break;
  129670. case 94: /* selcollist ::= sclp nm DOT STAR */
  129671. {
  129672. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
  129673. Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  129674. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  129675. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
  129676. }
  129677. break;
  129678. case 95: /* as ::= AS nm */
  129679. case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
  129680. case 224: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==224);
  129681. case 225: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==225);
  129682. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  129683. break;
  129684. case 97: /* from ::= */
  129685. {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
  129686. break;
  129687. case 98: /* from ::= FROM seltablist */
  129688. {
  129689. yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
  129690. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
  129691. }
  129692. break;
  129693. case 99: /* stl_prefix ::= seltablist joinop */
  129694. {
  129695. 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;
  129696. }
  129697. break;
  129698. case 100: /* stl_prefix ::= */
  129699. {yymsp[1].minor.yy185 = 0;}
  129700. break;
  129701. case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  129702. {
  129703. 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);
  129704. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
  129705. }
  129706. break;
  129707. case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  129708. {
  129709. 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);
  129710. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
  129711. }
  129712. break;
  129713. case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  129714. {
  129715. 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);
  129716. }
  129717. break;
  129718. case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  129719. {
  129720. if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
  129721. yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
  129722. }else if( yymsp[-4].minor.yy185->nSrc==1 ){
  129723. 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);
  129724. if( yymsp[-6].minor.yy185 ){
  129725. struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
  129726. struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
  129727. pNew->zName = pOld->zName;
  129728. pNew->zDatabase = pOld->zDatabase;
  129729. pNew->pSelect = pOld->pSelect;
  129730. pOld->zName = pOld->zDatabase = 0;
  129731. pOld->pSelect = 0;
  129732. }
  129733. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
  129734. }else{
  129735. Select *pSubquery;
  129736. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
  129737. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
  129738. 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);
  129739. }
  129740. }
  129741. break;
  129742. case 105: /* dbnm ::= */
  129743. case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
  129744. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  129745. break;
  129746. case 107: /* fullname ::= nm dbnm */
  129747. {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  129748. break;
  129749. case 108: /* joinop ::= COMMA|JOIN */
  129750. { yymsp[0].minor.yy194 = JT_INNER; }
  129751. break;
  129752. case 109: /* joinop ::= JOIN_KW JOIN */
  129753. {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  129754. break;
  129755. case 110: /* joinop ::= JOIN_KW nm JOIN */
  129756. {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  129757. break;
  129758. case 111: /* joinop ::= JOIN_KW nm nm JOIN */
  129759. {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  129760. break;
  129761. case 112: /* on_opt ::= ON expr */
  129762. case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
  129763. case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
  129764. case 198: /* case_else ::= ELSE expr */ yytestcase(yyruleno==198);
  129765. {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
  129766. break;
  129767. case 113: /* on_opt ::= */
  129768. case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
  129769. case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
  129770. case 199: /* case_else ::= */ yytestcase(yyruleno==199);
  129771. case 201: /* case_operand ::= */ yytestcase(yyruleno==201);
  129772. {yymsp[1].minor.yy72 = 0;}
  129773. break;
  129774. case 115: /* indexed_opt ::= INDEXED BY nm */
  129775. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  129776. break;
  129777. case 116: /* indexed_opt ::= NOT INDEXED */
  129778. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  129779. break;
  129780. case 117: /* using_opt ::= USING LP idlist RP */
  129781. {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
  129782. break;
  129783. case 118: /* using_opt ::= */
  129784. case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146);
  129785. {yymsp[1].minor.yy254 = 0;}
  129786. break;
  129787. case 120: /* orderby_opt ::= ORDER BY sortlist */
  129788. case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
  129789. {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
  129790. break;
  129791. case 121: /* sortlist ::= sortlist COMMA expr sortorder */
  129792. {
  129793. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
  129794. sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
  129795. }
  129796. break;
  129797. case 122: /* sortlist ::= expr sortorder */
  129798. {
  129799. yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
  129800. sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
  129801. }
  129802. break;
  129803. case 123: /* sortorder ::= ASC */
  129804. {yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
  129805. break;
  129806. case 124: /* sortorder ::= DESC */
  129807. {yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
  129808. break;
  129809. case 125: /* sortorder ::= */
  129810. {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
  129811. break;
  129812. case 130: /* limit_opt ::= */
  129813. {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
  129814. break;
  129815. case 131: /* limit_opt ::= LIMIT expr */
  129816. {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
  129817. break;
  129818. case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
  129819. {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
  129820. break;
  129821. case 133: /* limit_opt ::= LIMIT expr COMMA expr */
  129822. {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
  129823. break;
  129824. case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  129825. {
  129826. sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
  129827. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
  129828. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
  129829. }
  129830. break;
  129831. case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  129832. {
  129833. sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
  129834. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
  129835. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
  129836. sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
  129837. }
  129838. break;
  129839. case 138: /* setlist ::= setlist COMMA nm EQ expr */
  129840. {
  129841. yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
  129842. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
  129843. }
  129844. break;
  129845. case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
  129846. {
  129847. yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
  129848. }
  129849. break;
  129850. case 140: /* setlist ::= nm EQ expr */
  129851. {
  129852. yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
  129853. sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
  129854. }
  129855. yymsp[-2].minor.yy148 = yylhsminor.yy148;
  129856. break;
  129857. case 141: /* setlist ::= LP idlist RP EQ expr */
  129858. {
  129859. yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
  129860. }
  129861. break;
  129862. case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
  129863. {
  129864. sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
  129865. sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
  129866. }
  129867. break;
  129868. case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
  129869. {
  129870. sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
  129871. sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
  129872. }
  129873. break;
  129874. case 147: /* idlist_opt ::= LP idlist RP */
  129875. {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
  129876. break;
  129877. case 148: /* idlist ::= idlist COMMA nm */
  129878. {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
  129879. break;
  129880. case 149: /* idlist ::= nm */
  129881. {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  129882. break;
  129883. case 150: /* expr ::= LP expr RP */
  129884. {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;}
  129885. break;
  129886. case 151: /* term ::= NULL */
  129887. case 156: /* term ::= FLOAT|BLOB */ yytestcase(yyruleno==156);
  129888. case 157: /* term ::= STRING */ yytestcase(yyruleno==157);
  129889. {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
  129890. break;
  129891. case 152: /* expr ::= ID|INDEXED */
  129892. case 153: /* expr ::= JOIN_KW */ yytestcase(yyruleno==153);
  129893. {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  129894. break;
  129895. case 154: /* expr ::= nm DOT nm */
  129896. {
  129897. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  129898. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  129899. spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  129900. yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
  129901. }
  129902. break;
  129903. case 155: /* expr ::= nm DOT nm DOT nm */
  129904. {
  129905. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
  129906. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  129907. Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  129908. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  129909. spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  129910. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
  129911. }
  129912. break;
  129913. case 158: /* term ::= INTEGER */
  129914. {
  129915. yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  129916. yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z;
  129917. yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n;
  129918. if( yylhsminor.yy190.pExpr ) yylhsminor.yy190.pExpr->flags |= EP_Leaf|EP_Resolved;
  129919. }
  129920. yymsp[0].minor.yy190 = yylhsminor.yy190;
  129921. break;
  129922. case 159: /* expr ::= VARIABLE */
  129923. {
  129924. if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
  129925. u32 n = yymsp[0].minor.yy0.n;
  129926. spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
  129927. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n);
  129928. }else{
  129929. /* When doing a nested parse, one can include terms in an expression
  129930. ** that look like this: #1 #2 ... These terms refer to registers
  129931. ** in the virtual machine. #N is the N-th register. */
  129932. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  129933. assert( t.n>=2 );
  129934. spanSet(&yymsp[0].minor.yy190, &t, &t);
  129935. if( pParse->nested==0 ){
  129936. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  129937. yymsp[0].minor.yy190.pExpr = 0;
  129938. }else{
  129939. yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
  129940. if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
  129941. }
  129942. }
  129943. }
  129944. break;
  129945. case 160: /* expr ::= expr COLLATE ID|STRING */
  129946. {
  129947. yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
  129948. yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  129949. }
  129950. break;
  129951. case 161: /* expr ::= CAST LP expr AS typetoken RP */
  129952. {
  129953. spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  129954. yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  129955. sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0);
  129956. }
  129957. break;
  129958. case 162: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  129959. {
  129960. if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  129961. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  129962. }
  129963. yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
  129964. spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  129965. if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
  129966. yylhsminor.yy190.pExpr->flags |= EP_Distinct;
  129967. }
  129968. }
  129969. yymsp[-4].minor.yy190 = yylhsminor.yy190;
  129970. break;
  129971. case 163: /* expr ::= ID|INDEXED LP STAR RP */
  129972. {
  129973. yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  129974. spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  129975. }
  129976. yymsp[-3].minor.yy190 = yylhsminor.yy190;
  129977. break;
  129978. case 164: /* term ::= CTIME_KW */
  129979. {
  129980. yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  129981. spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  129982. }
  129983. yymsp[0].minor.yy190 = yylhsminor.yy190;
  129984. break;
  129985. case 165: /* expr ::= LP nexprlist COMMA expr RP */
  129986. {
  129987. ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr);
  129988. yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  129989. if( yylhsminor.yy190.pExpr ){
  129990. yylhsminor.yy190.pExpr->x.pList = pList;
  129991. spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
  129992. }else{
  129993. sqlite3ExprListDelete(pParse->db, pList);
  129994. }
  129995. }
  129996. yymsp[-4].minor.yy190 = yylhsminor.yy190;
  129997. break;
  129998. case 166: /* expr ::= expr AND expr */
  129999. case 167: /* expr ::= expr OR expr */ yytestcase(yyruleno==167);
  130000. case 168: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==168);
  130001. case 169: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==169);
  130002. case 170: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==170);
  130003. case 171: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==171);
  130004. case 172: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==172);
  130005. case 173: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==173);
  130006. {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
  130007. break;
  130008. case 174: /* likeop ::= NOT LIKE_KW|MATCH */
  130009. {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
  130010. break;
  130011. case 175: /* expr ::= expr likeop expr */
  130012. {
  130013. ExprList *pList;
  130014. int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  130015. yymsp[-1].minor.yy0.n &= 0x7fffffff;
  130016. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
  130017. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
  130018. yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
  130019. exprNot(pParse, bNot, &yymsp[-2].minor.yy190);
  130020. yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
  130021. if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
  130022. }
  130023. break;
  130024. case 176: /* expr ::= expr likeop expr ESCAPE expr */
  130025. {
  130026. ExprList *pList;
  130027. int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  130028. yymsp[-3].minor.yy0.n &= 0x7fffffff;
  130029. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
  130030. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
  130031. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
  130032. yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
  130033. exprNot(pParse, bNot, &yymsp[-4].minor.yy190);
  130034. yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
  130035. if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
  130036. }
  130037. break;
  130038. case 177: /* expr ::= expr ISNULL|NOTNULL */
  130039. {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
  130040. break;
  130041. case 178: /* expr ::= expr NOT NULL */
  130042. {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
  130043. break;
  130044. case 179: /* expr ::= expr IS expr */
  130045. {
  130046. spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
  130047. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
  130048. }
  130049. break;
  130050. case 180: /* expr ::= expr IS NOT expr */
  130051. {
  130052. spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
  130053. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
  130054. }
  130055. break;
  130056. case 181: /* expr ::= NOT expr */
  130057. case 182: /* expr ::= BITNOT expr */ yytestcase(yyruleno==182);
  130058. {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  130059. break;
  130060. case 183: /* expr ::= MINUS expr */
  130061. {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  130062. break;
  130063. case 184: /* expr ::= PLUS expr */
  130064. {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  130065. break;
  130066. case 185: /* between_op ::= BETWEEN */
  130067. case 188: /* in_op ::= IN */ yytestcase(yyruleno==188);
  130068. {yymsp[0].minor.yy194 = 0;}
  130069. break;
  130070. case 187: /* expr ::= expr between_op expr AND expr */
  130071. {
  130072. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
  130073. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
  130074. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0);
  130075. if( yymsp[-4].minor.yy190.pExpr ){
  130076. yymsp[-4].minor.yy190.pExpr->x.pList = pList;
  130077. }else{
  130078. sqlite3ExprListDelete(pParse->db, pList);
  130079. }
  130080. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  130081. yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
  130082. }
  130083. break;
  130084. case 190: /* expr ::= expr in_op LP exprlist RP */
  130085. {
  130086. if( yymsp[-1].minor.yy148==0 ){
  130087. /* Expressions of the form
  130088. **
  130089. ** expr1 IN ()
  130090. ** expr1 NOT IN ()
  130091. **
  130092. ** simplify to constants 0 (false) and 1 (true), respectively,
  130093. ** regardless of the value of expr1.
  130094. */
  130095. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
  130096. yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1);
  130097. }else if( yymsp[-1].minor.yy148->nExpr==1 ){
  130098. /* Expressions of the form:
  130099. **
  130100. ** expr1 IN (?1)
  130101. ** expr1 NOT IN (?2)
  130102. **
  130103. ** with exactly one value on the RHS can be simplified to something
  130104. ** like this:
  130105. **
  130106. ** expr1 == ?1
  130107. ** expr1 <> ?2
  130108. **
  130109. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  130110. ** so that it may not contribute to the computation of comparison
  130111. ** affinity or the collating sequence to use for comparison. Otherwise,
  130112. ** the semantics would be subtly different from IN or NOT IN.
  130113. */
  130114. Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
  130115. yymsp[-1].minor.yy148->a[0].pExpr = 0;
  130116. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
  130117. /* pRHS cannot be NULL because a malloc error would have been detected
  130118. ** before now and control would have never reached this point */
  130119. if( ALWAYS(pRHS) ){
  130120. pRHS->flags &= ~EP_Collate;
  130121. pRHS->flags |= EP_Generic;
  130122. }
  130123. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS);
  130124. }else{
  130125. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
  130126. if( yymsp[-4].minor.yy190.pExpr ){
  130127. yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
  130128. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
  130129. }else{
  130130. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
  130131. }
  130132. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  130133. }
  130134. yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  130135. }
  130136. break;
  130137. case 191: /* expr ::= LP select RP */
  130138. {
  130139. spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
  130140. yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  130141. sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
  130142. }
  130143. break;
  130144. case 192: /* expr ::= expr in_op LP select RP */
  130145. {
  130146. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
  130147. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
  130148. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  130149. yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  130150. }
  130151. break;
  130152. case 193: /* expr ::= expr in_op nm dbnm paren_exprlist */
  130153. {
  130154. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
  130155. Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  130156. if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
  130157. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
  130158. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
  130159. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  130160. 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];
  130161. }
  130162. break;
  130163. case 194: /* expr ::= EXISTS LP select RP */
  130164. {
  130165. Expr *p;
  130166. spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
  130167. p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
  130168. sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
  130169. }
  130170. break;
  130171. case 195: /* expr ::= CASE case_operand case_exprlist case_else END */
  130172. {
  130173. spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
  130174. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0);
  130175. if( yymsp[-4].minor.yy190.pExpr ){
  130176. 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;
  130177. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
  130178. }else{
  130179. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
  130180. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
  130181. }
  130182. }
  130183. break;
  130184. case 196: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  130185. {
  130186. yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
  130187. yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
  130188. }
  130189. break;
  130190. case 197: /* case_exprlist ::= WHEN expr THEN expr */
  130191. {
  130192. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
  130193. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
  130194. }
  130195. break;
  130196. case 200: /* case_operand ::= expr */
  130197. {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
  130198. break;
  130199. case 203: /* nexprlist ::= nexprlist COMMA expr */
  130200. {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
  130201. break;
  130202. case 204: /* nexprlist ::= expr */
  130203. {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
  130204. break;
  130205. case 206: /* paren_exprlist ::= LP exprlist RP */
  130206. case 211: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==211);
  130207. {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
  130208. break;
  130209. case 207: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  130210. {
  130211. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  130212. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
  130213. &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
  130214. }
  130215. break;
  130216. case 208: /* uniqueflag ::= UNIQUE */
  130217. case 249: /* raisetype ::= ABORT */ yytestcase(yyruleno==249);
  130218. {yymsp[0].minor.yy194 = OE_Abort;}
  130219. break;
  130220. case 209: /* uniqueflag ::= */
  130221. {yymsp[1].minor.yy194 = OE_None;}
  130222. break;
  130223. case 212: /* eidlist ::= eidlist COMMA nm collate sortorder */
  130224. {
  130225. yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
  130226. }
  130227. break;
  130228. case 213: /* eidlist ::= nm collate sortorder */
  130229. {
  130230. yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
  130231. }
  130232. break;
  130233. case 216: /* cmd ::= DROP INDEX ifexists fullname */
  130234. {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
  130235. break;
  130236. case 217: /* cmd ::= VACUUM */
  130237. {sqlite3Vacuum(pParse,0);}
  130238. break;
  130239. case 218: /* cmd ::= VACUUM nm */
  130240. {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
  130241. break;
  130242. case 219: /* cmd ::= PRAGMA nm dbnm */
  130243. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  130244. break;
  130245. case 220: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  130246. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  130247. break;
  130248. case 221: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  130249. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  130250. break;
  130251. case 222: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  130252. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  130253. break;
  130254. case 223: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  130255. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  130256. break;
  130257. case 226: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  130258. {
  130259. Token all;
  130260. all.z = yymsp[-3].minor.yy0.z;
  130261. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  130262. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
  130263. }
  130264. break;
  130265. case 227: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  130266. {
  130267. 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);
  130268. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  130269. }
  130270. break;
  130271. case 228: /* trigger_time ::= BEFORE */
  130272. { yymsp[0].minor.yy194 = TK_BEFORE; }
  130273. break;
  130274. case 229: /* trigger_time ::= AFTER */
  130275. { yymsp[0].minor.yy194 = TK_AFTER; }
  130276. break;
  130277. case 230: /* trigger_time ::= INSTEAD OF */
  130278. { yymsp[-1].minor.yy194 = TK_INSTEAD;}
  130279. break;
  130280. case 231: /* trigger_time ::= */
  130281. { yymsp[1].minor.yy194 = TK_BEFORE; }
  130282. break;
  130283. case 232: /* trigger_event ::= DELETE|INSERT */
  130284. case 233: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==233);
  130285. {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
  130286. break;
  130287. case 234: /* trigger_event ::= UPDATE OF idlist */
  130288. {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
  130289. break;
  130290. case 235: /* when_clause ::= */
  130291. case 254: /* key_opt ::= */ yytestcase(yyruleno==254);
  130292. { yymsp[1].minor.yy72 = 0; }
  130293. break;
  130294. case 236: /* when_clause ::= WHEN expr */
  130295. case 255: /* key_opt ::= KEY expr */ yytestcase(yyruleno==255);
  130296. { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
  130297. break;
  130298. case 237: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  130299. {
  130300. assert( yymsp[-2].minor.yy145!=0 );
  130301. yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
  130302. yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
  130303. }
  130304. break;
  130305. case 238: /* trigger_cmd_list ::= trigger_cmd SEMI */
  130306. {
  130307. assert( yymsp[-1].minor.yy145!=0 );
  130308. yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
  130309. }
  130310. break;
  130311. case 239: /* trnm ::= nm DOT nm */
  130312. {
  130313. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  130314. sqlite3ErrorMsg(pParse,
  130315. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  130316. "statements within triggers");
  130317. }
  130318. break;
  130319. case 240: /* tridxby ::= INDEXED BY nm */
  130320. {
  130321. sqlite3ErrorMsg(pParse,
  130322. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  130323. "within triggers");
  130324. }
  130325. break;
  130326. case 241: /* tridxby ::= NOT INDEXED */
  130327. {
  130328. sqlite3ErrorMsg(pParse,
  130329. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  130330. "within triggers");
  130331. }
  130332. break;
  130333. case 242: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  130334. {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
  130335. break;
  130336. case 243: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
  130337. {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*/}
  130338. break;
  130339. case 244: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  130340. {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
  130341. break;
  130342. case 245: /* trigger_cmd ::= select */
  130343. {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
  130344. break;
  130345. case 246: /* expr ::= RAISE LP IGNORE RP */
  130346. {
  130347. spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  130348. yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  130349. if( yymsp[-3].minor.yy190.pExpr ){
  130350. yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
  130351. }
  130352. }
  130353. break;
  130354. case 247: /* expr ::= RAISE LP raisetype COMMA nm RP */
  130355. {
  130356. spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  130357. yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  130358. if( yymsp[-5].minor.yy190.pExpr ) {
  130359. yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
  130360. }
  130361. }
  130362. break;
  130363. case 248: /* raisetype ::= ROLLBACK */
  130364. {yymsp[0].minor.yy194 = OE_Rollback;}
  130365. break;
  130366. case 250: /* raisetype ::= FAIL */
  130367. {yymsp[0].minor.yy194 = OE_Fail;}
  130368. break;
  130369. case 251: /* cmd ::= DROP TRIGGER ifexists fullname */
  130370. {
  130371. sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
  130372. }
  130373. break;
  130374. case 252: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  130375. {
  130376. sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
  130377. }
  130378. break;
  130379. case 253: /* cmd ::= DETACH database_kw_opt expr */
  130380. {
  130381. sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
  130382. }
  130383. break;
  130384. case 256: /* cmd ::= REINDEX */
  130385. {sqlite3Reindex(pParse, 0, 0);}
  130386. break;
  130387. case 257: /* cmd ::= REINDEX nm dbnm */
  130388. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  130389. break;
  130390. case 258: /* cmd ::= ANALYZE */
  130391. {sqlite3Analyze(pParse, 0, 0);}
  130392. break;
  130393. case 259: /* cmd ::= ANALYZE nm dbnm */
  130394. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  130395. break;
  130396. case 260: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  130397. {
  130398. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
  130399. }
  130400. break;
  130401. case 261: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  130402. {
  130403. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  130404. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  130405. }
  130406. break;
  130407. case 262: /* add_column_fullname ::= fullname */
  130408. {
  130409. disableLookaside(pParse);
  130410. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
  130411. }
  130412. break;
  130413. case 263: /* cmd ::= create_vtab */
  130414. {sqlite3VtabFinishParse(pParse,0);}
  130415. break;
  130416. case 264: /* cmd ::= create_vtab LP vtabarglist RP */
  130417. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  130418. break;
  130419. case 265: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  130420. {
  130421. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
  130422. }
  130423. break;
  130424. case 266: /* vtabarg ::= */
  130425. {sqlite3VtabArgInit(pParse);}
  130426. break;
  130427. case 267: /* vtabargtoken ::= ANY */
  130428. case 268: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==268);
  130429. case 269: /* lp ::= LP */ yytestcase(yyruleno==269);
  130430. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  130431. break;
  130432. case 270: /* with ::= */
  130433. {yymsp[1].minor.yy285 = 0;}
  130434. break;
  130435. case 271: /* with ::= WITH wqlist */
  130436. { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
  130437. break;
  130438. case 272: /* with ::= WITH RECURSIVE wqlist */
  130439. { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
  130440. break;
  130441. case 273: /* wqlist ::= nm eidlist_opt AS LP select RP */
  130442. {
  130443. yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
  130444. }
  130445. break;
  130446. case 274: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  130447. {
  130448. yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
  130449. }
  130450. break;
  130451. default:
  130452. /* (275) input ::= cmdlist */ yytestcase(yyruleno==275);
  130453. /* (276) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==276);
  130454. /* (277) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=277);
  130455. /* (278) ecmd ::= SEMI */ yytestcase(yyruleno==278);
  130456. /* (279) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==279);
  130457. /* (280) explain ::= */ yytestcase(yyruleno==280);
  130458. /* (281) trans_opt ::= */ yytestcase(yyruleno==281);
  130459. /* (282) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==282);
  130460. /* (283) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==283);
  130461. /* (284) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==284);
  130462. /* (285) savepoint_opt ::= */ yytestcase(yyruleno==285);
  130463. /* (286) cmd ::= create_table create_table_args */ yytestcase(yyruleno==286);
  130464. /* (287) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==287);
  130465. /* (288) columnlist ::= columnname carglist */ yytestcase(yyruleno==288);
  130466. /* (289) nm ::= ID|INDEXED */ yytestcase(yyruleno==289);
  130467. /* (290) nm ::= STRING */ yytestcase(yyruleno==290);
  130468. /* (291) nm ::= JOIN_KW */ yytestcase(yyruleno==291);
  130469. /* (292) typetoken ::= typename */ yytestcase(yyruleno==292);
  130470. /* (293) typename ::= ID|STRING */ yytestcase(yyruleno==293);
  130471. /* (294) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=294);
  130472. /* (295) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=295);
  130473. /* (296) carglist ::= carglist ccons */ yytestcase(yyruleno==296);
  130474. /* (297) carglist ::= */ yytestcase(yyruleno==297);
  130475. /* (298) ccons ::= NULL onconf */ yytestcase(yyruleno==298);
  130476. /* (299) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==299);
  130477. /* (300) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==300);
  130478. /* (301) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=301);
  130479. /* (302) tconscomma ::= */ yytestcase(yyruleno==302);
  130480. /* (303) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=303);
  130481. /* (304) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=304);
  130482. /* (305) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=305);
  130483. /* (306) oneselect ::= values */ yytestcase(yyruleno==306);
  130484. /* (307) sclp ::= selcollist COMMA */ yytestcase(yyruleno==307);
  130485. /* (308) as ::= ID|STRING */ yytestcase(yyruleno==308);
  130486. /* (309) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=309);
  130487. /* (310) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==310);
  130488. /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311);
  130489. /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312);
  130490. /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313);
  130491. /* (314) nmnum ::= ON */ yytestcase(yyruleno==314);
  130492. /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315);
  130493. /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316);
  130494. /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317);
  130495. /* (318) foreach_clause ::= */ yytestcase(yyruleno==318);
  130496. /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319);
  130497. /* (320) trnm ::= nm */ yytestcase(yyruleno==320);
  130498. /* (321) tridxby ::= */ yytestcase(yyruleno==321);
  130499. /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322);
  130500. /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323);
  130501. /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324);
  130502. /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325);
  130503. /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326);
  130504. /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327);
  130505. /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328);
  130506. /* (329) anylist ::= */ yytestcase(yyruleno==329);
  130507. /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330);
  130508. /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331);
  130509. break;
  130510. /********** End reduce actions ************************************************/
  130511. };
  130512. assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  130513. yygoto = yyRuleInfo[yyruleno].lhs;
  130514. yysize = yyRuleInfo[yyruleno].nrhs;
  130515. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  130516. if( yyact <= YY_MAX_SHIFTREDUCE ){
  130517. if( yyact>YY_MAX_SHIFT ){
  130518. yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  130519. }
  130520. yymsp -= yysize-1;
  130521. yypParser->yytos = yymsp;
  130522. yymsp->stateno = (YYACTIONTYPE)yyact;
  130523. yymsp->major = (YYCODETYPE)yygoto;
  130524. yyTraceShift(yypParser, yyact);
  130525. }else{
  130526. assert( yyact == YY_ACCEPT_ACTION );
  130527. yypParser->yytos -= yysize;
  130528. yy_accept(yypParser);
  130529. }
  130530. }
  130531. /*
  130532. ** The following code executes when the parse fails
  130533. */
  130534. #ifndef YYNOERRORRECOVERY
  130535. static void yy_parse_failed(
  130536. yyParser *yypParser /* The parser */
  130537. ){
  130538. sqlite3ParserARG_FETCH;
  130539. #ifndef NDEBUG
  130540. if( yyTraceFILE ){
  130541. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  130542. }
  130543. #endif
  130544. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  130545. /* Here code is inserted which will be executed whenever the
  130546. ** parser fails */
  130547. /************ Begin %parse_failure code ***************************************/
  130548. /************ End %parse_failure code *****************************************/
  130549. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  130550. }
  130551. #endif /* YYNOERRORRECOVERY */
  130552. /*
  130553. ** The following code executes when a syntax error first occurs.
  130554. */
  130555. static void yy_syntax_error(
  130556. yyParser *yypParser, /* The parser */
  130557. int yymajor, /* The major type of the error token */
  130558. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  130559. ){
  130560. sqlite3ParserARG_FETCH;
  130561. #define TOKEN yyminor
  130562. /************ Begin %syntax_error code ****************************************/
  130563. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  130564. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  130565. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  130566. /************ End %syntax_error code ******************************************/
  130567. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  130568. }
  130569. /*
  130570. ** The following is executed when the parser accepts
  130571. */
  130572. static void yy_accept(
  130573. yyParser *yypParser /* The parser */
  130574. ){
  130575. sqlite3ParserARG_FETCH;
  130576. #ifndef NDEBUG
  130577. if( yyTraceFILE ){
  130578. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  130579. }
  130580. #endif
  130581. #ifndef YYNOERRORRECOVERY
  130582. yypParser->yyerrcnt = -1;
  130583. #endif
  130584. assert( yypParser->yytos==yypParser->yystack );
  130585. /* Here code is inserted which will be executed whenever the
  130586. ** parser accepts */
  130587. /*********** Begin %parse_accept code *****************************************/
  130588. /*********** End %parse_accept code *******************************************/
  130589. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  130590. }
  130591. /* The main parser program.
  130592. ** The first argument is a pointer to a structure obtained from
  130593. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  130594. ** The second argument is the major token number. The third is
  130595. ** the minor token. The fourth optional argument is whatever the
  130596. ** user wants (and specified in the grammar) and is available for
  130597. ** use by the action routines.
  130598. **
  130599. ** Inputs:
  130600. ** <ul>
  130601. ** <li> A pointer to the parser (an opaque structure.)
  130602. ** <li> The major token number.
  130603. ** <li> The minor token number.
  130604. ** <li> An option argument of a grammar-specified type.
  130605. ** </ul>
  130606. **
  130607. ** Outputs:
  130608. ** None.
  130609. */
  130610. SQLITE_PRIVATE void sqlite3Parser(
  130611. void *yyp, /* The parser */
  130612. int yymajor, /* The major token code number */
  130613. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  130614. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  130615. ){
  130616. YYMINORTYPE yyminorunion;
  130617. unsigned int yyact; /* The parser action. */
  130618. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  130619. int yyendofinput; /* True if we are at the end of input */
  130620. #endif
  130621. #ifdef YYERRORSYMBOL
  130622. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  130623. #endif
  130624. yyParser *yypParser; /* The parser */
  130625. yypParser = (yyParser*)yyp;
  130626. assert( yypParser->yytos!=0 );
  130627. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  130628. yyendofinput = (yymajor==0);
  130629. #endif
  130630. sqlite3ParserARG_STORE;
  130631. #ifndef NDEBUG
  130632. if( yyTraceFILE ){
  130633. fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
  130634. }
  130635. #endif
  130636. do{
  130637. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  130638. if( yyact <= YY_MAX_SHIFTREDUCE ){
  130639. yy_shift(yypParser,yyact,yymajor,yyminor);
  130640. #ifndef YYNOERRORRECOVERY
  130641. yypParser->yyerrcnt--;
  130642. #endif
  130643. yymajor = YYNOCODE;
  130644. }else if( yyact <= YY_MAX_REDUCE ){
  130645. yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
  130646. }else{
  130647. assert( yyact == YY_ERROR_ACTION );
  130648. yyminorunion.yy0 = yyminor;
  130649. #ifdef YYERRORSYMBOL
  130650. int yymx;
  130651. #endif
  130652. #ifndef NDEBUG
  130653. if( yyTraceFILE ){
  130654. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  130655. }
  130656. #endif
  130657. #ifdef YYERRORSYMBOL
  130658. /* A syntax error has occurred.
  130659. ** The response to an error depends upon whether or not the
  130660. ** grammar defines an error token "ERROR".
  130661. **
  130662. ** This is what we do if the grammar does define ERROR:
  130663. **
  130664. ** * Call the %syntax_error function.
  130665. **
  130666. ** * Begin popping the stack until we enter a state where
  130667. ** it is legal to shift the error symbol, then shift
  130668. ** the error symbol.
  130669. **
  130670. ** * Set the error count to three.
  130671. **
  130672. ** * Begin accepting and shifting new tokens. No new error
  130673. ** processing will occur until three tokens have been
  130674. ** shifted successfully.
  130675. **
  130676. */
  130677. if( yypParser->yyerrcnt<0 ){
  130678. yy_syntax_error(yypParser,yymajor,yyminor);
  130679. }
  130680. yymx = yypParser->yytos->major;
  130681. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  130682. #ifndef NDEBUG
  130683. if( yyTraceFILE ){
  130684. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  130685. yyTracePrompt,yyTokenName[yymajor]);
  130686. }
  130687. #endif
  130688. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  130689. yymajor = YYNOCODE;
  130690. }else{
  130691. while( yypParser->yytos >= yypParser->yystack
  130692. && yymx != YYERRORSYMBOL
  130693. && (yyact = yy_find_reduce_action(
  130694. yypParser->yytos->stateno,
  130695. YYERRORSYMBOL)) >= YY_MIN_REDUCE
  130696. ){
  130697. yy_pop_parser_stack(yypParser);
  130698. }
  130699. if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
  130700. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  130701. yy_parse_failed(yypParser);
  130702. #ifndef YYNOERRORRECOVERY
  130703. yypParser->yyerrcnt = -1;
  130704. #endif
  130705. yymajor = YYNOCODE;
  130706. }else if( yymx!=YYERRORSYMBOL ){
  130707. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  130708. }
  130709. }
  130710. yypParser->yyerrcnt = 3;
  130711. yyerrorhit = 1;
  130712. #elif defined(YYNOERRORRECOVERY)
  130713. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  130714. ** do any kind of error recovery. Instead, simply invoke the syntax
  130715. ** error routine and continue going as if nothing had happened.
  130716. **
  130717. ** Applications can set this macro (for example inside %include) if
  130718. ** they intend to abandon the parse upon the first syntax error seen.
  130719. */
  130720. yy_syntax_error(yypParser,yymajor, yyminor);
  130721. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  130722. yymajor = YYNOCODE;
  130723. #else /* YYERRORSYMBOL is not defined */
  130724. /* This is what we do if the grammar does not define ERROR:
  130725. **
  130726. ** * Report an error message, and throw away the input token.
  130727. **
  130728. ** * If the input token is $, then fail the parse.
  130729. **
  130730. ** As before, subsequent error messages are suppressed until
  130731. ** three input tokens have been successfully shifted.
  130732. */
  130733. if( yypParser->yyerrcnt<=0 ){
  130734. yy_syntax_error(yypParser,yymajor, yyminor);
  130735. }
  130736. yypParser->yyerrcnt = 3;
  130737. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  130738. if( yyendofinput ){
  130739. yy_parse_failed(yypParser);
  130740. #ifndef YYNOERRORRECOVERY
  130741. yypParser->yyerrcnt = -1;
  130742. #endif
  130743. }
  130744. yymajor = YYNOCODE;
  130745. #endif
  130746. }
  130747. }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
  130748. #ifndef NDEBUG
  130749. if( yyTraceFILE ){
  130750. yyStackEntry *i;
  130751. char cDiv = '[';
  130752. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  130753. for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
  130754. fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
  130755. cDiv = ' ';
  130756. }
  130757. fprintf(yyTraceFILE,"]\n");
  130758. }
  130759. #endif
  130760. return;
  130761. }
  130762. /************** End of parse.c ***********************************************/
  130763. /************** Begin file tokenize.c ****************************************/
  130764. /*
  130765. ** 2001 September 15
  130766. **
  130767. ** The author disclaims copyright to this source code. In place of
  130768. ** a legal notice, here is a blessing:
  130769. **
  130770. ** May you do good and not evil.
  130771. ** May you find forgiveness for yourself and forgive others.
  130772. ** May you share freely, never taking more than you give.
  130773. **
  130774. *************************************************************************
  130775. ** An tokenizer for SQL
  130776. **
  130777. ** This file contains C code that splits an SQL input string up into
  130778. ** individual tokens and sends those tokens one-by-one over to the
  130779. ** parser for analysis.
  130780. */
  130781. /* #include "sqliteInt.h" */
  130782. /* #include <stdlib.h> */
  130783. /* Character classes for tokenizing
  130784. **
  130785. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  130786. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  130787. ** The lookup table is much faster. To maximize speed, and to ensure that
  130788. ** a lookup table is used, all of the classes need to be small integers and
  130789. ** all of them need to be used within the switch.
  130790. */
  130791. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  130792. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  130793. #define CC_ID 2 /* unicode characters usable in IDs */
  130794. #define CC_DIGIT 3 /* Digits */
  130795. #define CC_DOLLAR 4 /* '$' */
  130796. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  130797. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  130798. #define CC_SPACE 7 /* Space characters */
  130799. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  130800. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  130801. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  130802. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  130803. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  130804. #define CC_GT 13 /* '>'. Part of > or >= */
  130805. #define CC_EQ 14 /* '='. Part of = or == */
  130806. #define CC_BANG 15 /* '!'. Part of != */
  130807. #define CC_SLASH 16 /* '/'. / or c-style comment */
  130808. #define CC_LP 17 /* '(' */
  130809. #define CC_RP 18 /* ')' */
  130810. #define CC_SEMI 19 /* ';' */
  130811. #define CC_PLUS 20 /* '+' */
  130812. #define CC_STAR 21 /* '*' */
  130813. #define CC_PERCENT 22 /* '%' */
  130814. #define CC_COMMA 23 /* ',' */
  130815. #define CC_AND 24 /* '&' */
  130816. #define CC_TILDA 25 /* '~' */
  130817. #define CC_DOT 26 /* '.' */
  130818. #define CC_ILLEGAL 27 /* Illegal character */
  130819. static const unsigned char aiClass[] = {
  130820. #ifdef SQLITE_ASCII
  130821. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  130822. /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  130823. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  130824. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  130825. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  130826. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  130827. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  130828. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  130829. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  130830. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130831. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130832. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130833. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130834. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130835. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130836. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130837. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  130838. #endif
  130839. #ifdef SQLITE_EBCDIC
  130840. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  130841. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  130842. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  130843. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  130844. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  130845. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
  130846. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  130847. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
  130848. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  130849. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  130850. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  130851. /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  130852. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  130853. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  130854. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  130855. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  130856. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  130857. #endif
  130858. };
  130859. /*
  130860. ** The charMap() macro maps alphabetic characters (only) into their
  130861. ** lower-case ASCII equivalent. On ASCII machines, this is just
  130862. ** an upper-to-lower case map. On EBCDIC machines we also need
  130863. ** to adjust the encoding. The mapping is only valid for alphabetics
  130864. ** which are the only characters for which this feature is used.
  130865. **
  130866. ** Used by keywordhash.h
  130867. */
  130868. #ifdef SQLITE_ASCII
  130869. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  130870. #endif
  130871. #ifdef SQLITE_EBCDIC
  130872. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  130873. const unsigned char ebcdicToAscii[] = {
  130874. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  130875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  130876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  130877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  130878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  130879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  130880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  130881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  130882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  130883. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  130884. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  130885. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  130886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  130887. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  130888. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  130889. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  130890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  130891. };
  130892. #endif
  130893. /*
  130894. ** The sqlite3KeywordCode function looks up an identifier to determine if
  130895. ** it is a keyword. If it is a keyword, the token code of that keyword is
  130896. ** returned. If the input is not a keyword, TK_ID is returned.
  130897. **
  130898. ** The implementation of this routine was generated by a program,
  130899. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  130900. ** The output of the mkkeywordhash.c program is written into a file
  130901. ** named keywordhash.h and then included into this source file by
  130902. ** the #include below.
  130903. */
  130904. /************** Include keywordhash.h in the middle of tokenize.c ************/
  130905. /************** Begin file keywordhash.h *************************************/
  130906. /***** This file contains automatically generated code ******
  130907. **
  130908. ** The code in this file has been automatically generated by
  130909. **
  130910. ** sqlite/tool/mkkeywordhash.c
  130911. **
  130912. ** The code in this file implements a function that determines whether
  130913. ** or not a given identifier is really an SQL keyword. The same thing
  130914. ** might be implemented more directly using a hand-written hash table.
  130915. ** But by using this automatically generated code, the size of the code
  130916. ** is substantially reduced. This is important for embedded applications
  130917. ** on platforms with limited memory.
  130918. */
  130919. /* Hash score: 182 */
  130920. static int keywordCode(const char *z, int n, int *pType){
  130921. /* zText[] encodes 834 bytes of keywords in 554 bytes */
  130922. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  130923. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  130924. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  130925. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  130926. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  130927. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  130928. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  130929. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  130930. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  130931. /* VACUUMVIEWINITIALLY */
  130932. static const char zText[553] = {
  130933. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  130934. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  130935. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  130936. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  130937. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  130938. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  130939. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  130940. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  130941. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  130942. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  130943. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  130944. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  130945. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  130946. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  130947. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  130948. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  130949. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  130950. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  130951. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  130952. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  130953. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  130954. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  130955. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  130956. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  130957. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  130958. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  130959. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  130960. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  130961. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  130962. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  130963. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  130964. };
  130965. static const unsigned char aHash[127] = {
  130966. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  130967. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  130968. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  130969. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  130970. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  130971. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  130972. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  130973. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  130974. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  130975. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  130976. };
  130977. static const unsigned char aNext[124] = {
  130978. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  130980. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  130982. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  130983. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  130984. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  130985. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  130986. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  130987. 73, 83, 0, 35, 68, 0, 0,
  130988. };
  130989. static const unsigned char aLen[124] = {
  130990. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  130991. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  130992. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  130993. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  130994. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  130995. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  130996. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  130997. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  130998. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  130999. 3, 5, 5, 6, 4, 9, 3,
  131000. };
  131001. static const unsigned short int aOffset[124] = {
  131002. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  131003. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  131004. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  131005. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  131006. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  131007. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  131008. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  131009. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  131010. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  131011. 521, 524, 529, 534, 540, 544, 549,
  131012. };
  131013. static const unsigned char aCode[124] = {
  131014. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  131015. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  131016. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  131017. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  131018. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  131019. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  131020. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  131021. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  131022. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  131023. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  131024. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  131025. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  131026. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  131027. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  131028. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  131029. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  131030. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  131031. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  131032. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  131033. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  131034. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  131035. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  131036. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  131037. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  131038. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  131039. };
  131040. int i, j;
  131041. const char *zKW;
  131042. if( n>=2 ){
  131043. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  131044. for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
  131045. if( aLen[i]!=n ) continue;
  131046. j = 0;
  131047. zKW = &zText[aOffset[i]];
  131048. #ifdef SQLITE_ASCII
  131049. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  131050. #endif
  131051. #ifdef SQLITE_EBCDIC
  131052. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  131053. #endif
  131054. if( j<n ) continue;
  131055. testcase( i==0 ); /* REINDEX */
  131056. testcase( i==1 ); /* INDEXED */
  131057. testcase( i==2 ); /* INDEX */
  131058. testcase( i==3 ); /* DESC */
  131059. testcase( i==4 ); /* ESCAPE */
  131060. testcase( i==5 ); /* EACH */
  131061. testcase( i==6 ); /* CHECK */
  131062. testcase( i==7 ); /* KEY */
  131063. testcase( i==8 ); /* BEFORE */
  131064. testcase( i==9 ); /* FOREIGN */
  131065. testcase( i==10 ); /* FOR */
  131066. testcase( i==11 ); /* IGNORE */
  131067. testcase( i==12 ); /* REGEXP */
  131068. testcase( i==13 ); /* EXPLAIN */
  131069. testcase( i==14 ); /* INSTEAD */
  131070. testcase( i==15 ); /* ADD */
  131071. testcase( i==16 ); /* DATABASE */
  131072. testcase( i==17 ); /* AS */
  131073. testcase( i==18 ); /* SELECT */
  131074. testcase( i==19 ); /* TABLE */
  131075. testcase( i==20 ); /* LEFT */
  131076. testcase( i==21 ); /* THEN */
  131077. testcase( i==22 ); /* END */
  131078. testcase( i==23 ); /* DEFERRABLE */
  131079. testcase( i==24 ); /* ELSE */
  131080. testcase( i==25 ); /* EXCEPT */
  131081. testcase( i==26 ); /* TRANSACTION */
  131082. testcase( i==27 ); /* ACTION */
  131083. testcase( i==28 ); /* ON */
  131084. testcase( i==29 ); /* NATURAL */
  131085. testcase( i==30 ); /* ALTER */
  131086. testcase( i==31 ); /* RAISE */
  131087. testcase( i==32 ); /* EXCLUSIVE */
  131088. testcase( i==33 ); /* EXISTS */
  131089. testcase( i==34 ); /* SAVEPOINT */
  131090. testcase( i==35 ); /* INTERSECT */
  131091. testcase( i==36 ); /* TRIGGER */
  131092. testcase( i==37 ); /* REFERENCES */
  131093. testcase( i==38 ); /* CONSTRAINT */
  131094. testcase( i==39 ); /* INTO */
  131095. testcase( i==40 ); /* OFFSET */
  131096. testcase( i==41 ); /* OF */
  131097. testcase( i==42 ); /* SET */
  131098. testcase( i==43 ); /* TEMPORARY */
  131099. testcase( i==44 ); /* TEMP */
  131100. testcase( i==45 ); /* OR */
  131101. testcase( i==46 ); /* UNIQUE */
  131102. testcase( i==47 ); /* QUERY */
  131103. testcase( i==48 ); /* WITHOUT */
  131104. testcase( i==49 ); /* WITH */
  131105. testcase( i==50 ); /* OUTER */
  131106. testcase( i==51 ); /* RELEASE */
  131107. testcase( i==52 ); /* ATTACH */
  131108. testcase( i==53 ); /* HAVING */
  131109. testcase( i==54 ); /* GROUP */
  131110. testcase( i==55 ); /* UPDATE */
  131111. testcase( i==56 ); /* BEGIN */
  131112. testcase( i==57 ); /* INNER */
  131113. testcase( i==58 ); /* RECURSIVE */
  131114. testcase( i==59 ); /* BETWEEN */
  131115. testcase( i==60 ); /* NOTNULL */
  131116. testcase( i==61 ); /* NOT */
  131117. testcase( i==62 ); /* NO */
  131118. testcase( i==63 ); /* NULL */
  131119. testcase( i==64 ); /* LIKE */
  131120. testcase( i==65 ); /* CASCADE */
  131121. testcase( i==66 ); /* ASC */
  131122. testcase( i==67 ); /* DELETE */
  131123. testcase( i==68 ); /* CASE */
  131124. testcase( i==69 ); /* COLLATE */
  131125. testcase( i==70 ); /* CREATE */
  131126. testcase( i==71 ); /* CURRENT_DATE */
  131127. testcase( i==72 ); /* DETACH */
  131128. testcase( i==73 ); /* IMMEDIATE */
  131129. testcase( i==74 ); /* JOIN */
  131130. testcase( i==75 ); /* INSERT */
  131131. testcase( i==76 ); /* MATCH */
  131132. testcase( i==77 ); /* PLAN */
  131133. testcase( i==78 ); /* ANALYZE */
  131134. testcase( i==79 ); /* PRAGMA */
  131135. testcase( i==80 ); /* ABORT */
  131136. testcase( i==81 ); /* VALUES */
  131137. testcase( i==82 ); /* VIRTUAL */
  131138. testcase( i==83 ); /* LIMIT */
  131139. testcase( i==84 ); /* WHEN */
  131140. testcase( i==85 ); /* WHERE */
  131141. testcase( i==86 ); /* RENAME */
  131142. testcase( i==87 ); /* AFTER */
  131143. testcase( i==88 ); /* REPLACE */
  131144. testcase( i==89 ); /* AND */
  131145. testcase( i==90 ); /* DEFAULT */
  131146. testcase( i==91 ); /* AUTOINCREMENT */
  131147. testcase( i==92 ); /* TO */
  131148. testcase( i==93 ); /* IN */
  131149. testcase( i==94 ); /* CAST */
  131150. testcase( i==95 ); /* COLUMN */
  131151. testcase( i==96 ); /* COMMIT */
  131152. testcase( i==97 ); /* CONFLICT */
  131153. testcase( i==98 ); /* CROSS */
  131154. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  131155. testcase( i==100 ); /* CURRENT_TIME */
  131156. testcase( i==101 ); /* PRIMARY */
  131157. testcase( i==102 ); /* DEFERRED */
  131158. testcase( i==103 ); /* DISTINCT */
  131159. testcase( i==104 ); /* IS */
  131160. testcase( i==105 ); /* DROP */
  131161. testcase( i==106 ); /* FAIL */
  131162. testcase( i==107 ); /* FROM */
  131163. testcase( i==108 ); /* FULL */
  131164. testcase( i==109 ); /* GLOB */
  131165. testcase( i==110 ); /* BY */
  131166. testcase( i==111 ); /* IF */
  131167. testcase( i==112 ); /* ISNULL */
  131168. testcase( i==113 ); /* ORDER */
  131169. testcase( i==114 ); /* RESTRICT */
  131170. testcase( i==115 ); /* RIGHT */
  131171. testcase( i==116 ); /* ROLLBACK */
  131172. testcase( i==117 ); /* ROW */
  131173. testcase( i==118 ); /* UNION */
  131174. testcase( i==119 ); /* USING */
  131175. testcase( i==120 ); /* VACUUM */
  131176. testcase( i==121 ); /* VIEW */
  131177. testcase( i==122 ); /* INITIALLY */
  131178. testcase( i==123 ); /* ALL */
  131179. *pType = aCode[i];
  131180. break;
  131181. }
  131182. }
  131183. return n;
  131184. }
  131185. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  131186. int id = TK_ID;
  131187. keywordCode((char*)z, n, &id);
  131188. return id;
  131189. }
  131190. #define SQLITE_N_KEYWORD 124
  131191. /************** End of keywordhash.h *****************************************/
  131192. /************** Continuing where we left off in tokenize.c *******************/
  131193. /*
  131194. ** If X is a character that can be used in an identifier then
  131195. ** IdChar(X) will be true. Otherwise it is false.
  131196. **
  131197. ** For ASCII, any character with the high-order bit set is
  131198. ** allowed in an identifier. For 7-bit characters,
  131199. ** sqlite3IsIdChar[X] must be 1.
  131200. **
  131201. ** For EBCDIC, the rules are more complex but have the same
  131202. ** end result.
  131203. **
  131204. ** Ticket #1066. the SQL standard does not allow '$' in the
  131205. ** middle of identifiers. But many SQL implementations do.
  131206. ** SQLite will allow '$' in identifiers for compatibility.
  131207. ** But the feature is undocumented.
  131208. */
  131209. #ifdef SQLITE_ASCII
  131210. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  131211. #endif
  131212. #ifdef SQLITE_EBCDIC
  131213. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  131214. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  131215. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  131216. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  131217. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  131218. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  131219. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  131220. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  131221. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  131223. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  131224. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  131225. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  131226. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  131227. };
  131228. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  131229. #endif
  131230. /* Make the IdChar function accessible from ctime.c */
  131231. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  131232. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  131233. #endif
  131234. /*
  131235. ** Return the length (in bytes) of the token that begins at z[0].
  131236. ** Store the token type in *tokenType before returning.
  131237. */
  131238. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  131239. int i, c;
  131240. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  131241. ** of the token. See the comment on the CC_ defines
  131242. ** above. */
  131243. case CC_SPACE: {
  131244. testcase( z[0]==' ' );
  131245. testcase( z[0]=='\t' );
  131246. testcase( z[0]=='\n' );
  131247. testcase( z[0]=='\f' );
  131248. testcase( z[0]=='\r' );
  131249. for(i=1; sqlite3Isspace(z[i]); i++){}
  131250. *tokenType = TK_SPACE;
  131251. return i;
  131252. }
  131253. case CC_MINUS: {
  131254. if( z[1]=='-' ){
  131255. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  131256. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  131257. return i;
  131258. }
  131259. *tokenType = TK_MINUS;
  131260. return 1;
  131261. }
  131262. case CC_LP: {
  131263. *tokenType = TK_LP;
  131264. return 1;
  131265. }
  131266. case CC_RP: {
  131267. *tokenType = TK_RP;
  131268. return 1;
  131269. }
  131270. case CC_SEMI: {
  131271. *tokenType = TK_SEMI;
  131272. return 1;
  131273. }
  131274. case CC_PLUS: {
  131275. *tokenType = TK_PLUS;
  131276. return 1;
  131277. }
  131278. case CC_STAR: {
  131279. *tokenType = TK_STAR;
  131280. return 1;
  131281. }
  131282. case CC_SLASH: {
  131283. if( z[1]!='*' || z[2]==0 ){
  131284. *tokenType = TK_SLASH;
  131285. return 1;
  131286. }
  131287. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  131288. if( c ) i++;
  131289. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  131290. return i;
  131291. }
  131292. case CC_PERCENT: {
  131293. *tokenType = TK_REM;
  131294. return 1;
  131295. }
  131296. case CC_EQ: {
  131297. *tokenType = TK_EQ;
  131298. return 1 + (z[1]=='=');
  131299. }
  131300. case CC_LT: {
  131301. if( (c=z[1])=='=' ){
  131302. *tokenType = TK_LE;
  131303. return 2;
  131304. }else if( c=='>' ){
  131305. *tokenType = TK_NE;
  131306. return 2;
  131307. }else if( c=='<' ){
  131308. *tokenType = TK_LSHIFT;
  131309. return 2;
  131310. }else{
  131311. *tokenType = TK_LT;
  131312. return 1;
  131313. }
  131314. }
  131315. case CC_GT: {
  131316. if( (c=z[1])=='=' ){
  131317. *tokenType = TK_GE;
  131318. return 2;
  131319. }else if( c=='>' ){
  131320. *tokenType = TK_RSHIFT;
  131321. return 2;
  131322. }else{
  131323. *tokenType = TK_GT;
  131324. return 1;
  131325. }
  131326. }
  131327. case CC_BANG: {
  131328. if( z[1]!='=' ){
  131329. *tokenType = TK_ILLEGAL;
  131330. return 1;
  131331. }else{
  131332. *tokenType = TK_NE;
  131333. return 2;
  131334. }
  131335. }
  131336. case CC_PIPE: {
  131337. if( z[1]!='|' ){
  131338. *tokenType = TK_BITOR;
  131339. return 1;
  131340. }else{
  131341. *tokenType = TK_CONCAT;
  131342. return 2;
  131343. }
  131344. }
  131345. case CC_COMMA: {
  131346. *tokenType = TK_COMMA;
  131347. return 1;
  131348. }
  131349. case CC_AND: {
  131350. *tokenType = TK_BITAND;
  131351. return 1;
  131352. }
  131353. case CC_TILDA: {
  131354. *tokenType = TK_BITNOT;
  131355. return 1;
  131356. }
  131357. case CC_QUOTE: {
  131358. int delim = z[0];
  131359. testcase( delim=='`' );
  131360. testcase( delim=='\'' );
  131361. testcase( delim=='"' );
  131362. for(i=1; (c=z[i])!=0; i++){
  131363. if( c==delim ){
  131364. if( z[i+1]==delim ){
  131365. i++;
  131366. }else{
  131367. break;
  131368. }
  131369. }
  131370. }
  131371. if( c=='\'' ){
  131372. *tokenType = TK_STRING;
  131373. return i+1;
  131374. }else if( c!=0 ){
  131375. *tokenType = TK_ID;
  131376. return i+1;
  131377. }else{
  131378. *tokenType = TK_ILLEGAL;
  131379. return i;
  131380. }
  131381. }
  131382. case CC_DOT: {
  131383. #ifndef SQLITE_OMIT_FLOATING_POINT
  131384. if( !sqlite3Isdigit(z[1]) )
  131385. #endif
  131386. {
  131387. *tokenType = TK_DOT;
  131388. return 1;
  131389. }
  131390. /* If the next character is a digit, this is a floating point
  131391. ** number that begins with ".". Fall thru into the next case */
  131392. }
  131393. case CC_DIGIT: {
  131394. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  131395. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  131396. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  131397. testcase( z[0]=='9' );
  131398. *tokenType = TK_INTEGER;
  131399. #ifndef SQLITE_OMIT_HEX_INTEGER
  131400. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  131401. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  131402. return i;
  131403. }
  131404. #endif
  131405. for(i=0; sqlite3Isdigit(z[i]); i++){}
  131406. #ifndef SQLITE_OMIT_FLOATING_POINT
  131407. if( z[i]=='.' ){
  131408. i++;
  131409. while( sqlite3Isdigit(z[i]) ){ i++; }
  131410. *tokenType = TK_FLOAT;
  131411. }
  131412. if( (z[i]=='e' || z[i]=='E') &&
  131413. ( sqlite3Isdigit(z[i+1])
  131414. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  131415. )
  131416. ){
  131417. i += 2;
  131418. while( sqlite3Isdigit(z[i]) ){ i++; }
  131419. *tokenType = TK_FLOAT;
  131420. }
  131421. #endif
  131422. while( IdChar(z[i]) ){
  131423. *tokenType = TK_ILLEGAL;
  131424. i++;
  131425. }
  131426. return i;
  131427. }
  131428. case CC_QUOTE2: {
  131429. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  131430. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  131431. return i;
  131432. }
  131433. case CC_VARNUM: {
  131434. *tokenType = TK_VARIABLE;
  131435. for(i=1; sqlite3Isdigit(z[i]); i++){}
  131436. return i;
  131437. }
  131438. case CC_DOLLAR:
  131439. case CC_VARALPHA: {
  131440. int n = 0;
  131441. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  131442. testcase( z[0]==':' ); testcase( z[0]=='#' );
  131443. *tokenType = TK_VARIABLE;
  131444. for(i=1; (c=z[i])!=0; i++){
  131445. if( IdChar(c) ){
  131446. n++;
  131447. #ifndef SQLITE_OMIT_TCL_VARIABLE
  131448. }else if( c=='(' && n>0 ){
  131449. do{
  131450. i++;
  131451. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  131452. if( c==')' ){
  131453. i++;
  131454. }else{
  131455. *tokenType = TK_ILLEGAL;
  131456. }
  131457. break;
  131458. }else if( c==':' && z[i+1]==':' ){
  131459. i++;
  131460. #endif
  131461. }else{
  131462. break;
  131463. }
  131464. }
  131465. if( n==0 ) *tokenType = TK_ILLEGAL;
  131466. return i;
  131467. }
  131468. case CC_KYWD: {
  131469. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  131470. if( IdChar(z[i]) ){
  131471. /* This token started out using characters that can appear in keywords,
  131472. ** but z[i] is a character not allowed within keywords, so this must
  131473. ** be an identifier instead */
  131474. i++;
  131475. break;
  131476. }
  131477. *tokenType = TK_ID;
  131478. return keywordCode((char*)z, i, tokenType);
  131479. }
  131480. case CC_X: {
  131481. #ifndef SQLITE_OMIT_BLOB_LITERAL
  131482. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  131483. if( z[1]=='\'' ){
  131484. *tokenType = TK_BLOB;
  131485. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  131486. if( z[i]!='\'' || i%2 ){
  131487. *tokenType = TK_ILLEGAL;
  131488. while( z[i] && z[i]!='\'' ){ i++; }
  131489. }
  131490. if( z[i] ) i++;
  131491. return i;
  131492. }
  131493. #endif
  131494. /* If it is not a BLOB literal, then it must be an ID, since no
  131495. ** SQL keywords start with the letter 'x'. Fall through */
  131496. }
  131497. case CC_ID: {
  131498. i = 1;
  131499. break;
  131500. }
  131501. default: {
  131502. *tokenType = TK_ILLEGAL;
  131503. return 1;
  131504. }
  131505. }
  131506. while( IdChar(z[i]) ){ i++; }
  131507. *tokenType = TK_ID;
  131508. return i;
  131509. }
  131510. /*
  131511. ** Run the parser on the given SQL string. The parser structure is
  131512. ** passed in. An SQLITE_ status code is returned. If an error occurs
  131513. ** then an and attempt is made to write an error message into
  131514. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  131515. ** error message.
  131516. */
  131517. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  131518. int nErr = 0; /* Number of errors encountered */
  131519. void *pEngine; /* The LEMON-generated LALR(1) parser */
  131520. int n = 0; /* Length of the next token token */
  131521. int tokenType; /* type of the next token */
  131522. int lastTokenParsed = -1; /* type of the previous token */
  131523. sqlite3 *db = pParse->db; /* The database connection */
  131524. int mxSqlLen; /* Max length of an SQL string */
  131525. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  131526. yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
  131527. #endif
  131528. assert( zSql!=0 );
  131529. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  131530. if( db->nVdbeActive==0 ){
  131531. db->u1.isInterrupted = 0;
  131532. }
  131533. pParse->rc = SQLITE_OK;
  131534. pParse->zTail = zSql;
  131535. assert( pzErrMsg!=0 );
  131536. /* sqlite3ParserTrace(stdout, "parser: "); */
  131537. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  131538. pEngine = &sEngine;
  131539. sqlite3ParserInit(pEngine);
  131540. #else
  131541. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  131542. if( pEngine==0 ){
  131543. sqlite3OomFault(db);
  131544. return SQLITE_NOMEM_BKPT;
  131545. }
  131546. #endif
  131547. assert( pParse->pNewTable==0 );
  131548. assert( pParse->pNewTrigger==0 );
  131549. assert( pParse->nVar==0 );
  131550. assert( pParse->pVList==0 );
  131551. while( 1 ){
  131552. if( zSql[0]!=0 ){
  131553. n = sqlite3GetToken((u8*)zSql, &tokenType);
  131554. mxSqlLen -= n;
  131555. if( mxSqlLen<0 ){
  131556. pParse->rc = SQLITE_TOOBIG;
  131557. break;
  131558. }
  131559. }else{
  131560. /* Upon reaching the end of input, call the parser two more times
  131561. ** with tokens TK_SEMI and 0, in that order. */
  131562. if( lastTokenParsed==TK_SEMI ){
  131563. tokenType = 0;
  131564. }else if( lastTokenParsed==0 ){
  131565. break;
  131566. }else{
  131567. tokenType = TK_SEMI;
  131568. }
  131569. zSql -= n;
  131570. }
  131571. if( tokenType>=TK_SPACE ){
  131572. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  131573. if( db->u1.isInterrupted ){
  131574. pParse->rc = SQLITE_INTERRUPT;
  131575. break;
  131576. }
  131577. if( tokenType==TK_ILLEGAL ){
  131578. sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
  131579. break;
  131580. }
  131581. zSql += n;
  131582. }else{
  131583. pParse->sLastToken.z = zSql;
  131584. pParse->sLastToken.n = n;
  131585. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  131586. lastTokenParsed = tokenType;
  131587. zSql += n;
  131588. if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
  131589. }
  131590. }
  131591. assert( nErr==0 );
  131592. pParse->zTail = zSql;
  131593. #ifdef YYTRACKMAXSTACKDEPTH
  131594. sqlite3_mutex_enter(sqlite3MallocMutex());
  131595. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  131596. sqlite3ParserStackPeak(pEngine)
  131597. );
  131598. sqlite3_mutex_leave(sqlite3MallocMutex());
  131599. #endif /* YYDEBUG */
  131600. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  131601. sqlite3ParserFinalize(pEngine);
  131602. #else
  131603. sqlite3ParserFree(pEngine, sqlite3_free);
  131604. #endif
  131605. if( db->mallocFailed ){
  131606. pParse->rc = SQLITE_NOMEM_BKPT;
  131607. }
  131608. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  131609. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  131610. }
  131611. assert( pzErrMsg!=0 );
  131612. if( pParse->zErrMsg ){
  131613. *pzErrMsg = pParse->zErrMsg;
  131614. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  131615. pParse->zErrMsg = 0;
  131616. nErr++;
  131617. }
  131618. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  131619. sqlite3VdbeDelete(pParse->pVdbe);
  131620. pParse->pVdbe = 0;
  131621. }
  131622. #ifndef SQLITE_OMIT_SHARED_CACHE
  131623. if( pParse->nested==0 ){
  131624. sqlite3DbFree(db, pParse->aTableLock);
  131625. pParse->aTableLock = 0;
  131626. pParse->nTableLock = 0;
  131627. }
  131628. #endif
  131629. #ifndef SQLITE_OMIT_VIRTUALTABLE
  131630. sqlite3_free(pParse->apVtabLock);
  131631. #endif
  131632. if( !IN_DECLARE_VTAB ){
  131633. /* If the pParse->declareVtab flag is set, do not delete any table
  131634. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  131635. ** will take responsibility for freeing the Table structure.
  131636. */
  131637. sqlite3DeleteTable(db, pParse->pNewTable);
  131638. }
  131639. if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
  131640. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  131641. sqlite3DbFree(db, pParse->pVList);
  131642. while( pParse->pAinc ){
  131643. AutoincInfo *p = pParse->pAinc;
  131644. pParse->pAinc = p->pNext;
  131645. sqlite3DbFreeNN(db, p);
  131646. }
  131647. while( pParse->pZombieTab ){
  131648. Table *p = pParse->pZombieTab;
  131649. pParse->pZombieTab = p->pNextZombie;
  131650. sqlite3DeleteTable(db, p);
  131651. }
  131652. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  131653. return nErr;
  131654. }
  131655. /************** End of tokenize.c ********************************************/
  131656. /************** Begin file complete.c ****************************************/
  131657. /*
  131658. ** 2001 September 15
  131659. **
  131660. ** The author disclaims copyright to this source code. In place of
  131661. ** a legal notice, here is a blessing:
  131662. **
  131663. ** May you do good and not evil.
  131664. ** May you find forgiveness for yourself and forgive others.
  131665. ** May you share freely, never taking more than you give.
  131666. **
  131667. *************************************************************************
  131668. ** An tokenizer for SQL
  131669. **
  131670. ** This file contains C code that implements the sqlite3_complete() API.
  131671. ** This code used to be part of the tokenizer.c source file. But by
  131672. ** separating it out, the code will be automatically omitted from
  131673. ** static links that do not use it.
  131674. */
  131675. /* #include "sqliteInt.h" */
  131676. #ifndef SQLITE_OMIT_COMPLETE
  131677. /*
  131678. ** This is defined in tokenize.c. We just have to import the definition.
  131679. */
  131680. #ifndef SQLITE_AMALGAMATION
  131681. #ifdef SQLITE_ASCII
  131682. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  131683. #endif
  131684. #ifdef SQLITE_EBCDIC
  131685. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  131686. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  131687. #endif
  131688. #endif /* SQLITE_AMALGAMATION */
  131689. /*
  131690. ** Token types used by the sqlite3_complete() routine. See the header
  131691. ** comments on that procedure for additional information.
  131692. */
  131693. #define tkSEMI 0
  131694. #define tkWS 1
  131695. #define tkOTHER 2
  131696. #ifndef SQLITE_OMIT_TRIGGER
  131697. #define tkEXPLAIN 3
  131698. #define tkCREATE 4
  131699. #define tkTEMP 5
  131700. #define tkTRIGGER 6
  131701. #define tkEND 7
  131702. #endif
  131703. /*
  131704. ** Return TRUE if the given SQL string ends in a semicolon.
  131705. **
  131706. ** Special handling is require for CREATE TRIGGER statements.
  131707. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  131708. ** must end with ";END;".
  131709. **
  131710. ** This implementation uses a state machine with 8 states:
  131711. **
  131712. ** (0) INVALID We have not yet seen a non-whitespace character.
  131713. **
  131714. ** (1) START At the beginning or end of an SQL statement. This routine
  131715. ** returns 1 if it ends in the START state and 0 if it ends
  131716. ** in any other state.
  131717. **
  131718. ** (2) NORMAL We are in the middle of statement which ends with a single
  131719. ** semicolon.
  131720. **
  131721. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  131722. ** a statement.
  131723. **
  131724. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  131725. ** statement, possibly preceded by EXPLAIN and/or followed by
  131726. ** TEMP or TEMPORARY
  131727. **
  131728. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  131729. ** ended by a semicolon, the keyword END, and another semicolon.
  131730. **
  131731. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  131732. ** the end of a trigger definition.
  131733. **
  131734. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  131735. ** of a trigger definition.
  131736. **
  131737. ** Transitions between states above are determined by tokens extracted
  131738. ** from the input. The following tokens are significant:
  131739. **
  131740. ** (0) tkSEMI A semicolon.
  131741. ** (1) tkWS Whitespace.
  131742. ** (2) tkOTHER Any other SQL token.
  131743. ** (3) tkEXPLAIN The "explain" keyword.
  131744. ** (4) tkCREATE The "create" keyword.
  131745. ** (5) tkTEMP The "temp" or "temporary" keyword.
  131746. ** (6) tkTRIGGER The "trigger" keyword.
  131747. ** (7) tkEND The "end" keyword.
  131748. **
  131749. ** Whitespace never causes a state transition and is always ignored.
  131750. ** This means that a SQL string of all whitespace is invalid.
  131751. **
  131752. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  131753. ** to recognize the end of a trigger can be omitted. All we have to do
  131754. ** is look for a semicolon that is not part of an string or comment.
  131755. */
  131756. SQLITE_API int sqlite3_complete(const char *zSql){
  131757. u8 state = 0; /* Current state, using numbers defined in header comment */
  131758. u8 token; /* Value of the next token */
  131759. #ifndef SQLITE_OMIT_TRIGGER
  131760. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  131761. ** statement. This is the normal case.
  131762. */
  131763. static const u8 trans[8][8] = {
  131764. /* Token: */
  131765. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  131766. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  131767. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  131768. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  131769. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  131770. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  131771. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  131772. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  131773. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  131774. };
  131775. #else
  131776. /* If triggers are not supported by this compile then the statement machine
  131777. ** used to detect the end of a statement is much simpler
  131778. */
  131779. static const u8 trans[3][3] = {
  131780. /* Token: */
  131781. /* State: ** SEMI WS OTHER */
  131782. /* 0 INVALID: */ { 1, 0, 2, },
  131783. /* 1 START: */ { 1, 1, 2, },
  131784. /* 2 NORMAL: */ { 1, 2, 2, },
  131785. };
  131786. #endif /* SQLITE_OMIT_TRIGGER */
  131787. #ifdef SQLITE_ENABLE_API_ARMOR
  131788. if( zSql==0 ){
  131789. (void)SQLITE_MISUSE_BKPT;
  131790. return 0;
  131791. }
  131792. #endif
  131793. while( *zSql ){
  131794. switch( *zSql ){
  131795. case ';': { /* A semicolon */
  131796. token = tkSEMI;
  131797. break;
  131798. }
  131799. case ' ':
  131800. case '\r':
  131801. case '\t':
  131802. case '\n':
  131803. case '\f': { /* White space is ignored */
  131804. token = tkWS;
  131805. break;
  131806. }
  131807. case '/': { /* C-style comments */
  131808. if( zSql[1]!='*' ){
  131809. token = tkOTHER;
  131810. break;
  131811. }
  131812. zSql += 2;
  131813. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  131814. if( zSql[0]==0 ) return 0;
  131815. zSql++;
  131816. token = tkWS;
  131817. break;
  131818. }
  131819. case '-': { /* SQL-style comments from "--" to end of line */
  131820. if( zSql[1]!='-' ){
  131821. token = tkOTHER;
  131822. break;
  131823. }
  131824. while( *zSql && *zSql!='\n' ){ zSql++; }
  131825. if( *zSql==0 ) return state==1;
  131826. token = tkWS;
  131827. break;
  131828. }
  131829. case '[': { /* Microsoft-style identifiers in [...] */
  131830. zSql++;
  131831. while( *zSql && *zSql!=']' ){ zSql++; }
  131832. if( *zSql==0 ) return 0;
  131833. token = tkOTHER;
  131834. break;
  131835. }
  131836. case '`': /* Grave-accent quoted symbols used by MySQL */
  131837. case '"': /* single- and double-quoted strings */
  131838. case '\'': {
  131839. int c = *zSql;
  131840. zSql++;
  131841. while( *zSql && *zSql!=c ){ zSql++; }
  131842. if( *zSql==0 ) return 0;
  131843. token = tkOTHER;
  131844. break;
  131845. }
  131846. default: {
  131847. #ifdef SQLITE_EBCDIC
  131848. unsigned char c;
  131849. #endif
  131850. if( IdChar((u8)*zSql) ){
  131851. /* Keywords and unquoted identifiers */
  131852. int nId;
  131853. for(nId=1; IdChar(zSql[nId]); nId++){}
  131854. #ifdef SQLITE_OMIT_TRIGGER
  131855. token = tkOTHER;
  131856. #else
  131857. switch( *zSql ){
  131858. case 'c': case 'C': {
  131859. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  131860. token = tkCREATE;
  131861. }else{
  131862. token = tkOTHER;
  131863. }
  131864. break;
  131865. }
  131866. case 't': case 'T': {
  131867. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  131868. token = tkTRIGGER;
  131869. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  131870. token = tkTEMP;
  131871. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  131872. token = tkTEMP;
  131873. }else{
  131874. token = tkOTHER;
  131875. }
  131876. break;
  131877. }
  131878. case 'e': case 'E': {
  131879. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  131880. token = tkEND;
  131881. }else
  131882. #ifndef SQLITE_OMIT_EXPLAIN
  131883. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  131884. token = tkEXPLAIN;
  131885. }else
  131886. #endif
  131887. {
  131888. token = tkOTHER;
  131889. }
  131890. break;
  131891. }
  131892. default: {
  131893. token = tkOTHER;
  131894. break;
  131895. }
  131896. }
  131897. #endif /* SQLITE_OMIT_TRIGGER */
  131898. zSql += nId-1;
  131899. }else{
  131900. /* Operators and special symbols */
  131901. token = tkOTHER;
  131902. }
  131903. break;
  131904. }
  131905. }
  131906. state = trans[state][token];
  131907. zSql++;
  131908. }
  131909. return state==1;
  131910. }
  131911. #ifndef SQLITE_OMIT_UTF16
  131912. /*
  131913. ** This routine is the same as the sqlite3_complete() routine described
  131914. ** above, except that the parameter is required to be UTF-16 encoded, not
  131915. ** UTF-8.
  131916. */
  131917. SQLITE_API int sqlite3_complete16(const void *zSql){
  131918. sqlite3_value *pVal;
  131919. char const *zSql8;
  131920. int rc;
  131921. #ifndef SQLITE_OMIT_AUTOINIT
  131922. rc = sqlite3_initialize();
  131923. if( rc ) return rc;
  131924. #endif
  131925. pVal = sqlite3ValueNew(0);
  131926. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  131927. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  131928. if( zSql8 ){
  131929. rc = sqlite3_complete(zSql8);
  131930. }else{
  131931. rc = SQLITE_NOMEM_BKPT;
  131932. }
  131933. sqlite3ValueFree(pVal);
  131934. return rc & 0xff;
  131935. }
  131936. #endif /* SQLITE_OMIT_UTF16 */
  131937. #endif /* SQLITE_OMIT_COMPLETE */
  131938. /************** End of complete.c ********************************************/
  131939. /************** Begin file main.c ********************************************/
  131940. /*
  131941. ** 2001 September 15
  131942. **
  131943. ** The author disclaims copyright to this source code. In place of
  131944. ** a legal notice, here is a blessing:
  131945. **
  131946. ** May you do good and not evil.
  131947. ** May you find forgiveness for yourself and forgive others.
  131948. ** May you share freely, never taking more than you give.
  131949. **
  131950. *************************************************************************
  131951. ** Main file for the SQLite library. The routines in this file
  131952. ** implement the programmer interface to the library. Routines in
  131953. ** other files are for internal use by SQLite and should not be
  131954. ** accessed by users of the library.
  131955. */
  131956. /* #include "sqliteInt.h" */
  131957. #ifdef SQLITE_ENABLE_FTS3
  131958. /************** Include fts3.h in the middle of main.c ***********************/
  131959. /************** Begin file fts3.h ********************************************/
  131960. /*
  131961. ** 2006 Oct 10
  131962. **
  131963. ** The author disclaims copyright to this source code. In place of
  131964. ** a legal notice, here is a blessing:
  131965. **
  131966. ** May you do good and not evil.
  131967. ** May you find forgiveness for yourself and forgive others.
  131968. ** May you share freely, never taking more than you give.
  131969. **
  131970. ******************************************************************************
  131971. **
  131972. ** This header file is used by programs that want to link against the
  131973. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  131974. */
  131975. /* #include "sqlite3.h" */
  131976. #if 0
  131977. extern "C" {
  131978. #endif /* __cplusplus */
  131979. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  131980. #if 0
  131981. } /* extern "C" */
  131982. #endif /* __cplusplus */
  131983. /************** End of fts3.h ************************************************/
  131984. /************** Continuing where we left off in main.c ***********************/
  131985. #endif
  131986. #ifdef SQLITE_ENABLE_RTREE
  131987. /************** Include rtree.h in the middle of main.c **********************/
  131988. /************** Begin file rtree.h *******************************************/
  131989. /*
  131990. ** 2008 May 26
  131991. **
  131992. ** The author disclaims copyright to this source code. In place of
  131993. ** a legal notice, here is a blessing:
  131994. **
  131995. ** May you do good and not evil.
  131996. ** May you find forgiveness for yourself and forgive others.
  131997. ** May you share freely, never taking more than you give.
  131998. **
  131999. ******************************************************************************
  132000. **
  132001. ** This header file is used by programs that want to link against the
  132002. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  132003. */
  132004. /* #include "sqlite3.h" */
  132005. #if 0
  132006. extern "C" {
  132007. #endif /* __cplusplus */
  132008. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  132009. #if 0
  132010. } /* extern "C" */
  132011. #endif /* __cplusplus */
  132012. /************** End of rtree.h ***********************************************/
  132013. /************** Continuing where we left off in main.c ***********************/
  132014. #endif
  132015. #ifdef SQLITE_ENABLE_ICU
  132016. /************** Include sqliteicu.h in the middle of main.c ******************/
  132017. /************** Begin file sqliteicu.h ***************************************/
  132018. /*
  132019. ** 2008 May 26
  132020. **
  132021. ** The author disclaims copyright to this source code. In place of
  132022. ** a legal notice, here is a blessing:
  132023. **
  132024. ** May you do good and not evil.
  132025. ** May you find forgiveness for yourself and forgive others.
  132026. ** May you share freely, never taking more than you give.
  132027. **
  132028. ******************************************************************************
  132029. **
  132030. ** This header file is used by programs that want to link against the
  132031. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  132032. */
  132033. /* #include "sqlite3.h" */
  132034. #if 0
  132035. extern "C" {
  132036. #endif /* __cplusplus */
  132037. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  132038. #if 0
  132039. } /* extern "C" */
  132040. #endif /* __cplusplus */
  132041. /************** End of sqliteicu.h *******************************************/
  132042. /************** Continuing where we left off in main.c ***********************/
  132043. #endif
  132044. #ifdef SQLITE_ENABLE_JSON1
  132045. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  132046. #endif
  132047. #ifdef SQLITE_ENABLE_FTS5
  132048. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  132049. #endif
  132050. #ifndef SQLITE_AMALGAMATION
  132051. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  132052. ** contains the text of SQLITE_VERSION macro.
  132053. */
  132054. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  132055. #endif
  132056. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  132057. ** a pointer to the to the sqlite3_version[] string constant.
  132058. */
  132059. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  132060. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  132061. ** pointer to a string constant whose value is the same as the
  132062. ** SQLITE_SOURCE_ID C preprocessor macro.
  132063. */
  132064. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  132065. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  132066. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  132067. */
  132068. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  132069. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  132070. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  132071. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  132072. */
  132073. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  132074. /*
  132075. ** When compiling the test fixture or with debugging enabled (on Win32),
  132076. ** this variable being set to non-zero will cause OSTRACE macros to emit
  132077. ** extra diagnostic information.
  132078. */
  132079. #ifdef SQLITE_HAVE_OS_TRACE
  132080. # ifndef SQLITE_DEBUG_OS_TRACE
  132081. # define SQLITE_DEBUG_OS_TRACE 0
  132082. # endif
  132083. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  132084. #endif
  132085. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  132086. /*
  132087. ** If the following function pointer is not NULL and if
  132088. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  132089. ** I/O active are written using this function. These messages
  132090. ** are intended for debugging activity only.
  132091. */
  132092. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  132093. #endif
  132094. /*
  132095. ** If the following global variable points to a string which is the
  132096. ** name of a directory, then that directory will be used to store
  132097. ** temporary files.
  132098. **
  132099. ** See also the "PRAGMA temp_store_directory" SQL command.
  132100. */
  132101. SQLITE_API char *sqlite3_temp_directory = 0;
  132102. /*
  132103. ** If the following global variable points to a string which is the
  132104. ** name of a directory, then that directory will be used to store
  132105. ** all database files specified with a relative pathname.
  132106. **
  132107. ** See also the "PRAGMA data_store_directory" SQL command.
  132108. */
  132109. SQLITE_API char *sqlite3_data_directory = 0;
  132110. /*
  132111. ** Initialize SQLite.
  132112. **
  132113. ** This routine must be called to initialize the memory allocation,
  132114. ** VFS, and mutex subsystems prior to doing any serious work with
  132115. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  132116. ** this routine will be called automatically by key routines such as
  132117. ** sqlite3_open().
  132118. **
  132119. ** This routine is a no-op except on its very first call for the process,
  132120. ** or for the first call after a call to sqlite3_shutdown.
  132121. **
  132122. ** The first thread to call this routine runs the initialization to
  132123. ** completion. If subsequent threads call this routine before the first
  132124. ** thread has finished the initialization process, then the subsequent
  132125. ** threads must block until the first thread finishes with the initialization.
  132126. **
  132127. ** The first thread might call this routine recursively. Recursive
  132128. ** calls to this routine should not block, of course. Otherwise the
  132129. ** initialization process would never complete.
  132130. **
  132131. ** Let X be the first thread to enter this routine. Let Y be some other
  132132. ** thread. Then while the initial invocation of this routine by X is
  132133. ** incomplete, it is required that:
  132134. **
  132135. ** * Calls to this routine from Y must block until the outer-most
  132136. ** call by X completes.
  132137. **
  132138. ** * Recursive calls to this routine from thread X return immediately
  132139. ** without blocking.
  132140. */
  132141. SQLITE_API int sqlite3_initialize(void){
  132142. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  132143. int rc; /* Result code */
  132144. #ifdef SQLITE_EXTRA_INIT
  132145. int bRunExtraInit = 0; /* Extra initialization needed */
  132146. #endif
  132147. #ifdef SQLITE_OMIT_WSD
  132148. rc = sqlite3_wsd_init(4096, 24);
  132149. if( rc!=SQLITE_OK ){
  132150. return rc;
  132151. }
  132152. #endif
  132153. /* If the following assert() fails on some obscure processor/compiler
  132154. ** combination, the work-around is to set the correct pointer
  132155. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  132156. assert( SQLITE_PTRSIZE==sizeof(char*) );
  132157. /* If SQLite is already completely initialized, then this call
  132158. ** to sqlite3_initialize() should be a no-op. But the initialization
  132159. ** must be complete. So isInit must not be set until the very end
  132160. ** of this routine.
  132161. */
  132162. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  132163. /* Make sure the mutex subsystem is initialized. If unable to
  132164. ** initialize the mutex subsystem, return early with the error.
  132165. ** If the system is so sick that we are unable to allocate a mutex,
  132166. ** there is not much SQLite is going to be able to do.
  132167. **
  132168. ** The mutex subsystem must take care of serializing its own
  132169. ** initialization.
  132170. */
  132171. rc = sqlite3MutexInit();
  132172. if( rc ) return rc;
  132173. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  132174. ** This operation is protected by the STATIC_MASTER mutex. Note that
  132175. ** MutexAlloc() is called for a static mutex prior to initializing the
  132176. ** malloc subsystem - this implies that the allocation of a static
  132177. ** mutex must not require support from the malloc subsystem.
  132178. */
  132179. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  132180. sqlite3_mutex_enter(pMaster);
  132181. sqlite3GlobalConfig.isMutexInit = 1;
  132182. if( !sqlite3GlobalConfig.isMallocInit ){
  132183. rc = sqlite3MallocInit();
  132184. }
  132185. if( rc==SQLITE_OK ){
  132186. sqlite3GlobalConfig.isMallocInit = 1;
  132187. if( !sqlite3GlobalConfig.pInitMutex ){
  132188. sqlite3GlobalConfig.pInitMutex =
  132189. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  132190. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  132191. rc = SQLITE_NOMEM_BKPT;
  132192. }
  132193. }
  132194. }
  132195. if( rc==SQLITE_OK ){
  132196. sqlite3GlobalConfig.nRefInitMutex++;
  132197. }
  132198. sqlite3_mutex_leave(pMaster);
  132199. /* If rc is not SQLITE_OK at this point, then either the malloc
  132200. ** subsystem could not be initialized or the system failed to allocate
  132201. ** the pInitMutex mutex. Return an error in either case. */
  132202. if( rc!=SQLITE_OK ){
  132203. return rc;
  132204. }
  132205. /* Do the rest of the initialization under the recursive mutex so
  132206. ** that we will be able to handle recursive calls into
  132207. ** sqlite3_initialize(). The recursive calls normally come through
  132208. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  132209. ** recursive calls might also be possible.
  132210. **
  132211. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  132212. ** to the xInit method, so the xInit method need not be threadsafe.
  132213. **
  132214. ** The following mutex is what serializes access to the appdef pcache xInit
  132215. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  132216. ** call to sqlite3PcacheInitialize().
  132217. */
  132218. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  132219. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  132220. sqlite3GlobalConfig.inProgress = 1;
  132221. #ifdef SQLITE_ENABLE_SQLLOG
  132222. {
  132223. extern void sqlite3_init_sqllog(void);
  132224. sqlite3_init_sqllog();
  132225. }
  132226. #endif
  132227. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  132228. sqlite3RegisterBuiltinFunctions();
  132229. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  132230. rc = sqlite3PcacheInitialize();
  132231. }
  132232. if( rc==SQLITE_OK ){
  132233. sqlite3GlobalConfig.isPCacheInit = 1;
  132234. rc = sqlite3OsInit();
  132235. }
  132236. if( rc==SQLITE_OK ){
  132237. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  132238. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  132239. sqlite3GlobalConfig.isInit = 1;
  132240. #ifdef SQLITE_EXTRA_INIT
  132241. bRunExtraInit = 1;
  132242. #endif
  132243. }
  132244. sqlite3GlobalConfig.inProgress = 0;
  132245. }
  132246. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  132247. /* Go back under the static mutex and clean up the recursive
  132248. ** mutex to prevent a resource leak.
  132249. */
  132250. sqlite3_mutex_enter(pMaster);
  132251. sqlite3GlobalConfig.nRefInitMutex--;
  132252. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  132253. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  132254. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  132255. sqlite3GlobalConfig.pInitMutex = 0;
  132256. }
  132257. sqlite3_mutex_leave(pMaster);
  132258. /* The following is just a sanity check to make sure SQLite has
  132259. ** been compiled correctly. It is important to run this code, but
  132260. ** we don't want to run it too often and soak up CPU cycles for no
  132261. ** reason. So we run it once during initialization.
  132262. */
  132263. #ifndef NDEBUG
  132264. #ifndef SQLITE_OMIT_FLOATING_POINT
  132265. /* This section of code's only "output" is via assert() statements. */
  132266. if ( rc==SQLITE_OK ){
  132267. u64 x = (((u64)1)<<63)-1;
  132268. double y;
  132269. assert(sizeof(x)==8);
  132270. assert(sizeof(x)==sizeof(y));
  132271. memcpy(&y, &x, 8);
  132272. assert( sqlite3IsNaN(y) );
  132273. }
  132274. #endif
  132275. #endif
  132276. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  132277. ** compile-time option.
  132278. */
  132279. #ifdef SQLITE_EXTRA_INIT
  132280. if( bRunExtraInit ){
  132281. int SQLITE_EXTRA_INIT(const char*);
  132282. rc = SQLITE_EXTRA_INIT(0);
  132283. }
  132284. #endif
  132285. return rc;
  132286. }
  132287. /*
  132288. ** Undo the effects of sqlite3_initialize(). Must not be called while
  132289. ** there are outstanding database connections or memory allocations or
  132290. ** while any part of SQLite is otherwise in use in any thread. This
  132291. ** routine is not threadsafe. But it is safe to invoke this routine
  132292. ** on when SQLite is already shut down. If SQLite is already shut down
  132293. ** when this routine is invoked, then this routine is a harmless no-op.
  132294. */
  132295. SQLITE_API int sqlite3_shutdown(void){
  132296. #ifdef SQLITE_OMIT_WSD
  132297. int rc = sqlite3_wsd_init(4096, 24);
  132298. if( rc!=SQLITE_OK ){
  132299. return rc;
  132300. }
  132301. #endif
  132302. if( sqlite3GlobalConfig.isInit ){
  132303. #ifdef SQLITE_EXTRA_SHUTDOWN
  132304. void SQLITE_EXTRA_SHUTDOWN(void);
  132305. SQLITE_EXTRA_SHUTDOWN();
  132306. #endif
  132307. sqlite3_os_end();
  132308. sqlite3_reset_auto_extension();
  132309. sqlite3GlobalConfig.isInit = 0;
  132310. }
  132311. if( sqlite3GlobalConfig.isPCacheInit ){
  132312. sqlite3PcacheShutdown();
  132313. sqlite3GlobalConfig.isPCacheInit = 0;
  132314. }
  132315. if( sqlite3GlobalConfig.isMallocInit ){
  132316. sqlite3MallocEnd();
  132317. sqlite3GlobalConfig.isMallocInit = 0;
  132318. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  132319. /* The heap subsystem has now been shutdown and these values are supposed
  132320. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  132321. ** which would rely on that heap subsystem; therefore, make sure these
  132322. ** values cannot refer to heap memory that was just invalidated when the
  132323. ** heap subsystem was shutdown. This is only done if the current call to
  132324. ** this function resulted in the heap subsystem actually being shutdown.
  132325. */
  132326. sqlite3_data_directory = 0;
  132327. sqlite3_temp_directory = 0;
  132328. #endif
  132329. }
  132330. if( sqlite3GlobalConfig.isMutexInit ){
  132331. sqlite3MutexEnd();
  132332. sqlite3GlobalConfig.isMutexInit = 0;
  132333. }
  132334. return SQLITE_OK;
  132335. }
  132336. /*
  132337. ** This API allows applications to modify the global configuration of
  132338. ** the SQLite library at run-time.
  132339. **
  132340. ** This routine should only be called when there are no outstanding
  132341. ** database connections or memory allocations. This routine is not
  132342. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  132343. ** behavior.
  132344. */
  132345. SQLITE_API int sqlite3_config(int op, ...){
  132346. va_list ap;
  132347. int rc = SQLITE_OK;
  132348. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  132349. ** the SQLite library is in use. */
  132350. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  132351. va_start(ap, op);
  132352. switch( op ){
  132353. /* Mutex configuration options are only available in a threadsafe
  132354. ** compile.
  132355. */
  132356. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  132357. case SQLITE_CONFIG_SINGLETHREAD: {
  132358. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  132359. ** Single-thread. */
  132360. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  132361. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  132362. break;
  132363. }
  132364. #endif
  132365. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  132366. case SQLITE_CONFIG_MULTITHREAD: {
  132367. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  132368. ** Multi-thread. */
  132369. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  132370. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  132371. break;
  132372. }
  132373. #endif
  132374. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  132375. case SQLITE_CONFIG_SERIALIZED: {
  132376. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  132377. ** Serialized. */
  132378. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  132379. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  132380. break;
  132381. }
  132382. #endif
  132383. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  132384. case SQLITE_CONFIG_MUTEX: {
  132385. /* Specify an alternative mutex implementation */
  132386. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  132387. break;
  132388. }
  132389. #endif
  132390. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  132391. case SQLITE_CONFIG_GETMUTEX: {
  132392. /* Retrieve the current mutex implementation */
  132393. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  132394. break;
  132395. }
  132396. #endif
  132397. case SQLITE_CONFIG_MALLOC: {
  132398. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  132399. ** single argument which is a pointer to an instance of the
  132400. ** sqlite3_mem_methods structure. The argument specifies alternative
  132401. ** low-level memory allocation routines to be used in place of the memory
  132402. ** allocation routines built into SQLite. */
  132403. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  132404. break;
  132405. }
  132406. case SQLITE_CONFIG_GETMALLOC: {
  132407. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  132408. ** single argument which is a pointer to an instance of the
  132409. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  132410. ** filled with the currently defined memory allocation routines. */
  132411. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  132412. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  132413. break;
  132414. }
  132415. case SQLITE_CONFIG_MEMSTATUS: {
  132416. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  132417. ** single argument of type int, interpreted as a boolean, which enables
  132418. ** or disables the collection of memory allocation statistics. */
  132419. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  132420. break;
  132421. }
  132422. case SQLITE_CONFIG_SCRATCH: {
  132423. /* EVIDENCE-OF: R-08404-60887 There are three arguments to
  132424. ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
  132425. ** which the scratch allocations will be drawn, the size of each scratch
  132426. ** allocation (sz), and the maximum number of scratch allocations (N). */
  132427. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  132428. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  132429. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  132430. break;
  132431. }
  132432. case SQLITE_CONFIG_PAGECACHE: {
  132433. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  132434. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  132435. ** the size of each page cache line (sz), and the number of cache lines
  132436. ** (N). */
  132437. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  132438. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  132439. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  132440. break;
  132441. }
  132442. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  132443. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  132444. ** a single parameter which is a pointer to an integer and writes into
  132445. ** that integer the number of extra bytes per page required for each page
  132446. ** in SQLITE_CONFIG_PAGECACHE. */
  132447. *va_arg(ap, int*) =
  132448. sqlite3HeaderSizeBtree() +
  132449. sqlite3HeaderSizePcache() +
  132450. sqlite3HeaderSizePcache1();
  132451. break;
  132452. }
  132453. case SQLITE_CONFIG_PCACHE: {
  132454. /* no-op */
  132455. break;
  132456. }
  132457. case SQLITE_CONFIG_GETPCACHE: {
  132458. /* now an error */
  132459. rc = SQLITE_ERROR;
  132460. break;
  132461. }
  132462. case SQLITE_CONFIG_PCACHE2: {
  132463. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  132464. ** single argument which is a pointer to an sqlite3_pcache_methods2
  132465. ** object. This object specifies the interface to a custom page cache
  132466. ** implementation. */
  132467. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  132468. break;
  132469. }
  132470. case SQLITE_CONFIG_GETPCACHE2: {
  132471. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  132472. ** single argument which is a pointer to an sqlite3_pcache_methods2
  132473. ** object. SQLite copies of the current page cache implementation into
  132474. ** that object. */
  132475. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  132476. sqlite3PCacheSetDefault();
  132477. }
  132478. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  132479. break;
  132480. }
  132481. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  132482. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  132483. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  132484. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  132485. case SQLITE_CONFIG_HEAP: {
  132486. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  132487. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  132488. ** number of bytes in the memory buffer, and the minimum allocation size.
  132489. */
  132490. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  132491. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  132492. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  132493. if( sqlite3GlobalConfig.mnReq<1 ){
  132494. sqlite3GlobalConfig.mnReq = 1;
  132495. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  132496. /* cap min request size at 2^12 */
  132497. sqlite3GlobalConfig.mnReq = (1<<12);
  132498. }
  132499. if( sqlite3GlobalConfig.pHeap==0 ){
  132500. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  132501. ** is NULL, then SQLite reverts to using its default memory allocator
  132502. ** (the system malloc() implementation), undoing any prior invocation of
  132503. ** SQLITE_CONFIG_MALLOC.
  132504. **
  132505. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  132506. ** revert to its default implementation when sqlite3_initialize() is run
  132507. */
  132508. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  132509. }else{
  132510. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  132511. ** alternative memory allocator is engaged to handle all of SQLites
  132512. ** memory allocation needs. */
  132513. #ifdef SQLITE_ENABLE_MEMSYS3
  132514. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  132515. #endif
  132516. #ifdef SQLITE_ENABLE_MEMSYS5
  132517. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  132518. #endif
  132519. }
  132520. break;
  132521. }
  132522. #endif
  132523. case SQLITE_CONFIG_LOOKASIDE: {
  132524. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  132525. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  132526. break;
  132527. }
  132528. /* Record a pointer to the logger function and its first argument.
  132529. ** The default is NULL. Logging is disabled if the function pointer is
  132530. ** NULL.
  132531. */
  132532. case SQLITE_CONFIG_LOG: {
  132533. /* MSVC is picky about pulling func ptrs from va lists.
  132534. ** http://support.microsoft.com/kb/47961
  132535. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  132536. */
  132537. typedef void(*LOGFUNC_t)(void*,int,const char*);
  132538. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  132539. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  132540. break;
  132541. }
  132542. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  132543. ** can be changed at start-time using the
  132544. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  132545. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  132546. */
  132547. case SQLITE_CONFIG_URI: {
  132548. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  132549. ** argument of type int. If non-zero, then URI handling is globally
  132550. ** enabled. If the parameter is zero, then URI handling is globally
  132551. ** disabled. */
  132552. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  132553. break;
  132554. }
  132555. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  132556. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  132557. ** option takes a single integer argument which is interpreted as a
  132558. ** boolean in order to enable or disable the use of covering indices for
  132559. ** full table scans in the query optimizer. */
  132560. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  132561. break;
  132562. }
  132563. #ifdef SQLITE_ENABLE_SQLLOG
  132564. case SQLITE_CONFIG_SQLLOG: {
  132565. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  132566. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  132567. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  132568. break;
  132569. }
  132570. #endif
  132571. case SQLITE_CONFIG_MMAP_SIZE: {
  132572. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  132573. ** integer (sqlite3_int64) values that are the default mmap size limit
  132574. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  132575. ** mmap size limit. */
  132576. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  132577. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  132578. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  132579. ** negative, then that argument is changed to its compile-time default.
  132580. **
  132581. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  132582. ** silently truncated if necessary so that it does not exceed the
  132583. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  132584. ** compile-time option.
  132585. */
  132586. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  132587. mxMmap = SQLITE_MAX_MMAP_SIZE;
  132588. }
  132589. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  132590. if( szMmap>mxMmap) szMmap = mxMmap;
  132591. sqlite3GlobalConfig.mxMmap = mxMmap;
  132592. sqlite3GlobalConfig.szMmap = szMmap;
  132593. break;
  132594. }
  132595. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  132596. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  132597. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  132598. ** unsigned integer value that specifies the maximum size of the created
  132599. ** heap. */
  132600. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  132601. break;
  132602. }
  132603. #endif
  132604. case SQLITE_CONFIG_PMASZ: {
  132605. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  132606. break;
  132607. }
  132608. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  132609. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  132610. break;
  132611. }
  132612. default: {
  132613. rc = SQLITE_ERROR;
  132614. break;
  132615. }
  132616. }
  132617. va_end(ap);
  132618. return rc;
  132619. }
  132620. /*
  132621. ** Set up the lookaside buffers for a database connection.
  132622. ** Return SQLITE_OK on success.
  132623. ** If lookaside is already active, return SQLITE_BUSY.
  132624. **
  132625. ** The sz parameter is the number of bytes in each lookaside slot.
  132626. ** The cnt parameter is the number of slots. If pStart is NULL the
  132627. ** space for the lookaside memory is obtained from sqlite3_malloc().
  132628. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  132629. ** the lookaside memory.
  132630. */
  132631. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  132632. #ifndef SQLITE_OMIT_LOOKASIDE
  132633. void *pStart;
  132634. if( db->lookaside.nOut ){
  132635. return SQLITE_BUSY;
  132636. }
  132637. /* Free any existing lookaside buffer for this handle before
  132638. ** allocating a new one so we don't have to have space for
  132639. ** both at the same time.
  132640. */
  132641. if( db->lookaside.bMalloced ){
  132642. sqlite3_free(db->lookaside.pStart);
  132643. }
  132644. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  132645. ** than a pointer to be useful.
  132646. */
  132647. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  132648. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  132649. if( cnt<0 ) cnt = 0;
  132650. if( sz==0 || cnt==0 ){
  132651. sz = 0;
  132652. pStart = 0;
  132653. }else if( pBuf==0 ){
  132654. sqlite3BeginBenignMalloc();
  132655. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  132656. sqlite3EndBenignMalloc();
  132657. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  132658. }else{
  132659. pStart = pBuf;
  132660. }
  132661. db->lookaside.pStart = pStart;
  132662. db->lookaside.pFree = 0;
  132663. db->lookaside.sz = (u16)sz;
  132664. if( pStart ){
  132665. int i;
  132666. LookasideSlot *p;
  132667. assert( sz > (int)sizeof(LookasideSlot*) );
  132668. p = (LookasideSlot*)pStart;
  132669. for(i=cnt-1; i>=0; i--){
  132670. p->pNext = db->lookaside.pFree;
  132671. db->lookaside.pFree = p;
  132672. p = (LookasideSlot*)&((u8*)p)[sz];
  132673. }
  132674. db->lookaside.pEnd = p;
  132675. db->lookaside.bDisable = 0;
  132676. db->lookaside.bMalloced = pBuf==0 ?1:0;
  132677. }else{
  132678. db->lookaside.pStart = db;
  132679. db->lookaside.pEnd = db;
  132680. db->lookaside.bDisable = 1;
  132681. db->lookaside.bMalloced = 0;
  132682. }
  132683. #endif /* SQLITE_OMIT_LOOKASIDE */
  132684. return SQLITE_OK;
  132685. }
  132686. /*
  132687. ** Return the mutex associated with a database connection.
  132688. */
  132689. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  132690. #ifdef SQLITE_ENABLE_API_ARMOR
  132691. if( !sqlite3SafetyCheckOk(db) ){
  132692. (void)SQLITE_MISUSE_BKPT;
  132693. return 0;
  132694. }
  132695. #endif
  132696. return db->mutex;
  132697. }
  132698. /*
  132699. ** Free up as much memory as we can from the given database
  132700. ** connection.
  132701. */
  132702. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  132703. int i;
  132704. #ifdef SQLITE_ENABLE_API_ARMOR
  132705. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  132706. #endif
  132707. sqlite3_mutex_enter(db->mutex);
  132708. sqlite3BtreeEnterAll(db);
  132709. for(i=0; i<db->nDb; i++){
  132710. Btree *pBt = db->aDb[i].pBt;
  132711. if( pBt ){
  132712. Pager *pPager = sqlite3BtreePager(pBt);
  132713. sqlite3PagerShrink(pPager);
  132714. }
  132715. }
  132716. sqlite3BtreeLeaveAll(db);
  132717. sqlite3_mutex_leave(db->mutex);
  132718. return SQLITE_OK;
  132719. }
  132720. /*
  132721. ** Flush any dirty pages in the pager-cache for any attached database
  132722. ** to disk.
  132723. */
  132724. SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
  132725. int i;
  132726. int rc = SQLITE_OK;
  132727. int bSeenBusy = 0;
  132728. #ifdef SQLITE_ENABLE_API_ARMOR
  132729. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  132730. #endif
  132731. sqlite3_mutex_enter(db->mutex);
  132732. sqlite3BtreeEnterAll(db);
  132733. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  132734. Btree *pBt = db->aDb[i].pBt;
  132735. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  132736. Pager *pPager = sqlite3BtreePager(pBt);
  132737. rc = sqlite3PagerFlush(pPager);
  132738. if( rc==SQLITE_BUSY ){
  132739. bSeenBusy = 1;
  132740. rc = SQLITE_OK;
  132741. }
  132742. }
  132743. }
  132744. sqlite3BtreeLeaveAll(db);
  132745. sqlite3_mutex_leave(db->mutex);
  132746. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  132747. }
  132748. /*
  132749. ** Configuration settings for an individual database connection
  132750. */
  132751. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  132752. va_list ap;
  132753. int rc;
  132754. va_start(ap, op);
  132755. switch( op ){
  132756. case SQLITE_DBCONFIG_MAINDBNAME: {
  132757. db->aDb[0].zDbSName = va_arg(ap,char*);
  132758. rc = SQLITE_OK;
  132759. break;
  132760. }
  132761. case SQLITE_DBCONFIG_LOOKASIDE: {
  132762. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  132763. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  132764. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  132765. rc = setupLookaside(db, pBuf, sz, cnt);
  132766. break;
  132767. }
  132768. default: {
  132769. static const struct {
  132770. int op; /* The opcode */
  132771. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  132772. } aFlagOp[] = {
  132773. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  132774. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  132775. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  132776. { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
  132777. { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
  132778. };
  132779. unsigned int i;
  132780. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  132781. for(i=0; i<ArraySize(aFlagOp); i++){
  132782. if( aFlagOp[i].op==op ){
  132783. int onoff = va_arg(ap, int);
  132784. int *pRes = va_arg(ap, int*);
  132785. int oldFlags = db->flags;
  132786. if( onoff>0 ){
  132787. db->flags |= aFlagOp[i].mask;
  132788. }else if( onoff==0 ){
  132789. db->flags &= ~aFlagOp[i].mask;
  132790. }
  132791. if( oldFlags!=db->flags ){
  132792. sqlite3ExpirePreparedStatements(db);
  132793. }
  132794. if( pRes ){
  132795. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  132796. }
  132797. rc = SQLITE_OK;
  132798. break;
  132799. }
  132800. }
  132801. break;
  132802. }
  132803. }
  132804. va_end(ap);
  132805. return rc;
  132806. }
  132807. /*
  132808. ** Return true if the buffer z[0..n-1] contains all spaces.
  132809. */
  132810. static int allSpaces(const char *z, int n){
  132811. while( n>0 && z[n-1]==' ' ){ n--; }
  132812. return n==0;
  132813. }
  132814. /*
  132815. ** This is the default collating function named "BINARY" which is always
  132816. ** available.
  132817. **
  132818. ** If the padFlag argument is not NULL then space padding at the end
  132819. ** of strings is ignored. This implements the RTRIM collation.
  132820. */
  132821. static int binCollFunc(
  132822. void *padFlag,
  132823. int nKey1, const void *pKey1,
  132824. int nKey2, const void *pKey2
  132825. ){
  132826. int rc, n;
  132827. n = nKey1<nKey2 ? nKey1 : nKey2;
  132828. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  132829. ** strings byte by byte using the memcmp() function from the standard C
  132830. ** library. */
  132831. rc = memcmp(pKey1, pKey2, n);
  132832. if( rc==0 ){
  132833. if( padFlag
  132834. && allSpaces(((char*)pKey1)+n, nKey1-n)
  132835. && allSpaces(((char*)pKey2)+n, nKey2-n)
  132836. ){
  132837. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  132838. ** spaces at the end of either string do not change the result. In other
  132839. ** words, strings will compare equal to one another as long as they
  132840. ** differ only in the number of spaces at the end.
  132841. */
  132842. }else{
  132843. rc = nKey1 - nKey2;
  132844. }
  132845. }
  132846. return rc;
  132847. }
  132848. /*
  132849. ** Another built-in collating sequence: NOCASE.
  132850. **
  132851. ** This collating sequence is intended to be used for "case independent
  132852. ** comparison". SQLite's knowledge of upper and lower case equivalents
  132853. ** extends only to the 26 characters used in the English language.
  132854. **
  132855. ** At the moment there is only a UTF-8 implementation.
  132856. */
  132857. static int nocaseCollatingFunc(
  132858. void *NotUsed,
  132859. int nKey1, const void *pKey1,
  132860. int nKey2, const void *pKey2
  132861. ){
  132862. int r = sqlite3StrNICmp(
  132863. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  132864. UNUSED_PARAMETER(NotUsed);
  132865. if( 0==r ){
  132866. r = nKey1-nKey2;
  132867. }
  132868. return r;
  132869. }
  132870. /*
  132871. ** Return the ROWID of the most recent insert
  132872. */
  132873. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  132874. #ifdef SQLITE_ENABLE_API_ARMOR
  132875. if( !sqlite3SafetyCheckOk(db) ){
  132876. (void)SQLITE_MISUSE_BKPT;
  132877. return 0;
  132878. }
  132879. #endif
  132880. return db->lastRowid;
  132881. }
  132882. /*
  132883. ** Set the value returned by the sqlite3_last_insert_rowid() API function.
  132884. */
  132885. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
  132886. #ifdef SQLITE_ENABLE_API_ARMOR
  132887. if( !sqlite3SafetyCheckOk(db) ){
  132888. (void)SQLITE_MISUSE_BKPT;
  132889. return;
  132890. }
  132891. #endif
  132892. sqlite3_mutex_enter(db->mutex);
  132893. db->lastRowid = iRowid;
  132894. sqlite3_mutex_leave(db->mutex);
  132895. }
  132896. /*
  132897. ** Return the number of changes in the most recent call to sqlite3_exec().
  132898. */
  132899. SQLITE_API int sqlite3_changes(sqlite3 *db){
  132900. #ifdef SQLITE_ENABLE_API_ARMOR
  132901. if( !sqlite3SafetyCheckOk(db) ){
  132902. (void)SQLITE_MISUSE_BKPT;
  132903. return 0;
  132904. }
  132905. #endif
  132906. return db->nChange;
  132907. }
  132908. /*
  132909. ** Return the number of changes since the database handle was opened.
  132910. */
  132911. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  132912. #ifdef SQLITE_ENABLE_API_ARMOR
  132913. if( !sqlite3SafetyCheckOk(db) ){
  132914. (void)SQLITE_MISUSE_BKPT;
  132915. return 0;
  132916. }
  132917. #endif
  132918. return db->nTotalChange;
  132919. }
  132920. /*
  132921. ** Close all open savepoints. This function only manipulates fields of the
  132922. ** database handle object, it does not close any savepoints that may be open
  132923. ** at the b-tree/pager level.
  132924. */
  132925. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  132926. while( db->pSavepoint ){
  132927. Savepoint *pTmp = db->pSavepoint;
  132928. db->pSavepoint = pTmp->pNext;
  132929. sqlite3DbFree(db, pTmp);
  132930. }
  132931. db->nSavepoint = 0;
  132932. db->nStatement = 0;
  132933. db->isTransactionSavepoint = 0;
  132934. }
  132935. /*
  132936. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  132937. ** if this is not the last copy of the function, do not invoke it. Multiple
  132938. ** copies of a single function are created when create_function() is called
  132939. ** with SQLITE_ANY as the encoding.
  132940. */
  132941. static void functionDestroy(sqlite3 *db, FuncDef *p){
  132942. FuncDestructor *pDestructor = p->u.pDestructor;
  132943. if( pDestructor ){
  132944. pDestructor->nRef--;
  132945. if( pDestructor->nRef==0 ){
  132946. pDestructor->xDestroy(pDestructor->pUserData);
  132947. sqlite3DbFree(db, pDestructor);
  132948. }
  132949. }
  132950. }
  132951. /*
  132952. ** Disconnect all sqlite3_vtab objects that belong to database connection
  132953. ** db. This is called when db is being closed.
  132954. */
  132955. static void disconnectAllVtab(sqlite3 *db){
  132956. #ifndef SQLITE_OMIT_VIRTUALTABLE
  132957. int i;
  132958. HashElem *p;
  132959. sqlite3BtreeEnterAll(db);
  132960. for(i=0; i<db->nDb; i++){
  132961. Schema *pSchema = db->aDb[i].pSchema;
  132962. if( db->aDb[i].pSchema ){
  132963. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  132964. Table *pTab = (Table *)sqliteHashData(p);
  132965. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  132966. }
  132967. }
  132968. }
  132969. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  132970. Module *pMod = (Module *)sqliteHashData(p);
  132971. if( pMod->pEpoTab ){
  132972. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  132973. }
  132974. }
  132975. sqlite3VtabUnlockList(db);
  132976. sqlite3BtreeLeaveAll(db);
  132977. #else
  132978. UNUSED_PARAMETER(db);
  132979. #endif
  132980. }
  132981. /*
  132982. ** Return TRUE if database connection db has unfinalized prepared
  132983. ** statements or unfinished sqlite3_backup objects.
  132984. */
  132985. static int connectionIsBusy(sqlite3 *db){
  132986. int j;
  132987. assert( sqlite3_mutex_held(db->mutex) );
  132988. if( db->pVdbe ) return 1;
  132989. for(j=0; j<db->nDb; j++){
  132990. Btree *pBt = db->aDb[j].pBt;
  132991. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  132992. }
  132993. return 0;
  132994. }
  132995. /*
  132996. ** Close an existing SQLite database
  132997. */
  132998. static int sqlite3Close(sqlite3 *db, int forceZombie){
  132999. if( !db ){
  133000. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  133001. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  133002. return SQLITE_OK;
  133003. }
  133004. if( !sqlite3SafetyCheckSickOrOk(db) ){
  133005. return SQLITE_MISUSE_BKPT;
  133006. }
  133007. sqlite3_mutex_enter(db->mutex);
  133008. if( db->mTrace & SQLITE_TRACE_CLOSE ){
  133009. db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
  133010. }
  133011. /* Force xDisconnect calls on all virtual tables */
  133012. disconnectAllVtab(db);
  133013. /* If a transaction is open, the disconnectAllVtab() call above
  133014. ** will not have called the xDisconnect() method on any virtual
  133015. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  133016. ** call will do so. We need to do this before the check for active
  133017. ** SQL statements below, as the v-table implementation may be storing
  133018. ** some prepared statements internally.
  133019. */
  133020. sqlite3VtabRollback(db);
  133021. /* Legacy behavior (sqlite3_close() behavior) is to return
  133022. ** SQLITE_BUSY if the connection can not be closed immediately.
  133023. */
  133024. if( !forceZombie && connectionIsBusy(db) ){
  133025. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  133026. "statements or unfinished backups");
  133027. sqlite3_mutex_leave(db->mutex);
  133028. return SQLITE_BUSY;
  133029. }
  133030. #ifdef SQLITE_ENABLE_SQLLOG
  133031. if( sqlite3GlobalConfig.xSqllog ){
  133032. /* Closing the handle. Fourth parameter is passed the value 2. */
  133033. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  133034. }
  133035. #endif
  133036. /* Convert the connection into a zombie and then close it.
  133037. */
  133038. db->magic = SQLITE_MAGIC_ZOMBIE;
  133039. sqlite3LeaveMutexAndCloseZombie(db);
  133040. return SQLITE_OK;
  133041. }
  133042. /*
  133043. ** Two variations on the public interface for closing a database
  133044. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  133045. ** leaves the connection option if there are unfinalized prepared
  133046. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  133047. ** version forces the connection to become a zombie if there are
  133048. ** unclosed resources, and arranges for deallocation when the last
  133049. ** prepare statement or sqlite3_backup closes.
  133050. */
  133051. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  133052. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  133053. /*
  133054. ** Close the mutex on database connection db.
  133055. **
  133056. ** Furthermore, if database connection db is a zombie (meaning that there
  133057. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  133058. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  133059. ** finished, then free all resources.
  133060. */
  133061. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  133062. HashElem *i; /* Hash table iterator */
  133063. int j;
  133064. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  133065. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  133066. ** then just leave the mutex and return.
  133067. */
  133068. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  133069. sqlite3_mutex_leave(db->mutex);
  133070. return;
  133071. }
  133072. /* If we reach this point, it means that the database connection has
  133073. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  133074. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  133075. ** go ahead and free all resources.
  133076. */
  133077. /* If a transaction is open, roll it back. This also ensures that if
  133078. ** any database schemas have been modified by an uncommitted transaction
  133079. ** they are reset. And that the required b-tree mutex is held to make
  133080. ** the pager rollback and schema reset an atomic operation. */
  133081. sqlite3RollbackAll(db, SQLITE_OK);
  133082. /* Free any outstanding Savepoint structures. */
  133083. sqlite3CloseSavepoints(db);
  133084. /* Close all database connections */
  133085. for(j=0; j<db->nDb; j++){
  133086. struct Db *pDb = &db->aDb[j];
  133087. if( pDb->pBt ){
  133088. sqlite3BtreeClose(pDb->pBt);
  133089. pDb->pBt = 0;
  133090. if( j!=1 ){
  133091. pDb->pSchema = 0;
  133092. }
  133093. }
  133094. }
  133095. /* Clear the TEMP schema separately and last */
  133096. if( db->aDb[1].pSchema ){
  133097. sqlite3SchemaClear(db->aDb[1].pSchema);
  133098. }
  133099. sqlite3VtabUnlockList(db);
  133100. /* Free up the array of auxiliary databases */
  133101. sqlite3CollapseDatabaseArray(db);
  133102. assert( db->nDb<=2 );
  133103. assert( db->aDb==db->aDbStatic );
  133104. /* Tell the code in notify.c that the connection no longer holds any
  133105. ** locks and does not require any further unlock-notify callbacks.
  133106. */
  133107. sqlite3ConnectionClosed(db);
  133108. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  133109. FuncDef *pNext, *p;
  133110. p = sqliteHashData(i);
  133111. do{
  133112. functionDestroy(db, p);
  133113. pNext = p->pNext;
  133114. sqlite3DbFree(db, p);
  133115. p = pNext;
  133116. }while( p );
  133117. }
  133118. sqlite3HashClear(&db->aFunc);
  133119. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  133120. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  133121. /* Invoke any destructors registered for collation sequence user data. */
  133122. for(j=0; j<3; j++){
  133123. if( pColl[j].xDel ){
  133124. pColl[j].xDel(pColl[j].pUser);
  133125. }
  133126. }
  133127. sqlite3DbFree(db, pColl);
  133128. }
  133129. sqlite3HashClear(&db->aCollSeq);
  133130. #ifndef SQLITE_OMIT_VIRTUALTABLE
  133131. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  133132. Module *pMod = (Module *)sqliteHashData(i);
  133133. if( pMod->xDestroy ){
  133134. pMod->xDestroy(pMod->pAux);
  133135. }
  133136. sqlite3VtabEponymousTableClear(db, pMod);
  133137. sqlite3DbFree(db, pMod);
  133138. }
  133139. sqlite3HashClear(&db->aModule);
  133140. #endif
  133141. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  133142. sqlite3ValueFree(db->pErr);
  133143. sqlite3CloseExtensions(db);
  133144. #if SQLITE_USER_AUTHENTICATION
  133145. sqlite3_free(db->auth.zAuthUser);
  133146. sqlite3_free(db->auth.zAuthPW);
  133147. #endif
  133148. db->magic = SQLITE_MAGIC_ERROR;
  133149. /* The temp-database schema is allocated differently from the other schema
  133150. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  133151. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  133152. ** the same sqliteMalloc() as the one that allocates the database
  133153. ** structure?
  133154. */
  133155. sqlite3DbFree(db, db->aDb[1].pSchema);
  133156. sqlite3_mutex_leave(db->mutex);
  133157. db->magic = SQLITE_MAGIC_CLOSED;
  133158. sqlite3_mutex_free(db->mutex);
  133159. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  133160. if( db->lookaside.bMalloced ){
  133161. sqlite3_free(db->lookaside.pStart);
  133162. }
  133163. sqlite3_free(db);
  133164. }
  133165. /*
  133166. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  133167. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  133168. ** breaker") and made to return tripCode if there are any further
  133169. ** attempts to use that cursor. Read cursors remain open and valid
  133170. ** but are "saved" in case the table pages are moved around.
  133171. */
  133172. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  133173. int i;
  133174. int inTrans = 0;
  133175. int schemaChange;
  133176. assert( sqlite3_mutex_held(db->mutex) );
  133177. sqlite3BeginBenignMalloc();
  133178. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  133179. ** This is important in case the transaction being rolled back has
  133180. ** modified the database schema. If the b-tree mutexes are not taken
  133181. ** here, then another shared-cache connection might sneak in between
  133182. ** the database rollback and schema reset, which can cause false
  133183. ** corruption reports in some cases. */
  133184. sqlite3BtreeEnterAll(db);
  133185. schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
  133186. for(i=0; i<db->nDb; i++){
  133187. Btree *p = db->aDb[i].pBt;
  133188. if( p ){
  133189. if( sqlite3BtreeIsInTrans(p) ){
  133190. inTrans = 1;
  133191. }
  133192. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  133193. }
  133194. }
  133195. sqlite3VtabRollback(db);
  133196. sqlite3EndBenignMalloc();
  133197. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  133198. sqlite3ExpirePreparedStatements(db);
  133199. sqlite3ResetAllSchemasOfConnection(db);
  133200. }
  133201. sqlite3BtreeLeaveAll(db);
  133202. /* Any deferred constraint violations have now been resolved. */
  133203. db->nDeferredCons = 0;
  133204. db->nDeferredImmCons = 0;
  133205. db->flags &= ~SQLITE_DeferFKs;
  133206. /* If one has been configured, invoke the rollback-hook callback */
  133207. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  133208. db->xRollbackCallback(db->pRollbackArg);
  133209. }
  133210. }
  133211. /*
  133212. ** Return a static string containing the name corresponding to the error code
  133213. ** specified in the argument.
  133214. */
  133215. #if defined(SQLITE_NEED_ERR_NAME)
  133216. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  133217. const char *zName = 0;
  133218. int i, origRc = rc;
  133219. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  133220. switch( rc ){
  133221. case SQLITE_OK: zName = "SQLITE_OK"; break;
  133222. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  133223. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  133224. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  133225. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  133226. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  133227. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  133228. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  133229. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  133230. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  133231. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  133232. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  133233. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  133234. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  133235. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  133236. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  133237. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  133238. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  133239. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  133240. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  133241. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  133242. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  133243. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  133244. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  133245. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  133246. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  133247. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  133248. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  133249. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  133250. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  133251. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  133252. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  133253. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  133254. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  133255. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  133256. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  133257. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  133258. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  133259. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  133260. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  133261. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  133262. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  133263. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  133264. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  133265. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  133266. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  133267. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  133268. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  133269. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  133270. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  133271. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  133272. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  133273. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  133274. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  133275. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  133276. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  133277. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  133278. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  133279. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  133280. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  133281. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  133282. case SQLITE_CONSTRAINT_FOREIGNKEY:
  133283. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  133284. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  133285. case SQLITE_CONSTRAINT_PRIMARYKEY:
  133286. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  133287. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  133288. case SQLITE_CONSTRAINT_COMMITHOOK:
  133289. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  133290. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  133291. case SQLITE_CONSTRAINT_FUNCTION:
  133292. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  133293. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  133294. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  133295. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  133296. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  133297. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  133298. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  133299. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  133300. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  133301. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  133302. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  133303. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  133304. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  133305. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  133306. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  133307. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  133308. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  133309. }
  133310. }
  133311. if( zName==0 ){
  133312. static char zBuf[50];
  133313. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  133314. zName = zBuf;
  133315. }
  133316. return zName;
  133317. }
  133318. #endif
  133319. /*
  133320. ** Return a static string that describes the kind of error specified in the
  133321. ** argument.
  133322. */
  133323. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  133324. static const char* const aMsg[] = {
  133325. /* SQLITE_OK */ "not an error",
  133326. /* SQLITE_ERROR */ "SQL logic error or missing database",
  133327. /* SQLITE_INTERNAL */ 0,
  133328. /* SQLITE_PERM */ "access permission denied",
  133329. /* SQLITE_ABORT */ "callback requested query abort",
  133330. /* SQLITE_BUSY */ "database is locked",
  133331. /* SQLITE_LOCKED */ "database table is locked",
  133332. /* SQLITE_NOMEM */ "out of memory",
  133333. /* SQLITE_READONLY */ "attempt to write a readonly database",
  133334. /* SQLITE_INTERRUPT */ "interrupted",
  133335. /* SQLITE_IOERR */ "disk I/O error",
  133336. /* SQLITE_CORRUPT */ "database disk image is malformed",
  133337. /* SQLITE_NOTFOUND */ "unknown operation",
  133338. /* SQLITE_FULL */ "database or disk is full",
  133339. /* SQLITE_CANTOPEN */ "unable to open database file",
  133340. /* SQLITE_PROTOCOL */ "locking protocol",
  133341. /* SQLITE_EMPTY */ "table contains no data",
  133342. /* SQLITE_SCHEMA */ "database schema has changed",
  133343. /* SQLITE_TOOBIG */ "string or blob too big",
  133344. /* SQLITE_CONSTRAINT */ "constraint failed",
  133345. /* SQLITE_MISMATCH */ "datatype mismatch",
  133346. /* SQLITE_MISUSE */ "library routine called out of sequence",
  133347. /* SQLITE_NOLFS */ "large file support is disabled",
  133348. /* SQLITE_AUTH */ "authorization denied",
  133349. /* SQLITE_FORMAT */ "auxiliary database format error",
  133350. /* SQLITE_RANGE */ "bind or column index out of range",
  133351. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  133352. };
  133353. const char *zErr = "unknown error";
  133354. switch( rc ){
  133355. case SQLITE_ABORT_ROLLBACK: {
  133356. zErr = "abort due to ROLLBACK";
  133357. break;
  133358. }
  133359. default: {
  133360. rc &= 0xff;
  133361. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  133362. zErr = aMsg[rc];
  133363. }
  133364. break;
  133365. }
  133366. }
  133367. return zErr;
  133368. }
  133369. /*
  133370. ** This routine implements a busy callback that sleeps and tries
  133371. ** again until a timeout value is reached. The timeout value is
  133372. ** an integer number of milliseconds passed in as the first
  133373. ** argument.
  133374. */
  133375. static int sqliteDefaultBusyCallback(
  133376. void *ptr, /* Database connection */
  133377. int count /* Number of times table has been busy */
  133378. ){
  133379. #if SQLITE_OS_WIN || HAVE_USLEEP
  133380. static const u8 delays[] =
  133381. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  133382. static const u8 totals[] =
  133383. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  133384. # define NDELAY ArraySize(delays)
  133385. sqlite3 *db = (sqlite3 *)ptr;
  133386. int timeout = db->busyTimeout;
  133387. int delay, prior;
  133388. assert( count>=0 );
  133389. if( count < NDELAY ){
  133390. delay = delays[count];
  133391. prior = totals[count];
  133392. }else{
  133393. delay = delays[NDELAY-1];
  133394. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  133395. }
  133396. if( prior + delay > timeout ){
  133397. delay = timeout - prior;
  133398. if( delay<=0 ) return 0;
  133399. }
  133400. sqlite3OsSleep(db->pVfs, delay*1000);
  133401. return 1;
  133402. #else
  133403. sqlite3 *db = (sqlite3 *)ptr;
  133404. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  133405. if( (count+1)*1000 > timeout ){
  133406. return 0;
  133407. }
  133408. sqlite3OsSleep(db->pVfs, 1000000);
  133409. return 1;
  133410. #endif
  133411. }
  133412. /*
  133413. ** Invoke the given busy handler.
  133414. **
  133415. ** This routine is called when an operation failed with a lock.
  133416. ** If this routine returns non-zero, the lock is retried. If it
  133417. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  133418. */
  133419. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  133420. int rc;
  133421. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  133422. rc = p->xFunc(p->pArg, p->nBusy);
  133423. if( rc==0 ){
  133424. p->nBusy = -1;
  133425. }else{
  133426. p->nBusy++;
  133427. }
  133428. return rc;
  133429. }
  133430. /*
  133431. ** This routine sets the busy callback for an Sqlite database to the
  133432. ** given callback function with the given argument.
  133433. */
  133434. SQLITE_API int sqlite3_busy_handler(
  133435. sqlite3 *db,
  133436. int (*xBusy)(void*,int),
  133437. void *pArg
  133438. ){
  133439. #ifdef SQLITE_ENABLE_API_ARMOR
  133440. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  133441. #endif
  133442. sqlite3_mutex_enter(db->mutex);
  133443. db->busyHandler.xFunc = xBusy;
  133444. db->busyHandler.pArg = pArg;
  133445. db->busyHandler.nBusy = 0;
  133446. db->busyTimeout = 0;
  133447. sqlite3_mutex_leave(db->mutex);
  133448. return SQLITE_OK;
  133449. }
  133450. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  133451. /*
  133452. ** This routine sets the progress callback for an Sqlite database to the
  133453. ** given callback function with the given argument. The progress callback will
  133454. ** be invoked every nOps opcodes.
  133455. */
  133456. SQLITE_API void sqlite3_progress_handler(
  133457. sqlite3 *db,
  133458. int nOps,
  133459. int (*xProgress)(void*),
  133460. void *pArg
  133461. ){
  133462. #ifdef SQLITE_ENABLE_API_ARMOR
  133463. if( !sqlite3SafetyCheckOk(db) ){
  133464. (void)SQLITE_MISUSE_BKPT;
  133465. return;
  133466. }
  133467. #endif
  133468. sqlite3_mutex_enter(db->mutex);
  133469. if( nOps>0 ){
  133470. db->xProgress = xProgress;
  133471. db->nProgressOps = (unsigned)nOps;
  133472. db->pProgressArg = pArg;
  133473. }else{
  133474. db->xProgress = 0;
  133475. db->nProgressOps = 0;
  133476. db->pProgressArg = 0;
  133477. }
  133478. sqlite3_mutex_leave(db->mutex);
  133479. }
  133480. #endif
  133481. /*
  133482. ** This routine installs a default busy handler that waits for the
  133483. ** specified number of milliseconds before returning 0.
  133484. */
  133485. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  133486. #ifdef SQLITE_ENABLE_API_ARMOR
  133487. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  133488. #endif
  133489. if( ms>0 ){
  133490. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  133491. db->busyTimeout = ms;
  133492. }else{
  133493. sqlite3_busy_handler(db, 0, 0);
  133494. }
  133495. return SQLITE_OK;
  133496. }
  133497. /*
  133498. ** Cause any pending operation to stop at its earliest opportunity.
  133499. */
  133500. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  133501. #ifdef SQLITE_ENABLE_API_ARMOR
  133502. if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
  133503. (void)SQLITE_MISUSE_BKPT;
  133504. return;
  133505. }
  133506. #endif
  133507. db->u1.isInterrupted = 1;
  133508. }
  133509. /*
  133510. ** This function is exactly the same as sqlite3_create_function(), except
  133511. ** that it is designed to be called by internal code. The difference is
  133512. ** that if a malloc() fails in sqlite3_create_function(), an error code
  133513. ** is returned and the mallocFailed flag cleared.
  133514. */
  133515. SQLITE_PRIVATE int sqlite3CreateFunc(
  133516. sqlite3 *db,
  133517. const char *zFunctionName,
  133518. int nArg,
  133519. int enc,
  133520. void *pUserData,
  133521. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  133522. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  133523. void (*xFinal)(sqlite3_context*),
  133524. FuncDestructor *pDestructor
  133525. ){
  133526. FuncDef *p;
  133527. int nName;
  133528. int extraFlags;
  133529. assert( sqlite3_mutex_held(db->mutex) );
  133530. if( zFunctionName==0 ||
  133531. (xSFunc && (xFinal || xStep)) ||
  133532. (!xSFunc && (xFinal && !xStep)) ||
  133533. (!xSFunc && (!xFinal && xStep)) ||
  133534. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  133535. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  133536. return SQLITE_MISUSE_BKPT;
  133537. }
  133538. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  133539. extraFlags = enc & SQLITE_DETERMINISTIC;
  133540. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  133541. #ifndef SQLITE_OMIT_UTF16
  133542. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  133543. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  133544. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  133545. **
  133546. ** If SQLITE_ANY is specified, add three versions of the function
  133547. ** to the hash table.
  133548. */
  133549. if( enc==SQLITE_UTF16 ){
  133550. enc = SQLITE_UTF16NATIVE;
  133551. }else if( enc==SQLITE_ANY ){
  133552. int rc;
  133553. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  133554. pUserData, xSFunc, xStep, xFinal, pDestructor);
  133555. if( rc==SQLITE_OK ){
  133556. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  133557. pUserData, xSFunc, xStep, xFinal, pDestructor);
  133558. }
  133559. if( rc!=SQLITE_OK ){
  133560. return rc;
  133561. }
  133562. enc = SQLITE_UTF16BE;
  133563. }
  133564. #else
  133565. enc = SQLITE_UTF8;
  133566. #endif
  133567. /* Check if an existing function is being overridden or deleted. If so,
  133568. ** and there are active VMs, then return SQLITE_BUSY. If a function
  133569. ** is being overridden/deleted but there are no active VMs, allow the
  133570. ** operation to continue but invalidate all precompiled statements.
  133571. */
  133572. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  133573. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  133574. if( db->nVdbeActive ){
  133575. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  133576. "unable to delete/modify user-function due to active statements");
  133577. assert( !db->mallocFailed );
  133578. return SQLITE_BUSY;
  133579. }else{
  133580. sqlite3ExpirePreparedStatements(db);
  133581. }
  133582. }
  133583. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  133584. assert(p || db->mallocFailed);
  133585. if( !p ){
  133586. return SQLITE_NOMEM_BKPT;
  133587. }
  133588. /* If an older version of the function with a configured destructor is
  133589. ** being replaced invoke the destructor function here. */
  133590. functionDestroy(db, p);
  133591. if( pDestructor ){
  133592. pDestructor->nRef++;
  133593. }
  133594. p->u.pDestructor = pDestructor;
  133595. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  133596. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  133597. p->xSFunc = xSFunc ? xSFunc : xStep;
  133598. p->xFinalize = xFinal;
  133599. p->pUserData = pUserData;
  133600. p->nArg = (u16)nArg;
  133601. return SQLITE_OK;
  133602. }
  133603. /*
  133604. ** Create new user functions.
  133605. */
  133606. SQLITE_API int sqlite3_create_function(
  133607. sqlite3 *db,
  133608. const char *zFunc,
  133609. int nArg,
  133610. int enc,
  133611. void *p,
  133612. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  133613. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  133614. void (*xFinal)(sqlite3_context*)
  133615. ){
  133616. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
  133617. xFinal, 0);
  133618. }
  133619. SQLITE_API int sqlite3_create_function_v2(
  133620. sqlite3 *db,
  133621. const char *zFunc,
  133622. int nArg,
  133623. int enc,
  133624. void *p,
  133625. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  133626. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  133627. void (*xFinal)(sqlite3_context*),
  133628. void (*xDestroy)(void *)
  133629. ){
  133630. int rc = SQLITE_ERROR;
  133631. FuncDestructor *pArg = 0;
  133632. #ifdef SQLITE_ENABLE_API_ARMOR
  133633. if( !sqlite3SafetyCheckOk(db) ){
  133634. return SQLITE_MISUSE_BKPT;
  133635. }
  133636. #endif
  133637. sqlite3_mutex_enter(db->mutex);
  133638. if( xDestroy ){
  133639. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  133640. if( !pArg ){
  133641. xDestroy(p);
  133642. goto out;
  133643. }
  133644. pArg->xDestroy = xDestroy;
  133645. pArg->pUserData = p;
  133646. }
  133647. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
  133648. if( pArg && pArg->nRef==0 ){
  133649. assert( rc!=SQLITE_OK );
  133650. xDestroy(p);
  133651. sqlite3DbFree(db, pArg);
  133652. }
  133653. out:
  133654. rc = sqlite3ApiExit(db, rc);
  133655. sqlite3_mutex_leave(db->mutex);
  133656. return rc;
  133657. }
  133658. #ifndef SQLITE_OMIT_UTF16
  133659. SQLITE_API int sqlite3_create_function16(
  133660. sqlite3 *db,
  133661. const void *zFunctionName,
  133662. int nArg,
  133663. int eTextRep,
  133664. void *p,
  133665. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  133666. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  133667. void (*xFinal)(sqlite3_context*)
  133668. ){
  133669. int rc;
  133670. char *zFunc8;
  133671. #ifdef SQLITE_ENABLE_API_ARMOR
  133672. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  133673. #endif
  133674. sqlite3_mutex_enter(db->mutex);
  133675. assert( !db->mallocFailed );
  133676. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  133677. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
  133678. sqlite3DbFree(db, zFunc8);
  133679. rc = sqlite3ApiExit(db, rc);
  133680. sqlite3_mutex_leave(db->mutex);
  133681. return rc;
  133682. }
  133683. #endif
  133684. /*
  133685. ** Declare that a function has been overloaded by a virtual table.
  133686. **
  133687. ** If the function already exists as a regular global function, then
  133688. ** this routine is a no-op. If the function does not exist, then create
  133689. ** a new one that always throws a run-time error.
  133690. **
  133691. ** When virtual tables intend to provide an overloaded function, they
  133692. ** should call this routine to make sure the global function exists.
  133693. ** A global function must exist in order for name resolution to work
  133694. ** properly.
  133695. */
  133696. SQLITE_API int sqlite3_overload_function(
  133697. sqlite3 *db,
  133698. const char *zName,
  133699. int nArg
  133700. ){
  133701. int rc = SQLITE_OK;
  133702. #ifdef SQLITE_ENABLE_API_ARMOR
  133703. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  133704. return SQLITE_MISUSE_BKPT;
  133705. }
  133706. #endif
  133707. sqlite3_mutex_enter(db->mutex);
  133708. if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
  133709. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  133710. 0, sqlite3InvalidFunction, 0, 0, 0);
  133711. }
  133712. rc = sqlite3ApiExit(db, rc);
  133713. sqlite3_mutex_leave(db->mutex);
  133714. return rc;
  133715. }
  133716. #ifndef SQLITE_OMIT_TRACE
  133717. /*
  133718. ** Register a trace function. The pArg from the previously registered trace
  133719. ** is returned.
  133720. **
  133721. ** A NULL trace function means that no tracing is executes. A non-NULL
  133722. ** trace is a pointer to a function that is invoked at the start of each
  133723. ** SQL statement.
  133724. */
  133725. #ifndef SQLITE_OMIT_DEPRECATED
  133726. SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
  133727. void *pOld;
  133728. #ifdef SQLITE_ENABLE_API_ARMOR
  133729. if( !sqlite3SafetyCheckOk(db) ){
  133730. (void)SQLITE_MISUSE_BKPT;
  133731. return 0;
  133732. }
  133733. #endif
  133734. sqlite3_mutex_enter(db->mutex);
  133735. pOld = db->pTraceArg;
  133736. db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
  133737. db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
  133738. db->pTraceArg = pArg;
  133739. sqlite3_mutex_leave(db->mutex);
  133740. return pOld;
  133741. }
  133742. #endif /* SQLITE_OMIT_DEPRECATED */
  133743. /* Register a trace callback using the version-2 interface.
  133744. */
  133745. SQLITE_API int sqlite3_trace_v2(
  133746. sqlite3 *db, /* Trace this connection */
  133747. unsigned mTrace, /* Mask of events to be traced */
  133748. int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
  133749. void *pArg /* Context */
  133750. ){
  133751. #ifdef SQLITE_ENABLE_API_ARMOR
  133752. if( !sqlite3SafetyCheckOk(db) ){
  133753. return SQLITE_MISUSE_BKPT;
  133754. }
  133755. #endif
  133756. sqlite3_mutex_enter(db->mutex);
  133757. if( mTrace==0 ) xTrace = 0;
  133758. if( xTrace==0 ) mTrace = 0;
  133759. db->mTrace = mTrace;
  133760. db->xTrace = xTrace;
  133761. db->pTraceArg = pArg;
  133762. sqlite3_mutex_leave(db->mutex);
  133763. return SQLITE_OK;
  133764. }
  133765. #ifndef SQLITE_OMIT_DEPRECATED
  133766. /*
  133767. ** Register a profile function. The pArg from the previously registered
  133768. ** profile function is returned.
  133769. **
  133770. ** A NULL profile function means that no profiling is executes. A non-NULL
  133771. ** profile is a pointer to a function that is invoked at the conclusion of
  133772. ** each SQL statement that is run.
  133773. */
  133774. SQLITE_API void *sqlite3_profile(
  133775. sqlite3 *db,
  133776. void (*xProfile)(void*,const char*,sqlite_uint64),
  133777. void *pArg
  133778. ){
  133779. void *pOld;
  133780. #ifdef SQLITE_ENABLE_API_ARMOR
  133781. if( !sqlite3SafetyCheckOk(db) ){
  133782. (void)SQLITE_MISUSE_BKPT;
  133783. return 0;
  133784. }
  133785. #endif
  133786. sqlite3_mutex_enter(db->mutex);
  133787. pOld = db->pProfileArg;
  133788. db->xProfile = xProfile;
  133789. db->pProfileArg = pArg;
  133790. sqlite3_mutex_leave(db->mutex);
  133791. return pOld;
  133792. }
  133793. #endif /* SQLITE_OMIT_DEPRECATED */
  133794. #endif /* SQLITE_OMIT_TRACE */
  133795. /*
  133796. ** Register a function to be invoked when a transaction commits.
  133797. ** If the invoked function returns non-zero, then the commit becomes a
  133798. ** rollback.
  133799. */
  133800. SQLITE_API void *sqlite3_commit_hook(
  133801. sqlite3 *db, /* Attach the hook to this database */
  133802. int (*xCallback)(void*), /* Function to invoke on each commit */
  133803. void *pArg /* Argument to the function */
  133804. ){
  133805. void *pOld;
  133806. #ifdef SQLITE_ENABLE_API_ARMOR
  133807. if( !sqlite3SafetyCheckOk(db) ){
  133808. (void)SQLITE_MISUSE_BKPT;
  133809. return 0;
  133810. }
  133811. #endif
  133812. sqlite3_mutex_enter(db->mutex);
  133813. pOld = db->pCommitArg;
  133814. db->xCommitCallback = xCallback;
  133815. db->pCommitArg = pArg;
  133816. sqlite3_mutex_leave(db->mutex);
  133817. return pOld;
  133818. }
  133819. /*
  133820. ** Register a callback to be invoked each time a row is updated,
  133821. ** inserted or deleted using this database connection.
  133822. */
  133823. SQLITE_API void *sqlite3_update_hook(
  133824. sqlite3 *db, /* Attach the hook to this database */
  133825. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  133826. void *pArg /* Argument to the function */
  133827. ){
  133828. void *pRet;
  133829. #ifdef SQLITE_ENABLE_API_ARMOR
  133830. if( !sqlite3SafetyCheckOk(db) ){
  133831. (void)SQLITE_MISUSE_BKPT;
  133832. return 0;
  133833. }
  133834. #endif
  133835. sqlite3_mutex_enter(db->mutex);
  133836. pRet = db->pUpdateArg;
  133837. db->xUpdateCallback = xCallback;
  133838. db->pUpdateArg = pArg;
  133839. sqlite3_mutex_leave(db->mutex);
  133840. return pRet;
  133841. }
  133842. /*
  133843. ** Register a callback to be invoked each time a transaction is rolled
  133844. ** back by this database connection.
  133845. */
  133846. SQLITE_API void *sqlite3_rollback_hook(
  133847. sqlite3 *db, /* Attach the hook to this database */
  133848. void (*xCallback)(void*), /* Callback function */
  133849. void *pArg /* Argument to the function */
  133850. ){
  133851. void *pRet;
  133852. #ifdef SQLITE_ENABLE_API_ARMOR
  133853. if( !sqlite3SafetyCheckOk(db) ){
  133854. (void)SQLITE_MISUSE_BKPT;
  133855. return 0;
  133856. }
  133857. #endif
  133858. sqlite3_mutex_enter(db->mutex);
  133859. pRet = db->pRollbackArg;
  133860. db->xRollbackCallback = xCallback;
  133861. db->pRollbackArg = pArg;
  133862. sqlite3_mutex_leave(db->mutex);
  133863. return pRet;
  133864. }
  133865. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  133866. /*
  133867. ** Register a callback to be invoked each time a row is updated,
  133868. ** inserted or deleted using this database connection.
  133869. */
  133870. SQLITE_API void *sqlite3_preupdate_hook(
  133871. sqlite3 *db, /* Attach the hook to this database */
  133872. void(*xCallback)( /* Callback function */
  133873. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
  133874. void *pArg /* First callback argument */
  133875. ){
  133876. void *pRet;
  133877. sqlite3_mutex_enter(db->mutex);
  133878. pRet = db->pPreUpdateArg;
  133879. db->xPreUpdateCallback = xCallback;
  133880. db->pPreUpdateArg = pArg;
  133881. sqlite3_mutex_leave(db->mutex);
  133882. return pRet;
  133883. }
  133884. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  133885. #ifndef SQLITE_OMIT_WAL
  133886. /*
  133887. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  133888. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  133889. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  133890. ** wal_autocheckpoint()).
  133891. */
  133892. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  133893. void *pClientData, /* Argument */
  133894. sqlite3 *db, /* Connection */
  133895. const char *zDb, /* Database */
  133896. int nFrame /* Size of WAL */
  133897. ){
  133898. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  133899. sqlite3BeginBenignMalloc();
  133900. sqlite3_wal_checkpoint(db, zDb);
  133901. sqlite3EndBenignMalloc();
  133902. }
  133903. return SQLITE_OK;
  133904. }
  133905. #endif /* SQLITE_OMIT_WAL */
  133906. /*
  133907. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  133908. ** a database after committing a transaction if there are nFrame or
  133909. ** more frames in the log file. Passing zero or a negative value as the
  133910. ** nFrame parameter disables automatic checkpoints entirely.
  133911. **
  133912. ** The callback registered by this function replaces any existing callback
  133913. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  133914. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  133915. ** configured by this function.
  133916. */
  133917. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  133918. #ifdef SQLITE_OMIT_WAL
  133919. UNUSED_PARAMETER(db);
  133920. UNUSED_PARAMETER(nFrame);
  133921. #else
  133922. #ifdef SQLITE_ENABLE_API_ARMOR
  133923. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  133924. #endif
  133925. if( nFrame>0 ){
  133926. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  133927. }else{
  133928. sqlite3_wal_hook(db, 0, 0);
  133929. }
  133930. #endif
  133931. return SQLITE_OK;
  133932. }
  133933. /*
  133934. ** Register a callback to be invoked each time a transaction is written
  133935. ** into the write-ahead-log by this database connection.
  133936. */
  133937. SQLITE_API void *sqlite3_wal_hook(
  133938. sqlite3 *db, /* Attach the hook to this db handle */
  133939. int(*xCallback)(void *, sqlite3*, const char*, int),
  133940. void *pArg /* First argument passed to xCallback() */
  133941. ){
  133942. #ifndef SQLITE_OMIT_WAL
  133943. void *pRet;
  133944. #ifdef SQLITE_ENABLE_API_ARMOR
  133945. if( !sqlite3SafetyCheckOk(db) ){
  133946. (void)SQLITE_MISUSE_BKPT;
  133947. return 0;
  133948. }
  133949. #endif
  133950. sqlite3_mutex_enter(db->mutex);
  133951. pRet = db->pWalArg;
  133952. db->xWalCallback = xCallback;
  133953. db->pWalArg = pArg;
  133954. sqlite3_mutex_leave(db->mutex);
  133955. return pRet;
  133956. #else
  133957. return 0;
  133958. #endif
  133959. }
  133960. /*
  133961. ** Checkpoint database zDb.
  133962. */
  133963. SQLITE_API int sqlite3_wal_checkpoint_v2(
  133964. sqlite3 *db, /* Database handle */
  133965. const char *zDb, /* Name of attached database (or NULL) */
  133966. int eMode, /* SQLITE_CHECKPOINT_* value */
  133967. int *pnLog, /* OUT: Size of WAL log in frames */
  133968. int *pnCkpt /* OUT: Total number of frames checkpointed */
  133969. ){
  133970. #ifdef SQLITE_OMIT_WAL
  133971. return SQLITE_OK;
  133972. #else
  133973. int rc; /* Return code */
  133974. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  133975. #ifdef SQLITE_ENABLE_API_ARMOR
  133976. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  133977. #endif
  133978. /* Initialize the output variables to -1 in case an error occurs. */
  133979. if( pnLog ) *pnLog = -1;
  133980. if( pnCkpt ) *pnCkpt = -1;
  133981. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  133982. assert( SQLITE_CHECKPOINT_FULL==1 );
  133983. assert( SQLITE_CHECKPOINT_RESTART==2 );
  133984. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  133985. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  133986. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  133987. ** mode: */
  133988. return SQLITE_MISUSE;
  133989. }
  133990. sqlite3_mutex_enter(db->mutex);
  133991. if( zDb && zDb[0] ){
  133992. iDb = sqlite3FindDbName(db, zDb);
  133993. }
  133994. if( iDb<0 ){
  133995. rc = SQLITE_ERROR;
  133996. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  133997. }else{
  133998. db->busyHandler.nBusy = 0;
  133999. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  134000. sqlite3Error(db, rc);
  134001. }
  134002. rc = sqlite3ApiExit(db, rc);
  134003. /* If there are no active statements, clear the interrupt flag at this
  134004. ** point. */
  134005. if( db->nVdbeActive==0 ){
  134006. db->u1.isInterrupted = 0;
  134007. }
  134008. sqlite3_mutex_leave(db->mutex);
  134009. return rc;
  134010. #endif
  134011. }
  134012. /*
  134013. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  134014. ** to contains a zero-length string, all attached databases are
  134015. ** checkpointed.
  134016. */
  134017. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  134018. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  134019. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  134020. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  134021. }
  134022. #ifndef SQLITE_OMIT_WAL
  134023. /*
  134024. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  134025. ** not currently open in WAL mode.
  134026. **
  134027. ** If a transaction is open on the database being checkpointed, this
  134028. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  134029. ** an error occurs while running the checkpoint, an SQLite error code is
  134030. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  134031. **
  134032. ** The mutex on database handle db should be held by the caller. The mutex
  134033. ** associated with the specific b-tree being checkpointed is taken by
  134034. ** this function while the checkpoint is running.
  134035. **
  134036. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  134037. ** checkpointed. If an error is encountered it is returned immediately -
  134038. ** no attempt is made to checkpoint any remaining databases.
  134039. **
  134040. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  134041. */
  134042. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  134043. int rc = SQLITE_OK; /* Return code */
  134044. int i; /* Used to iterate through attached dbs */
  134045. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  134046. assert( sqlite3_mutex_held(db->mutex) );
  134047. assert( !pnLog || *pnLog==-1 );
  134048. assert( !pnCkpt || *pnCkpt==-1 );
  134049. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  134050. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  134051. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  134052. pnLog = 0;
  134053. pnCkpt = 0;
  134054. if( rc==SQLITE_BUSY ){
  134055. bBusy = 1;
  134056. rc = SQLITE_OK;
  134057. }
  134058. }
  134059. }
  134060. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  134061. }
  134062. #endif /* SQLITE_OMIT_WAL */
  134063. /*
  134064. ** This function returns true if main-memory should be used instead of
  134065. ** a temporary file for transient pager files and statement journals.
  134066. ** The value returned depends on the value of db->temp_store (runtime
  134067. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  134068. ** following table describes the relationship between these two values
  134069. ** and this functions return value.
  134070. **
  134071. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  134072. ** ----------------- -------------- ------------------------------
  134073. ** 0 any file (return 0)
  134074. ** 1 1 file (return 0)
  134075. ** 1 2 memory (return 1)
  134076. ** 1 0 file (return 0)
  134077. ** 2 1 file (return 0)
  134078. ** 2 2 memory (return 1)
  134079. ** 2 0 memory (return 1)
  134080. ** 3 any memory (return 1)
  134081. */
  134082. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  134083. #if SQLITE_TEMP_STORE==1
  134084. return ( db->temp_store==2 );
  134085. #endif
  134086. #if SQLITE_TEMP_STORE==2
  134087. return ( db->temp_store!=1 );
  134088. #endif
  134089. #if SQLITE_TEMP_STORE==3
  134090. UNUSED_PARAMETER(db);
  134091. return 1;
  134092. #endif
  134093. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  134094. UNUSED_PARAMETER(db);
  134095. return 0;
  134096. #endif
  134097. }
  134098. /*
  134099. ** Return UTF-8 encoded English language explanation of the most recent
  134100. ** error.
  134101. */
  134102. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  134103. const char *z;
  134104. if( !db ){
  134105. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  134106. }
  134107. if( !sqlite3SafetyCheckSickOrOk(db) ){
  134108. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  134109. }
  134110. sqlite3_mutex_enter(db->mutex);
  134111. if( db->mallocFailed ){
  134112. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  134113. }else{
  134114. testcase( db->pErr==0 );
  134115. z = (char*)sqlite3_value_text(db->pErr);
  134116. assert( !db->mallocFailed );
  134117. if( z==0 ){
  134118. z = sqlite3ErrStr(db->errCode);
  134119. }
  134120. }
  134121. sqlite3_mutex_leave(db->mutex);
  134122. return z;
  134123. }
  134124. #ifndef SQLITE_OMIT_UTF16
  134125. /*
  134126. ** Return UTF-16 encoded English language explanation of the most recent
  134127. ** error.
  134128. */
  134129. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  134130. static const u16 outOfMem[] = {
  134131. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  134132. };
  134133. static const u16 misuse[] = {
  134134. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  134135. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  134136. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  134137. 'o', 'u', 't', ' ',
  134138. 'o', 'f', ' ',
  134139. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  134140. };
  134141. const void *z;
  134142. if( !db ){
  134143. return (void *)outOfMem;
  134144. }
  134145. if( !sqlite3SafetyCheckSickOrOk(db) ){
  134146. return (void *)misuse;
  134147. }
  134148. sqlite3_mutex_enter(db->mutex);
  134149. if( db->mallocFailed ){
  134150. z = (void *)outOfMem;
  134151. }else{
  134152. z = sqlite3_value_text16(db->pErr);
  134153. if( z==0 ){
  134154. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  134155. z = sqlite3_value_text16(db->pErr);
  134156. }
  134157. /* A malloc() may have failed within the call to sqlite3_value_text16()
  134158. ** above. If this is the case, then the db->mallocFailed flag needs to
  134159. ** be cleared before returning. Do this directly, instead of via
  134160. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  134161. */
  134162. sqlite3OomClear(db);
  134163. }
  134164. sqlite3_mutex_leave(db->mutex);
  134165. return z;
  134166. }
  134167. #endif /* SQLITE_OMIT_UTF16 */
  134168. /*
  134169. ** Return the most recent error code generated by an SQLite routine. If NULL is
  134170. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  134171. */
  134172. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  134173. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  134174. return SQLITE_MISUSE_BKPT;
  134175. }
  134176. if( !db || db->mallocFailed ){
  134177. return SQLITE_NOMEM_BKPT;
  134178. }
  134179. return db->errCode & db->errMask;
  134180. }
  134181. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  134182. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  134183. return SQLITE_MISUSE_BKPT;
  134184. }
  134185. if( !db || db->mallocFailed ){
  134186. return SQLITE_NOMEM_BKPT;
  134187. }
  134188. return db->errCode;
  134189. }
  134190. SQLITE_API int sqlite3_system_errno(sqlite3 *db){
  134191. return db ? db->iSysErrno : 0;
  134192. }
  134193. /*
  134194. ** Return a string that describes the kind of error specified in the
  134195. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  134196. ** function.
  134197. */
  134198. SQLITE_API const char *sqlite3_errstr(int rc){
  134199. return sqlite3ErrStr(rc);
  134200. }
  134201. /*
  134202. ** Create a new collating function for database "db". The name is zName
  134203. ** and the encoding is enc.
  134204. */
  134205. static int createCollation(
  134206. sqlite3* db,
  134207. const char *zName,
  134208. u8 enc,
  134209. void* pCtx,
  134210. int(*xCompare)(void*,int,const void*,int,const void*),
  134211. void(*xDel)(void*)
  134212. ){
  134213. CollSeq *pColl;
  134214. int enc2;
  134215. assert( sqlite3_mutex_held(db->mutex) );
  134216. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  134217. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  134218. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  134219. */
  134220. enc2 = enc;
  134221. testcase( enc2==SQLITE_UTF16 );
  134222. testcase( enc2==SQLITE_UTF16_ALIGNED );
  134223. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  134224. enc2 = SQLITE_UTF16NATIVE;
  134225. }
  134226. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  134227. return SQLITE_MISUSE_BKPT;
  134228. }
  134229. /* Check if this call is removing or replacing an existing collation
  134230. ** sequence. If so, and there are active VMs, return busy. If there
  134231. ** are no active VMs, invalidate any pre-compiled statements.
  134232. */
  134233. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  134234. if( pColl && pColl->xCmp ){
  134235. if( db->nVdbeActive ){
  134236. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  134237. "unable to delete/modify collation sequence due to active statements");
  134238. return SQLITE_BUSY;
  134239. }
  134240. sqlite3ExpirePreparedStatements(db);
  134241. /* If collation sequence pColl was created directly by a call to
  134242. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  134243. ** then any copies made by synthCollSeq() need to be invalidated.
  134244. ** Also, collation destructor - CollSeq.xDel() - function may need
  134245. ** to be called.
  134246. */
  134247. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  134248. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  134249. int j;
  134250. for(j=0; j<3; j++){
  134251. CollSeq *p = &aColl[j];
  134252. if( p->enc==pColl->enc ){
  134253. if( p->xDel ){
  134254. p->xDel(p->pUser);
  134255. }
  134256. p->xCmp = 0;
  134257. }
  134258. }
  134259. }
  134260. }
  134261. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  134262. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  134263. pColl->xCmp = xCompare;
  134264. pColl->pUser = pCtx;
  134265. pColl->xDel = xDel;
  134266. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  134267. sqlite3Error(db, SQLITE_OK);
  134268. return SQLITE_OK;
  134269. }
  134270. /*
  134271. ** This array defines hard upper bounds on limit values. The
  134272. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  134273. ** #defines in sqlite3.h.
  134274. */
  134275. static const int aHardLimit[] = {
  134276. SQLITE_MAX_LENGTH,
  134277. SQLITE_MAX_SQL_LENGTH,
  134278. SQLITE_MAX_COLUMN,
  134279. SQLITE_MAX_EXPR_DEPTH,
  134280. SQLITE_MAX_COMPOUND_SELECT,
  134281. SQLITE_MAX_VDBE_OP,
  134282. SQLITE_MAX_FUNCTION_ARG,
  134283. SQLITE_MAX_ATTACHED,
  134284. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  134285. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  134286. SQLITE_MAX_TRIGGER_DEPTH,
  134287. SQLITE_MAX_WORKER_THREADS,
  134288. };
  134289. /*
  134290. ** Make sure the hard limits are set to reasonable values
  134291. */
  134292. #if SQLITE_MAX_LENGTH<100
  134293. # error SQLITE_MAX_LENGTH must be at least 100
  134294. #endif
  134295. #if SQLITE_MAX_SQL_LENGTH<100
  134296. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  134297. #endif
  134298. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  134299. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  134300. #endif
  134301. #if SQLITE_MAX_COMPOUND_SELECT<2
  134302. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  134303. #endif
  134304. #if SQLITE_MAX_VDBE_OP<40
  134305. # error SQLITE_MAX_VDBE_OP must be at least 40
  134306. #endif
  134307. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  134308. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  134309. #endif
  134310. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  134311. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  134312. #endif
  134313. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  134314. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  134315. #endif
  134316. #if SQLITE_MAX_COLUMN>32767
  134317. # error SQLITE_MAX_COLUMN must not exceed 32767
  134318. #endif
  134319. #if SQLITE_MAX_TRIGGER_DEPTH<1
  134320. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  134321. #endif
  134322. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  134323. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  134324. #endif
  134325. /*
  134326. ** Change the value of a limit. Report the old value.
  134327. ** If an invalid limit index is supplied, report -1.
  134328. ** Make no changes but still report the old value if the
  134329. ** new limit is negative.
  134330. **
  134331. ** A new lower limit does not shrink existing constructs.
  134332. ** It merely prevents new constructs that exceed the limit
  134333. ** from forming.
  134334. */
  134335. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  134336. int oldLimit;
  134337. #ifdef SQLITE_ENABLE_API_ARMOR
  134338. if( !sqlite3SafetyCheckOk(db) ){
  134339. (void)SQLITE_MISUSE_BKPT;
  134340. return -1;
  134341. }
  134342. #endif
  134343. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  134344. ** there is a hard upper bound set at compile-time by a C preprocessor
  134345. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  134346. ** "_MAX_".)
  134347. */
  134348. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  134349. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  134350. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  134351. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  134352. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  134353. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  134354. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  134355. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  134356. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  134357. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  134358. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  134359. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  134360. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  134361. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  134362. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  134363. return -1;
  134364. }
  134365. oldLimit = db->aLimit[limitId];
  134366. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  134367. if( newLimit>aHardLimit[limitId] ){
  134368. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  134369. }
  134370. db->aLimit[limitId] = newLimit;
  134371. }
  134372. return oldLimit; /* IMP: R-53341-35419 */
  134373. }
  134374. /*
  134375. ** This function is used to parse both URIs and non-URI filenames passed by the
  134376. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  134377. ** URIs specified as part of ATTACH statements.
  134378. **
  134379. ** The first argument to this function is the name of the VFS to use (or
  134380. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  134381. ** query parameter. The second argument contains the URI (or non-URI filename)
  134382. ** itself. When this function is called the *pFlags variable should contain
  134383. ** the default flags to open the database handle with. The value stored in
  134384. ** *pFlags may be updated before returning if the URI filename contains
  134385. ** "cache=xxx" or "mode=xxx" query parameters.
  134386. **
  134387. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  134388. ** the VFS that should be used to open the database file. *pzFile is set to
  134389. ** point to a buffer containing the name of the file to open. It is the
  134390. ** responsibility of the caller to eventually call sqlite3_free() to release
  134391. ** this buffer.
  134392. **
  134393. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  134394. ** may be set to point to a buffer containing an English language error
  134395. ** message. It is the responsibility of the caller to eventually release
  134396. ** this buffer by calling sqlite3_free().
  134397. */
  134398. SQLITE_PRIVATE int sqlite3ParseUri(
  134399. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  134400. const char *zUri, /* Nul-terminated URI to parse */
  134401. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  134402. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  134403. char **pzFile, /* OUT: Filename component of URI */
  134404. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  134405. ){
  134406. int rc = SQLITE_OK;
  134407. unsigned int flags = *pFlags;
  134408. const char *zVfs = zDefaultVfs;
  134409. char *zFile;
  134410. char c;
  134411. int nUri = sqlite3Strlen30(zUri);
  134412. assert( *pzErrMsg==0 );
  134413. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  134414. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  134415. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  134416. ){
  134417. char *zOpt;
  134418. int eState; /* Parser state when parsing URI */
  134419. int iIn; /* Input character index */
  134420. int iOut = 0; /* Output character index */
  134421. u64 nByte = nUri+2; /* Bytes of space to allocate */
  134422. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  134423. ** method that there may be extra parameters following the file-name. */
  134424. flags |= SQLITE_OPEN_URI;
  134425. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  134426. zFile = sqlite3_malloc64(nByte);
  134427. if( !zFile ) return SQLITE_NOMEM_BKPT;
  134428. iIn = 5;
  134429. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  134430. if( strncmp(zUri+5, "///", 3)==0 ){
  134431. iIn = 7;
  134432. /* The following condition causes URIs with five leading / characters
  134433. ** like file://///host/path to be converted into UNCs like //host/path.
  134434. ** The correct URI for that UNC has only two or four leading / characters
  134435. ** file://host/path or file:////host/path. But 5 leading slashes is a
  134436. ** common error, we are told, so we handle it as a special case. */
  134437. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  134438. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  134439. iIn = 16;
  134440. }
  134441. #else
  134442. /* Discard the scheme and authority segments of the URI. */
  134443. if( zUri[5]=='/' && zUri[6]=='/' ){
  134444. iIn = 7;
  134445. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  134446. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  134447. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  134448. iIn-7, &zUri[7]);
  134449. rc = SQLITE_ERROR;
  134450. goto parse_uri_out;
  134451. }
  134452. }
  134453. #endif
  134454. /* Copy the filename and any query parameters into the zFile buffer.
  134455. ** Decode %HH escape codes along the way.
  134456. **
  134457. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  134458. ** on the parsing context. As follows:
  134459. **
  134460. ** 0: Parsing file-name.
  134461. ** 1: Parsing name section of a name=value query parameter.
  134462. ** 2: Parsing value section of a name=value query parameter.
  134463. */
  134464. eState = 0;
  134465. while( (c = zUri[iIn])!=0 && c!='#' ){
  134466. iIn++;
  134467. if( c=='%'
  134468. && sqlite3Isxdigit(zUri[iIn])
  134469. && sqlite3Isxdigit(zUri[iIn+1])
  134470. ){
  134471. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  134472. octet += sqlite3HexToInt(zUri[iIn++]);
  134473. assert( octet>=0 && octet<256 );
  134474. if( octet==0 ){
  134475. #ifndef SQLITE_ENABLE_URI_00_ERROR
  134476. /* This branch is taken when "%00" appears within the URI. In this
  134477. ** case we ignore all text in the remainder of the path, name or
  134478. ** value currently being parsed. So ignore the current character
  134479. ** and skip to the next "?", "=" or "&", as appropriate. */
  134480. while( (c = zUri[iIn])!=0 && c!='#'
  134481. && (eState!=0 || c!='?')
  134482. && (eState!=1 || (c!='=' && c!='&'))
  134483. && (eState!=2 || c!='&')
  134484. ){
  134485. iIn++;
  134486. }
  134487. continue;
  134488. #else
  134489. /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
  134490. *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
  134491. rc = SQLITE_ERROR;
  134492. goto parse_uri_out;
  134493. #endif
  134494. }
  134495. c = octet;
  134496. }else if( eState==1 && (c=='&' || c=='=') ){
  134497. if( zFile[iOut-1]==0 ){
  134498. /* An empty option name. Ignore this option altogether. */
  134499. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  134500. continue;
  134501. }
  134502. if( c=='&' ){
  134503. zFile[iOut++] = '\0';
  134504. }else{
  134505. eState = 2;
  134506. }
  134507. c = 0;
  134508. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  134509. c = 0;
  134510. eState = 1;
  134511. }
  134512. zFile[iOut++] = c;
  134513. }
  134514. if( eState==1 ) zFile[iOut++] = '\0';
  134515. zFile[iOut++] = '\0';
  134516. zFile[iOut++] = '\0';
  134517. /* Check if there were any options specified that should be interpreted
  134518. ** here. Options that are interpreted here include "vfs" and those that
  134519. ** correspond to flags that may be passed to the sqlite3_open_v2()
  134520. ** method. */
  134521. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  134522. while( zOpt[0] ){
  134523. int nOpt = sqlite3Strlen30(zOpt);
  134524. char *zVal = &zOpt[nOpt+1];
  134525. int nVal = sqlite3Strlen30(zVal);
  134526. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  134527. zVfs = zVal;
  134528. }else{
  134529. struct OpenMode {
  134530. const char *z;
  134531. int mode;
  134532. } *aMode = 0;
  134533. char *zModeType = 0;
  134534. int mask = 0;
  134535. int limit = 0;
  134536. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  134537. static struct OpenMode aCacheMode[] = {
  134538. { "shared", SQLITE_OPEN_SHAREDCACHE },
  134539. { "private", SQLITE_OPEN_PRIVATECACHE },
  134540. { 0, 0 }
  134541. };
  134542. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  134543. aMode = aCacheMode;
  134544. limit = mask;
  134545. zModeType = "cache";
  134546. }
  134547. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  134548. static struct OpenMode aOpenMode[] = {
  134549. { "ro", SQLITE_OPEN_READONLY },
  134550. { "rw", SQLITE_OPEN_READWRITE },
  134551. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  134552. { "memory", SQLITE_OPEN_MEMORY },
  134553. { 0, 0 }
  134554. };
  134555. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  134556. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  134557. aMode = aOpenMode;
  134558. limit = mask & flags;
  134559. zModeType = "access";
  134560. }
  134561. if( aMode ){
  134562. int i;
  134563. int mode = 0;
  134564. for(i=0; aMode[i].z; i++){
  134565. const char *z = aMode[i].z;
  134566. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  134567. mode = aMode[i].mode;
  134568. break;
  134569. }
  134570. }
  134571. if( mode==0 ){
  134572. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  134573. rc = SQLITE_ERROR;
  134574. goto parse_uri_out;
  134575. }
  134576. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  134577. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  134578. zModeType, zVal);
  134579. rc = SQLITE_PERM;
  134580. goto parse_uri_out;
  134581. }
  134582. flags = (flags & ~mask) | mode;
  134583. }
  134584. }
  134585. zOpt = &zVal[nVal+1];
  134586. }
  134587. }else{
  134588. zFile = sqlite3_malloc64(nUri+2);
  134589. if( !zFile ) return SQLITE_NOMEM_BKPT;
  134590. if( nUri ){
  134591. memcpy(zFile, zUri, nUri);
  134592. }
  134593. zFile[nUri] = '\0';
  134594. zFile[nUri+1] = '\0';
  134595. flags &= ~SQLITE_OPEN_URI;
  134596. }
  134597. *ppVfs = sqlite3_vfs_find(zVfs);
  134598. if( *ppVfs==0 ){
  134599. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  134600. rc = SQLITE_ERROR;
  134601. }
  134602. parse_uri_out:
  134603. if( rc!=SQLITE_OK ){
  134604. sqlite3_free(zFile);
  134605. zFile = 0;
  134606. }
  134607. *pFlags = flags;
  134608. *pzFile = zFile;
  134609. return rc;
  134610. }
  134611. /*
  134612. ** This routine does the work of opening a database on behalf of
  134613. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  134614. ** is UTF-8 encoded.
  134615. */
  134616. static int openDatabase(
  134617. const char *zFilename, /* Database filename UTF-8 encoded */
  134618. sqlite3 **ppDb, /* OUT: Returned database handle */
  134619. unsigned int flags, /* Operational flags */
  134620. const char *zVfs /* Name of the VFS to use */
  134621. ){
  134622. sqlite3 *db; /* Store allocated handle here */
  134623. int rc; /* Return code */
  134624. int isThreadsafe; /* True for threadsafe connections */
  134625. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  134626. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  134627. #ifdef SQLITE_ENABLE_API_ARMOR
  134628. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  134629. #endif
  134630. *ppDb = 0;
  134631. #ifndef SQLITE_OMIT_AUTOINIT
  134632. rc = sqlite3_initialize();
  134633. if( rc ) return rc;
  134634. #endif
  134635. /* Only allow sensible combinations of bits in the flags argument.
  134636. ** Throw an error if any non-sense combination is used. If we
  134637. ** do not block illegal combinations here, it could trigger
  134638. ** assert() statements in deeper layers. Sensible combinations
  134639. ** are:
  134640. **
  134641. ** 1: SQLITE_OPEN_READONLY
  134642. ** 2: SQLITE_OPEN_READWRITE
  134643. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  134644. */
  134645. assert( SQLITE_OPEN_READONLY == 0x01 );
  134646. assert( SQLITE_OPEN_READWRITE == 0x02 );
  134647. assert( SQLITE_OPEN_CREATE == 0x04 );
  134648. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  134649. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  134650. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  134651. if( ((1<<(flags&7)) & 0x46)==0 ){
  134652. return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  134653. }
  134654. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  134655. isThreadsafe = 0;
  134656. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  134657. isThreadsafe = 0;
  134658. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  134659. isThreadsafe = 1;
  134660. }else{
  134661. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  134662. }
  134663. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  134664. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  134665. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  134666. flags |= SQLITE_OPEN_SHAREDCACHE;
  134667. }
  134668. /* Remove harmful bits from the flags parameter
  134669. **
  134670. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  134671. ** dealt with in the previous code block. Besides these, the only
  134672. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  134673. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  134674. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  134675. ** off all other flags.
  134676. */
  134677. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  134678. SQLITE_OPEN_EXCLUSIVE |
  134679. SQLITE_OPEN_MAIN_DB |
  134680. SQLITE_OPEN_TEMP_DB |
  134681. SQLITE_OPEN_TRANSIENT_DB |
  134682. SQLITE_OPEN_MAIN_JOURNAL |
  134683. SQLITE_OPEN_TEMP_JOURNAL |
  134684. SQLITE_OPEN_SUBJOURNAL |
  134685. SQLITE_OPEN_MASTER_JOURNAL |
  134686. SQLITE_OPEN_NOMUTEX |
  134687. SQLITE_OPEN_FULLMUTEX |
  134688. SQLITE_OPEN_WAL
  134689. );
  134690. /* Allocate the sqlite data structure */
  134691. db = sqlite3MallocZero( sizeof(sqlite3) );
  134692. if( db==0 ) goto opendb_out;
  134693. if( isThreadsafe ){
  134694. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  134695. if( db->mutex==0 ){
  134696. sqlite3_free(db);
  134697. db = 0;
  134698. goto opendb_out;
  134699. }
  134700. }
  134701. sqlite3_mutex_enter(db->mutex);
  134702. db->errMask = 0xff;
  134703. db->nDb = 2;
  134704. db->magic = SQLITE_MAGIC_BUSY;
  134705. db->aDb = db->aDbStatic;
  134706. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  134707. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  134708. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  134709. db->autoCommit = 1;
  134710. db->nextAutovac = -1;
  134711. db->szMmap = sqlite3GlobalConfig.szMmap;
  134712. db->nextPagesize = 0;
  134713. db->nMaxSorterMmap = 0x7FFFFFFF;
  134714. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  134715. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  134716. | SQLITE_AutoIndex
  134717. #endif
  134718. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  134719. | SQLITE_CkptFullFSync
  134720. #endif
  134721. #if SQLITE_DEFAULT_FILE_FORMAT<4
  134722. | SQLITE_LegacyFileFmt
  134723. #endif
  134724. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  134725. | SQLITE_LoadExtension
  134726. #endif
  134727. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  134728. | SQLITE_RecTriggers
  134729. #endif
  134730. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  134731. | SQLITE_ForeignKeys
  134732. #endif
  134733. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  134734. | SQLITE_ReverseOrder
  134735. #endif
  134736. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  134737. | SQLITE_CellSizeCk
  134738. #endif
  134739. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  134740. | SQLITE_Fts3Tokenizer
  134741. #endif
  134742. ;
  134743. sqlite3HashInit(&db->aCollSeq);
  134744. #ifndef SQLITE_OMIT_VIRTUALTABLE
  134745. sqlite3HashInit(&db->aModule);
  134746. #endif
  134747. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  134748. ** and UTF-16, so add a version for each to avoid any unnecessary
  134749. ** conversions. The only error that can occur here is a malloc() failure.
  134750. **
  134751. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  134752. ** functions:
  134753. */
  134754. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  134755. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  134756. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  134757. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  134758. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  134759. if( db->mallocFailed ){
  134760. goto opendb_out;
  134761. }
  134762. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  134763. ** strings is BINARY.
  134764. */
  134765. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  134766. assert( db->pDfltColl!=0 );
  134767. /* Parse the filename/URI argument. */
  134768. db->openFlags = flags;
  134769. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  134770. if( rc!=SQLITE_OK ){
  134771. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  134772. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  134773. sqlite3_free(zErrMsg);
  134774. goto opendb_out;
  134775. }
  134776. /* Open the backend database driver */
  134777. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  134778. flags | SQLITE_OPEN_MAIN_DB);
  134779. if( rc!=SQLITE_OK ){
  134780. if( rc==SQLITE_IOERR_NOMEM ){
  134781. rc = SQLITE_NOMEM_BKPT;
  134782. }
  134783. sqlite3Error(db, rc);
  134784. goto opendb_out;
  134785. }
  134786. sqlite3BtreeEnter(db->aDb[0].pBt);
  134787. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  134788. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  134789. sqlite3BtreeLeave(db->aDb[0].pBt);
  134790. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  134791. /* The default safety_level for the main database is FULL; for the temp
  134792. ** database it is OFF. This matches the pager layer defaults.
  134793. */
  134794. db->aDb[0].zDbSName = "main";
  134795. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  134796. db->aDb[1].zDbSName = "temp";
  134797. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  134798. db->magic = SQLITE_MAGIC_OPEN;
  134799. if( db->mallocFailed ){
  134800. goto opendb_out;
  134801. }
  134802. /* Register all built-in functions, but do not attempt to read the
  134803. ** database schema yet. This is delayed until the first time the database
  134804. ** is accessed.
  134805. */
  134806. sqlite3Error(db, SQLITE_OK);
  134807. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  134808. rc = sqlite3_errcode(db);
  134809. #ifdef SQLITE_ENABLE_FTS5
  134810. /* Register any built-in FTS5 module before loading the automatic
  134811. ** extensions. This allows automatic extensions to register FTS5
  134812. ** tokenizers and auxiliary functions. */
  134813. if( !db->mallocFailed && rc==SQLITE_OK ){
  134814. rc = sqlite3Fts5Init(db);
  134815. }
  134816. #endif
  134817. /* Load automatic extensions - extensions that have been registered
  134818. ** using the sqlite3_automatic_extension() API.
  134819. */
  134820. if( rc==SQLITE_OK ){
  134821. sqlite3AutoLoadExtensions(db);
  134822. rc = sqlite3_errcode(db);
  134823. if( rc!=SQLITE_OK ){
  134824. goto opendb_out;
  134825. }
  134826. }
  134827. #ifdef SQLITE_ENABLE_FTS1
  134828. if( !db->mallocFailed ){
  134829. extern int sqlite3Fts1Init(sqlite3*);
  134830. rc = sqlite3Fts1Init(db);
  134831. }
  134832. #endif
  134833. #ifdef SQLITE_ENABLE_FTS2
  134834. if( !db->mallocFailed && rc==SQLITE_OK ){
  134835. extern int sqlite3Fts2Init(sqlite3*);
  134836. rc = sqlite3Fts2Init(db);
  134837. }
  134838. #endif
  134839. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  134840. if( !db->mallocFailed && rc==SQLITE_OK ){
  134841. rc = sqlite3Fts3Init(db);
  134842. }
  134843. #endif
  134844. #ifdef SQLITE_ENABLE_ICU
  134845. if( !db->mallocFailed && rc==SQLITE_OK ){
  134846. rc = sqlite3IcuInit(db);
  134847. }
  134848. #endif
  134849. #ifdef SQLITE_ENABLE_RTREE
  134850. if( !db->mallocFailed && rc==SQLITE_OK){
  134851. rc = sqlite3RtreeInit(db);
  134852. }
  134853. #endif
  134854. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  134855. if( !db->mallocFailed && rc==SQLITE_OK){
  134856. rc = sqlite3DbstatRegister(db);
  134857. }
  134858. #endif
  134859. #ifdef SQLITE_ENABLE_JSON1
  134860. if( !db->mallocFailed && rc==SQLITE_OK){
  134861. rc = sqlite3Json1Init(db);
  134862. }
  134863. #endif
  134864. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  134865. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  134866. ** mode. Doing nothing at all also makes NORMAL the default.
  134867. */
  134868. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  134869. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  134870. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  134871. SQLITE_DEFAULT_LOCKING_MODE);
  134872. #endif
  134873. if( rc ) sqlite3Error(db, rc);
  134874. /* Enable the lookaside-malloc subsystem */
  134875. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  134876. sqlite3GlobalConfig.nLookaside);
  134877. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  134878. opendb_out:
  134879. if( db ){
  134880. assert( db->mutex!=0 || isThreadsafe==0
  134881. || sqlite3GlobalConfig.bFullMutex==0 );
  134882. sqlite3_mutex_leave(db->mutex);
  134883. }
  134884. rc = sqlite3_errcode(db);
  134885. assert( db!=0 || rc==SQLITE_NOMEM );
  134886. if( rc==SQLITE_NOMEM ){
  134887. sqlite3_close(db);
  134888. db = 0;
  134889. }else if( rc!=SQLITE_OK ){
  134890. db->magic = SQLITE_MAGIC_SICK;
  134891. }
  134892. *ppDb = db;
  134893. #ifdef SQLITE_ENABLE_SQLLOG
  134894. if( sqlite3GlobalConfig.xSqllog ){
  134895. /* Opening a db handle. Fourth parameter is passed 0. */
  134896. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  134897. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  134898. }
  134899. #endif
  134900. #if defined(SQLITE_HAS_CODEC)
  134901. if( rc==SQLITE_OK ){
  134902. const char *zKey;
  134903. if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
  134904. u8 iByte;
  134905. int i;
  134906. char zDecoded[40];
  134907. for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
  134908. iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
  134909. if( (i&1)!=0 ) zDecoded[i/2] = iByte;
  134910. }
  134911. sqlite3_key_v2(db, 0, zDecoded, i/2);
  134912. }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
  134913. sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
  134914. }
  134915. }
  134916. #endif
  134917. sqlite3_free(zOpen);
  134918. return rc & 0xff;
  134919. }
  134920. /*
  134921. ** Open a new database handle.
  134922. */
  134923. SQLITE_API int sqlite3_open(
  134924. const char *zFilename,
  134925. sqlite3 **ppDb
  134926. ){
  134927. return openDatabase(zFilename, ppDb,
  134928. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  134929. }
  134930. SQLITE_API int sqlite3_open_v2(
  134931. const char *filename, /* Database filename (UTF-8) */
  134932. sqlite3 **ppDb, /* OUT: SQLite db handle */
  134933. int flags, /* Flags */
  134934. const char *zVfs /* Name of VFS module to use */
  134935. ){
  134936. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  134937. }
  134938. #ifndef SQLITE_OMIT_UTF16
  134939. /*
  134940. ** Open a new database handle.
  134941. */
  134942. SQLITE_API int sqlite3_open16(
  134943. const void *zFilename,
  134944. sqlite3 **ppDb
  134945. ){
  134946. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  134947. sqlite3_value *pVal;
  134948. int rc;
  134949. #ifdef SQLITE_ENABLE_API_ARMOR
  134950. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  134951. #endif
  134952. *ppDb = 0;
  134953. #ifndef SQLITE_OMIT_AUTOINIT
  134954. rc = sqlite3_initialize();
  134955. if( rc ) return rc;
  134956. #endif
  134957. if( zFilename==0 ) zFilename = "\000\000";
  134958. pVal = sqlite3ValueNew(0);
  134959. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  134960. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  134961. if( zFilename8 ){
  134962. rc = openDatabase(zFilename8, ppDb,
  134963. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  134964. assert( *ppDb || rc==SQLITE_NOMEM );
  134965. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  134966. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  134967. }
  134968. }else{
  134969. rc = SQLITE_NOMEM_BKPT;
  134970. }
  134971. sqlite3ValueFree(pVal);
  134972. return rc & 0xff;
  134973. }
  134974. #endif /* SQLITE_OMIT_UTF16 */
  134975. /*
  134976. ** Register a new collation sequence with the database handle db.
  134977. */
  134978. SQLITE_API int sqlite3_create_collation(
  134979. sqlite3* db,
  134980. const char *zName,
  134981. int enc,
  134982. void* pCtx,
  134983. int(*xCompare)(void*,int,const void*,int,const void*)
  134984. ){
  134985. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  134986. }
  134987. /*
  134988. ** Register a new collation sequence with the database handle db.
  134989. */
  134990. SQLITE_API int sqlite3_create_collation_v2(
  134991. sqlite3* db,
  134992. const char *zName,
  134993. int enc,
  134994. void* pCtx,
  134995. int(*xCompare)(void*,int,const void*,int,const void*),
  134996. void(*xDel)(void*)
  134997. ){
  134998. int rc;
  134999. #ifdef SQLITE_ENABLE_API_ARMOR
  135000. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  135001. #endif
  135002. sqlite3_mutex_enter(db->mutex);
  135003. assert( !db->mallocFailed );
  135004. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  135005. rc = sqlite3ApiExit(db, rc);
  135006. sqlite3_mutex_leave(db->mutex);
  135007. return rc;
  135008. }
  135009. #ifndef SQLITE_OMIT_UTF16
  135010. /*
  135011. ** Register a new collation sequence with the database handle db.
  135012. */
  135013. SQLITE_API int sqlite3_create_collation16(
  135014. sqlite3* db,
  135015. const void *zName,
  135016. int enc,
  135017. void* pCtx,
  135018. int(*xCompare)(void*,int,const void*,int,const void*)
  135019. ){
  135020. int rc = SQLITE_OK;
  135021. char *zName8;
  135022. #ifdef SQLITE_ENABLE_API_ARMOR
  135023. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  135024. #endif
  135025. sqlite3_mutex_enter(db->mutex);
  135026. assert( !db->mallocFailed );
  135027. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  135028. if( zName8 ){
  135029. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  135030. sqlite3DbFree(db, zName8);
  135031. }
  135032. rc = sqlite3ApiExit(db, rc);
  135033. sqlite3_mutex_leave(db->mutex);
  135034. return rc;
  135035. }
  135036. #endif /* SQLITE_OMIT_UTF16 */
  135037. /*
  135038. ** Register a collation sequence factory callback with the database handle
  135039. ** db. Replace any previously installed collation sequence factory.
  135040. */
  135041. SQLITE_API int sqlite3_collation_needed(
  135042. sqlite3 *db,
  135043. void *pCollNeededArg,
  135044. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  135045. ){
  135046. #ifdef SQLITE_ENABLE_API_ARMOR
  135047. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135048. #endif
  135049. sqlite3_mutex_enter(db->mutex);
  135050. db->xCollNeeded = xCollNeeded;
  135051. db->xCollNeeded16 = 0;
  135052. db->pCollNeededArg = pCollNeededArg;
  135053. sqlite3_mutex_leave(db->mutex);
  135054. return SQLITE_OK;
  135055. }
  135056. #ifndef SQLITE_OMIT_UTF16
  135057. /*
  135058. ** Register a collation sequence factory callback with the database handle
  135059. ** db. Replace any previously installed collation sequence factory.
  135060. */
  135061. SQLITE_API int sqlite3_collation_needed16(
  135062. sqlite3 *db,
  135063. void *pCollNeededArg,
  135064. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  135065. ){
  135066. #ifdef SQLITE_ENABLE_API_ARMOR
  135067. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135068. #endif
  135069. sqlite3_mutex_enter(db->mutex);
  135070. db->xCollNeeded = 0;
  135071. db->xCollNeeded16 = xCollNeeded16;
  135072. db->pCollNeededArg = pCollNeededArg;
  135073. sqlite3_mutex_leave(db->mutex);
  135074. return SQLITE_OK;
  135075. }
  135076. #endif /* SQLITE_OMIT_UTF16 */
  135077. #ifndef SQLITE_OMIT_DEPRECATED
  135078. /*
  135079. ** This function is now an anachronism. It used to be used to recover from a
  135080. ** malloc() failure, but SQLite now does this automatically.
  135081. */
  135082. SQLITE_API int sqlite3_global_recover(void){
  135083. return SQLITE_OK;
  135084. }
  135085. #endif
  135086. /*
  135087. ** Test to see whether or not the database connection is in autocommit
  135088. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  135089. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  135090. ** by the next COMMIT or ROLLBACK.
  135091. */
  135092. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  135093. #ifdef SQLITE_ENABLE_API_ARMOR
  135094. if( !sqlite3SafetyCheckOk(db) ){
  135095. (void)SQLITE_MISUSE_BKPT;
  135096. return 0;
  135097. }
  135098. #endif
  135099. return db->autoCommit;
  135100. }
  135101. /*
  135102. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  135103. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  135104. ** constants. They serve two purposes:
  135105. **
  135106. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  135107. ** to detect when version error conditions occurs.
  135108. **
  135109. ** 2. Invoke sqlite3_log() to provide the source code location where
  135110. ** a low-level error is first detected.
  135111. */
  135112. static int reportError(int iErr, int lineno, const char *zType){
  135113. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  135114. zType, lineno, 20+sqlite3_sourceid());
  135115. return iErr;
  135116. }
  135117. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  135118. testcase( sqlite3GlobalConfig.xLog!=0 );
  135119. return reportError(SQLITE_CORRUPT, lineno, "database corruption");
  135120. }
  135121. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  135122. testcase( sqlite3GlobalConfig.xLog!=0 );
  135123. return reportError(SQLITE_MISUSE, lineno, "misuse");
  135124. }
  135125. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  135126. testcase( sqlite3GlobalConfig.xLog!=0 );
  135127. return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  135128. }
  135129. #ifdef SQLITE_DEBUG
  135130. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  135131. testcase( sqlite3GlobalConfig.xLog!=0 );
  135132. return reportError(SQLITE_NOMEM, lineno, "OOM");
  135133. }
  135134. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  135135. testcase( sqlite3GlobalConfig.xLog!=0 );
  135136. return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  135137. }
  135138. #endif
  135139. #ifndef SQLITE_OMIT_DEPRECATED
  135140. /*
  135141. ** This is a convenience routine that makes sure that all thread-specific
  135142. ** data for this thread has been deallocated.
  135143. **
  135144. ** SQLite no longer uses thread-specific data so this routine is now a
  135145. ** no-op. It is retained for historical compatibility.
  135146. */
  135147. SQLITE_API void sqlite3_thread_cleanup(void){
  135148. }
  135149. #endif
  135150. /*
  135151. ** Return meta information about a specific column of a database table.
  135152. ** See comment in sqlite3.h (sqlite.h.in) for details.
  135153. */
  135154. SQLITE_API int sqlite3_table_column_metadata(
  135155. sqlite3 *db, /* Connection handle */
  135156. const char *zDbName, /* Database name or NULL */
  135157. const char *zTableName, /* Table name */
  135158. const char *zColumnName, /* Column name */
  135159. char const **pzDataType, /* OUTPUT: Declared data type */
  135160. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  135161. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  135162. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  135163. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  135164. ){
  135165. int rc;
  135166. char *zErrMsg = 0;
  135167. Table *pTab = 0;
  135168. Column *pCol = 0;
  135169. int iCol = 0;
  135170. char const *zDataType = 0;
  135171. char const *zCollSeq = 0;
  135172. int notnull = 0;
  135173. int primarykey = 0;
  135174. int autoinc = 0;
  135175. #ifdef SQLITE_ENABLE_API_ARMOR
  135176. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  135177. return SQLITE_MISUSE_BKPT;
  135178. }
  135179. #endif
  135180. /* Ensure the database schema has been loaded */
  135181. sqlite3_mutex_enter(db->mutex);
  135182. sqlite3BtreeEnterAll(db);
  135183. rc = sqlite3Init(db, &zErrMsg);
  135184. if( SQLITE_OK!=rc ){
  135185. goto error_out;
  135186. }
  135187. /* Locate the table in question */
  135188. pTab = sqlite3FindTable(db, zTableName, zDbName);
  135189. if( !pTab || pTab->pSelect ){
  135190. pTab = 0;
  135191. goto error_out;
  135192. }
  135193. /* Find the column for which info is requested */
  135194. if( zColumnName==0 ){
  135195. /* Query for existance of table only */
  135196. }else{
  135197. for(iCol=0; iCol<pTab->nCol; iCol++){
  135198. pCol = &pTab->aCol[iCol];
  135199. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  135200. break;
  135201. }
  135202. }
  135203. if( iCol==pTab->nCol ){
  135204. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  135205. iCol = pTab->iPKey;
  135206. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  135207. }else{
  135208. pTab = 0;
  135209. goto error_out;
  135210. }
  135211. }
  135212. }
  135213. /* The following block stores the meta information that will be returned
  135214. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  135215. ** and autoinc. At this point there are two possibilities:
  135216. **
  135217. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  135218. ** and there is no explicitly declared IPK column.
  135219. **
  135220. ** 2. The table is not a view and the column name identified an
  135221. ** explicitly declared column. Copy meta information from *pCol.
  135222. */
  135223. if( pCol ){
  135224. zDataType = sqlite3ColumnType(pCol,0);
  135225. zCollSeq = pCol->zColl;
  135226. notnull = pCol->notNull!=0;
  135227. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  135228. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  135229. }else{
  135230. zDataType = "INTEGER";
  135231. primarykey = 1;
  135232. }
  135233. if( !zCollSeq ){
  135234. zCollSeq = sqlite3StrBINARY;
  135235. }
  135236. error_out:
  135237. sqlite3BtreeLeaveAll(db);
  135238. /* Whether the function call succeeded or failed, set the output parameters
  135239. ** to whatever their local counterparts contain. If an error did occur,
  135240. ** this has the effect of zeroing all output parameters.
  135241. */
  135242. if( pzDataType ) *pzDataType = zDataType;
  135243. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  135244. if( pNotNull ) *pNotNull = notnull;
  135245. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  135246. if( pAutoinc ) *pAutoinc = autoinc;
  135247. if( SQLITE_OK==rc && !pTab ){
  135248. sqlite3DbFree(db, zErrMsg);
  135249. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  135250. zColumnName);
  135251. rc = SQLITE_ERROR;
  135252. }
  135253. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  135254. sqlite3DbFree(db, zErrMsg);
  135255. rc = sqlite3ApiExit(db, rc);
  135256. sqlite3_mutex_leave(db->mutex);
  135257. return rc;
  135258. }
  135259. /*
  135260. ** Sleep for a little while. Return the amount of time slept.
  135261. */
  135262. SQLITE_API int sqlite3_sleep(int ms){
  135263. sqlite3_vfs *pVfs;
  135264. int rc;
  135265. pVfs = sqlite3_vfs_find(0);
  135266. if( pVfs==0 ) return 0;
  135267. /* This function works in milliseconds, but the underlying OsSleep()
  135268. ** API uses microseconds. Hence the 1000's.
  135269. */
  135270. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  135271. return rc;
  135272. }
  135273. /*
  135274. ** Enable or disable the extended result codes.
  135275. */
  135276. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  135277. #ifdef SQLITE_ENABLE_API_ARMOR
  135278. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135279. #endif
  135280. sqlite3_mutex_enter(db->mutex);
  135281. db->errMask = onoff ? 0xffffffff : 0xff;
  135282. sqlite3_mutex_leave(db->mutex);
  135283. return SQLITE_OK;
  135284. }
  135285. /*
  135286. ** Invoke the xFileControl method on a particular database.
  135287. */
  135288. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  135289. int rc = SQLITE_ERROR;
  135290. Btree *pBtree;
  135291. #ifdef SQLITE_ENABLE_API_ARMOR
  135292. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135293. #endif
  135294. sqlite3_mutex_enter(db->mutex);
  135295. pBtree = sqlite3DbNameToBtree(db, zDbName);
  135296. if( pBtree ){
  135297. Pager *pPager;
  135298. sqlite3_file *fd;
  135299. sqlite3BtreeEnter(pBtree);
  135300. pPager = sqlite3BtreePager(pBtree);
  135301. assert( pPager!=0 );
  135302. fd = sqlite3PagerFile(pPager);
  135303. assert( fd!=0 );
  135304. if( op==SQLITE_FCNTL_FILE_POINTER ){
  135305. *(sqlite3_file**)pArg = fd;
  135306. rc = SQLITE_OK;
  135307. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  135308. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  135309. rc = SQLITE_OK;
  135310. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  135311. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  135312. rc = SQLITE_OK;
  135313. }else if( fd->pMethods ){
  135314. rc = sqlite3OsFileControl(fd, op, pArg);
  135315. }else{
  135316. rc = SQLITE_NOTFOUND;
  135317. }
  135318. sqlite3BtreeLeave(pBtree);
  135319. }
  135320. sqlite3_mutex_leave(db->mutex);
  135321. return rc;
  135322. }
  135323. /*
  135324. ** Interface to the testing logic.
  135325. */
  135326. SQLITE_API int sqlite3_test_control(int op, ...){
  135327. int rc = 0;
  135328. #ifdef SQLITE_UNTESTABLE
  135329. UNUSED_PARAMETER(op);
  135330. #else
  135331. va_list ap;
  135332. va_start(ap, op);
  135333. switch( op ){
  135334. /*
  135335. ** Save the current state of the PRNG.
  135336. */
  135337. case SQLITE_TESTCTRL_PRNG_SAVE: {
  135338. sqlite3PrngSaveState();
  135339. break;
  135340. }
  135341. /*
  135342. ** Restore the state of the PRNG to the last state saved using
  135343. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  135344. ** this verb acts like PRNG_RESET.
  135345. */
  135346. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  135347. sqlite3PrngRestoreState();
  135348. break;
  135349. }
  135350. /*
  135351. ** Reset the PRNG back to its uninitialized state. The next call
  135352. ** to sqlite3_randomness() will reseed the PRNG using a single call
  135353. ** to the xRandomness method of the default VFS.
  135354. */
  135355. case SQLITE_TESTCTRL_PRNG_RESET: {
  135356. sqlite3_randomness(0,0);
  135357. break;
  135358. }
  135359. /*
  135360. ** sqlite3_test_control(BITVEC_TEST, size, program)
  135361. **
  135362. ** Run a test against a Bitvec object of size. The program argument
  135363. ** is an array of integers that defines the test. Return -1 on a
  135364. ** memory allocation error, 0 on success, or non-zero for an error.
  135365. ** See the sqlite3BitvecBuiltinTest() for additional information.
  135366. */
  135367. case SQLITE_TESTCTRL_BITVEC_TEST: {
  135368. int sz = va_arg(ap, int);
  135369. int *aProg = va_arg(ap, int*);
  135370. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  135371. break;
  135372. }
  135373. /*
  135374. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  135375. **
  135376. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  135377. ** if xCallback is not NULL.
  135378. **
  135379. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  135380. ** is called immediately after installing the new callback and the return
  135381. ** value from sqlite3FaultSim(0) becomes the return from
  135382. ** sqlite3_test_control().
  135383. */
  135384. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  135385. /* MSVC is picky about pulling func ptrs from va lists.
  135386. ** http://support.microsoft.com/kb/47961
  135387. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  135388. */
  135389. typedef int(*TESTCALLBACKFUNC_t)(int);
  135390. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  135391. rc = sqlite3FaultSim(0);
  135392. break;
  135393. }
  135394. /*
  135395. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  135396. **
  135397. ** Register hooks to call to indicate which malloc() failures
  135398. ** are benign.
  135399. */
  135400. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  135401. typedef void (*void_function)(void);
  135402. void_function xBenignBegin;
  135403. void_function xBenignEnd;
  135404. xBenignBegin = va_arg(ap, void_function);
  135405. xBenignEnd = va_arg(ap, void_function);
  135406. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  135407. break;
  135408. }
  135409. /*
  135410. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  135411. **
  135412. ** Set the PENDING byte to the value in the argument, if X>0.
  135413. ** Make no changes if X==0. Return the value of the pending byte
  135414. ** as it existing before this routine was called.
  135415. **
  135416. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  135417. ** an incompatible database file format. Changing the PENDING byte
  135418. ** while any database connection is open results in undefined and
  135419. ** deleterious behavior.
  135420. */
  135421. case SQLITE_TESTCTRL_PENDING_BYTE: {
  135422. rc = PENDING_BYTE;
  135423. #ifndef SQLITE_OMIT_WSD
  135424. {
  135425. unsigned int newVal = va_arg(ap, unsigned int);
  135426. if( newVal ) sqlite3PendingByte = newVal;
  135427. }
  135428. #endif
  135429. break;
  135430. }
  135431. /*
  135432. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  135433. **
  135434. ** This action provides a run-time test to see whether or not
  135435. ** assert() was enabled at compile-time. If X is true and assert()
  135436. ** is enabled, then the return value is true. If X is true and
  135437. ** assert() is disabled, then the return value is zero. If X is
  135438. ** false and assert() is enabled, then the assertion fires and the
  135439. ** process aborts. If X is false and assert() is disabled, then the
  135440. ** return value is zero.
  135441. */
  135442. case SQLITE_TESTCTRL_ASSERT: {
  135443. volatile int x = 0;
  135444. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  135445. rc = x;
  135446. break;
  135447. }
  135448. /*
  135449. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  135450. **
  135451. ** This action provides a run-time test to see how the ALWAYS and
  135452. ** NEVER macros were defined at compile-time.
  135453. **
  135454. ** The return value is ALWAYS(X).
  135455. **
  135456. ** The recommended test is X==2. If the return value is 2, that means
  135457. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  135458. ** default setting. If the return value is 1, then ALWAYS() is either
  135459. ** hard-coded to true or else it asserts if its argument is false.
  135460. ** The first behavior (hard-coded to true) is the case if
  135461. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  135462. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  135463. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  135464. **
  135465. ** The run-time test procedure might look something like this:
  135466. **
  135467. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  135468. ** // ALWAYS() and NEVER() are no-op pass-through macros
  135469. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  135470. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  135471. ** }else{
  135472. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  135473. ** }
  135474. */
  135475. case SQLITE_TESTCTRL_ALWAYS: {
  135476. int x = va_arg(ap,int);
  135477. rc = ALWAYS(x);
  135478. break;
  135479. }
  135480. /*
  135481. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  135482. **
  135483. ** The integer returned reveals the byte-order of the computer on which
  135484. ** SQLite is running:
  135485. **
  135486. ** 1 big-endian, determined at run-time
  135487. ** 10 little-endian, determined at run-time
  135488. ** 432101 big-endian, determined at compile-time
  135489. ** 123410 little-endian, determined at compile-time
  135490. */
  135491. case SQLITE_TESTCTRL_BYTEORDER: {
  135492. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  135493. break;
  135494. }
  135495. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  135496. **
  135497. ** Set the nReserve size to N for the main database on the database
  135498. ** connection db.
  135499. */
  135500. case SQLITE_TESTCTRL_RESERVE: {
  135501. sqlite3 *db = va_arg(ap, sqlite3*);
  135502. int x = va_arg(ap,int);
  135503. sqlite3_mutex_enter(db->mutex);
  135504. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  135505. sqlite3_mutex_leave(db->mutex);
  135506. break;
  135507. }
  135508. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  135509. **
  135510. ** Enable or disable various optimizations for testing purposes. The
  135511. ** argument N is a bitmask of optimizations to be disabled. For normal
  135512. ** operation N should be 0. The idea is that a test program (like the
  135513. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  135514. ** with various optimizations disabled to verify that the same answer
  135515. ** is obtained in every case.
  135516. */
  135517. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  135518. sqlite3 *db = va_arg(ap, sqlite3*);
  135519. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  135520. break;
  135521. }
  135522. #ifdef SQLITE_N_KEYWORD
  135523. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  135524. **
  135525. ** If zWord is a keyword recognized by the parser, then return the
  135526. ** number of keywords. Or if zWord is not a keyword, return 0.
  135527. **
  135528. ** This test feature is only available in the amalgamation since
  135529. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  135530. ** is built using separate source files.
  135531. */
  135532. case SQLITE_TESTCTRL_ISKEYWORD: {
  135533. const char *zWord = va_arg(ap, const char*);
  135534. int n = sqlite3Strlen30(zWord);
  135535. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  135536. break;
  135537. }
  135538. #endif
  135539. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  135540. **
  135541. ** Pass pFree into sqlite3ScratchFree().
  135542. ** If sz>0 then allocate a scratch buffer into pNew.
  135543. */
  135544. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  135545. void *pFree, **ppNew;
  135546. int sz;
  135547. sz = va_arg(ap, int);
  135548. ppNew = va_arg(ap, void**);
  135549. pFree = va_arg(ap, void*);
  135550. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  135551. sqlite3ScratchFree(pFree);
  135552. break;
  135553. }
  135554. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  135555. **
  135556. ** If parameter onoff is non-zero, configure the wrappers so that all
  135557. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  135558. ** undo this setting.
  135559. */
  135560. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  135561. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  135562. break;
  135563. }
  135564. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  135565. **
  135566. ** Set or clear a flag that indicates that the database file is always well-
  135567. ** formed and never corrupt. This flag is clear by default, indicating that
  135568. ** database files might have arbitrary corruption. Setting the flag during
  135569. ** testing causes certain assert() statements in the code to be activated
  135570. ** that demonstrat invariants on well-formed database files.
  135571. */
  135572. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  135573. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  135574. break;
  135575. }
  135576. /* Set the threshold at which OP_Once counters reset back to zero.
  135577. ** By default this is 0x7ffffffe (over 2 billion), but that value is
  135578. ** too big to test in a reasonable amount of time, so this control is
  135579. ** provided to set a small and easily reachable reset value.
  135580. */
  135581. case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
  135582. sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
  135583. break;
  135584. }
  135585. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  135586. **
  135587. ** Set the VDBE coverage callback function to xCallback with context
  135588. ** pointer ptr.
  135589. */
  135590. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  135591. #ifdef SQLITE_VDBE_COVERAGE
  135592. typedef void (*branch_callback)(void*,int,u8,u8);
  135593. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  135594. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  135595. #endif
  135596. break;
  135597. }
  135598. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  135599. case SQLITE_TESTCTRL_SORTER_MMAP: {
  135600. sqlite3 *db = va_arg(ap, sqlite3*);
  135601. db->nMaxSorterMmap = va_arg(ap, int);
  135602. break;
  135603. }
  135604. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  135605. **
  135606. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  135607. ** not.
  135608. */
  135609. case SQLITE_TESTCTRL_ISINIT: {
  135610. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  135611. break;
  135612. }
  135613. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  135614. **
  135615. ** This test control is used to create imposter tables. "db" is a pointer
  135616. ** to the database connection. dbName is the database name (ex: "main" or
  135617. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  135618. ** or off. "tnum" is the root page of the b-tree to which the imposter
  135619. ** table should connect.
  135620. **
  135621. ** Enable imposter mode only when the schema has already been parsed. Then
  135622. ** run a single CREATE TABLE statement to construct the imposter table in
  135623. ** the parsed schema. Then turn imposter mode back off again.
  135624. **
  135625. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  135626. ** the schema to be reparsed the next time it is needed. This has the
  135627. ** effect of erasing all imposter tables.
  135628. */
  135629. case SQLITE_TESTCTRL_IMPOSTER: {
  135630. sqlite3 *db = va_arg(ap, sqlite3*);
  135631. sqlite3_mutex_enter(db->mutex);
  135632. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  135633. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  135634. db->init.newTnum = va_arg(ap,int);
  135635. if( db->init.busy==0 && db->init.newTnum>0 ){
  135636. sqlite3ResetAllSchemasOfConnection(db);
  135637. }
  135638. sqlite3_mutex_leave(db->mutex);
  135639. break;
  135640. }
  135641. }
  135642. va_end(ap);
  135643. #endif /* SQLITE_UNTESTABLE */
  135644. return rc;
  135645. }
  135646. /*
  135647. ** This is a utility routine, useful to VFS implementations, that checks
  135648. ** to see if a database file was a URI that contained a specific query
  135649. ** parameter, and if so obtains the value of the query parameter.
  135650. **
  135651. ** The zFilename argument is the filename pointer passed into the xOpen()
  135652. ** method of a VFS implementation. The zParam argument is the name of the
  135653. ** query parameter we seek. This routine returns the value of the zParam
  135654. ** parameter if it exists. If the parameter does not exist, this routine
  135655. ** returns a NULL pointer.
  135656. */
  135657. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  135658. if( zFilename==0 || zParam==0 ) return 0;
  135659. zFilename += sqlite3Strlen30(zFilename) + 1;
  135660. while( zFilename[0] ){
  135661. int x = strcmp(zFilename, zParam);
  135662. zFilename += sqlite3Strlen30(zFilename) + 1;
  135663. if( x==0 ) return zFilename;
  135664. zFilename += sqlite3Strlen30(zFilename) + 1;
  135665. }
  135666. return 0;
  135667. }
  135668. /*
  135669. ** Return a boolean value for a query parameter.
  135670. */
  135671. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  135672. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  135673. bDflt = bDflt!=0;
  135674. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  135675. }
  135676. /*
  135677. ** Return a 64-bit integer value for a query parameter.
  135678. */
  135679. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  135680. const char *zFilename, /* Filename as passed to xOpen */
  135681. const char *zParam, /* URI parameter sought */
  135682. sqlite3_int64 bDflt /* return if parameter is missing */
  135683. ){
  135684. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  135685. sqlite3_int64 v;
  135686. if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
  135687. bDflt = v;
  135688. }
  135689. return bDflt;
  135690. }
  135691. /*
  135692. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  135693. */
  135694. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  135695. int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
  135696. return iDb<0 ? 0 : db->aDb[iDb].pBt;
  135697. }
  135698. /*
  135699. ** Return the filename of the database associated with a database
  135700. ** connection.
  135701. */
  135702. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  135703. Btree *pBt;
  135704. #ifdef SQLITE_ENABLE_API_ARMOR
  135705. if( !sqlite3SafetyCheckOk(db) ){
  135706. (void)SQLITE_MISUSE_BKPT;
  135707. return 0;
  135708. }
  135709. #endif
  135710. pBt = sqlite3DbNameToBtree(db, zDbName);
  135711. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  135712. }
  135713. /*
  135714. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  135715. ** no such database exists.
  135716. */
  135717. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  135718. Btree *pBt;
  135719. #ifdef SQLITE_ENABLE_API_ARMOR
  135720. if( !sqlite3SafetyCheckOk(db) ){
  135721. (void)SQLITE_MISUSE_BKPT;
  135722. return -1;
  135723. }
  135724. #endif
  135725. pBt = sqlite3DbNameToBtree(db, zDbName);
  135726. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  135727. }
  135728. #ifdef SQLITE_ENABLE_SNAPSHOT
  135729. /*
  135730. ** Obtain a snapshot handle for the snapshot of database zDb currently
  135731. ** being read by handle db.
  135732. */
  135733. SQLITE_API int sqlite3_snapshot_get(
  135734. sqlite3 *db,
  135735. const char *zDb,
  135736. sqlite3_snapshot **ppSnapshot
  135737. ){
  135738. int rc = SQLITE_ERROR;
  135739. #ifndef SQLITE_OMIT_WAL
  135740. #ifdef SQLITE_ENABLE_API_ARMOR
  135741. if( !sqlite3SafetyCheckOk(db) ){
  135742. return SQLITE_MISUSE_BKPT;
  135743. }
  135744. #endif
  135745. sqlite3_mutex_enter(db->mutex);
  135746. if( db->autoCommit==0 ){
  135747. int iDb = sqlite3FindDbName(db, zDb);
  135748. if( iDb==0 || iDb>1 ){
  135749. Btree *pBt = db->aDb[iDb].pBt;
  135750. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  135751. rc = sqlite3BtreeBeginTrans(pBt, 0);
  135752. if( rc==SQLITE_OK ){
  135753. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  135754. }
  135755. }
  135756. }
  135757. }
  135758. sqlite3_mutex_leave(db->mutex);
  135759. #endif /* SQLITE_OMIT_WAL */
  135760. return rc;
  135761. }
  135762. /*
  135763. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  135764. */
  135765. SQLITE_API int sqlite3_snapshot_open(
  135766. sqlite3 *db,
  135767. const char *zDb,
  135768. sqlite3_snapshot *pSnapshot
  135769. ){
  135770. int rc = SQLITE_ERROR;
  135771. #ifndef SQLITE_OMIT_WAL
  135772. #ifdef SQLITE_ENABLE_API_ARMOR
  135773. if( !sqlite3SafetyCheckOk(db) ){
  135774. return SQLITE_MISUSE_BKPT;
  135775. }
  135776. #endif
  135777. sqlite3_mutex_enter(db->mutex);
  135778. if( db->autoCommit==0 ){
  135779. int iDb;
  135780. iDb = sqlite3FindDbName(db, zDb);
  135781. if( iDb==0 || iDb>1 ){
  135782. Btree *pBt = db->aDb[iDb].pBt;
  135783. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  135784. rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
  135785. if( rc==SQLITE_OK ){
  135786. rc = sqlite3BtreeBeginTrans(pBt, 0);
  135787. sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
  135788. }
  135789. }
  135790. }
  135791. }
  135792. sqlite3_mutex_leave(db->mutex);
  135793. #endif /* SQLITE_OMIT_WAL */
  135794. return rc;
  135795. }
  135796. /*
  135797. ** Recover as many snapshots as possible from the wal file associated with
  135798. ** schema zDb of database db.
  135799. */
  135800. SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
  135801. int rc = SQLITE_ERROR;
  135802. int iDb;
  135803. #ifndef SQLITE_OMIT_WAL
  135804. #ifdef SQLITE_ENABLE_API_ARMOR
  135805. if( !sqlite3SafetyCheckOk(db) ){
  135806. return SQLITE_MISUSE_BKPT;
  135807. }
  135808. #endif
  135809. sqlite3_mutex_enter(db->mutex);
  135810. iDb = sqlite3FindDbName(db, zDb);
  135811. if( iDb==0 || iDb>1 ){
  135812. Btree *pBt = db->aDb[iDb].pBt;
  135813. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  135814. rc = sqlite3BtreeBeginTrans(pBt, 0);
  135815. if( rc==SQLITE_OK ){
  135816. rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
  135817. sqlite3BtreeCommit(pBt);
  135818. }
  135819. }
  135820. }
  135821. sqlite3_mutex_leave(db->mutex);
  135822. #endif /* SQLITE_OMIT_WAL */
  135823. return rc;
  135824. }
  135825. /*
  135826. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  135827. */
  135828. SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  135829. sqlite3_free(pSnapshot);
  135830. }
  135831. #endif /* SQLITE_ENABLE_SNAPSHOT */
  135832. /************** End of main.c ************************************************/
  135833. /************** Begin file notify.c ******************************************/
  135834. /*
  135835. ** 2009 March 3
  135836. **
  135837. ** The author disclaims copyright to this source code. In place of
  135838. ** a legal notice, here is a blessing:
  135839. **
  135840. ** May you do good and not evil.
  135841. ** May you find forgiveness for yourself and forgive others.
  135842. ** May you share freely, never taking more than you give.
  135843. **
  135844. *************************************************************************
  135845. **
  135846. ** This file contains the implementation of the sqlite3_unlock_notify()
  135847. ** API method and its associated functionality.
  135848. */
  135849. /* #include "sqliteInt.h" */
  135850. /* #include "btreeInt.h" */
  135851. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  135852. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  135853. /*
  135854. ** Public interfaces:
  135855. **
  135856. ** sqlite3ConnectionBlocked()
  135857. ** sqlite3ConnectionUnlocked()
  135858. ** sqlite3ConnectionClosed()
  135859. ** sqlite3_unlock_notify()
  135860. */
  135861. #define assertMutexHeld() \
  135862. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  135863. /*
  135864. ** Head of a linked list of all sqlite3 objects created by this process
  135865. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  135866. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  135867. ** mutex is held.
  135868. */
  135869. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  135870. #ifndef NDEBUG
  135871. /*
  135872. ** This function is a complex assert() that verifies the following
  135873. ** properties of the blocked connections list:
  135874. **
  135875. ** 1) Each entry in the list has a non-NULL value for either
  135876. ** pUnlockConnection or pBlockingConnection, or both.
  135877. **
  135878. ** 2) All entries in the list that share a common value for
  135879. ** xUnlockNotify are grouped together.
  135880. **
  135881. ** 3) If the argument db is not NULL, then none of the entries in the
  135882. ** blocked connections list have pUnlockConnection or pBlockingConnection
  135883. ** set to db. This is used when closing connection db.
  135884. */
  135885. static void checkListProperties(sqlite3 *db){
  135886. sqlite3 *p;
  135887. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  135888. int seen = 0;
  135889. sqlite3 *p2;
  135890. /* Verify property (1) */
  135891. assert( p->pUnlockConnection || p->pBlockingConnection );
  135892. /* Verify property (2) */
  135893. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  135894. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  135895. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  135896. assert( db==0 || p->pUnlockConnection!=db );
  135897. assert( db==0 || p->pBlockingConnection!=db );
  135898. }
  135899. }
  135900. }
  135901. #else
  135902. # define checkListProperties(x)
  135903. #endif
  135904. /*
  135905. ** Remove connection db from the blocked connections list. If connection
  135906. ** db is not currently a part of the list, this function is a no-op.
  135907. */
  135908. static void removeFromBlockedList(sqlite3 *db){
  135909. sqlite3 **pp;
  135910. assertMutexHeld();
  135911. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  135912. if( *pp==db ){
  135913. *pp = (*pp)->pNextBlocked;
  135914. break;
  135915. }
  135916. }
  135917. }
  135918. /*
  135919. ** Add connection db to the blocked connections list. It is assumed
  135920. ** that it is not already a part of the list.
  135921. */
  135922. static void addToBlockedList(sqlite3 *db){
  135923. sqlite3 **pp;
  135924. assertMutexHeld();
  135925. for(
  135926. pp=&sqlite3BlockedList;
  135927. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  135928. pp=&(*pp)->pNextBlocked
  135929. );
  135930. db->pNextBlocked = *pp;
  135931. *pp = db;
  135932. }
  135933. /*
  135934. ** Obtain the STATIC_MASTER mutex.
  135935. */
  135936. static void enterMutex(void){
  135937. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  135938. checkListProperties(0);
  135939. }
  135940. /*
  135941. ** Release the STATIC_MASTER mutex.
  135942. */
  135943. static void leaveMutex(void){
  135944. assertMutexHeld();
  135945. checkListProperties(0);
  135946. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  135947. }
  135948. /*
  135949. ** Register an unlock-notify callback.
  135950. **
  135951. ** This is called after connection "db" has attempted some operation
  135952. ** but has received an SQLITE_LOCKED error because another connection
  135953. ** (call it pOther) in the same process was busy using the same shared
  135954. ** cache. pOther is found by looking at db->pBlockingConnection.
  135955. **
  135956. ** If there is no blocking connection, the callback is invoked immediately,
  135957. ** before this routine returns.
  135958. **
  135959. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  135960. ** a deadlock.
  135961. **
  135962. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  135963. ** its locks.
  135964. **
  135965. ** Each call to this routine overrides any prior callbacks registered
  135966. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  135967. ** cancelled.
  135968. */
  135969. SQLITE_API int sqlite3_unlock_notify(
  135970. sqlite3 *db,
  135971. void (*xNotify)(void **, int),
  135972. void *pArg
  135973. ){
  135974. int rc = SQLITE_OK;
  135975. sqlite3_mutex_enter(db->mutex);
  135976. enterMutex();
  135977. if( xNotify==0 ){
  135978. removeFromBlockedList(db);
  135979. db->pBlockingConnection = 0;
  135980. db->pUnlockConnection = 0;
  135981. db->xUnlockNotify = 0;
  135982. db->pUnlockArg = 0;
  135983. }else if( 0==db->pBlockingConnection ){
  135984. /* The blocking transaction has been concluded. Or there never was a
  135985. ** blocking transaction. In either case, invoke the notify callback
  135986. ** immediately.
  135987. */
  135988. xNotify(&pArg, 1);
  135989. }else{
  135990. sqlite3 *p;
  135991. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  135992. if( p ){
  135993. rc = SQLITE_LOCKED; /* Deadlock detected. */
  135994. }else{
  135995. db->pUnlockConnection = db->pBlockingConnection;
  135996. db->xUnlockNotify = xNotify;
  135997. db->pUnlockArg = pArg;
  135998. removeFromBlockedList(db);
  135999. addToBlockedList(db);
  136000. }
  136001. }
  136002. leaveMutex();
  136003. assert( !db->mallocFailed );
  136004. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  136005. sqlite3_mutex_leave(db->mutex);
  136006. return rc;
  136007. }
  136008. /*
  136009. ** This function is called while stepping or preparing a statement
  136010. ** associated with connection db. The operation will return SQLITE_LOCKED
  136011. ** to the user because it requires a lock that will not be available
  136012. ** until connection pBlocker concludes its current transaction.
  136013. */
  136014. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  136015. enterMutex();
  136016. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  136017. addToBlockedList(db);
  136018. }
  136019. db->pBlockingConnection = pBlocker;
  136020. leaveMutex();
  136021. }
  136022. /*
  136023. ** This function is called when
  136024. ** the transaction opened by database db has just finished. Locks held
  136025. ** by database connection db have been released.
  136026. **
  136027. ** This function loops through each entry in the blocked connections
  136028. ** list and does the following:
  136029. **
  136030. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  136031. ** set to db, then set pBlockingConnection=0.
  136032. **
  136033. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  136034. ** set to db, then invoke the configured unlock-notify callback and
  136035. ** set pUnlockConnection=0.
  136036. **
  136037. ** 3) If the two steps above mean that pBlockingConnection==0 and
  136038. ** pUnlockConnection==0, remove the entry from the blocked connections
  136039. ** list.
  136040. */
  136041. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  136042. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  136043. int nArg = 0; /* Number of entries in aArg[] */
  136044. sqlite3 **pp; /* Iterator variable */
  136045. void **aArg; /* Arguments to the unlock callback */
  136046. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  136047. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  136048. aArg = aStatic;
  136049. enterMutex(); /* Enter STATIC_MASTER mutex */
  136050. /* This loop runs once for each entry in the blocked-connections list. */
  136051. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  136052. sqlite3 *p = *pp;
  136053. /* Step 1. */
  136054. if( p->pBlockingConnection==db ){
  136055. p->pBlockingConnection = 0;
  136056. }
  136057. /* Step 2. */
  136058. if( p->pUnlockConnection==db ){
  136059. assert( p->xUnlockNotify );
  136060. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  136061. xUnlockNotify(aArg, nArg);
  136062. nArg = 0;
  136063. }
  136064. sqlite3BeginBenignMalloc();
  136065. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  136066. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  136067. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  136068. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  136069. ){
  136070. /* The aArg[] array needs to grow. */
  136071. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  136072. if( pNew ){
  136073. memcpy(pNew, aArg, nArg*sizeof(void *));
  136074. sqlite3_free(aDyn);
  136075. aDyn = aArg = pNew;
  136076. }else{
  136077. /* This occurs when the array of context pointers that need to
  136078. ** be passed to the unlock-notify callback is larger than the
  136079. ** aStatic[] array allocated on the stack and the attempt to
  136080. ** allocate a larger array from the heap has failed.
  136081. **
  136082. ** This is a difficult situation to handle. Returning an error
  136083. ** code to the caller is insufficient, as even if an error code
  136084. ** is returned the transaction on connection db will still be
  136085. ** closed and the unlock-notify callbacks on blocked connections
  136086. ** will go unissued. This might cause the application to wait
  136087. ** indefinitely for an unlock-notify callback that will never
  136088. ** arrive.
  136089. **
  136090. ** Instead, invoke the unlock-notify callback with the context
  136091. ** array already accumulated. We can then clear the array and
  136092. ** begin accumulating any further context pointers without
  136093. ** requiring any dynamic allocation. This is sub-optimal because
  136094. ** it means that instead of one callback with a large array of
  136095. ** context pointers the application will receive two or more
  136096. ** callbacks with smaller arrays of context pointers, which will
  136097. ** reduce the applications ability to prioritize multiple
  136098. ** connections. But it is the best that can be done under the
  136099. ** circumstances.
  136100. */
  136101. xUnlockNotify(aArg, nArg);
  136102. nArg = 0;
  136103. }
  136104. }
  136105. sqlite3EndBenignMalloc();
  136106. aArg[nArg++] = p->pUnlockArg;
  136107. xUnlockNotify = p->xUnlockNotify;
  136108. p->pUnlockConnection = 0;
  136109. p->xUnlockNotify = 0;
  136110. p->pUnlockArg = 0;
  136111. }
  136112. /* Step 3. */
  136113. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  136114. /* Remove connection p from the blocked connections list. */
  136115. *pp = p->pNextBlocked;
  136116. p->pNextBlocked = 0;
  136117. }else{
  136118. pp = &p->pNextBlocked;
  136119. }
  136120. }
  136121. if( nArg!=0 ){
  136122. xUnlockNotify(aArg, nArg);
  136123. }
  136124. sqlite3_free(aDyn);
  136125. leaveMutex(); /* Leave STATIC_MASTER mutex */
  136126. }
  136127. /*
  136128. ** This is called when the database connection passed as an argument is
  136129. ** being closed. The connection is removed from the blocked list.
  136130. */
  136131. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  136132. sqlite3ConnectionUnlocked(db);
  136133. enterMutex();
  136134. removeFromBlockedList(db);
  136135. checkListProperties(db);
  136136. leaveMutex();
  136137. }
  136138. #endif
  136139. /************** End of notify.c **********************************************/
  136140. /************** Begin file fts3.c ********************************************/
  136141. /*
  136142. ** 2006 Oct 10
  136143. **
  136144. ** The author disclaims copyright to this source code. In place of
  136145. ** a legal notice, here is a blessing:
  136146. **
  136147. ** May you do good and not evil.
  136148. ** May you find forgiveness for yourself and forgive others.
  136149. ** May you share freely, never taking more than you give.
  136150. **
  136151. ******************************************************************************
  136152. **
  136153. ** This is an SQLite module implementing full-text search.
  136154. */
  136155. /*
  136156. ** The code in this file is only compiled if:
  136157. **
  136158. ** * The FTS3 module is being built as an extension
  136159. ** (in which case SQLITE_CORE is not defined), or
  136160. **
  136161. ** * The FTS3 module is being built into the core of
  136162. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  136163. */
  136164. /* The full-text index is stored in a series of b+tree (-like)
  136165. ** structures called segments which map terms to doclists. The
  136166. ** structures are like b+trees in layout, but are constructed from the
  136167. ** bottom up in optimal fashion and are not updatable. Since trees
  136168. ** are built from the bottom up, things will be described from the
  136169. ** bottom up.
  136170. **
  136171. **
  136172. **** Varints ****
  136173. ** The basic unit of encoding is a variable-length integer called a
  136174. ** varint. We encode variable-length integers in little-endian order
  136175. ** using seven bits * per byte as follows:
  136176. **
  136177. ** KEY:
  136178. ** A = 0xxxxxxx 7 bits of data and one flag bit
  136179. ** B = 1xxxxxxx 7 bits of data and one flag bit
  136180. **
  136181. ** 7 bits - A
  136182. ** 14 bits - BA
  136183. ** 21 bits - BBA
  136184. ** and so on.
  136185. **
  136186. ** This is similar in concept to how sqlite encodes "varints" but
  136187. ** the encoding is not the same. SQLite varints are big-endian
  136188. ** are are limited to 9 bytes in length whereas FTS3 varints are
  136189. ** little-endian and can be up to 10 bytes in length (in theory).
  136190. **
  136191. ** Example encodings:
  136192. **
  136193. ** 1: 0x01
  136194. ** 127: 0x7f
  136195. ** 128: 0x81 0x00
  136196. **
  136197. **
  136198. **** Document lists ****
  136199. ** A doclist (document list) holds a docid-sorted list of hits for a
  136200. ** given term. Doclists hold docids and associated token positions.
  136201. ** A docid is the unique integer identifier for a single document.
  136202. ** A position is the index of a word within the document. The first
  136203. ** word of the document has a position of 0.
  136204. **
  136205. ** FTS3 used to optionally store character offsets using a compile-time
  136206. ** option. But that functionality is no longer supported.
  136207. **
  136208. ** A doclist is stored like this:
  136209. **
  136210. ** array {
  136211. ** varint docid; (delta from previous doclist)
  136212. ** array { (position list for column 0)
  136213. ** varint position; (2 more than the delta from previous position)
  136214. ** }
  136215. ** array {
  136216. ** varint POS_COLUMN; (marks start of position list for new column)
  136217. ** varint column; (index of new column)
  136218. ** array {
  136219. ** varint position; (2 more than the delta from previous position)
  136220. ** }
  136221. ** }
  136222. ** varint POS_END; (marks end of positions for this document.
  136223. ** }
  136224. **
  136225. ** Here, array { X } means zero or more occurrences of X, adjacent in
  136226. ** memory. A "position" is an index of a token in the token stream
  136227. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  136228. ** in the same logical place as the position element, and act as sentinals
  136229. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  136230. ** The positions numbers are not stored literally but rather as two more
  136231. ** than the difference from the prior position, or the just the position plus
  136232. ** 2 for the first position. Example:
  136233. **
  136234. ** label: A B C D E F G H I J K
  136235. ** value: 123 5 9 1 1 14 35 0 234 72 0
  136236. **
  136237. ** The 123 value is the first docid. For column zero in this document
  136238. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  136239. ** at D signals the start of a new column; the 1 at E indicates that the
  136240. ** new column is column number 1. There are two positions at 12 and 45
  136241. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  136242. ** 234 at I is the delta to next docid (357). It has one position 70
  136243. ** (72-2) and then terminates with the 0 at K.
  136244. **
  136245. ** A "position-list" is the list of positions for multiple columns for
  136246. ** a single docid. A "column-list" is the set of positions for a single
  136247. ** column. Hence, a position-list consists of one or more column-lists,
  136248. ** a document record consists of a docid followed by a position-list and
  136249. ** a doclist consists of one or more document records.
  136250. **
  136251. ** A bare doclist omits the position information, becoming an
  136252. ** array of varint-encoded docids.
  136253. **
  136254. **** Segment leaf nodes ****
  136255. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  136256. ** nodes are written using LeafWriter, and read using LeafReader (to
  136257. ** iterate through a single leaf node's data) and LeavesReader (to
  136258. ** iterate through a segment's entire leaf layer). Leaf nodes have
  136259. ** the format:
  136260. **
  136261. ** varint iHeight; (height from leaf level, always 0)
  136262. ** varint nTerm; (length of first term)
  136263. ** char pTerm[nTerm]; (content of first term)
  136264. ** varint nDoclist; (length of term's associated doclist)
  136265. ** char pDoclist[nDoclist]; (content of doclist)
  136266. ** array {
  136267. ** (further terms are delta-encoded)
  136268. ** varint nPrefix; (length of prefix shared with previous term)
  136269. ** varint nSuffix; (length of unshared suffix)
  136270. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  136271. ** varint nDoclist; (length of term's associated doclist)
  136272. ** char pDoclist[nDoclist]; (content of doclist)
  136273. ** }
  136274. **
  136275. ** Here, array { X } means zero or more occurrences of X, adjacent in
  136276. ** memory.
  136277. **
  136278. ** Leaf nodes are broken into blocks which are stored contiguously in
  136279. ** the %_segments table in sorted order. This means that when the end
  136280. ** of a node is reached, the next term is in the node with the next
  136281. ** greater node id.
  136282. **
  136283. ** New data is spilled to a new leaf node when the current node
  136284. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  136285. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  136286. ** node (a leaf node with a single term and doclist). The goal of
  136287. ** these settings is to pack together groups of small doclists while
  136288. ** making it efficient to directly access large doclists. The
  136289. ** assumption is that large doclists represent terms which are more
  136290. ** likely to be query targets.
  136291. **
  136292. ** TODO(shess) It may be useful for blocking decisions to be more
  136293. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  136294. ** node rather than splitting into 2k and .5k nodes. My intuition is
  136295. ** that this might extend through 2x or 4x the pagesize.
  136296. **
  136297. **
  136298. **** Segment interior nodes ****
  136299. ** Segment interior nodes store blockids for subtree nodes and terms
  136300. ** to describe what data is stored by the each subtree. Interior
  136301. ** nodes are written using InteriorWriter, and read using
  136302. ** InteriorReader. InteriorWriters are created as needed when
  136303. ** SegmentWriter creates new leaf nodes, or when an interior node
  136304. ** itself grows too big and must be split. The format of interior
  136305. ** nodes:
  136306. **
  136307. ** varint iHeight; (height from leaf level, always >0)
  136308. ** varint iBlockid; (block id of node's leftmost subtree)
  136309. ** optional {
  136310. ** varint nTerm; (length of first term)
  136311. ** char pTerm[nTerm]; (content of first term)
  136312. ** array {
  136313. ** (further terms are delta-encoded)
  136314. ** varint nPrefix; (length of shared prefix with previous term)
  136315. ** varint nSuffix; (length of unshared suffix)
  136316. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  136317. ** }
  136318. ** }
  136319. **
  136320. ** Here, optional { X } means an optional element, while array { X }
  136321. ** means zero or more occurrences of X, adjacent in memory.
  136322. **
  136323. ** An interior node encodes n terms separating n+1 subtrees. The
  136324. ** subtree blocks are contiguous, so only the first subtree's blockid
  136325. ** is encoded. The subtree at iBlockid will contain all terms less
  136326. ** than the first term encoded (or all terms if no term is encoded).
  136327. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  136328. ** than pTerm[i+1], the subtree for that term will be rooted at
  136329. ** iBlockid+i. Interior nodes only store enough term data to
  136330. ** distinguish adjacent children (if the rightmost term of the left
  136331. ** child is "something", and the leftmost term of the right child is
  136332. ** "wicked", only "w" is stored).
  136333. **
  136334. ** New data is spilled to a new interior node at the same height when
  136335. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  136336. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  136337. ** interior nodes and making the tree too skinny. The interior nodes
  136338. ** at a given height are naturally tracked by interior nodes at
  136339. ** height+1, and so on.
  136340. **
  136341. **
  136342. **** Segment directory ****
  136343. ** The segment directory in table %_segdir stores meta-information for
  136344. ** merging and deleting segments, and also the root node of the
  136345. ** segment's tree.
  136346. **
  136347. ** The root node is the top node of the segment's tree after encoding
  136348. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  136349. ** This could be either a leaf node or an interior node. If the top
  136350. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  136351. ** and a new root interior node is generated (which should always fit
  136352. ** within ROOT_MAX because it only needs space for 2 varints, the
  136353. ** height and the blockid of the previous root).
  136354. **
  136355. ** The meta-information in the segment directory is:
  136356. ** level - segment level (see below)
  136357. ** idx - index within level
  136358. ** - (level,idx uniquely identify a segment)
  136359. ** start_block - first leaf node
  136360. ** leaves_end_block - last leaf node
  136361. ** end_block - last block (including interior nodes)
  136362. ** root - contents of root node
  136363. **
  136364. ** If the root node is a leaf node, then start_block,
  136365. ** leaves_end_block, and end_block are all 0.
  136366. **
  136367. **
  136368. **** Segment merging ****
  136369. ** To amortize update costs, segments are grouped into levels and
  136370. ** merged in batches. Each increase in level represents exponentially
  136371. ** more documents.
  136372. **
  136373. ** New documents (actually, document updates) are tokenized and
  136374. ** written individually (using LeafWriter) to a level 0 segment, with
  136375. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  136376. ** level 0 segments are merged into a single level 1 segment. Level 1
  136377. ** is populated like level 0, and eventually MERGE_COUNT level 1
  136378. ** segments are merged to a single level 2 segment (representing
  136379. ** MERGE_COUNT^2 updates), and so on.
  136380. **
  136381. ** A segment merge traverses all segments at a given level in
  136382. ** parallel, performing a straightforward sorted merge. Since segment
  136383. ** leaf nodes are written in to the %_segments table in order, this
  136384. ** merge traverses the underlying sqlite disk structures efficiently.
  136385. ** After the merge, all segment blocks from the merged level are
  136386. ** deleted.
  136387. **
  136388. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  136389. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  136390. ** very similar performance numbers to 16 on insertion, though they're
  136391. ** a tiny bit slower (perhaps due to more overhead in merge-time
  136392. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  136393. ** 16, 2 about 66% slower than 16.
  136394. **
  136395. ** At query time, high MERGE_COUNT increases the number of segments
  136396. ** which need to be scanned and merged. For instance, with 100k docs
  136397. ** inserted:
  136398. **
  136399. ** MERGE_COUNT segments
  136400. ** 16 25
  136401. ** 8 12
  136402. ** 4 10
  136403. ** 2 6
  136404. **
  136405. ** This appears to have only a moderate impact on queries for very
  136406. ** frequent terms (which are somewhat dominated by segment merge
  136407. ** costs), and infrequent and non-existent terms still seem to be fast
  136408. ** even with many segments.
  136409. **
  136410. ** TODO(shess) That said, it would be nice to have a better query-side
  136411. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  136412. ** optimizations to things like doclist merging will swing the sweet
  136413. ** spot around.
  136414. **
  136415. **
  136416. **
  136417. **** Handling of deletions and updates ****
  136418. ** Since we're using a segmented structure, with no docid-oriented
  136419. ** index into the term index, we clearly cannot simply update the term
  136420. ** index when a document is deleted or updated. For deletions, we
  136421. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  136422. ** we simply write the new doclist. Segment merges overwrite older
  136423. ** data for a particular docid with newer data, so deletes or updates
  136424. ** will eventually overtake the earlier data and knock it out. The
  136425. ** query logic likewise merges doclists so that newer data knocks out
  136426. ** older data.
  136427. */
  136428. /************** Include fts3Int.h in the middle of fts3.c ********************/
  136429. /************** Begin file fts3Int.h *****************************************/
  136430. /*
  136431. ** 2009 Nov 12
  136432. **
  136433. ** The author disclaims copyright to this source code. In place of
  136434. ** a legal notice, here is a blessing:
  136435. **
  136436. ** May you do good and not evil.
  136437. ** May you find forgiveness for yourself and forgive others.
  136438. ** May you share freely, never taking more than you give.
  136439. **
  136440. ******************************************************************************
  136441. **
  136442. */
  136443. #ifndef _FTSINT_H
  136444. #define _FTSINT_H
  136445. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  136446. # define NDEBUG 1
  136447. #endif
  136448. /* FTS3/FTS4 require virtual tables */
  136449. #ifdef SQLITE_OMIT_VIRTUALTABLE
  136450. # undef SQLITE_ENABLE_FTS3
  136451. # undef SQLITE_ENABLE_FTS4
  136452. #endif
  136453. /*
  136454. ** FTS4 is really an extension for FTS3. It is enabled using the
  136455. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  136456. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  136457. */
  136458. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  136459. # define SQLITE_ENABLE_FTS3
  136460. #endif
  136461. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  136462. /* If not building as part of the core, include sqlite3ext.h. */
  136463. #ifndef SQLITE_CORE
  136464. /* # include "sqlite3ext.h" */
  136465. SQLITE_EXTENSION_INIT3
  136466. #endif
  136467. /* #include "sqlite3.h" */
  136468. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  136469. /************** Begin file fts3_tokenizer.h **********************************/
  136470. /*
  136471. ** 2006 July 10
  136472. **
  136473. ** The author disclaims copyright to this source code.
  136474. **
  136475. *************************************************************************
  136476. ** Defines the interface to tokenizers used by fulltext-search. There
  136477. ** are three basic components:
  136478. **
  136479. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  136480. ** interface functions. This is essentially the class structure for
  136481. ** tokenizers.
  136482. **
  136483. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  136484. ** including customization information defined at creation time.
  136485. **
  136486. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  136487. ** tokens from a particular input.
  136488. */
  136489. #ifndef _FTS3_TOKENIZER_H_
  136490. #define _FTS3_TOKENIZER_H_
  136491. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  136492. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  136493. ** we will need a way to register the API consistently.
  136494. */
  136495. /* #include "sqlite3.h" */
  136496. /*
  136497. ** Structures used by the tokenizer interface. When a new tokenizer
  136498. ** implementation is registered, the caller provides a pointer to
  136499. ** an sqlite3_tokenizer_module containing pointers to the callback
  136500. ** functions that make up an implementation.
  136501. **
  136502. ** When an fts3 table is created, it passes any arguments passed to
  136503. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  136504. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  136505. ** implementation. The xCreate() function in turn returns an
  136506. ** sqlite3_tokenizer structure representing the specific tokenizer to
  136507. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  136508. **
  136509. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  136510. ** method is called. It returns an sqlite3_tokenizer_cursor object
  136511. ** that may be used to tokenize a specific input buffer based on
  136512. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  136513. ** object.
  136514. */
  136515. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  136516. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  136517. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  136518. struct sqlite3_tokenizer_module {
  136519. /*
  136520. ** Structure version. Should always be set to 0 or 1.
  136521. */
  136522. int iVersion;
  136523. /*
  136524. ** Create a new tokenizer. The values in the argv[] array are the
  136525. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  136526. ** TABLE statement that created the fts3 table. For example, if
  136527. ** the following SQL is executed:
  136528. **
  136529. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  136530. **
  136531. ** then argc is set to 2, and the argv[] array contains pointers
  136532. ** to the strings "arg1" and "arg2".
  136533. **
  136534. ** This method should return either SQLITE_OK (0), or an SQLite error
  136535. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  136536. ** to point at the newly created tokenizer structure. The generic
  136537. ** sqlite3_tokenizer.pModule variable should not be initialized by
  136538. ** this callback. The caller will do so.
  136539. */
  136540. int (*xCreate)(
  136541. int argc, /* Size of argv array */
  136542. const char *const*argv, /* Tokenizer argument strings */
  136543. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  136544. );
  136545. /*
  136546. ** Destroy an existing tokenizer. The fts3 module calls this method
  136547. ** exactly once for each successful call to xCreate().
  136548. */
  136549. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  136550. /*
  136551. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  136552. ** is responsible for ensuring that the input buffer remains valid
  136553. ** until the cursor is closed (using the xClose() method).
  136554. */
  136555. int (*xOpen)(
  136556. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  136557. const char *pInput, int nBytes, /* Input buffer */
  136558. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  136559. );
  136560. /*
  136561. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  136562. ** method exactly once for each successful call to xOpen().
  136563. */
  136564. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  136565. /*
  136566. ** Retrieve the next token from the tokenizer cursor pCursor. This
  136567. ** method should either return SQLITE_OK and set the values of the
  136568. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  136569. ** the end of the buffer has been reached, or an SQLite error code.
  136570. **
  136571. ** *ppToken should be set to point at a buffer containing the
  136572. ** normalized version of the token (i.e. after any case-folding and/or
  136573. ** stemming has been performed). *pnBytes should be set to the length
  136574. ** of this buffer in bytes. The input text that generated the token is
  136575. ** identified by the byte offsets returned in *piStartOffset and
  136576. ** *piEndOffset. *piStartOffset should be set to the index of the first
  136577. ** byte of the token in the input buffer. *piEndOffset should be set
  136578. ** to the index of the first byte just past the end of the token in
  136579. ** the input buffer.
  136580. **
  136581. ** The buffer *ppToken is set to point at is managed by the tokenizer
  136582. ** implementation. It is only required to be valid until the next call
  136583. ** to xNext() or xClose().
  136584. */
  136585. /* TODO(shess) current implementation requires pInput to be
  136586. ** nul-terminated. This should either be fixed, or pInput/nBytes
  136587. ** should be converted to zInput.
  136588. */
  136589. int (*xNext)(
  136590. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  136591. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  136592. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  136593. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  136594. int *piPosition /* OUT: Number of tokens returned before this one */
  136595. );
  136596. /***********************************************************************
  136597. ** Methods below this point are only available if iVersion>=1.
  136598. */
  136599. /*
  136600. ** Configure the language id of a tokenizer cursor.
  136601. */
  136602. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  136603. };
  136604. struct sqlite3_tokenizer {
  136605. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  136606. /* Tokenizer implementations will typically add additional fields */
  136607. };
  136608. struct sqlite3_tokenizer_cursor {
  136609. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  136610. /* Tokenizer implementations will typically add additional fields */
  136611. };
  136612. int fts3_global_term_cnt(int iTerm, int iCol);
  136613. int fts3_term_cnt(int iTerm, int iCol);
  136614. #endif /* _FTS3_TOKENIZER_H_ */
  136615. /************** End of fts3_tokenizer.h **************************************/
  136616. /************** Continuing where we left off in fts3Int.h ********************/
  136617. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  136618. /************** Begin file fts3_hash.h ***************************************/
  136619. /*
  136620. ** 2001 September 22
  136621. **
  136622. ** The author disclaims copyright to this source code. In place of
  136623. ** a legal notice, here is a blessing:
  136624. **
  136625. ** May you do good and not evil.
  136626. ** May you find forgiveness for yourself and forgive others.
  136627. ** May you share freely, never taking more than you give.
  136628. **
  136629. *************************************************************************
  136630. ** This is the header file for the generic hash-table implementation
  136631. ** used in SQLite. We've modified it slightly to serve as a standalone
  136632. ** hash table implementation for the full-text indexing module.
  136633. **
  136634. */
  136635. #ifndef _FTS3_HASH_H_
  136636. #define _FTS3_HASH_H_
  136637. /* Forward declarations of structures. */
  136638. typedef struct Fts3Hash Fts3Hash;
  136639. typedef struct Fts3HashElem Fts3HashElem;
  136640. /* A complete hash table is an instance of the following structure.
  136641. ** The internals of this structure are intended to be opaque -- client
  136642. ** code should not attempt to access or modify the fields of this structure
  136643. ** directly. Change this structure only by using the routines below.
  136644. ** However, many of the "procedures" and "functions" for modifying and
  136645. ** accessing this structure are really macros, so we can't really make
  136646. ** this structure opaque.
  136647. */
  136648. struct Fts3Hash {
  136649. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  136650. char copyKey; /* True if copy of key made on insert */
  136651. int count; /* Number of entries in this table */
  136652. Fts3HashElem *first; /* The first element of the array */
  136653. int htsize; /* Number of buckets in the hash table */
  136654. struct _fts3ht { /* the hash table */
  136655. int count; /* Number of entries with this hash */
  136656. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  136657. } *ht;
  136658. };
  136659. /* Each element in the hash table is an instance of the following
  136660. ** structure. All elements are stored on a single doubly-linked list.
  136661. **
  136662. ** Again, this structure is intended to be opaque, but it can't really
  136663. ** be opaque because it is used by macros.
  136664. */
  136665. struct Fts3HashElem {
  136666. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  136667. void *data; /* Data associated with this element */
  136668. void *pKey; int nKey; /* Key associated with this element */
  136669. };
  136670. /*
  136671. ** There are 2 different modes of operation for a hash table:
  136672. **
  136673. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  136674. ** (including the null-terminator, if any). Case
  136675. ** is respected in comparisons.
  136676. **
  136677. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  136678. ** memcmp() is used to compare keys.
  136679. **
  136680. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  136681. */
  136682. #define FTS3_HASH_STRING 1
  136683. #define FTS3_HASH_BINARY 2
  136684. /*
  136685. ** Access routines. To delete, insert a NULL pointer.
  136686. */
  136687. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  136688. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  136689. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  136690. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  136691. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  136692. /*
  136693. ** Shorthand for the functions above
  136694. */
  136695. #define fts3HashInit sqlite3Fts3HashInit
  136696. #define fts3HashInsert sqlite3Fts3HashInsert
  136697. #define fts3HashFind sqlite3Fts3HashFind
  136698. #define fts3HashClear sqlite3Fts3HashClear
  136699. #define fts3HashFindElem sqlite3Fts3HashFindElem
  136700. /*
  136701. ** Macros for looping over all elements of a hash table. The idiom is
  136702. ** like this:
  136703. **
  136704. ** Fts3Hash h;
  136705. ** Fts3HashElem *p;
  136706. ** ...
  136707. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  136708. ** SomeStructure *pData = fts3HashData(p);
  136709. ** // do something with pData
  136710. ** }
  136711. */
  136712. #define fts3HashFirst(H) ((H)->first)
  136713. #define fts3HashNext(E) ((E)->next)
  136714. #define fts3HashData(E) ((E)->data)
  136715. #define fts3HashKey(E) ((E)->pKey)
  136716. #define fts3HashKeysize(E) ((E)->nKey)
  136717. /*
  136718. ** Number of entries in a hash table
  136719. */
  136720. #define fts3HashCount(H) ((H)->count)
  136721. #endif /* _FTS3_HASH_H_ */
  136722. /************** End of fts3_hash.h *******************************************/
  136723. /************** Continuing where we left off in fts3Int.h ********************/
  136724. /*
  136725. ** This constant determines the maximum depth of an FTS expression tree
  136726. ** that the library will create and use. FTS uses recursion to perform
  136727. ** various operations on the query tree, so the disadvantage of a large
  136728. ** limit is that it may allow very large queries to use large amounts
  136729. ** of stack space (perhaps causing a stack overflow).
  136730. */
  136731. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  136732. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  136733. #endif
  136734. /*
  136735. ** This constant controls how often segments are merged. Once there are
  136736. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  136737. ** segment of level N+1.
  136738. */
  136739. #define FTS3_MERGE_COUNT 16
  136740. /*
  136741. ** This is the maximum amount of data (in bytes) to store in the
  136742. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  136743. ** populated as documents are inserted/updated/deleted in a transaction
  136744. ** and used to create a new segment when the transaction is committed.
  136745. ** However if this limit is reached midway through a transaction, a new
  136746. ** segment is created and the hash table cleared immediately.
  136747. */
  136748. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  136749. /*
  136750. ** Macro to return the number of elements in an array. SQLite has a
  136751. ** similar macro called ArraySize(). Use a different name to avoid
  136752. ** a collision when building an amalgamation with built-in FTS3.
  136753. */
  136754. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  136755. #ifndef MIN
  136756. # define MIN(x,y) ((x)<(y)?(x):(y))
  136757. #endif
  136758. #ifndef MAX
  136759. # define MAX(x,y) ((x)>(y)?(x):(y))
  136760. #endif
  136761. /*
  136762. ** Maximum length of a varint encoded integer. The varint format is different
  136763. ** from that used by SQLite, so the maximum length is 10, not 9.
  136764. */
  136765. #define FTS3_VARINT_MAX 10
  136766. /*
  136767. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  136768. ** in the document set and zero or more prefix indexes. All indexes are stored
  136769. ** as one or more b+-trees in the %_segments and %_segdir tables.
  136770. **
  136771. ** It is possible to determine which index a b+-tree belongs to based on the
  136772. ** value stored in the "%_segdir.level" column. Given this value L, the index
  136773. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  136774. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  136775. ** between 1024 and 2047 to index 1, and so on.
  136776. **
  136777. ** It is considered impossible for an index to use more than 1024 levels. In
  136778. ** theory though this may happen, but only after at least
  136779. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  136780. */
  136781. #define FTS3_SEGDIR_MAXLEVEL 1024
  136782. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  136783. /*
  136784. ** The testcase() macro is only used by the amalgamation. If undefined,
  136785. ** make it a no-op.
  136786. */
  136787. #ifndef testcase
  136788. # define testcase(X)
  136789. #endif
  136790. /*
  136791. ** Terminator values for position-lists and column-lists.
  136792. */
  136793. #define POS_COLUMN (1) /* Column-list terminator */
  136794. #define POS_END (0) /* Position-list terminator */
  136795. /*
  136796. ** This section provides definitions to allow the
  136797. ** FTS3 extension to be compiled outside of the
  136798. ** amalgamation.
  136799. */
  136800. #ifndef SQLITE_AMALGAMATION
  136801. /*
  136802. ** Macros indicating that conditional expressions are always true or
  136803. ** false.
  136804. */
  136805. #ifdef SQLITE_COVERAGE_TEST
  136806. # define ALWAYS(x) (1)
  136807. # define NEVER(X) (0)
  136808. #elif defined(SQLITE_DEBUG)
  136809. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  136810. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  136811. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  136812. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  136813. #else
  136814. # define ALWAYS(x) (x)
  136815. # define NEVER(x) (x)
  136816. #endif
  136817. /*
  136818. ** Internal types used by SQLite.
  136819. */
  136820. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  136821. typedef short int i16; /* 2-byte (or larger) signed integer */
  136822. typedef unsigned int u32; /* 4-byte unsigned integer */
  136823. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  136824. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  136825. /*
  136826. ** Macro used to suppress compiler warnings for unused parameters.
  136827. */
  136828. #define UNUSED_PARAMETER(x) (void)(x)
  136829. /*
  136830. ** Activate assert() only if SQLITE_TEST is enabled.
  136831. */
  136832. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  136833. # define NDEBUG 1
  136834. #endif
  136835. /*
  136836. ** The TESTONLY macro is used to enclose variable declarations or
  136837. ** other bits of code that are needed to support the arguments
  136838. ** within testcase() and assert() macros.
  136839. */
  136840. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  136841. # define TESTONLY(X) X
  136842. #else
  136843. # define TESTONLY(X)
  136844. #endif
  136845. #endif /* SQLITE_AMALGAMATION */
  136846. #ifdef SQLITE_DEBUG
  136847. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  136848. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  136849. #else
  136850. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  136851. #endif
  136852. typedef struct Fts3Table Fts3Table;
  136853. typedef struct Fts3Cursor Fts3Cursor;
  136854. typedef struct Fts3Expr Fts3Expr;
  136855. typedef struct Fts3Phrase Fts3Phrase;
  136856. typedef struct Fts3PhraseToken Fts3PhraseToken;
  136857. typedef struct Fts3Doclist Fts3Doclist;
  136858. typedef struct Fts3SegFilter Fts3SegFilter;
  136859. typedef struct Fts3DeferredToken Fts3DeferredToken;
  136860. typedef struct Fts3SegReader Fts3SegReader;
  136861. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  136862. typedef struct MatchinfoBuffer MatchinfoBuffer;
  136863. /*
  136864. ** A connection to a fulltext index is an instance of the following
  136865. ** structure. The xCreate and xConnect methods create an instance
  136866. ** of this structure and xDestroy and xDisconnect free that instance.
  136867. ** All other methods receive a pointer to the structure as one of their
  136868. ** arguments.
  136869. */
  136870. struct Fts3Table {
  136871. sqlite3_vtab base; /* Base class used by SQLite core */
  136872. sqlite3 *db; /* The database connection */
  136873. const char *zDb; /* logical database name */
  136874. const char *zName; /* virtual table name */
  136875. int nColumn; /* number of named columns in virtual table */
  136876. char **azColumn; /* column names. malloced */
  136877. u8 *abNotindexed; /* True for 'notindexed' columns */
  136878. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  136879. char *zContentTbl; /* content=xxx option, or NULL */
  136880. char *zLanguageid; /* languageid=xxx option, or NULL */
  136881. int nAutoincrmerge; /* Value configured by 'automerge' */
  136882. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  136883. /* Precompiled statements used by the implementation. Each of these
  136884. ** statements is run and reset within a single virtual table API call.
  136885. */
  136886. sqlite3_stmt *aStmt[40];
  136887. sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
  136888. char *zReadExprlist;
  136889. char *zWriteExprlist;
  136890. int nNodeSize; /* Soft limit for node size */
  136891. u8 bFts4; /* True for FTS4, false for FTS3 */
  136892. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  136893. u8 bHasDocsize; /* True if %_docsize table exists */
  136894. u8 bDescIdx; /* True if doclists are in reverse order */
  136895. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  136896. int nPgsz; /* Page size for host database */
  136897. char *zSegmentsTbl; /* Name of %_segments table */
  136898. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  136899. /*
  136900. ** The following array of hash tables is used to buffer pending index
  136901. ** updates during transactions. All pending updates buffered at any one
  136902. ** time must share a common language-id (see the FTS4 langid= feature).
  136903. ** The current language id is stored in variable iPrevLangid.
  136904. **
  136905. ** A single FTS4 table may have multiple full-text indexes. For each index
  136906. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  136907. ** terms that appear in the document set. Each subsequent index in aIndex[]
  136908. ** is an index of prefixes of a specific length.
  136909. **
  136910. ** Variable nPendingData contains an estimate the memory consumed by the
  136911. ** pending data structures, including hash table overhead, but not including
  136912. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  136913. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  136914. ** recently inserted record.
  136915. */
  136916. int nIndex; /* Size of aIndex[] */
  136917. struct Fts3Index {
  136918. int nPrefix; /* Prefix length (0 for main terms index) */
  136919. Fts3Hash hPending; /* Pending terms table for this index */
  136920. } *aIndex;
  136921. int nMaxPendingData; /* Max pending data before flush to disk */
  136922. int nPendingData; /* Current bytes of pending data */
  136923. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  136924. int iPrevLangid; /* Langid of recently inserted document */
  136925. int bPrevDelete; /* True if last operation was a delete */
  136926. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  136927. /* State variables used for validating that the transaction control
  136928. ** methods of the virtual table are called at appropriate times. These
  136929. ** values do not contribute to FTS functionality; they are used for
  136930. ** verifying the operation of the SQLite core.
  136931. */
  136932. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  136933. int mxSavepoint; /* Largest valid xSavepoint integer */
  136934. #endif
  136935. #ifdef SQLITE_TEST
  136936. /* True to disable the incremental doclist optimization. This is controled
  136937. ** by special insert command 'test-no-incr-doclist'. */
  136938. int bNoIncrDoclist;
  136939. #endif
  136940. };
  136941. /*
  136942. ** When the core wants to read from the virtual table, it creates a
  136943. ** virtual table cursor (an instance of the following structure) using
  136944. ** the xOpen method. Cursors are destroyed using the xClose method.
  136945. */
  136946. struct Fts3Cursor {
  136947. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  136948. i16 eSearch; /* Search strategy (see below) */
  136949. u8 isEof; /* True if at End Of Results */
  136950. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  136951. u8 bSeekStmt; /* True if pStmt is a seek */
  136952. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  136953. Fts3Expr *pExpr; /* Parsed MATCH query string */
  136954. int iLangid; /* Language being queried for */
  136955. int nPhrase; /* Number of matchable phrases in query */
  136956. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  136957. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  136958. char *pNextId; /* Pointer into the body of aDoclist */
  136959. char *aDoclist; /* List of docids for full-text queries */
  136960. int nDoclist; /* Size of buffer at aDoclist */
  136961. u8 bDesc; /* True to sort in descending order */
  136962. int eEvalmode; /* An FTS3_EVAL_XX constant */
  136963. int nRowAvg; /* Average size of database rows, in pages */
  136964. sqlite3_int64 nDoc; /* Documents in table */
  136965. i64 iMinDocid; /* Minimum docid to return */
  136966. i64 iMaxDocid; /* Maximum docid to return */
  136967. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  136968. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  136969. };
  136970. #define FTS3_EVAL_FILTER 0
  136971. #define FTS3_EVAL_NEXT 1
  136972. #define FTS3_EVAL_MATCHINFO 2
  136973. /*
  136974. ** The Fts3Cursor.eSearch member is always set to one of the following.
  136975. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  136976. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  136977. ** of the column to be searched. For example, in
  136978. **
  136979. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  136980. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  136981. **
  136982. ** Because the LHS of the MATCH operator is 2nd column "b",
  136983. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  136984. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  136985. ** indicating that all columns should be searched,
  136986. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  136987. */
  136988. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  136989. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  136990. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  136991. /*
  136992. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  136993. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  136994. ** above. The upper 16-bits contain a combination of the following
  136995. ** bits, used to describe extra constraints on full-text searches.
  136996. */
  136997. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  136998. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  136999. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  137000. struct Fts3Doclist {
  137001. char *aAll; /* Array containing doclist (or NULL) */
  137002. int nAll; /* Size of a[] in bytes */
  137003. char *pNextDocid; /* Pointer to next docid */
  137004. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  137005. int bFreeList; /* True if pList should be sqlite3_free()d */
  137006. char *pList; /* Pointer to position list following iDocid */
  137007. int nList; /* Length of position list */
  137008. };
  137009. /*
  137010. ** A "phrase" is a sequence of one or more tokens that must match in
  137011. ** sequence. A single token is the base case and the most common case.
  137012. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  137013. ** nToken will be the number of tokens in the string.
  137014. */
  137015. struct Fts3PhraseToken {
  137016. char *z; /* Text of the token */
  137017. int n; /* Number of bytes in buffer z */
  137018. int isPrefix; /* True if token ends with a "*" character */
  137019. int bFirst; /* True if token must appear at position 0 */
  137020. /* Variables above this point are populated when the expression is
  137021. ** parsed (by code in fts3_expr.c). Below this point the variables are
  137022. ** used when evaluating the expression. */
  137023. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  137024. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  137025. };
  137026. struct Fts3Phrase {
  137027. /* Cache of doclist for this phrase. */
  137028. Fts3Doclist doclist;
  137029. int bIncr; /* True if doclist is loaded incrementally */
  137030. int iDoclistToken;
  137031. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  137032. ** OR condition. */
  137033. char *pOrPoslist;
  137034. i64 iOrDocid;
  137035. /* Variables below this point are populated by fts3_expr.c when parsing
  137036. ** a MATCH expression. Everything above is part of the evaluation phase.
  137037. */
  137038. int nToken; /* Number of tokens in the phrase */
  137039. int iColumn; /* Index of column this phrase must match */
  137040. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  137041. };
  137042. /*
  137043. ** A tree of these objects forms the RHS of a MATCH operator.
  137044. **
  137045. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  137046. ** points to a malloced buffer, size nDoclist bytes, containing the results
  137047. ** of this phrase query in FTS3 doclist format. As usual, the initial
  137048. ** "Length" field found in doclists stored on disk is omitted from this
  137049. ** buffer.
  137050. **
  137051. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  137052. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  137053. ** where nCol is the number of columns in the queried FTS table. The array
  137054. ** is populated as follows:
  137055. **
  137056. ** aMI[iCol*3 + 0] = Undefined
  137057. ** aMI[iCol*3 + 1] = Number of occurrences
  137058. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  137059. **
  137060. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  137061. ** when the expression node is.
  137062. */
  137063. struct Fts3Expr {
  137064. int eType; /* One of the FTSQUERY_XXX values defined below */
  137065. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  137066. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  137067. Fts3Expr *pLeft; /* Left operand */
  137068. Fts3Expr *pRight; /* Right operand */
  137069. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  137070. /* The following are used by the fts3_eval.c module. */
  137071. sqlite3_int64 iDocid; /* Current docid */
  137072. u8 bEof; /* True this expression is at EOF already */
  137073. u8 bStart; /* True if iDocid is valid */
  137074. u8 bDeferred; /* True if this expression is entirely deferred */
  137075. /* The following are used by the fts3_snippet.c module. */
  137076. int iPhrase; /* Index of this phrase in matchinfo() results */
  137077. u32 *aMI; /* See above */
  137078. };
  137079. /*
  137080. ** Candidate values for Fts3Query.eType. Note that the order of the first
  137081. ** four values is in order of precedence when parsing expressions. For
  137082. ** example, the following:
  137083. **
  137084. ** "a OR b AND c NOT d NEAR e"
  137085. **
  137086. ** is equivalent to:
  137087. **
  137088. ** "a OR (b AND (c NOT (d NEAR e)))"
  137089. */
  137090. #define FTSQUERY_NEAR 1
  137091. #define FTSQUERY_NOT 2
  137092. #define FTSQUERY_AND 3
  137093. #define FTSQUERY_OR 4
  137094. #define FTSQUERY_PHRASE 5
  137095. /* fts3_write.c */
  137096. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  137097. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  137098. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  137099. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  137100. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  137101. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  137102. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  137103. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  137104. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  137105. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  137106. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  137107. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  137108. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  137109. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  137110. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  137111. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  137112. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  137113. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  137114. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  137115. #else
  137116. # define sqlite3Fts3FreeDeferredTokens(x)
  137117. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  137118. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  137119. # define sqlite3Fts3FreeDeferredDoclists(x)
  137120. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  137121. #endif
  137122. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  137123. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  137124. /* Special values interpreted by sqlite3SegReaderCursor() */
  137125. #define FTS3_SEGCURSOR_PENDING -1
  137126. #define FTS3_SEGCURSOR_ALL -2
  137127. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  137128. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  137129. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  137130. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  137131. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  137132. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  137133. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  137134. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  137135. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  137136. #define FTS3_SEGMENT_PREFIX 0x00000008
  137137. #define FTS3_SEGMENT_SCAN 0x00000010
  137138. #define FTS3_SEGMENT_FIRST 0x00000020
  137139. /* Type passed as 4th argument to SegmentReaderIterate() */
  137140. struct Fts3SegFilter {
  137141. const char *zTerm;
  137142. int nTerm;
  137143. int iCol;
  137144. int flags;
  137145. };
  137146. struct Fts3MultiSegReader {
  137147. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  137148. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  137149. int nSegment; /* Size of apSegment array */
  137150. int nAdvance; /* How many seg-readers to advance */
  137151. Fts3SegFilter *pFilter; /* Pointer to filter object */
  137152. char *aBuffer; /* Buffer to merge doclists in */
  137153. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  137154. int iColFilter; /* If >=0, filter for this column */
  137155. int bRestart;
  137156. /* Used by fts3.c only. */
  137157. int nCost; /* Cost of running iterator */
  137158. int bLookup; /* True if a lookup of a single entry. */
  137159. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  137160. char *zTerm; /* Pointer to term buffer */
  137161. int nTerm; /* Size of zTerm in bytes */
  137162. char *aDoclist; /* Pointer to doclist buffer */
  137163. int nDoclist; /* Size of aDoclist[] in bytes */
  137164. };
  137165. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  137166. #define fts3GetVarint32(p, piVal) ( \
  137167. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  137168. )
  137169. /* fts3.c */
  137170. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  137171. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  137172. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  137173. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  137174. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  137175. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  137176. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  137177. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  137178. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  137179. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  137180. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  137181. /* fts3_tokenizer.c */
  137182. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  137183. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  137184. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  137185. sqlite3_tokenizer **, char **
  137186. );
  137187. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  137188. /* fts3_snippet.c */
  137189. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  137190. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  137191. const char *, const char *, int, int
  137192. );
  137193. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  137194. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  137195. /* fts3_expr.c */
  137196. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  137197. char **, int, int, int, const char *, int, Fts3Expr **, char **
  137198. );
  137199. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  137200. #ifdef SQLITE_TEST
  137201. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  137202. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  137203. #endif
  137204. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  137205. sqlite3_tokenizer_cursor **
  137206. );
  137207. /* fts3_aux.c */
  137208. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  137209. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  137210. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  137211. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  137212. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  137213. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  137214. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  137215. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  137216. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  137217. /* fts3_tokenize_vtab.c */
  137218. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  137219. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  137220. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  137221. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  137222. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  137223. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  137224. #endif
  137225. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  137226. #endif /* _FTSINT_H */
  137227. /************** End of fts3Int.h *********************************************/
  137228. /************** Continuing where we left off in fts3.c ***********************/
  137229. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137230. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  137231. # define SQLITE_CORE 1
  137232. #endif
  137233. /* #include <assert.h> */
  137234. /* #include <stdlib.h> */
  137235. /* #include <stddef.h> */
  137236. /* #include <stdio.h> */
  137237. /* #include <string.h> */
  137238. /* #include <stdarg.h> */
  137239. /* #include "fts3.h" */
  137240. #ifndef SQLITE_CORE
  137241. /* # include "sqlite3ext.h" */
  137242. SQLITE_EXTENSION_INIT1
  137243. #endif
  137244. static int fts3EvalNext(Fts3Cursor *pCsr);
  137245. static int fts3EvalStart(Fts3Cursor *pCsr);
  137246. static int fts3TermSegReaderCursor(
  137247. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  137248. #ifndef SQLITE_AMALGAMATION
  137249. # if defined(SQLITE_DEBUG)
  137250. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  137251. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  137252. # endif
  137253. #endif
  137254. /*
  137255. ** Write a 64-bit variable-length integer to memory starting at p[0].
  137256. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  137257. ** The number of bytes written is returned.
  137258. */
  137259. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  137260. unsigned char *q = (unsigned char *) p;
  137261. sqlite_uint64 vu = v;
  137262. do{
  137263. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  137264. vu >>= 7;
  137265. }while( vu!=0 );
  137266. q[-1] &= 0x7f; /* turn off high bit in final byte */
  137267. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  137268. return (int) (q - (unsigned char *)p);
  137269. }
  137270. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  137271. v = (v & mask1) | ( (*ptr++) << shift ); \
  137272. if( (v & mask2)==0 ){ var = v; return ret; }
  137273. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  137274. v = (*ptr++); \
  137275. if( (v & mask2)==0 ){ var = v; return ret; }
  137276. /*
  137277. ** Read a 64-bit variable-length integer from memory starting at p[0].
  137278. ** Return the number of bytes read, or 0 on error.
  137279. ** The value is stored in *v.
  137280. */
  137281. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
  137282. const unsigned char *p = (const unsigned char*)pBuf;
  137283. const unsigned char *pStart = p;
  137284. u32 a;
  137285. u64 b;
  137286. int shift;
  137287. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  137288. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  137289. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  137290. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  137291. b = (a & 0x0FFFFFFF );
  137292. for(shift=28; shift<=63; shift+=7){
  137293. u64 c = *p++;
  137294. b += (c&0x7F) << shift;
  137295. if( (c & 0x80)==0 ) break;
  137296. }
  137297. *v = b;
  137298. return (int)(p - pStart);
  137299. }
  137300. /*
  137301. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
  137302. ** a non-negative 32-bit integer before it is returned.
  137303. */
  137304. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  137305. u32 a;
  137306. #ifndef fts3GetVarint32
  137307. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  137308. #else
  137309. a = (*p++);
  137310. assert( a & 0x80 );
  137311. #endif
  137312. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  137313. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  137314. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  137315. a = (a & 0x0FFFFFFF );
  137316. *pi = (int)(a | ((u32)(*p & 0x07) << 28));
  137317. assert( 0==(a & 0x80000000) );
  137318. assert( *pi>=0 );
  137319. return 5;
  137320. }
  137321. /*
  137322. ** Return the number of bytes required to encode v as a varint
  137323. */
  137324. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  137325. int i = 0;
  137326. do{
  137327. i++;
  137328. v >>= 7;
  137329. }while( v!=0 );
  137330. return i;
  137331. }
  137332. /*
  137333. ** Convert an SQL-style quoted string into a normal string by removing
  137334. ** the quote characters. The conversion is done in-place. If the
  137335. ** input does not begin with a quote character, then this routine
  137336. ** is a no-op.
  137337. **
  137338. ** Examples:
  137339. **
  137340. ** "abc" becomes abc
  137341. ** 'xyz' becomes xyz
  137342. ** [pqr] becomes pqr
  137343. ** `mno` becomes mno
  137344. **
  137345. */
  137346. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  137347. char quote; /* Quote character (if any ) */
  137348. quote = z[0];
  137349. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  137350. int iIn = 1; /* Index of next byte to read from input */
  137351. int iOut = 0; /* Index of next byte to write to output */
  137352. /* If the first byte was a '[', then the close-quote character is a ']' */
  137353. if( quote=='[' ) quote = ']';
  137354. while( z[iIn] ){
  137355. if( z[iIn]==quote ){
  137356. if( z[iIn+1]!=quote ) break;
  137357. z[iOut++] = quote;
  137358. iIn += 2;
  137359. }else{
  137360. z[iOut++] = z[iIn++];
  137361. }
  137362. }
  137363. z[iOut] = '\0';
  137364. }
  137365. }
  137366. /*
  137367. ** Read a single varint from the doclist at *pp and advance *pp to point
  137368. ** to the first byte past the end of the varint. Add the value of the varint
  137369. ** to *pVal.
  137370. */
  137371. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  137372. sqlite3_int64 iVal;
  137373. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  137374. *pVal += iVal;
  137375. }
  137376. /*
  137377. ** When this function is called, *pp points to the first byte following a
  137378. ** varint that is part of a doclist (or position-list, or any other list
  137379. ** of varints). This function moves *pp to point to the start of that varint,
  137380. ** and sets *pVal by the varint value.
  137381. **
  137382. ** Argument pStart points to the first byte of the doclist that the
  137383. ** varint is part of.
  137384. */
  137385. static void fts3GetReverseVarint(
  137386. char **pp,
  137387. char *pStart,
  137388. sqlite3_int64 *pVal
  137389. ){
  137390. sqlite3_int64 iVal;
  137391. char *p;
  137392. /* Pointer p now points at the first byte past the varint we are
  137393. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  137394. ** clear on character p[-1]. */
  137395. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  137396. p++;
  137397. *pp = p;
  137398. sqlite3Fts3GetVarint(p, &iVal);
  137399. *pVal = iVal;
  137400. }
  137401. /*
  137402. ** The xDisconnect() virtual table method.
  137403. */
  137404. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  137405. Fts3Table *p = (Fts3Table *)pVtab;
  137406. int i;
  137407. assert( p->nPendingData==0 );
  137408. assert( p->pSegments==0 );
  137409. /* Free any prepared statements held */
  137410. sqlite3_finalize(p->pSeekStmt);
  137411. for(i=0; i<SizeofArray(p->aStmt); i++){
  137412. sqlite3_finalize(p->aStmt[i]);
  137413. }
  137414. sqlite3_free(p->zSegmentsTbl);
  137415. sqlite3_free(p->zReadExprlist);
  137416. sqlite3_free(p->zWriteExprlist);
  137417. sqlite3_free(p->zContentTbl);
  137418. sqlite3_free(p->zLanguageid);
  137419. /* Invoke the tokenizer destructor to free the tokenizer. */
  137420. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  137421. sqlite3_free(p);
  137422. return SQLITE_OK;
  137423. }
  137424. /*
  137425. ** Write an error message into *pzErr
  137426. */
  137427. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  137428. va_list ap;
  137429. sqlite3_free(*pzErr);
  137430. va_start(ap, zFormat);
  137431. *pzErr = sqlite3_vmprintf(zFormat, ap);
  137432. va_end(ap);
  137433. }
  137434. /*
  137435. ** Construct one or more SQL statements from the format string given
  137436. ** and then evaluate those statements. The success code is written
  137437. ** into *pRc.
  137438. **
  137439. ** If *pRc is initially non-zero then this routine is a no-op.
  137440. */
  137441. static void fts3DbExec(
  137442. int *pRc, /* Success code */
  137443. sqlite3 *db, /* Database in which to run SQL */
  137444. const char *zFormat, /* Format string for SQL */
  137445. ... /* Arguments to the format string */
  137446. ){
  137447. va_list ap;
  137448. char *zSql;
  137449. if( *pRc ) return;
  137450. va_start(ap, zFormat);
  137451. zSql = sqlite3_vmprintf(zFormat, ap);
  137452. va_end(ap);
  137453. if( zSql==0 ){
  137454. *pRc = SQLITE_NOMEM;
  137455. }else{
  137456. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  137457. sqlite3_free(zSql);
  137458. }
  137459. }
  137460. /*
  137461. ** The xDestroy() virtual table method.
  137462. */
  137463. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  137464. Fts3Table *p = (Fts3Table *)pVtab;
  137465. int rc = SQLITE_OK; /* Return code */
  137466. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  137467. sqlite3 *db = p->db; /* Database handle */
  137468. /* Drop the shadow tables */
  137469. if( p->zContentTbl==0 ){
  137470. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  137471. }
  137472. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  137473. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  137474. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  137475. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  137476. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  137477. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  137478. ** Otherwise, return an SQLite error code.
  137479. */
  137480. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  137481. }
  137482. /*
  137483. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  137484. ** passed as the first argument. This is done as part of the xConnect()
  137485. ** and xCreate() methods.
  137486. **
  137487. ** If *pRc is non-zero when this function is called, it is a no-op.
  137488. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  137489. ** before returning.
  137490. */
  137491. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  137492. if( *pRc==SQLITE_OK ){
  137493. int i; /* Iterator variable */
  137494. int rc; /* Return code */
  137495. char *zSql; /* SQL statement passed to declare_vtab() */
  137496. char *zCols; /* List of user defined columns */
  137497. const char *zLanguageid;
  137498. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  137499. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  137500. /* Create a list of user columns for the virtual table */
  137501. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  137502. for(i=1; zCols && i<p->nColumn; i++){
  137503. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  137504. }
  137505. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  137506. zSql = sqlite3_mprintf(
  137507. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  137508. zCols, p->zName, zLanguageid
  137509. );
  137510. if( !zCols || !zSql ){
  137511. rc = SQLITE_NOMEM;
  137512. }else{
  137513. rc = sqlite3_declare_vtab(p->db, zSql);
  137514. }
  137515. sqlite3_free(zSql);
  137516. sqlite3_free(zCols);
  137517. *pRc = rc;
  137518. }
  137519. }
  137520. /*
  137521. ** Create the %_stat table if it does not already exist.
  137522. */
  137523. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  137524. fts3DbExec(pRc, p->db,
  137525. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  137526. "(id INTEGER PRIMARY KEY, value BLOB);",
  137527. p->zDb, p->zName
  137528. );
  137529. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  137530. }
  137531. /*
  137532. ** Create the backing store tables (%_content, %_segments and %_segdir)
  137533. ** required by the FTS3 table passed as the only argument. This is done
  137534. ** as part of the vtab xCreate() method.
  137535. **
  137536. ** If the p->bHasDocsize boolean is true (indicating that this is an
  137537. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  137538. ** %_stat tables required by FTS4.
  137539. */
  137540. static int fts3CreateTables(Fts3Table *p){
  137541. int rc = SQLITE_OK; /* Return code */
  137542. int i; /* Iterator variable */
  137543. sqlite3 *db = p->db; /* The database connection */
  137544. if( p->zContentTbl==0 ){
  137545. const char *zLanguageid = p->zLanguageid;
  137546. char *zContentCols; /* Columns of %_content table */
  137547. /* Create a list of user columns for the content table */
  137548. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  137549. for(i=0; zContentCols && i<p->nColumn; i++){
  137550. char *z = p->azColumn[i];
  137551. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  137552. }
  137553. if( zLanguageid && zContentCols ){
  137554. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  137555. }
  137556. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  137557. /* Create the content table */
  137558. fts3DbExec(&rc, db,
  137559. "CREATE TABLE %Q.'%q_content'(%s)",
  137560. p->zDb, p->zName, zContentCols
  137561. );
  137562. sqlite3_free(zContentCols);
  137563. }
  137564. /* Create other tables */
  137565. fts3DbExec(&rc, db,
  137566. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  137567. p->zDb, p->zName
  137568. );
  137569. fts3DbExec(&rc, db,
  137570. "CREATE TABLE %Q.'%q_segdir'("
  137571. "level INTEGER,"
  137572. "idx INTEGER,"
  137573. "start_block INTEGER,"
  137574. "leaves_end_block INTEGER,"
  137575. "end_block INTEGER,"
  137576. "root BLOB,"
  137577. "PRIMARY KEY(level, idx)"
  137578. ");",
  137579. p->zDb, p->zName
  137580. );
  137581. if( p->bHasDocsize ){
  137582. fts3DbExec(&rc, db,
  137583. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  137584. p->zDb, p->zName
  137585. );
  137586. }
  137587. assert( p->bHasStat==p->bFts4 );
  137588. if( p->bHasStat ){
  137589. sqlite3Fts3CreateStatTable(&rc, p);
  137590. }
  137591. return rc;
  137592. }
  137593. /*
  137594. ** Store the current database page-size in bytes in p->nPgsz.
  137595. **
  137596. ** If *pRc is non-zero when this function is called, it is a no-op.
  137597. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  137598. ** before returning.
  137599. */
  137600. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  137601. if( *pRc==SQLITE_OK ){
  137602. int rc; /* Return code */
  137603. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  137604. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  137605. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  137606. if( !zSql ){
  137607. rc = SQLITE_NOMEM;
  137608. }else{
  137609. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  137610. if( rc==SQLITE_OK ){
  137611. sqlite3_step(pStmt);
  137612. p->nPgsz = sqlite3_column_int(pStmt, 0);
  137613. rc = sqlite3_finalize(pStmt);
  137614. }else if( rc==SQLITE_AUTH ){
  137615. p->nPgsz = 1024;
  137616. rc = SQLITE_OK;
  137617. }
  137618. }
  137619. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  137620. sqlite3_free(zSql);
  137621. *pRc = rc;
  137622. }
  137623. }
  137624. /*
  137625. ** "Special" FTS4 arguments are column specifications of the following form:
  137626. **
  137627. ** <key> = <value>
  137628. **
  137629. ** There may not be whitespace surrounding the "=" character. The <value>
  137630. ** term may be quoted, but the <key> may not.
  137631. */
  137632. static int fts3IsSpecialColumn(
  137633. const char *z,
  137634. int *pnKey,
  137635. char **pzValue
  137636. ){
  137637. char *zValue;
  137638. const char *zCsr = z;
  137639. while( *zCsr!='=' ){
  137640. if( *zCsr=='\0' ) return 0;
  137641. zCsr++;
  137642. }
  137643. *pnKey = (int)(zCsr-z);
  137644. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  137645. if( zValue ){
  137646. sqlite3Fts3Dequote(zValue);
  137647. }
  137648. *pzValue = zValue;
  137649. return 1;
  137650. }
  137651. /*
  137652. ** Append the output of a printf() style formatting to an existing string.
  137653. */
  137654. static void fts3Appendf(
  137655. int *pRc, /* IN/OUT: Error code */
  137656. char **pz, /* IN/OUT: Pointer to string buffer */
  137657. const char *zFormat, /* Printf format string to append */
  137658. ... /* Arguments for printf format string */
  137659. ){
  137660. if( *pRc==SQLITE_OK ){
  137661. va_list ap;
  137662. char *z;
  137663. va_start(ap, zFormat);
  137664. z = sqlite3_vmprintf(zFormat, ap);
  137665. va_end(ap);
  137666. if( z && *pz ){
  137667. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  137668. sqlite3_free(z);
  137669. z = z2;
  137670. }
  137671. if( z==0 ) *pRc = SQLITE_NOMEM;
  137672. sqlite3_free(*pz);
  137673. *pz = z;
  137674. }
  137675. }
  137676. /*
  137677. ** Return a copy of input string zInput enclosed in double-quotes (") and
  137678. ** with all double quote characters escaped. For example:
  137679. **
  137680. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  137681. **
  137682. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  137683. ** is the callers responsibility to call sqlite3_free() to release this
  137684. ** memory.
  137685. */
  137686. static char *fts3QuoteId(char const *zInput){
  137687. int nRet;
  137688. char *zRet;
  137689. nRet = 2 + (int)strlen(zInput)*2 + 1;
  137690. zRet = sqlite3_malloc(nRet);
  137691. if( zRet ){
  137692. int i;
  137693. char *z = zRet;
  137694. *(z++) = '"';
  137695. for(i=0; zInput[i]; i++){
  137696. if( zInput[i]=='"' ) *(z++) = '"';
  137697. *(z++) = zInput[i];
  137698. }
  137699. *(z++) = '"';
  137700. *(z++) = '\0';
  137701. }
  137702. return zRet;
  137703. }
  137704. /*
  137705. ** Return a list of comma separated SQL expressions and a FROM clause that
  137706. ** could be used in a SELECT statement such as the following:
  137707. **
  137708. ** SELECT <list of expressions> FROM %_content AS x ...
  137709. **
  137710. ** to return the docid, followed by each column of text data in order
  137711. ** from left to write. If parameter zFunc is not NULL, then instead of
  137712. ** being returned directly each column of text data is passed to an SQL
  137713. ** function named zFunc first. For example, if zFunc is "unzip" and the
  137714. ** table has the three user-defined columns "a", "b", and "c", the following
  137715. ** string is returned:
  137716. **
  137717. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  137718. **
  137719. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  137720. ** is the responsibility of the caller to eventually free it.
  137721. **
  137722. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  137723. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  137724. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  137725. ** no error occurs, *pRc is left unmodified.
  137726. */
  137727. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  137728. char *zRet = 0;
  137729. char *zFree = 0;
  137730. char *zFunction;
  137731. int i;
  137732. if( p->zContentTbl==0 ){
  137733. if( !zFunc ){
  137734. zFunction = "";
  137735. }else{
  137736. zFree = zFunction = fts3QuoteId(zFunc);
  137737. }
  137738. fts3Appendf(pRc, &zRet, "docid");
  137739. for(i=0; i<p->nColumn; i++){
  137740. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  137741. }
  137742. if( p->zLanguageid ){
  137743. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  137744. }
  137745. sqlite3_free(zFree);
  137746. }else{
  137747. fts3Appendf(pRc, &zRet, "rowid");
  137748. for(i=0; i<p->nColumn; i++){
  137749. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  137750. }
  137751. if( p->zLanguageid ){
  137752. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  137753. }
  137754. }
  137755. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  137756. p->zDb,
  137757. (p->zContentTbl ? p->zContentTbl : p->zName),
  137758. (p->zContentTbl ? "" : "_content")
  137759. );
  137760. return zRet;
  137761. }
  137762. /*
  137763. ** Return a list of N comma separated question marks, where N is the number
  137764. ** of columns in the %_content table (one for the docid plus one for each
  137765. ** user-defined text column).
  137766. **
  137767. ** If argument zFunc is not NULL, then all but the first question mark
  137768. ** is preceded by zFunc and an open bracket, and followed by a closed
  137769. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  137770. ** user-defined text columns, the following string is returned:
  137771. **
  137772. ** "?, zip(?), zip(?), zip(?)"
  137773. **
  137774. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  137775. ** is the responsibility of the caller to eventually free it.
  137776. **
  137777. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  137778. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  137779. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  137780. ** no error occurs, *pRc is left unmodified.
  137781. */
  137782. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  137783. char *zRet = 0;
  137784. char *zFree = 0;
  137785. char *zFunction;
  137786. int i;
  137787. if( !zFunc ){
  137788. zFunction = "";
  137789. }else{
  137790. zFree = zFunction = fts3QuoteId(zFunc);
  137791. }
  137792. fts3Appendf(pRc, &zRet, "?");
  137793. for(i=0; i<p->nColumn; i++){
  137794. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  137795. }
  137796. if( p->zLanguageid ){
  137797. fts3Appendf(pRc, &zRet, ", ?");
  137798. }
  137799. sqlite3_free(zFree);
  137800. return zRet;
  137801. }
  137802. /*
  137803. ** This function interprets the string at (*pp) as a non-negative integer
  137804. ** value. It reads the integer and sets *pnOut to the value read, then
  137805. ** sets *pp to point to the byte immediately following the last byte of
  137806. ** the integer value.
  137807. **
  137808. ** Only decimal digits ('0'..'9') may be part of an integer value.
  137809. **
  137810. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  137811. ** the output value undefined. Otherwise SQLITE_OK is returned.
  137812. **
  137813. ** This function is used when parsing the "prefix=" FTS4 parameter.
  137814. */
  137815. static int fts3GobbleInt(const char **pp, int *pnOut){
  137816. const int MAX_NPREFIX = 10000000;
  137817. const char *p; /* Iterator pointer */
  137818. int nInt = 0; /* Output value */
  137819. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  137820. nInt = nInt * 10 + (p[0] - '0');
  137821. if( nInt>MAX_NPREFIX ){
  137822. nInt = 0;
  137823. break;
  137824. }
  137825. }
  137826. if( p==*pp ) return SQLITE_ERROR;
  137827. *pnOut = nInt;
  137828. *pp = p;
  137829. return SQLITE_OK;
  137830. }
  137831. /*
  137832. ** This function is called to allocate an array of Fts3Index structures
  137833. ** representing the indexes maintained by the current FTS table. FTS tables
  137834. ** always maintain the main "terms" index, but may also maintain one or
  137835. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  137836. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  137837. **
  137838. ** Argument zParam is passed the value of the "prefix=" option if one was
  137839. ** specified, or NULL otherwise.
  137840. **
  137841. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  137842. ** the allocated array. *pnIndex is set to the number of elements in the
  137843. ** array. If an error does occur, an SQLite error code is returned.
  137844. **
  137845. ** Regardless of whether or not an error is returned, it is the responsibility
  137846. ** of the caller to call sqlite3_free() on the output array to free it.
  137847. */
  137848. static int fts3PrefixParameter(
  137849. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  137850. int *pnIndex, /* OUT: size of *apIndex[] array */
  137851. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  137852. ){
  137853. struct Fts3Index *aIndex; /* Allocated array */
  137854. int nIndex = 1; /* Number of entries in array */
  137855. if( zParam && zParam[0] ){
  137856. const char *p;
  137857. nIndex++;
  137858. for(p=zParam; *p; p++){
  137859. if( *p==',' ) nIndex++;
  137860. }
  137861. }
  137862. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  137863. *apIndex = aIndex;
  137864. if( !aIndex ){
  137865. return SQLITE_NOMEM;
  137866. }
  137867. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  137868. if( zParam ){
  137869. const char *p = zParam;
  137870. int i;
  137871. for(i=1; i<nIndex; i++){
  137872. int nPrefix = 0;
  137873. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  137874. assert( nPrefix>=0 );
  137875. if( nPrefix==0 ){
  137876. nIndex--;
  137877. i--;
  137878. }else{
  137879. aIndex[i].nPrefix = nPrefix;
  137880. }
  137881. p++;
  137882. }
  137883. }
  137884. *pnIndex = nIndex;
  137885. return SQLITE_OK;
  137886. }
  137887. /*
  137888. ** This function is called when initializing an FTS4 table that uses the
  137889. ** content=xxx option. It determines the number of and names of the columns
  137890. ** of the new FTS4 table.
  137891. **
  137892. ** The third argument passed to this function is the value passed to the
  137893. ** config=xxx option (i.e. "xxx"). This function queries the database for
  137894. ** a table of that name. If found, the output variables are populated
  137895. ** as follows:
  137896. **
  137897. ** *pnCol: Set to the number of columns table xxx has,
  137898. **
  137899. ** *pnStr: Set to the total amount of space required to store a copy
  137900. ** of each columns name, including the nul-terminator.
  137901. **
  137902. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  137903. ** the name of the corresponding column in table xxx. The array
  137904. ** and its contents are allocated using a single allocation. It
  137905. ** is the responsibility of the caller to free this allocation
  137906. ** by eventually passing the *pazCol value to sqlite3_free().
  137907. **
  137908. ** If the table cannot be found, an error code is returned and the output
  137909. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  137910. ** returned (and the output variables are undefined).
  137911. */
  137912. static int fts3ContentColumns(
  137913. sqlite3 *db, /* Database handle */
  137914. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  137915. const char *zTbl, /* Name of content table */
  137916. const char ***pazCol, /* OUT: Malloc'd array of column names */
  137917. int *pnCol, /* OUT: Size of array *pazCol */
  137918. int *pnStr, /* OUT: Bytes of string content */
  137919. char **pzErr /* OUT: error message */
  137920. ){
  137921. int rc = SQLITE_OK; /* Return code */
  137922. char *zSql; /* "SELECT *" statement on zTbl */
  137923. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  137924. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  137925. if( !zSql ){
  137926. rc = SQLITE_NOMEM;
  137927. }else{
  137928. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  137929. if( rc!=SQLITE_OK ){
  137930. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  137931. }
  137932. }
  137933. sqlite3_free(zSql);
  137934. if( rc==SQLITE_OK ){
  137935. const char **azCol; /* Output array */
  137936. int nStr = 0; /* Size of all column names (incl. 0x00) */
  137937. int nCol; /* Number of table columns */
  137938. int i; /* Used to iterate through columns */
  137939. /* Loop through the returned columns. Set nStr to the number of bytes of
  137940. ** space required to store a copy of each column name, including the
  137941. ** nul-terminator byte. */
  137942. nCol = sqlite3_column_count(pStmt);
  137943. for(i=0; i<nCol; i++){
  137944. const char *zCol = sqlite3_column_name(pStmt, i);
  137945. nStr += (int)strlen(zCol) + 1;
  137946. }
  137947. /* Allocate and populate the array to return. */
  137948. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  137949. if( azCol==0 ){
  137950. rc = SQLITE_NOMEM;
  137951. }else{
  137952. char *p = (char *)&azCol[nCol];
  137953. for(i=0; i<nCol; i++){
  137954. const char *zCol = sqlite3_column_name(pStmt, i);
  137955. int n = (int)strlen(zCol)+1;
  137956. memcpy(p, zCol, n);
  137957. azCol[i] = p;
  137958. p += n;
  137959. }
  137960. }
  137961. sqlite3_finalize(pStmt);
  137962. /* Set the output variables. */
  137963. *pnCol = nCol;
  137964. *pnStr = nStr;
  137965. *pazCol = azCol;
  137966. }
  137967. return rc;
  137968. }
  137969. /*
  137970. ** This function is the implementation of both the xConnect and xCreate
  137971. ** methods of the FTS3 virtual table.
  137972. **
  137973. ** The argv[] array contains the following:
  137974. **
  137975. ** argv[0] -> module name ("fts3" or "fts4")
  137976. ** argv[1] -> database name
  137977. ** argv[2] -> table name
  137978. ** argv[...] -> "column name" and other module argument fields.
  137979. */
  137980. static int fts3InitVtab(
  137981. int isCreate, /* True for xCreate, false for xConnect */
  137982. sqlite3 *db, /* The SQLite database connection */
  137983. void *pAux, /* Hash table containing tokenizers */
  137984. int argc, /* Number of elements in argv array */
  137985. const char * const *argv, /* xCreate/xConnect argument array */
  137986. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  137987. char **pzErr /* Write any error message here */
  137988. ){
  137989. Fts3Hash *pHash = (Fts3Hash *)pAux;
  137990. Fts3Table *p = 0; /* Pointer to allocated vtab */
  137991. int rc = SQLITE_OK; /* Return code */
  137992. int i; /* Iterator variable */
  137993. int nByte; /* Size of allocation used for *p */
  137994. int iCol; /* Column index */
  137995. int nString = 0; /* Bytes required to hold all column names */
  137996. int nCol = 0; /* Number of columns in the FTS table */
  137997. char *zCsr; /* Space for holding column names */
  137998. int nDb; /* Bytes required to hold database name */
  137999. int nName; /* Bytes required to hold table name */
  138000. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  138001. const char **aCol; /* Array of column names */
  138002. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  138003. int nIndex = 0; /* Size of aIndex[] array */
  138004. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  138005. /* The results of parsing supported FTS4 key=value options: */
  138006. int bNoDocsize = 0; /* True to omit %_docsize table */
  138007. int bDescIdx = 0; /* True to store descending indexes */
  138008. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  138009. char *zCompress = 0; /* compress=? parameter (or NULL) */
  138010. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  138011. char *zContent = 0; /* content=? parameter (or NULL) */
  138012. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  138013. char **azNotindexed = 0; /* The set of notindexed= columns */
  138014. int nNotindexed = 0; /* Size of azNotindexed[] array */
  138015. assert( strlen(argv[0])==4 );
  138016. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  138017. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  138018. );
  138019. nDb = (int)strlen(argv[1]) + 1;
  138020. nName = (int)strlen(argv[2]) + 1;
  138021. nByte = sizeof(const char *) * (argc-2);
  138022. aCol = (const char **)sqlite3_malloc(nByte);
  138023. if( aCol ){
  138024. memset((void*)aCol, 0, nByte);
  138025. azNotindexed = (char **)sqlite3_malloc(nByte);
  138026. }
  138027. if( azNotindexed ){
  138028. memset(azNotindexed, 0, nByte);
  138029. }
  138030. if( !aCol || !azNotindexed ){
  138031. rc = SQLITE_NOMEM;
  138032. goto fts3_init_out;
  138033. }
  138034. /* Loop through all of the arguments passed by the user to the FTS3/4
  138035. ** module (i.e. all the column names and special arguments). This loop
  138036. ** does the following:
  138037. **
  138038. ** + Figures out the number of columns the FTSX table will have, and
  138039. ** the number of bytes of space that must be allocated to store copies
  138040. ** of the column names.
  138041. **
  138042. ** + If there is a tokenizer specification included in the arguments,
  138043. ** initializes the tokenizer pTokenizer.
  138044. */
  138045. for(i=3; rc==SQLITE_OK && i<argc; i++){
  138046. char const *z = argv[i];
  138047. int nKey;
  138048. char *zVal;
  138049. /* Check if this is a tokenizer specification */
  138050. if( !pTokenizer
  138051. && strlen(z)>8
  138052. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  138053. && 0==sqlite3Fts3IsIdChar(z[8])
  138054. ){
  138055. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  138056. }
  138057. /* Check if it is an FTS4 special argument. */
  138058. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  138059. struct Fts4Option {
  138060. const char *zOpt;
  138061. int nOpt;
  138062. } aFts4Opt[] = {
  138063. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  138064. { "prefix", 6 }, /* 1 -> PREFIX */
  138065. { "compress", 8 }, /* 2 -> COMPRESS */
  138066. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  138067. { "order", 5 }, /* 4 -> ORDER */
  138068. { "content", 7 }, /* 5 -> CONTENT */
  138069. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  138070. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  138071. };
  138072. int iOpt;
  138073. if( !zVal ){
  138074. rc = SQLITE_NOMEM;
  138075. }else{
  138076. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  138077. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  138078. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  138079. break;
  138080. }
  138081. }
  138082. switch( iOpt ){
  138083. case 0: /* MATCHINFO */
  138084. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  138085. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  138086. rc = SQLITE_ERROR;
  138087. }
  138088. bNoDocsize = 1;
  138089. break;
  138090. case 1: /* PREFIX */
  138091. sqlite3_free(zPrefix);
  138092. zPrefix = zVal;
  138093. zVal = 0;
  138094. break;
  138095. case 2: /* COMPRESS */
  138096. sqlite3_free(zCompress);
  138097. zCompress = zVal;
  138098. zVal = 0;
  138099. break;
  138100. case 3: /* UNCOMPRESS */
  138101. sqlite3_free(zUncompress);
  138102. zUncompress = zVal;
  138103. zVal = 0;
  138104. break;
  138105. case 4: /* ORDER */
  138106. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  138107. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  138108. ){
  138109. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  138110. rc = SQLITE_ERROR;
  138111. }
  138112. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  138113. break;
  138114. case 5: /* CONTENT */
  138115. sqlite3_free(zContent);
  138116. zContent = zVal;
  138117. zVal = 0;
  138118. break;
  138119. case 6: /* LANGUAGEID */
  138120. assert( iOpt==6 );
  138121. sqlite3_free(zLanguageid);
  138122. zLanguageid = zVal;
  138123. zVal = 0;
  138124. break;
  138125. case 7: /* NOTINDEXED */
  138126. azNotindexed[nNotindexed++] = zVal;
  138127. zVal = 0;
  138128. break;
  138129. default:
  138130. assert( iOpt==SizeofArray(aFts4Opt) );
  138131. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  138132. rc = SQLITE_ERROR;
  138133. break;
  138134. }
  138135. sqlite3_free(zVal);
  138136. }
  138137. }
  138138. /* Otherwise, the argument is a column name. */
  138139. else {
  138140. nString += (int)(strlen(z) + 1);
  138141. aCol[nCol++] = z;
  138142. }
  138143. }
  138144. /* If a content=xxx option was specified, the following:
  138145. **
  138146. ** 1. Ignore any compress= and uncompress= options.
  138147. **
  138148. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  138149. ** TABLE statement, use all columns from the content table.
  138150. */
  138151. if( rc==SQLITE_OK && zContent ){
  138152. sqlite3_free(zCompress);
  138153. sqlite3_free(zUncompress);
  138154. zCompress = 0;
  138155. zUncompress = 0;
  138156. if( nCol==0 ){
  138157. sqlite3_free((void*)aCol);
  138158. aCol = 0;
  138159. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  138160. /* If a languageid= option was specified, remove the language id
  138161. ** column from the aCol[] array. */
  138162. if( rc==SQLITE_OK && zLanguageid ){
  138163. int j;
  138164. for(j=0; j<nCol; j++){
  138165. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  138166. int k;
  138167. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  138168. nCol--;
  138169. break;
  138170. }
  138171. }
  138172. }
  138173. }
  138174. }
  138175. if( rc!=SQLITE_OK ) goto fts3_init_out;
  138176. if( nCol==0 ){
  138177. assert( nString==0 );
  138178. aCol[0] = "content";
  138179. nString = 8;
  138180. nCol = 1;
  138181. }
  138182. if( pTokenizer==0 ){
  138183. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  138184. if( rc!=SQLITE_OK ) goto fts3_init_out;
  138185. }
  138186. assert( pTokenizer );
  138187. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  138188. if( rc==SQLITE_ERROR ){
  138189. assert( zPrefix );
  138190. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  138191. }
  138192. if( rc!=SQLITE_OK ) goto fts3_init_out;
  138193. /* Allocate and populate the Fts3Table structure. */
  138194. nByte = sizeof(Fts3Table) + /* Fts3Table */
  138195. nCol * sizeof(char *) + /* azColumn */
  138196. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  138197. nCol * sizeof(u8) + /* abNotindexed */
  138198. nName + /* zName */
  138199. nDb + /* zDb */
  138200. nString; /* Space for azColumn strings */
  138201. p = (Fts3Table*)sqlite3_malloc(nByte);
  138202. if( p==0 ){
  138203. rc = SQLITE_NOMEM;
  138204. goto fts3_init_out;
  138205. }
  138206. memset(p, 0, nByte);
  138207. p->db = db;
  138208. p->nColumn = nCol;
  138209. p->nPendingData = 0;
  138210. p->azColumn = (char **)&p[1];
  138211. p->pTokenizer = pTokenizer;
  138212. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  138213. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  138214. p->bHasStat = (u8)isFts4;
  138215. p->bFts4 = (u8)isFts4;
  138216. p->bDescIdx = (u8)bDescIdx;
  138217. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  138218. p->zContentTbl = zContent;
  138219. p->zLanguageid = zLanguageid;
  138220. zContent = 0;
  138221. zLanguageid = 0;
  138222. TESTONLY( p->inTransaction = -1 );
  138223. TESTONLY( p->mxSavepoint = -1 );
  138224. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  138225. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  138226. p->nIndex = nIndex;
  138227. for(i=0; i<nIndex; i++){
  138228. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  138229. }
  138230. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  138231. /* Fill in the zName and zDb fields of the vtab structure. */
  138232. zCsr = (char *)&p->abNotindexed[nCol];
  138233. p->zName = zCsr;
  138234. memcpy(zCsr, argv[2], nName);
  138235. zCsr += nName;
  138236. p->zDb = zCsr;
  138237. memcpy(zCsr, argv[1], nDb);
  138238. zCsr += nDb;
  138239. /* Fill in the azColumn array */
  138240. for(iCol=0; iCol<nCol; iCol++){
  138241. char *z;
  138242. int n = 0;
  138243. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  138244. if( n>0 ){
  138245. memcpy(zCsr, z, n);
  138246. }
  138247. zCsr[n] = '\0';
  138248. sqlite3Fts3Dequote(zCsr);
  138249. p->azColumn[iCol] = zCsr;
  138250. zCsr += n+1;
  138251. assert( zCsr <= &((char *)p)[nByte] );
  138252. }
  138253. /* Fill in the abNotindexed array */
  138254. for(iCol=0; iCol<nCol; iCol++){
  138255. int n = (int)strlen(p->azColumn[iCol]);
  138256. for(i=0; i<nNotindexed; i++){
  138257. char *zNot = azNotindexed[i];
  138258. if( zNot && n==(int)strlen(zNot)
  138259. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  138260. ){
  138261. p->abNotindexed[iCol] = 1;
  138262. sqlite3_free(zNot);
  138263. azNotindexed[i] = 0;
  138264. }
  138265. }
  138266. }
  138267. for(i=0; i<nNotindexed; i++){
  138268. if( azNotindexed[i] ){
  138269. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  138270. rc = SQLITE_ERROR;
  138271. }
  138272. }
  138273. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  138274. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  138275. rc = SQLITE_ERROR;
  138276. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  138277. }
  138278. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  138279. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  138280. if( rc!=SQLITE_OK ) goto fts3_init_out;
  138281. /* If this is an xCreate call, create the underlying tables in the
  138282. ** database. TODO: For xConnect(), it could verify that said tables exist.
  138283. */
  138284. if( isCreate ){
  138285. rc = fts3CreateTables(p);
  138286. }
  138287. /* Check to see if a legacy fts3 table has been "upgraded" by the
  138288. ** addition of a %_stat table so that it can use incremental merge.
  138289. */
  138290. if( !isFts4 && !isCreate ){
  138291. p->bHasStat = 2;
  138292. }
  138293. /* Figure out the page-size for the database. This is required in order to
  138294. ** estimate the cost of loading large doclists from the database. */
  138295. fts3DatabasePageSize(&rc, p);
  138296. p->nNodeSize = p->nPgsz-35;
  138297. /* Declare the table schema to SQLite. */
  138298. fts3DeclareVtab(&rc, p);
  138299. fts3_init_out:
  138300. sqlite3_free(zPrefix);
  138301. sqlite3_free(aIndex);
  138302. sqlite3_free(zCompress);
  138303. sqlite3_free(zUncompress);
  138304. sqlite3_free(zContent);
  138305. sqlite3_free(zLanguageid);
  138306. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  138307. sqlite3_free((void *)aCol);
  138308. sqlite3_free((void *)azNotindexed);
  138309. if( rc!=SQLITE_OK ){
  138310. if( p ){
  138311. fts3DisconnectMethod((sqlite3_vtab *)p);
  138312. }else if( pTokenizer ){
  138313. pTokenizer->pModule->xDestroy(pTokenizer);
  138314. }
  138315. }else{
  138316. assert( p->pSegments==0 );
  138317. *ppVTab = &p->base;
  138318. }
  138319. return rc;
  138320. }
  138321. /*
  138322. ** The xConnect() and xCreate() methods for the virtual table. All the
  138323. ** work is done in function fts3InitVtab().
  138324. */
  138325. static int fts3ConnectMethod(
  138326. sqlite3 *db, /* Database connection */
  138327. void *pAux, /* Pointer to tokenizer hash table */
  138328. int argc, /* Number of elements in argv array */
  138329. const char * const *argv, /* xCreate/xConnect argument array */
  138330. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  138331. char **pzErr /* OUT: sqlite3_malloc'd error message */
  138332. ){
  138333. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  138334. }
  138335. static int fts3CreateMethod(
  138336. sqlite3 *db, /* Database connection */
  138337. void *pAux, /* Pointer to tokenizer hash table */
  138338. int argc, /* Number of elements in argv array */
  138339. const char * const *argv, /* xCreate/xConnect argument array */
  138340. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  138341. char **pzErr /* OUT: sqlite3_malloc'd error message */
  138342. ){
  138343. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  138344. }
  138345. /*
  138346. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  138347. ** extension is currently being used by a version of SQLite too old to
  138348. ** support estimatedRows. In that case this function is a no-op.
  138349. */
  138350. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  138351. #if SQLITE_VERSION_NUMBER>=3008002
  138352. if( sqlite3_libversion_number()>=3008002 ){
  138353. pIdxInfo->estimatedRows = nRow;
  138354. }
  138355. #endif
  138356. }
  138357. /*
  138358. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  138359. ** extension is currently being used by a version of SQLite too old to
  138360. ** support index-info flags. In that case this function is a no-op.
  138361. */
  138362. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  138363. #if SQLITE_VERSION_NUMBER>=3008012
  138364. if( sqlite3_libversion_number()>=3008012 ){
  138365. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  138366. }
  138367. #endif
  138368. }
  138369. /*
  138370. ** Implementation of the xBestIndex method for FTS3 tables. There
  138371. ** are three possible strategies, in order of preference:
  138372. **
  138373. ** 1. Direct lookup by rowid or docid.
  138374. ** 2. Full-text search using a MATCH operator on a non-docid column.
  138375. ** 3. Linear scan of %_content table.
  138376. */
  138377. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  138378. Fts3Table *p = (Fts3Table *)pVTab;
  138379. int i; /* Iterator variable */
  138380. int iCons = -1; /* Index of constraint to use */
  138381. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  138382. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  138383. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  138384. int iIdx;
  138385. /* By default use a full table scan. This is an expensive option,
  138386. ** so search through the constraints to see if a more efficient
  138387. ** strategy is possible.
  138388. */
  138389. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  138390. pInfo->estimatedCost = 5000000;
  138391. for(i=0; i<pInfo->nConstraint; i++){
  138392. int bDocid; /* True if this constraint is on docid */
  138393. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  138394. if( pCons->usable==0 ){
  138395. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  138396. /* There exists an unusable MATCH constraint. This means that if
  138397. ** the planner does elect to use the results of this call as part
  138398. ** of the overall query plan the user will see an "unable to use
  138399. ** function MATCH in the requested context" error. To discourage
  138400. ** this, return a very high cost here. */
  138401. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  138402. pInfo->estimatedCost = 1e50;
  138403. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  138404. return SQLITE_OK;
  138405. }
  138406. continue;
  138407. }
  138408. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  138409. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  138410. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  138411. pInfo->idxNum = FTS3_DOCID_SEARCH;
  138412. pInfo->estimatedCost = 1.0;
  138413. iCons = i;
  138414. }
  138415. /* A MATCH constraint. Use a full-text search.
  138416. **
  138417. ** If there is more than one MATCH constraint available, use the first
  138418. ** one encountered. If there is both a MATCH constraint and a direct
  138419. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  138420. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  138421. ** it would lead to an "unable to use function MATCH in the requested
  138422. ** context" error.
  138423. */
  138424. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  138425. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  138426. ){
  138427. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  138428. pInfo->estimatedCost = 2.0;
  138429. iCons = i;
  138430. }
  138431. /* Equality constraint on the langid column */
  138432. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  138433. && pCons->iColumn==p->nColumn + 2
  138434. ){
  138435. iLangidCons = i;
  138436. }
  138437. if( bDocid ){
  138438. switch( pCons->op ){
  138439. case SQLITE_INDEX_CONSTRAINT_GE:
  138440. case SQLITE_INDEX_CONSTRAINT_GT:
  138441. iDocidGe = i;
  138442. break;
  138443. case SQLITE_INDEX_CONSTRAINT_LE:
  138444. case SQLITE_INDEX_CONSTRAINT_LT:
  138445. iDocidLe = i;
  138446. break;
  138447. }
  138448. }
  138449. }
  138450. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  138451. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  138452. iIdx = 1;
  138453. if( iCons>=0 ){
  138454. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  138455. pInfo->aConstraintUsage[iCons].omit = 1;
  138456. }
  138457. if( iLangidCons>=0 ){
  138458. pInfo->idxNum |= FTS3_HAVE_LANGID;
  138459. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  138460. }
  138461. if( iDocidGe>=0 ){
  138462. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  138463. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  138464. }
  138465. if( iDocidLe>=0 ){
  138466. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  138467. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  138468. }
  138469. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  138470. ** docid) order. Both ascending and descending are possible.
  138471. */
  138472. if( pInfo->nOrderBy==1 ){
  138473. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  138474. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  138475. if( pOrder->desc ){
  138476. pInfo->idxStr = "DESC";
  138477. }else{
  138478. pInfo->idxStr = "ASC";
  138479. }
  138480. pInfo->orderByConsumed = 1;
  138481. }
  138482. }
  138483. assert( p->pSegments==0 );
  138484. return SQLITE_OK;
  138485. }
  138486. /*
  138487. ** Implementation of xOpen method.
  138488. */
  138489. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  138490. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  138491. UNUSED_PARAMETER(pVTab);
  138492. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  138493. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  138494. ** if the allocation fails, return SQLITE_NOMEM.
  138495. */
  138496. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  138497. if( !pCsr ){
  138498. return SQLITE_NOMEM;
  138499. }
  138500. memset(pCsr, 0, sizeof(Fts3Cursor));
  138501. return SQLITE_OK;
  138502. }
  138503. /*
  138504. ** Finalize the statement handle at pCsr->pStmt.
  138505. **
  138506. ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
  138507. ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
  138508. ** pointer there instead of finalizing it.
  138509. */
  138510. static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
  138511. if( pCsr->bSeekStmt ){
  138512. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  138513. if( p->pSeekStmt==0 ){
  138514. p->pSeekStmt = pCsr->pStmt;
  138515. sqlite3_reset(pCsr->pStmt);
  138516. pCsr->pStmt = 0;
  138517. }
  138518. pCsr->bSeekStmt = 0;
  138519. }
  138520. sqlite3_finalize(pCsr->pStmt);
  138521. }
  138522. /*
  138523. ** Close the cursor. For additional information see the documentation
  138524. ** on the xClose method of the virtual table interface.
  138525. */
  138526. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  138527. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  138528. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  138529. fts3CursorFinalizeStmt(pCsr);
  138530. sqlite3Fts3ExprFree(pCsr->pExpr);
  138531. sqlite3Fts3FreeDeferredTokens(pCsr);
  138532. sqlite3_free(pCsr->aDoclist);
  138533. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  138534. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  138535. sqlite3_free(pCsr);
  138536. return SQLITE_OK;
  138537. }
  138538. /*
  138539. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  138540. ** compose and prepare an SQL statement of the form:
  138541. **
  138542. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  138543. **
  138544. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  138545. ** it. If an error occurs, return an SQLite error code.
  138546. */
  138547. static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
  138548. int rc = SQLITE_OK;
  138549. if( pCsr->pStmt==0 ){
  138550. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  138551. char *zSql;
  138552. if( p->pSeekStmt ){
  138553. pCsr->pStmt = p->pSeekStmt;
  138554. p->pSeekStmt = 0;
  138555. }else{
  138556. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  138557. if( !zSql ) return SQLITE_NOMEM;
  138558. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  138559. sqlite3_free(zSql);
  138560. }
  138561. if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
  138562. }
  138563. return rc;
  138564. }
  138565. /*
  138566. ** Position the pCsr->pStmt statement so that it is on the row
  138567. ** of the %_content table that contains the last match. Return
  138568. ** SQLITE_OK on success.
  138569. */
  138570. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  138571. int rc = SQLITE_OK;
  138572. if( pCsr->isRequireSeek ){
  138573. rc = fts3CursorSeekStmt(pCsr);
  138574. if( rc==SQLITE_OK ){
  138575. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  138576. pCsr->isRequireSeek = 0;
  138577. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  138578. return SQLITE_OK;
  138579. }else{
  138580. rc = sqlite3_reset(pCsr->pStmt);
  138581. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  138582. /* If no row was found and no error has occurred, then the %_content
  138583. ** table is missing a row that is present in the full-text index.
  138584. ** The data structures are corrupt. */
  138585. rc = FTS_CORRUPT_VTAB;
  138586. pCsr->isEof = 1;
  138587. }
  138588. }
  138589. }
  138590. }
  138591. if( rc!=SQLITE_OK && pContext ){
  138592. sqlite3_result_error_code(pContext, rc);
  138593. }
  138594. return rc;
  138595. }
  138596. /*
  138597. ** This function is used to process a single interior node when searching
  138598. ** a b-tree for a term or term prefix. The node data is passed to this
  138599. ** function via the zNode/nNode parameters. The term to search for is
  138600. ** passed in zTerm/nTerm.
  138601. **
  138602. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  138603. ** of the child node that heads the sub-tree that may contain the term.
  138604. **
  138605. ** If piLast is not NULL, then *piLast is set to the right-most child node
  138606. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  138607. ** a prefix.
  138608. **
  138609. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  138610. */
  138611. static int fts3ScanInteriorNode(
  138612. const char *zTerm, /* Term to select leaves for */
  138613. int nTerm, /* Size of term zTerm in bytes */
  138614. const char *zNode, /* Buffer containing segment interior node */
  138615. int nNode, /* Size of buffer at zNode */
  138616. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  138617. sqlite3_int64 *piLast /* OUT: Selected child node */
  138618. ){
  138619. int rc = SQLITE_OK; /* Return code */
  138620. const char *zCsr = zNode; /* Cursor to iterate through node */
  138621. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  138622. char *zBuffer = 0; /* Buffer to load terms into */
  138623. int nAlloc = 0; /* Size of allocated buffer */
  138624. int isFirstTerm = 1; /* True when processing first term on page */
  138625. sqlite3_int64 iChild; /* Block id of child node to descend to */
  138626. /* Skip over the 'height' varint that occurs at the start of every
  138627. ** interior node. Then load the blockid of the left-child of the b-tree
  138628. ** node into variable iChild.
  138629. **
  138630. ** Even if the data structure on disk is corrupted, this (reading two
  138631. ** varints from the buffer) does not risk an overread. If zNode is a
  138632. ** root node, then the buffer comes from a SELECT statement. SQLite does
  138633. ** not make this guarantee explicitly, but in practice there are always
  138634. ** either more than 20 bytes of allocated space following the nNode bytes of
  138635. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  138636. ** table, then there are always 20 bytes of zeroed padding following the
  138637. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  138638. */
  138639. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  138640. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  138641. if( zCsr>zEnd ){
  138642. return FTS_CORRUPT_VTAB;
  138643. }
  138644. while( zCsr<zEnd && (piFirst || piLast) ){
  138645. int cmp; /* memcmp() result */
  138646. int nSuffix; /* Size of term suffix */
  138647. int nPrefix = 0; /* Size of term prefix */
  138648. int nBuffer; /* Total term size */
  138649. /* Load the next term on the node into zBuffer. Use realloc() to expand
  138650. ** the size of zBuffer if required. */
  138651. if( !isFirstTerm ){
  138652. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  138653. }
  138654. isFirstTerm = 0;
  138655. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  138656. assert( nPrefix>=0 && nSuffix>=0 );
  138657. if( &zCsr[nSuffix]>zEnd ){
  138658. rc = FTS_CORRUPT_VTAB;
  138659. goto finish_scan;
  138660. }
  138661. if( nPrefix+nSuffix>nAlloc ){
  138662. char *zNew;
  138663. nAlloc = (nPrefix+nSuffix) * 2;
  138664. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  138665. if( !zNew ){
  138666. rc = SQLITE_NOMEM;
  138667. goto finish_scan;
  138668. }
  138669. zBuffer = zNew;
  138670. }
  138671. assert( zBuffer );
  138672. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  138673. nBuffer = nPrefix + nSuffix;
  138674. zCsr += nSuffix;
  138675. /* Compare the term we are searching for with the term just loaded from
  138676. ** the interior node. If the specified term is greater than or equal
  138677. ** to the term from the interior node, then all terms on the sub-tree
  138678. ** headed by node iChild are smaller than zTerm. No need to search
  138679. ** iChild.
  138680. **
  138681. ** If the interior node term is larger than the specified term, then
  138682. ** the tree headed by iChild may contain the specified term.
  138683. */
  138684. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  138685. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  138686. *piFirst = iChild;
  138687. piFirst = 0;
  138688. }
  138689. if( piLast && cmp<0 ){
  138690. *piLast = iChild;
  138691. piLast = 0;
  138692. }
  138693. iChild++;
  138694. };
  138695. if( piFirst ) *piFirst = iChild;
  138696. if( piLast ) *piLast = iChild;
  138697. finish_scan:
  138698. sqlite3_free(zBuffer);
  138699. return rc;
  138700. }
  138701. /*
  138702. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  138703. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  138704. ** contains a term. This function searches the sub-tree headed by the zNode
  138705. ** node for the range of leaf nodes that may contain the specified term
  138706. ** or terms for which the specified term is a prefix.
  138707. **
  138708. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  138709. ** left-most leaf node in the tree that may contain the specified term.
  138710. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  138711. ** right-most leaf node that may contain a term for which the specified
  138712. ** term is a prefix.
  138713. **
  138714. ** It is possible that the range of returned leaf nodes does not contain
  138715. ** the specified term or any terms for which it is a prefix. However, if the
  138716. ** segment does contain any such terms, they are stored within the identified
  138717. ** range. Because this function only inspects interior segment nodes (and
  138718. ** never loads leaf nodes into memory), it is not possible to be sure.
  138719. **
  138720. ** If an error occurs, an error code other than SQLITE_OK is returned.
  138721. */
  138722. static int fts3SelectLeaf(
  138723. Fts3Table *p, /* Virtual table handle */
  138724. const char *zTerm, /* Term to select leaves for */
  138725. int nTerm, /* Size of term zTerm in bytes */
  138726. const char *zNode, /* Buffer containing segment interior node */
  138727. int nNode, /* Size of buffer at zNode */
  138728. sqlite3_int64 *piLeaf, /* Selected leaf node */
  138729. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  138730. ){
  138731. int rc = SQLITE_OK; /* Return code */
  138732. int iHeight; /* Height of this node in tree */
  138733. assert( piLeaf || piLeaf2 );
  138734. fts3GetVarint32(zNode, &iHeight);
  138735. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  138736. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  138737. if( rc==SQLITE_OK && iHeight>1 ){
  138738. char *zBlob = 0; /* Blob read from %_segments table */
  138739. int nBlob = 0; /* Size of zBlob in bytes */
  138740. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  138741. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  138742. if( rc==SQLITE_OK ){
  138743. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  138744. }
  138745. sqlite3_free(zBlob);
  138746. piLeaf = 0;
  138747. zBlob = 0;
  138748. }
  138749. if( rc==SQLITE_OK ){
  138750. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  138751. }
  138752. if( rc==SQLITE_OK ){
  138753. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  138754. }
  138755. sqlite3_free(zBlob);
  138756. }
  138757. return rc;
  138758. }
  138759. /*
  138760. ** This function is used to create delta-encoded serialized lists of FTS3
  138761. ** varints. Each call to this function appends a single varint to a list.
  138762. */
  138763. static void fts3PutDeltaVarint(
  138764. char **pp, /* IN/OUT: Output pointer */
  138765. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  138766. sqlite3_int64 iVal /* Write this value to the list */
  138767. ){
  138768. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  138769. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  138770. *piPrev = iVal;
  138771. }
  138772. /*
  138773. ** When this function is called, *ppPoslist is assumed to point to the
  138774. ** start of a position-list. After it returns, *ppPoslist points to the
  138775. ** first byte after the position-list.
  138776. **
  138777. ** A position list is list of positions (delta encoded) and columns for
  138778. ** a single document record of a doclist. So, in other words, this
  138779. ** routine advances *ppPoslist so that it points to the next docid in
  138780. ** the doclist, or to the first byte past the end of the doclist.
  138781. **
  138782. ** If pp is not NULL, then the contents of the position list are copied
  138783. ** to *pp. *pp is set to point to the first byte past the last byte copied
  138784. ** before this function returns.
  138785. */
  138786. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  138787. char *pEnd = *ppPoslist;
  138788. char c = 0;
  138789. /* The end of a position list is marked by a zero encoded as an FTS3
  138790. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  138791. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  138792. ** of some other, multi-byte, value.
  138793. **
  138794. ** The following while-loop moves pEnd to point to the first byte that is not
  138795. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  138796. ** pEnd once more so that it points to the byte immediately following the
  138797. ** last byte in the position-list.
  138798. */
  138799. while( *pEnd | c ){
  138800. c = *pEnd++ & 0x80;
  138801. testcase( c!=0 && (*pEnd)==0 );
  138802. }
  138803. pEnd++; /* Advance past the POS_END terminator byte */
  138804. if( pp ){
  138805. int n = (int)(pEnd - *ppPoslist);
  138806. char *p = *pp;
  138807. memcpy(p, *ppPoslist, n);
  138808. p += n;
  138809. *pp = p;
  138810. }
  138811. *ppPoslist = pEnd;
  138812. }
  138813. /*
  138814. ** When this function is called, *ppPoslist is assumed to point to the
  138815. ** start of a column-list. After it returns, *ppPoslist points to the
  138816. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  138817. **
  138818. ** A column-list is list of delta-encoded positions for a single column
  138819. ** within a single document within a doclist.
  138820. **
  138821. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  138822. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  138823. ** the POS_COLUMN or POS_END that terminates the column-list.
  138824. **
  138825. ** If pp is not NULL, then the contents of the column-list are copied
  138826. ** to *pp. *pp is set to point to the first byte past the last byte copied
  138827. ** before this function returns. The POS_COLUMN or POS_END terminator
  138828. ** is not copied into *pp.
  138829. */
  138830. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  138831. char *pEnd = *ppPoslist;
  138832. char c = 0;
  138833. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  138834. ** not part of a multi-byte varint.
  138835. */
  138836. while( 0xFE & (*pEnd | c) ){
  138837. c = *pEnd++ & 0x80;
  138838. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  138839. }
  138840. if( pp ){
  138841. int n = (int)(pEnd - *ppPoslist);
  138842. char *p = *pp;
  138843. memcpy(p, *ppPoslist, n);
  138844. p += n;
  138845. *pp = p;
  138846. }
  138847. *ppPoslist = pEnd;
  138848. }
  138849. /*
  138850. ** Value used to signify the end of an position-list. This is safe because
  138851. ** it is not possible to have a document with 2^31 terms.
  138852. */
  138853. #define POSITION_LIST_END 0x7fffffff
  138854. /*
  138855. ** This function is used to help parse position-lists. When this function is
  138856. ** called, *pp may point to the start of the next varint in the position-list
  138857. ** being parsed, or it may point to 1 byte past the end of the position-list
  138858. ** (in which case **pp will be a terminator bytes POS_END (0) or
  138859. ** (1)).
  138860. **
  138861. ** If *pp points past the end of the current position-list, set *pi to
  138862. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  138863. ** increment the current value of *pi by the value read, and set *pp to
  138864. ** point to the next value before returning.
  138865. **
  138866. ** Before calling this routine *pi must be initialized to the value of
  138867. ** the previous position, or zero if we are reading the first position
  138868. ** in the position-list. Because positions are delta-encoded, the value
  138869. ** of the previous position is needed in order to compute the value of
  138870. ** the next position.
  138871. */
  138872. static void fts3ReadNextPos(
  138873. char **pp, /* IN/OUT: Pointer into position-list buffer */
  138874. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  138875. ){
  138876. if( (**pp)&0xFE ){
  138877. fts3GetDeltaVarint(pp, pi);
  138878. *pi -= 2;
  138879. }else{
  138880. *pi = POSITION_LIST_END;
  138881. }
  138882. }
  138883. /*
  138884. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  138885. ** the value of iCol encoded as a varint to *pp. This will start a new
  138886. ** column list.
  138887. **
  138888. ** Set *pp to point to the byte just after the last byte written before
  138889. ** returning (do not modify it if iCol==0). Return the total number of bytes
  138890. ** written (0 if iCol==0).
  138891. */
  138892. static int fts3PutColNumber(char **pp, int iCol){
  138893. int n = 0; /* Number of bytes written */
  138894. if( iCol ){
  138895. char *p = *pp; /* Output pointer */
  138896. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  138897. *p = 0x01;
  138898. *pp = &p[n];
  138899. }
  138900. return n;
  138901. }
  138902. /*
  138903. ** Compute the union of two position lists. The output written
  138904. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  138905. ** order and with any duplicates removed. All pointers are
  138906. ** updated appropriately. The caller is responsible for insuring
  138907. ** that there is enough space in *pp to hold the complete output.
  138908. */
  138909. static void fts3PoslistMerge(
  138910. char **pp, /* Output buffer */
  138911. char **pp1, /* Left input list */
  138912. char **pp2 /* Right input list */
  138913. ){
  138914. char *p = *pp;
  138915. char *p1 = *pp1;
  138916. char *p2 = *pp2;
  138917. while( *p1 || *p2 ){
  138918. int iCol1; /* The current column index in pp1 */
  138919. int iCol2; /* The current column index in pp2 */
  138920. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  138921. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  138922. else iCol1 = 0;
  138923. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  138924. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  138925. else iCol2 = 0;
  138926. if( iCol1==iCol2 ){
  138927. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  138928. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  138929. sqlite3_int64 iPrev = 0;
  138930. int n = fts3PutColNumber(&p, iCol1);
  138931. p1 += n;
  138932. p2 += n;
  138933. /* At this point, both p1 and p2 point to the start of column-lists
  138934. ** for the same column (the column with index iCol1 and iCol2).
  138935. ** A column-list is a list of non-negative delta-encoded varints, each
  138936. ** incremented by 2 before being stored. Each list is terminated by a
  138937. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  138938. ** and writes the results to buffer p. p is left pointing to the byte
  138939. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  138940. ** written to the output.
  138941. */
  138942. fts3GetDeltaVarint(&p1, &i1);
  138943. fts3GetDeltaVarint(&p2, &i2);
  138944. do {
  138945. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  138946. iPrev -= 2;
  138947. if( i1==i2 ){
  138948. fts3ReadNextPos(&p1, &i1);
  138949. fts3ReadNextPos(&p2, &i2);
  138950. }else if( i1<i2 ){
  138951. fts3ReadNextPos(&p1, &i1);
  138952. }else{
  138953. fts3ReadNextPos(&p2, &i2);
  138954. }
  138955. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  138956. }else if( iCol1<iCol2 ){
  138957. p1 += fts3PutColNumber(&p, iCol1);
  138958. fts3ColumnlistCopy(&p, &p1);
  138959. }else{
  138960. p2 += fts3PutColNumber(&p, iCol2);
  138961. fts3ColumnlistCopy(&p, &p2);
  138962. }
  138963. }
  138964. *p++ = POS_END;
  138965. *pp = p;
  138966. *pp1 = p1 + 1;
  138967. *pp2 = p2 + 1;
  138968. }
  138969. /*
  138970. ** This function is used to merge two position lists into one. When it is
  138971. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  138972. ** the part of a doclist that follows each document id. For example, if a row
  138973. ** contains:
  138974. **
  138975. ** 'a b c'|'x y z'|'a b b a'
  138976. **
  138977. ** Then the position list for this row for token 'b' would consist of:
  138978. **
  138979. ** 0x02 0x01 0x02 0x03 0x03 0x00
  138980. **
  138981. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  138982. ** byte following the 0x00 terminator of their respective position lists.
  138983. **
  138984. ** If isSaveLeft is 0, an entry is added to the output position list for
  138985. ** each position in *pp2 for which there exists one or more positions in
  138986. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  138987. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  138988. ** slots before it.
  138989. **
  138990. ** e.g. nToken==1 searches for adjacent positions.
  138991. */
  138992. static int fts3PoslistPhraseMerge(
  138993. char **pp, /* IN/OUT: Preallocated output buffer */
  138994. int nToken, /* Maximum difference in token positions */
  138995. int isSaveLeft, /* Save the left position */
  138996. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  138997. char **pp1, /* IN/OUT: Left input list */
  138998. char **pp2 /* IN/OUT: Right input list */
  138999. ){
  139000. char *p = *pp;
  139001. char *p1 = *pp1;
  139002. char *p2 = *pp2;
  139003. int iCol1 = 0;
  139004. int iCol2 = 0;
  139005. /* Never set both isSaveLeft and isExact for the same invocation. */
  139006. assert( isSaveLeft==0 || isExact==0 );
  139007. assert( p!=0 && *p1!=0 && *p2!=0 );
  139008. if( *p1==POS_COLUMN ){
  139009. p1++;
  139010. p1 += fts3GetVarint32(p1, &iCol1);
  139011. }
  139012. if( *p2==POS_COLUMN ){
  139013. p2++;
  139014. p2 += fts3GetVarint32(p2, &iCol2);
  139015. }
  139016. while( 1 ){
  139017. if( iCol1==iCol2 ){
  139018. char *pSave = p;
  139019. sqlite3_int64 iPrev = 0;
  139020. sqlite3_int64 iPos1 = 0;
  139021. sqlite3_int64 iPos2 = 0;
  139022. if( iCol1 ){
  139023. *p++ = POS_COLUMN;
  139024. p += sqlite3Fts3PutVarint(p, iCol1);
  139025. }
  139026. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  139027. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  139028. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  139029. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  139030. while( 1 ){
  139031. if( iPos2==iPos1+nToken
  139032. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  139033. ){
  139034. sqlite3_int64 iSave;
  139035. iSave = isSaveLeft ? iPos1 : iPos2;
  139036. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  139037. pSave = 0;
  139038. assert( p );
  139039. }
  139040. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  139041. if( (*p2&0xFE)==0 ) break;
  139042. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  139043. }else{
  139044. if( (*p1&0xFE)==0 ) break;
  139045. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  139046. }
  139047. }
  139048. if( pSave ){
  139049. assert( pp && p );
  139050. p = pSave;
  139051. }
  139052. fts3ColumnlistCopy(0, &p1);
  139053. fts3ColumnlistCopy(0, &p2);
  139054. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  139055. if( 0==*p1 || 0==*p2 ) break;
  139056. p1++;
  139057. p1 += fts3GetVarint32(p1, &iCol1);
  139058. p2++;
  139059. p2 += fts3GetVarint32(p2, &iCol2);
  139060. }
  139061. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  139062. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  139063. ** end of the position list, or the 0x01 that precedes the next
  139064. ** column-number in the position list.
  139065. */
  139066. else if( iCol1<iCol2 ){
  139067. fts3ColumnlistCopy(0, &p1);
  139068. if( 0==*p1 ) break;
  139069. p1++;
  139070. p1 += fts3GetVarint32(p1, &iCol1);
  139071. }else{
  139072. fts3ColumnlistCopy(0, &p2);
  139073. if( 0==*p2 ) break;
  139074. p2++;
  139075. p2 += fts3GetVarint32(p2, &iCol2);
  139076. }
  139077. }
  139078. fts3PoslistCopy(0, &p2);
  139079. fts3PoslistCopy(0, &p1);
  139080. *pp1 = p1;
  139081. *pp2 = p2;
  139082. if( *pp==p ){
  139083. return 0;
  139084. }
  139085. *p++ = 0x00;
  139086. *pp = p;
  139087. return 1;
  139088. }
  139089. /*
  139090. ** Merge two position-lists as required by the NEAR operator. The argument
  139091. ** position lists correspond to the left and right phrases of an expression
  139092. ** like:
  139093. **
  139094. ** "phrase 1" NEAR "phrase number 2"
  139095. **
  139096. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  139097. ** expression and *pp2 to the right. As usual, the indexes in the position
  139098. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  139099. ** in the example above).
  139100. **
  139101. ** The output position list - written to *pp - is a copy of *pp2 with those
  139102. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  139103. */
  139104. static int fts3PoslistNearMerge(
  139105. char **pp, /* Output buffer */
  139106. char *aTmp, /* Temporary buffer space */
  139107. int nRight, /* Maximum difference in token positions */
  139108. int nLeft, /* Maximum difference in token positions */
  139109. char **pp1, /* IN/OUT: Left input list */
  139110. char **pp2 /* IN/OUT: Right input list */
  139111. ){
  139112. char *p1 = *pp1;
  139113. char *p2 = *pp2;
  139114. char *pTmp1 = aTmp;
  139115. char *pTmp2;
  139116. char *aTmp2;
  139117. int res = 1;
  139118. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  139119. aTmp2 = pTmp2 = pTmp1;
  139120. *pp1 = p1;
  139121. *pp2 = p2;
  139122. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  139123. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  139124. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  139125. }else if( pTmp1!=aTmp ){
  139126. fts3PoslistCopy(pp, &aTmp);
  139127. }else if( pTmp2!=aTmp2 ){
  139128. fts3PoslistCopy(pp, &aTmp2);
  139129. }else{
  139130. res = 0;
  139131. }
  139132. return res;
  139133. }
  139134. /*
  139135. ** An instance of this function is used to merge together the (potentially
  139136. ** large number of) doclists for each term that matches a prefix query.
  139137. ** See function fts3TermSelectMerge() for details.
  139138. */
  139139. typedef struct TermSelect TermSelect;
  139140. struct TermSelect {
  139141. char *aaOutput[16]; /* Malloc'd output buffers */
  139142. int anOutput[16]; /* Size each output buffer in bytes */
  139143. };
  139144. /*
  139145. ** This function is used to read a single varint from a buffer. Parameter
  139146. ** pEnd points 1 byte past the end of the buffer. When this function is
  139147. ** called, if *pp points to pEnd or greater, then the end of the buffer
  139148. ** has been reached. In this case *pp is set to 0 and the function returns.
  139149. **
  139150. ** If *pp does not point to or past pEnd, then a single varint is read
  139151. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  139152. **
  139153. ** If bDescIdx is false, the value read is added to *pVal before returning.
  139154. ** If it is true, the value read is subtracted from *pVal before this
  139155. ** function returns.
  139156. */
  139157. static void fts3GetDeltaVarint3(
  139158. char **pp, /* IN/OUT: Point to read varint from */
  139159. char *pEnd, /* End of buffer */
  139160. int bDescIdx, /* True if docids are descending */
  139161. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  139162. ){
  139163. if( *pp>=pEnd ){
  139164. *pp = 0;
  139165. }else{
  139166. sqlite3_int64 iVal;
  139167. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  139168. if( bDescIdx ){
  139169. *pVal -= iVal;
  139170. }else{
  139171. *pVal += iVal;
  139172. }
  139173. }
  139174. }
  139175. /*
  139176. ** This function is used to write a single varint to a buffer. The varint
  139177. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  139178. ** end of the value written.
  139179. **
  139180. ** If *pbFirst is zero when this function is called, the value written to
  139181. ** the buffer is that of parameter iVal.
  139182. **
  139183. ** If *pbFirst is non-zero when this function is called, then the value
  139184. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  139185. ** (if bDescIdx is non-zero).
  139186. **
  139187. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  139188. ** to the value of parameter iVal.
  139189. */
  139190. static void fts3PutDeltaVarint3(
  139191. char **pp, /* IN/OUT: Output pointer */
  139192. int bDescIdx, /* True for descending docids */
  139193. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  139194. int *pbFirst, /* IN/OUT: True after first int written */
  139195. sqlite3_int64 iVal /* Write this value to the list */
  139196. ){
  139197. sqlite3_int64 iWrite;
  139198. if( bDescIdx==0 || *pbFirst==0 ){
  139199. iWrite = iVal - *piPrev;
  139200. }else{
  139201. iWrite = *piPrev - iVal;
  139202. }
  139203. assert( *pbFirst || *piPrev==0 );
  139204. assert( *pbFirst==0 || iWrite>0 );
  139205. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  139206. *piPrev = iVal;
  139207. *pbFirst = 1;
  139208. }
  139209. /*
  139210. ** This macro is used by various functions that merge doclists. The two
  139211. ** arguments are 64-bit docid values. If the value of the stack variable
  139212. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  139213. ** Otherwise, (i2-i1).
  139214. **
  139215. ** Using this makes it easier to write code that can merge doclists that are
  139216. ** sorted in either ascending or descending order.
  139217. */
  139218. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  139219. /*
  139220. ** This function does an "OR" merge of two doclists (output contains all
  139221. ** positions contained in either argument doclist). If the docids in the
  139222. ** input doclists are sorted in ascending order, parameter bDescDoclist
  139223. ** should be false. If they are sorted in ascending order, it should be
  139224. ** passed a non-zero value.
  139225. **
  139226. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  139227. ** containing the output doclist and SQLITE_OK is returned. In this case
  139228. ** *pnOut is set to the number of bytes in the output doclist.
  139229. **
  139230. ** If an error occurs, an SQLite error code is returned. The output values
  139231. ** are undefined in this case.
  139232. */
  139233. static int fts3DoclistOrMerge(
  139234. int bDescDoclist, /* True if arguments are desc */
  139235. char *a1, int n1, /* First doclist */
  139236. char *a2, int n2, /* Second doclist */
  139237. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  139238. ){
  139239. sqlite3_int64 i1 = 0;
  139240. sqlite3_int64 i2 = 0;
  139241. sqlite3_int64 iPrev = 0;
  139242. char *pEnd1 = &a1[n1];
  139243. char *pEnd2 = &a2[n2];
  139244. char *p1 = a1;
  139245. char *p2 = a2;
  139246. char *p;
  139247. char *aOut;
  139248. int bFirstOut = 0;
  139249. *paOut = 0;
  139250. *pnOut = 0;
  139251. /* Allocate space for the output. Both the input and output doclists
  139252. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  139253. ** then the first docid in each list is simply encoded as a varint. For
  139254. ** each subsequent docid, the varint stored is the difference between the
  139255. ** current and previous docid (a positive number - since the list is in
  139256. ** ascending order).
  139257. **
  139258. ** The first docid written to the output is therefore encoded using the
  139259. ** same number of bytes as it is in whichever of the input lists it is
  139260. ** read from. And each subsequent docid read from the same input list
  139261. ** consumes either the same or less bytes as it did in the input (since
  139262. ** the difference between it and the previous value in the output must
  139263. ** be a positive value less than or equal to the delta value read from
  139264. ** the input list). The same argument applies to all but the first docid
  139265. ** read from the 'other' list. And to the contents of all position lists
  139266. ** that will be copied and merged from the input to the output.
  139267. **
  139268. ** However, if the first docid copied to the output is a negative number,
  139269. ** then the encoding of the first docid from the 'other' input list may
  139270. ** be larger in the output than it was in the input (since the delta value
  139271. ** may be a larger positive integer than the actual docid).
  139272. **
  139273. ** The space required to store the output is therefore the sum of the
  139274. ** sizes of the two inputs, plus enough space for exactly one of the input
  139275. ** docids to grow.
  139276. **
  139277. ** A symetric argument may be made if the doclists are in descending
  139278. ** order.
  139279. */
  139280. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  139281. if( !aOut ) return SQLITE_NOMEM;
  139282. p = aOut;
  139283. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  139284. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  139285. while( p1 || p2 ){
  139286. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  139287. if( p2 && p1 && iDiff==0 ){
  139288. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  139289. fts3PoslistMerge(&p, &p1, &p2);
  139290. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  139291. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  139292. }else if( !p2 || (p1 && iDiff<0) ){
  139293. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  139294. fts3PoslistCopy(&p, &p1);
  139295. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  139296. }else{
  139297. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  139298. fts3PoslistCopy(&p, &p2);
  139299. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  139300. }
  139301. }
  139302. *paOut = aOut;
  139303. *pnOut = (int)(p-aOut);
  139304. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  139305. return SQLITE_OK;
  139306. }
  139307. /*
  139308. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  139309. ** the output contains a copy of each position from the right-hand input
  139310. ** doclist for which there is a position in the left-hand input doclist
  139311. ** exactly nDist tokens before it.
  139312. **
  139313. ** If the docids in the input doclists are sorted in ascending order,
  139314. ** parameter bDescDoclist should be false. If they are sorted in ascending
  139315. ** order, it should be passed a non-zero value.
  139316. **
  139317. ** The right-hand input doclist is overwritten by this function.
  139318. */
  139319. static int fts3DoclistPhraseMerge(
  139320. int bDescDoclist, /* True if arguments are desc */
  139321. int nDist, /* Distance from left to right (1=adjacent) */
  139322. char *aLeft, int nLeft, /* Left doclist */
  139323. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  139324. ){
  139325. sqlite3_int64 i1 = 0;
  139326. sqlite3_int64 i2 = 0;
  139327. sqlite3_int64 iPrev = 0;
  139328. char *aRight = *paRight;
  139329. char *pEnd1 = &aLeft[nLeft];
  139330. char *pEnd2 = &aRight[*pnRight];
  139331. char *p1 = aLeft;
  139332. char *p2 = aRight;
  139333. char *p;
  139334. int bFirstOut = 0;
  139335. char *aOut;
  139336. assert( nDist>0 );
  139337. if( bDescDoclist ){
  139338. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  139339. if( aOut==0 ) return SQLITE_NOMEM;
  139340. }else{
  139341. aOut = aRight;
  139342. }
  139343. p = aOut;
  139344. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  139345. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  139346. while( p1 && p2 ){
  139347. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  139348. if( iDiff==0 ){
  139349. char *pSave = p;
  139350. sqlite3_int64 iPrevSave = iPrev;
  139351. int bFirstOutSave = bFirstOut;
  139352. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  139353. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  139354. p = pSave;
  139355. iPrev = iPrevSave;
  139356. bFirstOut = bFirstOutSave;
  139357. }
  139358. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  139359. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  139360. }else if( iDiff<0 ){
  139361. fts3PoslistCopy(0, &p1);
  139362. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  139363. }else{
  139364. fts3PoslistCopy(0, &p2);
  139365. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  139366. }
  139367. }
  139368. *pnRight = (int)(p - aOut);
  139369. if( bDescDoclist ){
  139370. sqlite3_free(aRight);
  139371. *paRight = aOut;
  139372. }
  139373. return SQLITE_OK;
  139374. }
  139375. /*
  139376. ** Argument pList points to a position list nList bytes in size. This
  139377. ** function checks to see if the position list contains any entries for
  139378. ** a token in position 0 (of any column). If so, it writes argument iDelta
  139379. ** to the output buffer pOut, followed by a position list consisting only
  139380. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  139381. ** The value returned is the number of bytes written to pOut (if any).
  139382. */
  139383. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  139384. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  139385. char *pList, /* Position list (no 0x00 term) */
  139386. int nList, /* Size of pList in bytes */
  139387. char *pOut /* Write output here */
  139388. ){
  139389. int nOut = 0;
  139390. int bWritten = 0; /* True once iDelta has been written */
  139391. char *p = pList;
  139392. char *pEnd = &pList[nList];
  139393. if( *p!=0x01 ){
  139394. if( *p==0x02 ){
  139395. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  139396. pOut[nOut++] = 0x02;
  139397. bWritten = 1;
  139398. }
  139399. fts3ColumnlistCopy(0, &p);
  139400. }
  139401. while( p<pEnd ){
  139402. sqlite3_int64 iCol;
  139403. p++;
  139404. p += sqlite3Fts3GetVarint(p, &iCol);
  139405. if( *p==0x02 ){
  139406. if( bWritten==0 ){
  139407. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  139408. bWritten = 1;
  139409. }
  139410. pOut[nOut++] = 0x01;
  139411. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  139412. pOut[nOut++] = 0x02;
  139413. }
  139414. fts3ColumnlistCopy(0, &p);
  139415. }
  139416. if( bWritten ){
  139417. pOut[nOut++] = 0x00;
  139418. }
  139419. return nOut;
  139420. }
  139421. /*
  139422. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  139423. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  139424. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  139425. **
  139426. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  139427. ** the responsibility of the caller to free any doclists left in the
  139428. ** TermSelect.aaOutput[] array.
  139429. */
  139430. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  139431. char *aOut = 0;
  139432. int nOut = 0;
  139433. int i;
  139434. /* Loop through the doclists in the aaOutput[] array. Merge them all
  139435. ** into a single doclist.
  139436. */
  139437. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  139438. if( pTS->aaOutput[i] ){
  139439. if( !aOut ){
  139440. aOut = pTS->aaOutput[i];
  139441. nOut = pTS->anOutput[i];
  139442. pTS->aaOutput[i] = 0;
  139443. }else{
  139444. int nNew;
  139445. char *aNew;
  139446. int rc = fts3DoclistOrMerge(p->bDescIdx,
  139447. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  139448. );
  139449. if( rc!=SQLITE_OK ){
  139450. sqlite3_free(aOut);
  139451. return rc;
  139452. }
  139453. sqlite3_free(pTS->aaOutput[i]);
  139454. sqlite3_free(aOut);
  139455. pTS->aaOutput[i] = 0;
  139456. aOut = aNew;
  139457. nOut = nNew;
  139458. }
  139459. }
  139460. }
  139461. pTS->aaOutput[0] = aOut;
  139462. pTS->anOutput[0] = nOut;
  139463. return SQLITE_OK;
  139464. }
  139465. /*
  139466. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  139467. ** as the first argument. The merge is an "OR" merge (see function
  139468. ** fts3DoclistOrMerge() for details).
  139469. **
  139470. ** This function is called with the doclist for each term that matches
  139471. ** a queried prefix. It merges all these doclists into one, the doclist
  139472. ** for the specified prefix. Since there can be a very large number of
  139473. ** doclists to merge, the merging is done pair-wise using the TermSelect
  139474. ** object.
  139475. **
  139476. ** This function returns SQLITE_OK if the merge is successful, or an
  139477. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  139478. */
  139479. static int fts3TermSelectMerge(
  139480. Fts3Table *p, /* FTS table handle */
  139481. TermSelect *pTS, /* TermSelect object to merge into */
  139482. char *aDoclist, /* Pointer to doclist */
  139483. int nDoclist /* Size of aDoclist in bytes */
  139484. ){
  139485. if( pTS->aaOutput[0]==0 ){
  139486. /* If this is the first term selected, copy the doclist to the output
  139487. ** buffer using memcpy().
  139488. **
  139489. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  139490. ** allocation. This is so as to ensure that the buffer is big enough
  139491. ** to hold the current doclist AND'd with any other doclist. If the
  139492. ** doclists are stored in order=ASC order, this padding would not be
  139493. ** required (since the size of [doclistA AND doclistB] is always less
  139494. ** than or equal to the size of [doclistA] in that case). But this is
  139495. ** not true for order=DESC. For example, a doclist containing (1, -1)
  139496. ** may be smaller than (-1), as in the first example the -1 may be stored
  139497. ** as a single-byte delta, whereas in the second it must be stored as a
  139498. ** FTS3_VARINT_MAX byte varint.
  139499. **
  139500. ** Similar padding is added in the fts3DoclistOrMerge() function.
  139501. */
  139502. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  139503. pTS->anOutput[0] = nDoclist;
  139504. if( pTS->aaOutput[0] ){
  139505. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  139506. }else{
  139507. return SQLITE_NOMEM;
  139508. }
  139509. }else{
  139510. char *aMerge = aDoclist;
  139511. int nMerge = nDoclist;
  139512. int iOut;
  139513. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  139514. if( pTS->aaOutput[iOut]==0 ){
  139515. assert( iOut>0 );
  139516. pTS->aaOutput[iOut] = aMerge;
  139517. pTS->anOutput[iOut] = nMerge;
  139518. break;
  139519. }else{
  139520. char *aNew;
  139521. int nNew;
  139522. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  139523. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  139524. );
  139525. if( rc!=SQLITE_OK ){
  139526. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  139527. return rc;
  139528. }
  139529. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  139530. sqlite3_free(pTS->aaOutput[iOut]);
  139531. pTS->aaOutput[iOut] = 0;
  139532. aMerge = aNew;
  139533. nMerge = nNew;
  139534. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  139535. pTS->aaOutput[iOut] = aMerge;
  139536. pTS->anOutput[iOut] = nMerge;
  139537. }
  139538. }
  139539. }
  139540. }
  139541. return SQLITE_OK;
  139542. }
  139543. /*
  139544. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  139545. */
  139546. static int fts3SegReaderCursorAppend(
  139547. Fts3MultiSegReader *pCsr,
  139548. Fts3SegReader *pNew
  139549. ){
  139550. if( (pCsr->nSegment%16)==0 ){
  139551. Fts3SegReader **apNew;
  139552. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  139553. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  139554. if( !apNew ){
  139555. sqlite3Fts3SegReaderFree(pNew);
  139556. return SQLITE_NOMEM;
  139557. }
  139558. pCsr->apSegment = apNew;
  139559. }
  139560. pCsr->apSegment[pCsr->nSegment++] = pNew;
  139561. return SQLITE_OK;
  139562. }
  139563. /*
  139564. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  139565. ** 8th argument.
  139566. **
  139567. ** This function returns SQLITE_OK if successful, or an SQLite error code
  139568. ** otherwise.
  139569. */
  139570. static int fts3SegReaderCursor(
  139571. Fts3Table *p, /* FTS3 table handle */
  139572. int iLangid, /* Language id */
  139573. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  139574. int iLevel, /* Level of segments to scan */
  139575. const char *zTerm, /* Term to query for */
  139576. int nTerm, /* Size of zTerm in bytes */
  139577. int isPrefix, /* True for a prefix search */
  139578. int isScan, /* True to scan from zTerm to EOF */
  139579. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  139580. ){
  139581. int rc = SQLITE_OK; /* Error code */
  139582. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  139583. int rc2; /* Result of sqlite3_reset() */
  139584. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  139585. ** for the pending-terms. If this is a scan, then this call must be being
  139586. ** made by an fts4aux module, not an FTS table. In this case calling
  139587. ** Fts3SegReaderPending might segfault, as the data structures used by
  139588. ** fts4aux are not completely populated. So it's easiest to filter these
  139589. ** calls out here. */
  139590. if( iLevel<0 && p->aIndex ){
  139591. Fts3SegReader *pSeg = 0;
  139592. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  139593. if( rc==SQLITE_OK && pSeg ){
  139594. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  139595. }
  139596. }
  139597. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  139598. if( rc==SQLITE_OK ){
  139599. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  139600. }
  139601. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  139602. Fts3SegReader *pSeg = 0;
  139603. /* Read the values returned by the SELECT into local variables. */
  139604. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  139605. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  139606. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  139607. int nRoot = sqlite3_column_bytes(pStmt, 4);
  139608. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  139609. /* If zTerm is not NULL, and this segment is not stored entirely on its
  139610. ** root node, the range of leaves scanned can be reduced. Do this. */
  139611. if( iStartBlock && zTerm ){
  139612. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  139613. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  139614. if( rc!=SQLITE_OK ) goto finished;
  139615. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  139616. }
  139617. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  139618. (isPrefix==0 && isScan==0),
  139619. iStartBlock, iLeavesEndBlock,
  139620. iEndBlock, zRoot, nRoot, &pSeg
  139621. );
  139622. if( rc!=SQLITE_OK ) goto finished;
  139623. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  139624. }
  139625. }
  139626. finished:
  139627. rc2 = sqlite3_reset(pStmt);
  139628. if( rc==SQLITE_DONE ) rc = rc2;
  139629. return rc;
  139630. }
  139631. /*
  139632. ** Set up a cursor object for iterating through a full-text index or a
  139633. ** single level therein.
  139634. */
  139635. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  139636. Fts3Table *p, /* FTS3 table handle */
  139637. int iLangid, /* Language-id to search */
  139638. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  139639. int iLevel, /* Level of segments to scan */
  139640. const char *zTerm, /* Term to query for */
  139641. int nTerm, /* Size of zTerm in bytes */
  139642. int isPrefix, /* True for a prefix search */
  139643. int isScan, /* True to scan from zTerm to EOF */
  139644. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  139645. ){
  139646. assert( iIndex>=0 && iIndex<p->nIndex );
  139647. assert( iLevel==FTS3_SEGCURSOR_ALL
  139648. || iLevel==FTS3_SEGCURSOR_PENDING
  139649. || iLevel>=0
  139650. );
  139651. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  139652. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  139653. assert( isPrefix==0 || isScan==0 );
  139654. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  139655. return fts3SegReaderCursor(
  139656. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  139657. );
  139658. }
  139659. /*
  139660. ** In addition to its current configuration, have the Fts3MultiSegReader
  139661. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  139662. **
  139663. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  139664. */
  139665. static int fts3SegReaderCursorAddZero(
  139666. Fts3Table *p, /* FTS virtual table handle */
  139667. int iLangid,
  139668. const char *zTerm, /* Term to scan doclist of */
  139669. int nTerm, /* Number of bytes in zTerm */
  139670. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  139671. ){
  139672. return fts3SegReaderCursor(p,
  139673. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  139674. );
  139675. }
  139676. /*
  139677. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  139678. ** if isPrefix is true, to scan the doclist for all terms for which
  139679. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  139680. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  139681. ** an SQLite error code.
  139682. **
  139683. ** It is the responsibility of the caller to free this object by eventually
  139684. ** passing it to fts3SegReaderCursorFree()
  139685. **
  139686. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  139687. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  139688. */
  139689. static int fts3TermSegReaderCursor(
  139690. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  139691. const char *zTerm, /* Term to query for */
  139692. int nTerm, /* Size of zTerm in bytes */
  139693. int isPrefix, /* True for a prefix search */
  139694. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  139695. ){
  139696. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  139697. int rc = SQLITE_NOMEM; /* Return code */
  139698. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  139699. if( pSegcsr ){
  139700. int i;
  139701. int bFound = 0; /* True once an index has been found */
  139702. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  139703. if( isPrefix ){
  139704. for(i=1; bFound==0 && i<p->nIndex; i++){
  139705. if( p->aIndex[i].nPrefix==nTerm ){
  139706. bFound = 1;
  139707. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  139708. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  139709. );
  139710. pSegcsr->bLookup = 1;
  139711. }
  139712. }
  139713. for(i=1; bFound==0 && i<p->nIndex; i++){
  139714. if( p->aIndex[i].nPrefix==nTerm+1 ){
  139715. bFound = 1;
  139716. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  139717. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  139718. );
  139719. if( rc==SQLITE_OK ){
  139720. rc = fts3SegReaderCursorAddZero(
  139721. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  139722. );
  139723. }
  139724. }
  139725. }
  139726. }
  139727. if( bFound==0 ){
  139728. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  139729. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  139730. );
  139731. pSegcsr->bLookup = !isPrefix;
  139732. }
  139733. }
  139734. *ppSegcsr = pSegcsr;
  139735. return rc;
  139736. }
  139737. /*
  139738. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  139739. */
  139740. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  139741. sqlite3Fts3SegReaderFinish(pSegcsr);
  139742. sqlite3_free(pSegcsr);
  139743. }
  139744. /*
  139745. ** This function retrieves the doclist for the specified term (or term
  139746. ** prefix) from the database.
  139747. */
  139748. static int fts3TermSelect(
  139749. Fts3Table *p, /* Virtual table handle */
  139750. Fts3PhraseToken *pTok, /* Token to query for */
  139751. int iColumn, /* Column to query (or -ve for all columns) */
  139752. int *pnOut, /* OUT: Size of buffer at *ppOut */
  139753. char **ppOut /* OUT: Malloced result buffer */
  139754. ){
  139755. int rc; /* Return code */
  139756. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  139757. TermSelect tsc; /* Object for pair-wise doclist merging */
  139758. Fts3SegFilter filter; /* Segment term filter configuration */
  139759. pSegcsr = pTok->pSegcsr;
  139760. memset(&tsc, 0, sizeof(TermSelect));
  139761. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  139762. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  139763. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  139764. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  139765. filter.iCol = iColumn;
  139766. filter.zTerm = pTok->z;
  139767. filter.nTerm = pTok->n;
  139768. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  139769. while( SQLITE_OK==rc
  139770. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  139771. ){
  139772. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  139773. }
  139774. if( rc==SQLITE_OK ){
  139775. rc = fts3TermSelectFinishMerge(p, &tsc);
  139776. }
  139777. if( rc==SQLITE_OK ){
  139778. *ppOut = tsc.aaOutput[0];
  139779. *pnOut = tsc.anOutput[0];
  139780. }else{
  139781. int i;
  139782. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  139783. sqlite3_free(tsc.aaOutput[i]);
  139784. }
  139785. }
  139786. fts3SegReaderCursorFree(pSegcsr);
  139787. pTok->pSegcsr = 0;
  139788. return rc;
  139789. }
  139790. /*
  139791. ** This function counts the total number of docids in the doclist stored
  139792. ** in buffer aList[], size nList bytes.
  139793. **
  139794. ** If the isPoslist argument is true, then it is assumed that the doclist
  139795. ** contains a position-list following each docid. Otherwise, it is assumed
  139796. ** that the doclist is simply a list of docids stored as delta encoded
  139797. ** varints.
  139798. */
  139799. static int fts3DoclistCountDocids(char *aList, int nList){
  139800. int nDoc = 0; /* Return value */
  139801. if( aList ){
  139802. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  139803. char *p = aList; /* Cursor */
  139804. while( p<aEnd ){
  139805. nDoc++;
  139806. while( (*p++)&0x80 ); /* Skip docid varint */
  139807. fts3PoslistCopy(0, &p); /* Skip over position list */
  139808. }
  139809. }
  139810. return nDoc;
  139811. }
  139812. /*
  139813. ** Advance the cursor to the next row in the %_content table that
  139814. ** matches the search criteria. For a MATCH search, this will be
  139815. ** the next row that matches. For a full-table scan, this will be
  139816. ** simply the next row in the %_content table. For a docid lookup,
  139817. ** this routine simply sets the EOF flag.
  139818. **
  139819. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  139820. ** even if we reach end-of-file. The fts3EofMethod() will be called
  139821. ** subsequently to determine whether or not an EOF was hit.
  139822. */
  139823. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  139824. int rc;
  139825. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  139826. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  139827. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  139828. pCsr->isEof = 1;
  139829. rc = sqlite3_reset(pCsr->pStmt);
  139830. }else{
  139831. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  139832. rc = SQLITE_OK;
  139833. }
  139834. }else{
  139835. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  139836. }
  139837. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  139838. return rc;
  139839. }
  139840. /*
  139841. ** The following are copied from sqliteInt.h.
  139842. **
  139843. ** Constants for the largest and smallest possible 64-bit signed integers.
  139844. ** These macros are designed to work correctly on both 32-bit and 64-bit
  139845. ** compilers.
  139846. */
  139847. #ifndef SQLITE_AMALGAMATION
  139848. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  139849. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  139850. #endif
  139851. /*
  139852. ** If the numeric type of argument pVal is "integer", then return it
  139853. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  139854. ** the second parameter, iDefault.
  139855. */
  139856. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  139857. if( pVal ){
  139858. int eType = sqlite3_value_numeric_type(pVal);
  139859. if( eType==SQLITE_INTEGER ){
  139860. return sqlite3_value_int64(pVal);
  139861. }
  139862. }
  139863. return iDefault;
  139864. }
  139865. /*
  139866. ** This is the xFilter interface for the virtual table. See
  139867. ** the virtual table xFilter method documentation for additional
  139868. ** information.
  139869. **
  139870. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  139871. ** the %_content table.
  139872. **
  139873. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  139874. ** in the %_content table.
  139875. **
  139876. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  139877. ** column on the left-hand side of the MATCH operator is column
  139878. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  139879. ** side of the MATCH operator.
  139880. */
  139881. static int fts3FilterMethod(
  139882. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  139883. int idxNum, /* Strategy index */
  139884. const char *idxStr, /* Unused */
  139885. int nVal, /* Number of elements in apVal */
  139886. sqlite3_value **apVal /* Arguments for the indexing scheme */
  139887. ){
  139888. int rc = SQLITE_OK;
  139889. char *zSql; /* SQL statement used to access %_content */
  139890. int eSearch;
  139891. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  139892. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  139893. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  139894. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  139895. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  139896. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  139897. int iIdx;
  139898. UNUSED_PARAMETER(idxStr);
  139899. UNUSED_PARAMETER(nVal);
  139900. eSearch = (idxNum & 0x0000FFFF);
  139901. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  139902. assert( p->pSegments==0 );
  139903. /* Collect arguments into local variables */
  139904. iIdx = 0;
  139905. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  139906. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  139907. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  139908. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  139909. assert( iIdx==nVal );
  139910. /* In case the cursor has been used before, clear it now. */
  139911. fts3CursorFinalizeStmt(pCsr);
  139912. sqlite3_free(pCsr->aDoclist);
  139913. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  139914. sqlite3Fts3ExprFree(pCsr->pExpr);
  139915. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  139916. /* Set the lower and upper bounds on docids to return */
  139917. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  139918. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  139919. if( idxStr ){
  139920. pCsr->bDesc = (idxStr[0]=='D');
  139921. }else{
  139922. pCsr->bDesc = p->bDescIdx;
  139923. }
  139924. pCsr->eSearch = (i16)eSearch;
  139925. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  139926. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  139927. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  139928. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  139929. return SQLITE_NOMEM;
  139930. }
  139931. pCsr->iLangid = 0;
  139932. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  139933. assert( p->base.zErrMsg==0 );
  139934. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  139935. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  139936. &p->base.zErrMsg
  139937. );
  139938. if( rc!=SQLITE_OK ){
  139939. return rc;
  139940. }
  139941. rc = fts3EvalStart(pCsr);
  139942. sqlite3Fts3SegmentsClose(p);
  139943. if( rc!=SQLITE_OK ) return rc;
  139944. pCsr->pNextId = pCsr->aDoclist;
  139945. pCsr->iPrevId = 0;
  139946. }
  139947. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  139948. ** statement loops through all rows of the %_content table. For a
  139949. ** full-text query or docid lookup, the statement retrieves a single
  139950. ** row by docid.
  139951. */
  139952. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  139953. if( pDocidGe || pDocidLe ){
  139954. zSql = sqlite3_mprintf(
  139955. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  139956. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  139957. (pCsr->bDesc ? "DESC" : "ASC")
  139958. );
  139959. }else{
  139960. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  139961. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  139962. );
  139963. }
  139964. if( zSql ){
  139965. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  139966. sqlite3_free(zSql);
  139967. }else{
  139968. rc = SQLITE_NOMEM;
  139969. }
  139970. }else if( eSearch==FTS3_DOCID_SEARCH ){
  139971. rc = fts3CursorSeekStmt(pCsr);
  139972. if( rc==SQLITE_OK ){
  139973. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  139974. }
  139975. }
  139976. if( rc!=SQLITE_OK ) return rc;
  139977. return fts3NextMethod(pCursor);
  139978. }
  139979. /*
  139980. ** This is the xEof method of the virtual table. SQLite calls this
  139981. ** routine to find out if it has reached the end of a result set.
  139982. */
  139983. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  139984. return ((Fts3Cursor *)pCursor)->isEof;
  139985. }
  139986. /*
  139987. ** This is the xRowid method. The SQLite core calls this routine to
  139988. ** retrieve the rowid for the current row of the result set. fts3
  139989. ** exposes %_content.docid as the rowid for the virtual table. The
  139990. ** rowid should be written to *pRowid.
  139991. */
  139992. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  139993. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  139994. *pRowid = pCsr->iPrevId;
  139995. return SQLITE_OK;
  139996. }
  139997. /*
  139998. ** This is the xColumn method, called by SQLite to request a value from
  139999. ** the row that the supplied cursor currently points to.
  140000. **
  140001. ** If:
  140002. **
  140003. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  140004. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  140005. ** (iCol == p->nColumn+1) -> Docid column
  140006. ** (iCol == p->nColumn+2) -> Langid column
  140007. */
  140008. static int fts3ColumnMethod(
  140009. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  140010. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  140011. int iCol /* Index of column to read value from */
  140012. ){
  140013. int rc = SQLITE_OK; /* Return Code */
  140014. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  140015. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  140016. /* The column value supplied by SQLite must be in range. */
  140017. assert( iCol>=0 && iCol<=p->nColumn+2 );
  140018. switch( iCol-p->nColumn ){
  140019. case 0:
  140020. /* The special 'table-name' column */
  140021. sqlite3_result_blob(pCtx, &pCsr, sizeof(Fts3Cursor*), SQLITE_TRANSIENT);
  140022. sqlite3_result_subtype(pCtx, SQLITE_BLOB);
  140023. break;
  140024. case 1:
  140025. /* The docid column */
  140026. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  140027. break;
  140028. case 2:
  140029. if( pCsr->pExpr ){
  140030. sqlite3_result_int64(pCtx, pCsr->iLangid);
  140031. break;
  140032. }else if( p->zLanguageid==0 ){
  140033. sqlite3_result_int(pCtx, 0);
  140034. break;
  140035. }else{
  140036. iCol = p->nColumn;
  140037. /* fall-through */
  140038. }
  140039. default:
  140040. /* A user column. Or, if this is a full-table scan, possibly the
  140041. ** language-id column. Seek the cursor. */
  140042. rc = fts3CursorSeek(0, pCsr);
  140043. if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
  140044. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  140045. }
  140046. break;
  140047. }
  140048. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  140049. return rc;
  140050. }
  140051. /*
  140052. ** This function is the implementation of the xUpdate callback used by
  140053. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  140054. ** inserted, updated or deleted.
  140055. */
  140056. static int fts3UpdateMethod(
  140057. sqlite3_vtab *pVtab, /* Virtual table handle */
  140058. int nArg, /* Size of argument array */
  140059. sqlite3_value **apVal, /* Array of arguments */
  140060. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  140061. ){
  140062. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  140063. }
  140064. /*
  140065. ** Implementation of xSync() method. Flush the contents of the pending-terms
  140066. ** hash-table to the database.
  140067. */
  140068. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  140069. /* Following an incremental-merge operation, assuming that the input
  140070. ** segments are not completely consumed (the usual case), they are updated
  140071. ** in place to remove the entries that have already been merged. This
  140072. ** involves updating the leaf block that contains the smallest unmerged
  140073. ** entry and each block (if any) between the leaf and the root node. So
  140074. ** if the height of the input segment b-trees is N, and input segments
  140075. ** are merged eight at a time, updating the input segments at the end
  140076. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  140077. ** small - often between 0 and 2. So the overhead of the incremental
  140078. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  140079. ** dwarfing the actual productive work accomplished, the incremental merge
  140080. ** is only attempted if it will write at least 64 leaf blocks. Hence
  140081. ** nMinMerge.
  140082. **
  140083. ** Of course, updating the input segments also involves deleting a bunch
  140084. ** of blocks from the segments table. But this is not considered overhead
  140085. ** as it would also be required by a crisis-merge that used the same input
  140086. ** segments.
  140087. */
  140088. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  140089. Fts3Table *p = (Fts3Table*)pVtab;
  140090. int rc;
  140091. i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
  140092. rc = sqlite3Fts3PendingTermsFlush(p);
  140093. if( rc==SQLITE_OK
  140094. && p->nLeafAdd>(nMinMerge/16)
  140095. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  140096. ){
  140097. int mxLevel = 0; /* Maximum relative level value in db */
  140098. int A; /* Incr-merge parameter A */
  140099. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  140100. assert( rc==SQLITE_OK || mxLevel==0 );
  140101. A = p->nLeafAdd * mxLevel;
  140102. A += (A/2);
  140103. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  140104. }
  140105. sqlite3Fts3SegmentsClose(p);
  140106. sqlite3_set_last_insert_rowid(p->db, iLastRowid);
  140107. return rc;
  140108. }
  140109. /*
  140110. ** If it is currently unknown whether or not the FTS table has an %_stat
  140111. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  140112. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  140113. ** if an error occurs.
  140114. */
  140115. static int fts3SetHasStat(Fts3Table *p){
  140116. int rc = SQLITE_OK;
  140117. if( p->bHasStat==2 ){
  140118. char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
  140119. if( zTbl ){
  140120. int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
  140121. sqlite3_free(zTbl);
  140122. p->bHasStat = (res==SQLITE_OK);
  140123. }else{
  140124. rc = SQLITE_NOMEM;
  140125. }
  140126. }
  140127. return rc;
  140128. }
  140129. /*
  140130. ** Implementation of xBegin() method.
  140131. */
  140132. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  140133. Fts3Table *p = (Fts3Table*)pVtab;
  140134. UNUSED_PARAMETER(pVtab);
  140135. assert( p->pSegments==0 );
  140136. assert( p->nPendingData==0 );
  140137. assert( p->inTransaction!=1 );
  140138. TESTONLY( p->inTransaction = 1 );
  140139. TESTONLY( p->mxSavepoint = -1; );
  140140. p->nLeafAdd = 0;
  140141. return fts3SetHasStat(p);
  140142. }
  140143. /*
  140144. ** Implementation of xCommit() method. This is a no-op. The contents of
  140145. ** the pending-terms hash-table have already been flushed into the database
  140146. ** by fts3SyncMethod().
  140147. */
  140148. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  140149. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  140150. UNUSED_PARAMETER(pVtab);
  140151. assert( p->nPendingData==0 );
  140152. assert( p->inTransaction!=0 );
  140153. assert( p->pSegments==0 );
  140154. TESTONLY( p->inTransaction = 0 );
  140155. TESTONLY( p->mxSavepoint = -1; );
  140156. return SQLITE_OK;
  140157. }
  140158. /*
  140159. ** Implementation of xRollback(). Discard the contents of the pending-terms
  140160. ** hash-table. Any changes made to the database are reverted by SQLite.
  140161. */
  140162. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  140163. Fts3Table *p = (Fts3Table*)pVtab;
  140164. sqlite3Fts3PendingTermsClear(p);
  140165. assert( p->inTransaction!=0 );
  140166. TESTONLY( p->inTransaction = 0 );
  140167. TESTONLY( p->mxSavepoint = -1; );
  140168. return SQLITE_OK;
  140169. }
  140170. /*
  140171. ** When called, *ppPoslist must point to the byte immediately following the
  140172. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  140173. ** moves *ppPoslist so that it instead points to the first byte of the
  140174. ** same position list.
  140175. */
  140176. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  140177. char *p = &(*ppPoslist)[-2];
  140178. char c = 0;
  140179. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  140180. while( p>pStart && (c=*p--)==0 );
  140181. /* Search backwards for a varint with value zero (the end of the previous
  140182. ** poslist). This is an 0x00 byte preceded by some byte that does not
  140183. ** have the 0x80 bit set. */
  140184. while( p>pStart && (*p & 0x80) | c ){
  140185. c = *p--;
  140186. }
  140187. assert( p==pStart || c==0 );
  140188. /* At this point p points to that preceding byte without the 0x80 bit
  140189. ** set. So to find the start of the poslist, skip forward 2 bytes then
  140190. ** over a varint.
  140191. **
  140192. ** Normally. The other case is that p==pStart and the poslist to return
  140193. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  140194. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  140195. ** is required for cases where the first byte of a doclist and the
  140196. ** doclist is empty. For example, if the first docid is 10, a doclist
  140197. ** that begins with:
  140198. **
  140199. ** 0x0A 0x00 <next docid delta varint>
  140200. */
  140201. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  140202. while( *p++&0x80 );
  140203. *ppPoslist = p;
  140204. }
  140205. /*
  140206. ** Helper function used by the implementation of the overloaded snippet(),
  140207. ** offsets() and optimize() SQL functions.
  140208. **
  140209. ** If the value passed as the third argument is a blob of size
  140210. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  140211. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  140212. ** message is written to context pContext and SQLITE_ERROR returned. The
  140213. ** string passed via zFunc is used as part of the error message.
  140214. */
  140215. static int fts3FunctionArg(
  140216. sqlite3_context *pContext, /* SQL function call context */
  140217. const char *zFunc, /* Function name */
  140218. sqlite3_value *pVal, /* argv[0] passed to function */
  140219. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  140220. ){
  140221. int rc = SQLITE_OK;
  140222. if( sqlite3_value_subtype(pVal)==SQLITE_BLOB ){
  140223. *ppCsr = *(Fts3Cursor**)sqlite3_value_blob(pVal);
  140224. }else{
  140225. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  140226. sqlite3_result_error(pContext, zErr, -1);
  140227. sqlite3_free(zErr);
  140228. rc = SQLITE_ERROR;
  140229. }
  140230. return rc;
  140231. }
  140232. /*
  140233. ** Implementation of the snippet() function for FTS3
  140234. */
  140235. static void fts3SnippetFunc(
  140236. sqlite3_context *pContext, /* SQLite function call context */
  140237. int nVal, /* Size of apVal[] array */
  140238. sqlite3_value **apVal /* Array of arguments */
  140239. ){
  140240. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  140241. const char *zStart = "<b>";
  140242. const char *zEnd = "</b>";
  140243. const char *zEllipsis = "<b>...</b>";
  140244. int iCol = -1;
  140245. int nToken = 15; /* Default number of tokens in snippet */
  140246. /* There must be at least one argument passed to this function (otherwise
  140247. ** the non-overloaded version would have been called instead of this one).
  140248. */
  140249. assert( nVal>=1 );
  140250. if( nVal>6 ){
  140251. sqlite3_result_error(pContext,
  140252. "wrong number of arguments to function snippet()", -1);
  140253. return;
  140254. }
  140255. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  140256. switch( nVal ){
  140257. case 6: nToken = sqlite3_value_int(apVal[5]);
  140258. case 5: iCol = sqlite3_value_int(apVal[4]);
  140259. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  140260. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  140261. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  140262. }
  140263. if( !zEllipsis || !zEnd || !zStart ){
  140264. sqlite3_result_error_nomem(pContext);
  140265. }else if( nToken==0 ){
  140266. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  140267. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  140268. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  140269. }
  140270. }
  140271. /*
  140272. ** Implementation of the offsets() function for FTS3
  140273. */
  140274. static void fts3OffsetsFunc(
  140275. sqlite3_context *pContext, /* SQLite function call context */
  140276. int nVal, /* Size of argument array */
  140277. sqlite3_value **apVal /* Array of arguments */
  140278. ){
  140279. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  140280. UNUSED_PARAMETER(nVal);
  140281. assert( nVal==1 );
  140282. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  140283. assert( pCsr );
  140284. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  140285. sqlite3Fts3Offsets(pContext, pCsr);
  140286. }
  140287. }
  140288. /*
  140289. ** Implementation of the special optimize() function for FTS3. This
  140290. ** function merges all segments in the database to a single segment.
  140291. ** Example usage is:
  140292. **
  140293. ** SELECT optimize(t) FROM t LIMIT 1;
  140294. **
  140295. ** where 't' is the name of an FTS3 table.
  140296. */
  140297. static void fts3OptimizeFunc(
  140298. sqlite3_context *pContext, /* SQLite function call context */
  140299. int nVal, /* Size of argument array */
  140300. sqlite3_value **apVal /* Array of arguments */
  140301. ){
  140302. int rc; /* Return code */
  140303. Fts3Table *p; /* Virtual table handle */
  140304. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  140305. UNUSED_PARAMETER(nVal);
  140306. assert( nVal==1 );
  140307. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  140308. p = (Fts3Table *)pCursor->base.pVtab;
  140309. assert( p );
  140310. rc = sqlite3Fts3Optimize(p);
  140311. switch( rc ){
  140312. case SQLITE_OK:
  140313. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  140314. break;
  140315. case SQLITE_DONE:
  140316. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  140317. break;
  140318. default:
  140319. sqlite3_result_error_code(pContext, rc);
  140320. break;
  140321. }
  140322. }
  140323. /*
  140324. ** Implementation of the matchinfo() function for FTS3
  140325. */
  140326. static void fts3MatchinfoFunc(
  140327. sqlite3_context *pContext, /* SQLite function call context */
  140328. int nVal, /* Size of argument array */
  140329. sqlite3_value **apVal /* Array of arguments */
  140330. ){
  140331. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  140332. assert( nVal==1 || nVal==2 );
  140333. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  140334. const char *zArg = 0;
  140335. if( nVal>1 ){
  140336. zArg = (const char *)sqlite3_value_text(apVal[1]);
  140337. }
  140338. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  140339. }
  140340. }
  140341. /*
  140342. ** This routine implements the xFindFunction method for the FTS3
  140343. ** virtual table.
  140344. */
  140345. static int fts3FindFunctionMethod(
  140346. sqlite3_vtab *pVtab, /* Virtual table handle */
  140347. int nArg, /* Number of SQL function arguments */
  140348. const char *zName, /* Name of SQL function */
  140349. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  140350. void **ppArg /* Unused */
  140351. ){
  140352. struct Overloaded {
  140353. const char *zName;
  140354. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  140355. } aOverload[] = {
  140356. { "snippet", fts3SnippetFunc },
  140357. { "offsets", fts3OffsetsFunc },
  140358. { "optimize", fts3OptimizeFunc },
  140359. { "matchinfo", fts3MatchinfoFunc },
  140360. };
  140361. int i; /* Iterator variable */
  140362. UNUSED_PARAMETER(pVtab);
  140363. UNUSED_PARAMETER(nArg);
  140364. UNUSED_PARAMETER(ppArg);
  140365. for(i=0; i<SizeofArray(aOverload); i++){
  140366. if( strcmp(zName, aOverload[i].zName)==0 ){
  140367. *pxFunc = aOverload[i].xFunc;
  140368. return 1;
  140369. }
  140370. }
  140371. /* No function of the specified name was found. Return 0. */
  140372. return 0;
  140373. }
  140374. /*
  140375. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  140376. */
  140377. static int fts3RenameMethod(
  140378. sqlite3_vtab *pVtab, /* Virtual table handle */
  140379. const char *zName /* New name of table */
  140380. ){
  140381. Fts3Table *p = (Fts3Table *)pVtab;
  140382. sqlite3 *db = p->db; /* Database connection */
  140383. int rc; /* Return Code */
  140384. /* At this point it must be known if the %_stat table exists or not.
  140385. ** So bHasStat may not be 2. */
  140386. rc = fts3SetHasStat(p);
  140387. /* As it happens, the pending terms table is always empty here. This is
  140388. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  140389. ** always opens a savepoint transaction. And the xSavepoint() method
  140390. ** flushes the pending terms table. But leave the (no-op) call to
  140391. ** PendingTermsFlush() in in case that changes.
  140392. */
  140393. assert( p->nPendingData==0 );
  140394. if( rc==SQLITE_OK ){
  140395. rc = sqlite3Fts3PendingTermsFlush(p);
  140396. }
  140397. if( p->zContentTbl==0 ){
  140398. fts3DbExec(&rc, db,
  140399. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  140400. p->zDb, p->zName, zName
  140401. );
  140402. }
  140403. if( p->bHasDocsize ){
  140404. fts3DbExec(&rc, db,
  140405. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  140406. p->zDb, p->zName, zName
  140407. );
  140408. }
  140409. if( p->bHasStat ){
  140410. fts3DbExec(&rc, db,
  140411. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  140412. p->zDb, p->zName, zName
  140413. );
  140414. }
  140415. fts3DbExec(&rc, db,
  140416. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  140417. p->zDb, p->zName, zName
  140418. );
  140419. fts3DbExec(&rc, db,
  140420. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  140421. p->zDb, p->zName, zName
  140422. );
  140423. return rc;
  140424. }
  140425. /*
  140426. ** The xSavepoint() method.
  140427. **
  140428. ** Flush the contents of the pending-terms table to disk.
  140429. */
  140430. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  140431. int rc = SQLITE_OK;
  140432. UNUSED_PARAMETER(iSavepoint);
  140433. assert( ((Fts3Table *)pVtab)->inTransaction );
  140434. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  140435. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  140436. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  140437. rc = fts3SyncMethod(pVtab);
  140438. }
  140439. return rc;
  140440. }
  140441. /*
  140442. ** The xRelease() method.
  140443. **
  140444. ** This is a no-op.
  140445. */
  140446. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  140447. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  140448. UNUSED_PARAMETER(iSavepoint);
  140449. UNUSED_PARAMETER(pVtab);
  140450. assert( p->inTransaction );
  140451. assert( p->mxSavepoint >= iSavepoint );
  140452. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  140453. return SQLITE_OK;
  140454. }
  140455. /*
  140456. ** The xRollbackTo() method.
  140457. **
  140458. ** Discard the contents of the pending terms table.
  140459. */
  140460. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  140461. Fts3Table *p = (Fts3Table*)pVtab;
  140462. UNUSED_PARAMETER(iSavepoint);
  140463. assert( p->inTransaction );
  140464. assert( p->mxSavepoint >= iSavepoint );
  140465. TESTONLY( p->mxSavepoint = iSavepoint );
  140466. sqlite3Fts3PendingTermsClear(p);
  140467. return SQLITE_OK;
  140468. }
  140469. static const sqlite3_module fts3Module = {
  140470. /* iVersion */ 2,
  140471. /* xCreate */ fts3CreateMethod,
  140472. /* xConnect */ fts3ConnectMethod,
  140473. /* xBestIndex */ fts3BestIndexMethod,
  140474. /* xDisconnect */ fts3DisconnectMethod,
  140475. /* xDestroy */ fts3DestroyMethod,
  140476. /* xOpen */ fts3OpenMethod,
  140477. /* xClose */ fts3CloseMethod,
  140478. /* xFilter */ fts3FilterMethod,
  140479. /* xNext */ fts3NextMethod,
  140480. /* xEof */ fts3EofMethod,
  140481. /* xColumn */ fts3ColumnMethod,
  140482. /* xRowid */ fts3RowidMethod,
  140483. /* xUpdate */ fts3UpdateMethod,
  140484. /* xBegin */ fts3BeginMethod,
  140485. /* xSync */ fts3SyncMethod,
  140486. /* xCommit */ fts3CommitMethod,
  140487. /* xRollback */ fts3RollbackMethod,
  140488. /* xFindFunction */ fts3FindFunctionMethod,
  140489. /* xRename */ fts3RenameMethod,
  140490. /* xSavepoint */ fts3SavepointMethod,
  140491. /* xRelease */ fts3ReleaseMethod,
  140492. /* xRollbackTo */ fts3RollbackToMethod,
  140493. };
  140494. /*
  140495. ** This function is registered as the module destructor (called when an
  140496. ** FTS3 enabled database connection is closed). It frees the memory
  140497. ** allocated for the tokenizer hash table.
  140498. */
  140499. static void hashDestroy(void *p){
  140500. Fts3Hash *pHash = (Fts3Hash *)p;
  140501. sqlite3Fts3HashClear(pHash);
  140502. sqlite3_free(pHash);
  140503. }
  140504. /*
  140505. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  140506. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  140507. ** respectively. The following three forward declarations are for functions
  140508. ** declared in these files used to retrieve the respective implementations.
  140509. **
  140510. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  140511. ** to by the argument to point to the "simple" tokenizer implementation.
  140512. ** And so on.
  140513. */
  140514. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  140515. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  140516. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140517. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  140518. #endif
  140519. #ifdef SQLITE_ENABLE_ICU
  140520. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  140521. #endif
  140522. /*
  140523. ** Initialize the fts3 extension. If this extension is built as part
  140524. ** of the sqlite library, then this function is called directly by
  140525. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  140526. ** function is called by the sqlite3_extension_init() entry point.
  140527. */
  140528. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  140529. int rc = SQLITE_OK;
  140530. Fts3Hash *pHash = 0;
  140531. const sqlite3_tokenizer_module *pSimple = 0;
  140532. const sqlite3_tokenizer_module *pPorter = 0;
  140533. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140534. const sqlite3_tokenizer_module *pUnicode = 0;
  140535. #endif
  140536. #ifdef SQLITE_ENABLE_ICU
  140537. const sqlite3_tokenizer_module *pIcu = 0;
  140538. sqlite3Fts3IcuTokenizerModule(&pIcu);
  140539. #endif
  140540. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140541. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  140542. #endif
  140543. #ifdef SQLITE_TEST
  140544. rc = sqlite3Fts3InitTerm(db);
  140545. if( rc!=SQLITE_OK ) return rc;
  140546. #endif
  140547. rc = sqlite3Fts3InitAux(db);
  140548. if( rc!=SQLITE_OK ) return rc;
  140549. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  140550. sqlite3Fts3PorterTokenizerModule(&pPorter);
  140551. /* Allocate and initialize the hash-table used to store tokenizers. */
  140552. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  140553. if( !pHash ){
  140554. rc = SQLITE_NOMEM;
  140555. }else{
  140556. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  140557. }
  140558. /* Load the built-in tokenizers into the hash table */
  140559. if( rc==SQLITE_OK ){
  140560. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  140561. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  140562. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140563. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  140564. #endif
  140565. #ifdef SQLITE_ENABLE_ICU
  140566. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  140567. #endif
  140568. ){
  140569. rc = SQLITE_NOMEM;
  140570. }
  140571. }
  140572. #ifdef SQLITE_TEST
  140573. if( rc==SQLITE_OK ){
  140574. rc = sqlite3Fts3ExprInitTestInterface(db);
  140575. }
  140576. #endif
  140577. /* Create the virtual table wrapper around the hash-table and overload
  140578. ** the four scalar functions. If this is successful, register the
  140579. ** module with sqlite.
  140580. */
  140581. if( SQLITE_OK==rc
  140582. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  140583. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  140584. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  140585. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  140586. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  140587. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  140588. ){
  140589. rc = sqlite3_create_module_v2(
  140590. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  140591. );
  140592. if( rc==SQLITE_OK ){
  140593. rc = sqlite3_create_module_v2(
  140594. db, "fts4", &fts3Module, (void *)pHash, 0
  140595. );
  140596. }
  140597. if( rc==SQLITE_OK ){
  140598. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  140599. }
  140600. return rc;
  140601. }
  140602. /* An error has occurred. Delete the hash table and return the error code. */
  140603. assert( rc!=SQLITE_OK );
  140604. if( pHash ){
  140605. sqlite3Fts3HashClear(pHash);
  140606. sqlite3_free(pHash);
  140607. }
  140608. return rc;
  140609. }
  140610. /*
  140611. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  140612. ** by pExpr.
  140613. **
  140614. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  140615. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  140616. ** Fts3SegReader objects internally to provide an interface to seek or scan
  140617. ** within the union of all segments of a b-tree. Hence the name.
  140618. **
  140619. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  140620. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  140621. ** there exists prefix b-tree of the right length) then it may be traversed
  140622. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  140623. ** doclist and then traversed.
  140624. */
  140625. static void fts3EvalAllocateReaders(
  140626. Fts3Cursor *pCsr, /* FTS cursor handle */
  140627. Fts3Expr *pExpr, /* Allocate readers for this expression */
  140628. int *pnToken, /* OUT: Total number of tokens in phrase. */
  140629. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  140630. int *pRc /* IN/OUT: Error code */
  140631. ){
  140632. if( pExpr && SQLITE_OK==*pRc ){
  140633. if( pExpr->eType==FTSQUERY_PHRASE ){
  140634. int i;
  140635. int nToken = pExpr->pPhrase->nToken;
  140636. *pnToken += nToken;
  140637. for(i=0; i<nToken; i++){
  140638. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  140639. int rc = fts3TermSegReaderCursor(pCsr,
  140640. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  140641. );
  140642. if( rc!=SQLITE_OK ){
  140643. *pRc = rc;
  140644. return;
  140645. }
  140646. }
  140647. assert( pExpr->pPhrase->iDoclistToken==0 );
  140648. pExpr->pPhrase->iDoclistToken = -1;
  140649. }else{
  140650. *pnOr += (pExpr->eType==FTSQUERY_OR);
  140651. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  140652. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  140653. }
  140654. }
  140655. }
  140656. /*
  140657. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  140658. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  140659. **
  140660. ** This function assumes that pList points to a buffer allocated using
  140661. ** sqlite3_malloc(). This function takes responsibility for eventually
  140662. ** freeing the buffer.
  140663. **
  140664. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  140665. */
  140666. static int fts3EvalPhraseMergeToken(
  140667. Fts3Table *pTab, /* FTS Table pointer */
  140668. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  140669. int iToken, /* Token pList/nList corresponds to */
  140670. char *pList, /* Pointer to doclist */
  140671. int nList /* Number of bytes in pList */
  140672. ){
  140673. int rc = SQLITE_OK;
  140674. assert( iToken!=p->iDoclistToken );
  140675. if( pList==0 ){
  140676. sqlite3_free(p->doclist.aAll);
  140677. p->doclist.aAll = 0;
  140678. p->doclist.nAll = 0;
  140679. }
  140680. else if( p->iDoclistToken<0 ){
  140681. p->doclist.aAll = pList;
  140682. p->doclist.nAll = nList;
  140683. }
  140684. else if( p->doclist.aAll==0 ){
  140685. sqlite3_free(pList);
  140686. }
  140687. else {
  140688. char *pLeft;
  140689. char *pRight;
  140690. int nLeft;
  140691. int nRight;
  140692. int nDiff;
  140693. if( p->iDoclistToken<iToken ){
  140694. pLeft = p->doclist.aAll;
  140695. nLeft = p->doclist.nAll;
  140696. pRight = pList;
  140697. nRight = nList;
  140698. nDiff = iToken - p->iDoclistToken;
  140699. }else{
  140700. pRight = p->doclist.aAll;
  140701. nRight = p->doclist.nAll;
  140702. pLeft = pList;
  140703. nLeft = nList;
  140704. nDiff = p->iDoclistToken - iToken;
  140705. }
  140706. rc = fts3DoclistPhraseMerge(
  140707. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  140708. );
  140709. sqlite3_free(pLeft);
  140710. p->doclist.aAll = pRight;
  140711. p->doclist.nAll = nRight;
  140712. }
  140713. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  140714. return rc;
  140715. }
  140716. /*
  140717. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  140718. ** does not take deferred tokens into account.
  140719. **
  140720. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  140721. */
  140722. static int fts3EvalPhraseLoad(
  140723. Fts3Cursor *pCsr, /* FTS Cursor handle */
  140724. Fts3Phrase *p /* Phrase object */
  140725. ){
  140726. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  140727. int iToken;
  140728. int rc = SQLITE_OK;
  140729. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  140730. Fts3PhraseToken *pToken = &p->aToken[iToken];
  140731. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  140732. if( pToken->pSegcsr ){
  140733. int nThis = 0;
  140734. char *pThis = 0;
  140735. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  140736. if( rc==SQLITE_OK ){
  140737. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  140738. }
  140739. }
  140740. assert( pToken->pSegcsr==0 );
  140741. }
  140742. return rc;
  140743. }
  140744. /*
  140745. ** This function is called on each phrase after the position lists for
  140746. ** any deferred tokens have been loaded into memory. It updates the phrases
  140747. ** current position list to include only those positions that are really
  140748. ** instances of the phrase (after considering deferred tokens). If this
  140749. ** means that the phrase does not appear in the current row, doclist.pList
  140750. ** and doclist.nList are both zeroed.
  140751. **
  140752. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  140753. */
  140754. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  140755. int iToken; /* Used to iterate through phrase tokens */
  140756. char *aPoslist = 0; /* Position list for deferred tokens */
  140757. int nPoslist = 0; /* Number of bytes in aPoslist */
  140758. int iPrev = -1; /* Token number of previous deferred token */
  140759. assert( pPhrase->doclist.bFreeList==0 );
  140760. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  140761. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  140762. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  140763. if( pDeferred ){
  140764. char *pList;
  140765. int nList;
  140766. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  140767. if( rc!=SQLITE_OK ) return rc;
  140768. if( pList==0 ){
  140769. sqlite3_free(aPoslist);
  140770. pPhrase->doclist.pList = 0;
  140771. pPhrase->doclist.nList = 0;
  140772. return SQLITE_OK;
  140773. }else if( aPoslist==0 ){
  140774. aPoslist = pList;
  140775. nPoslist = nList;
  140776. }else{
  140777. char *aOut = pList;
  140778. char *p1 = aPoslist;
  140779. char *p2 = aOut;
  140780. assert( iPrev>=0 );
  140781. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  140782. sqlite3_free(aPoslist);
  140783. aPoslist = pList;
  140784. nPoslist = (int)(aOut - aPoslist);
  140785. if( nPoslist==0 ){
  140786. sqlite3_free(aPoslist);
  140787. pPhrase->doclist.pList = 0;
  140788. pPhrase->doclist.nList = 0;
  140789. return SQLITE_OK;
  140790. }
  140791. }
  140792. iPrev = iToken;
  140793. }
  140794. }
  140795. if( iPrev>=0 ){
  140796. int nMaxUndeferred = pPhrase->iDoclistToken;
  140797. if( nMaxUndeferred<0 ){
  140798. pPhrase->doclist.pList = aPoslist;
  140799. pPhrase->doclist.nList = nPoslist;
  140800. pPhrase->doclist.iDocid = pCsr->iPrevId;
  140801. pPhrase->doclist.bFreeList = 1;
  140802. }else{
  140803. int nDistance;
  140804. char *p1;
  140805. char *p2;
  140806. char *aOut;
  140807. if( nMaxUndeferred>iPrev ){
  140808. p1 = aPoslist;
  140809. p2 = pPhrase->doclist.pList;
  140810. nDistance = nMaxUndeferred - iPrev;
  140811. }else{
  140812. p1 = pPhrase->doclist.pList;
  140813. p2 = aPoslist;
  140814. nDistance = iPrev - nMaxUndeferred;
  140815. }
  140816. aOut = (char *)sqlite3_malloc(nPoslist+8);
  140817. if( !aOut ){
  140818. sqlite3_free(aPoslist);
  140819. return SQLITE_NOMEM;
  140820. }
  140821. pPhrase->doclist.pList = aOut;
  140822. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  140823. pPhrase->doclist.bFreeList = 1;
  140824. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  140825. }else{
  140826. sqlite3_free(aOut);
  140827. pPhrase->doclist.pList = 0;
  140828. pPhrase->doclist.nList = 0;
  140829. }
  140830. sqlite3_free(aPoslist);
  140831. }
  140832. }
  140833. return SQLITE_OK;
  140834. }
  140835. /*
  140836. ** Maximum number of tokens a phrase may have to be considered for the
  140837. ** incremental doclists strategy.
  140838. */
  140839. #define MAX_INCR_PHRASE_TOKENS 4
  140840. /*
  140841. ** This function is called for each Fts3Phrase in a full-text query
  140842. ** expression to initialize the mechanism for returning rows. Once this
  140843. ** function has been called successfully on an Fts3Phrase, it may be
  140844. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  140845. **
  140846. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  140847. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  140848. ** memory within this call.
  140849. **
  140850. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  140851. */
  140852. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  140853. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  140854. int rc = SQLITE_OK; /* Error code */
  140855. int i;
  140856. /* Determine if doclists may be loaded from disk incrementally. This is
  140857. ** possible if the bOptOk argument is true, the FTS doclists will be
  140858. ** scanned in forward order, and the phrase consists of
  140859. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  140860. ** tokens or prefix tokens that cannot use a prefix-index. */
  140861. int bHaveIncr = 0;
  140862. int bIncrOk = (bOptOk
  140863. && pCsr->bDesc==pTab->bDescIdx
  140864. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  140865. #ifdef SQLITE_TEST
  140866. && pTab->bNoIncrDoclist==0
  140867. #endif
  140868. );
  140869. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  140870. Fts3PhraseToken *pToken = &p->aToken[i];
  140871. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  140872. bIncrOk = 0;
  140873. }
  140874. if( pToken->pSegcsr ) bHaveIncr = 1;
  140875. }
  140876. if( bIncrOk && bHaveIncr ){
  140877. /* Use the incremental approach. */
  140878. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  140879. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  140880. Fts3PhraseToken *pToken = &p->aToken[i];
  140881. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  140882. if( pSegcsr ){
  140883. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  140884. }
  140885. }
  140886. p->bIncr = 1;
  140887. }else{
  140888. /* Load the full doclist for the phrase into memory. */
  140889. rc = fts3EvalPhraseLoad(pCsr, p);
  140890. p->bIncr = 0;
  140891. }
  140892. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  140893. return rc;
  140894. }
  140895. /*
  140896. ** This function is used to iterate backwards (from the end to start)
  140897. ** through doclists. It is used by this module to iterate through phrase
  140898. ** doclists in reverse and by the fts3_write.c module to iterate through
  140899. ** pending-terms lists when writing to databases with "order=desc".
  140900. **
  140901. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  140902. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  140903. ** function iterates from the end of the doclist to the beginning.
  140904. */
  140905. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  140906. int bDescIdx, /* True if the doclist is desc */
  140907. char *aDoclist, /* Pointer to entire doclist */
  140908. int nDoclist, /* Length of aDoclist in bytes */
  140909. char **ppIter, /* IN/OUT: Iterator pointer */
  140910. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  140911. int *pnList, /* OUT: List length pointer */
  140912. u8 *pbEof /* OUT: End-of-file flag */
  140913. ){
  140914. char *p = *ppIter;
  140915. assert( nDoclist>0 );
  140916. assert( *pbEof==0 );
  140917. assert( p || *piDocid==0 );
  140918. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  140919. if( p==0 ){
  140920. sqlite3_int64 iDocid = 0;
  140921. char *pNext = 0;
  140922. char *pDocid = aDoclist;
  140923. char *pEnd = &aDoclist[nDoclist];
  140924. int iMul = 1;
  140925. while( pDocid<pEnd ){
  140926. sqlite3_int64 iDelta;
  140927. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  140928. iDocid += (iMul * iDelta);
  140929. pNext = pDocid;
  140930. fts3PoslistCopy(0, &pDocid);
  140931. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  140932. iMul = (bDescIdx ? -1 : 1);
  140933. }
  140934. *pnList = (int)(pEnd - pNext);
  140935. *ppIter = pNext;
  140936. *piDocid = iDocid;
  140937. }else{
  140938. int iMul = (bDescIdx ? -1 : 1);
  140939. sqlite3_int64 iDelta;
  140940. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  140941. *piDocid -= (iMul * iDelta);
  140942. if( p==aDoclist ){
  140943. *pbEof = 1;
  140944. }else{
  140945. char *pSave = p;
  140946. fts3ReversePoslist(aDoclist, &p);
  140947. *pnList = (int)(pSave - p);
  140948. }
  140949. *ppIter = p;
  140950. }
  140951. }
  140952. /*
  140953. ** Iterate forwards through a doclist.
  140954. */
  140955. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  140956. int bDescIdx, /* True if the doclist is desc */
  140957. char *aDoclist, /* Pointer to entire doclist */
  140958. int nDoclist, /* Length of aDoclist in bytes */
  140959. char **ppIter, /* IN/OUT: Iterator pointer */
  140960. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  140961. u8 *pbEof /* OUT: End-of-file flag */
  140962. ){
  140963. char *p = *ppIter;
  140964. assert( nDoclist>0 );
  140965. assert( *pbEof==0 );
  140966. assert( p || *piDocid==0 );
  140967. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  140968. if( p==0 ){
  140969. p = aDoclist;
  140970. p += sqlite3Fts3GetVarint(p, piDocid);
  140971. }else{
  140972. fts3PoslistCopy(0, &p);
  140973. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  140974. if( p>=&aDoclist[nDoclist] ){
  140975. *pbEof = 1;
  140976. }else{
  140977. sqlite3_int64 iVar;
  140978. p += sqlite3Fts3GetVarint(p, &iVar);
  140979. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  140980. }
  140981. }
  140982. *ppIter = p;
  140983. }
  140984. /*
  140985. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  140986. ** to true if EOF is reached.
  140987. */
  140988. static void fts3EvalDlPhraseNext(
  140989. Fts3Table *pTab,
  140990. Fts3Doclist *pDL,
  140991. u8 *pbEof
  140992. ){
  140993. char *pIter; /* Used to iterate through aAll */
  140994. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  140995. if( pDL->pNextDocid ){
  140996. pIter = pDL->pNextDocid;
  140997. }else{
  140998. pIter = pDL->aAll;
  140999. }
  141000. if( pIter>=pEnd ){
  141001. /* We have already reached the end of this doclist. EOF. */
  141002. *pbEof = 1;
  141003. }else{
  141004. sqlite3_int64 iDelta;
  141005. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  141006. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  141007. pDL->iDocid += iDelta;
  141008. }else{
  141009. pDL->iDocid -= iDelta;
  141010. }
  141011. pDL->pList = pIter;
  141012. fts3PoslistCopy(0, &pIter);
  141013. pDL->nList = (int)(pIter - pDL->pList);
  141014. /* pIter now points just past the 0x00 that terminates the position-
  141015. ** list for document pDL->iDocid. However, if this position-list was
  141016. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  141017. ** point to the start of the next docid value. The following line deals
  141018. ** with this case by advancing pIter past the zero-padding added by
  141019. ** fts3EvalNearTrim(). */
  141020. while( pIter<pEnd && *pIter==0 ) pIter++;
  141021. pDL->pNextDocid = pIter;
  141022. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  141023. *pbEof = 0;
  141024. }
  141025. }
  141026. /*
  141027. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  141028. */
  141029. typedef struct TokenDoclist TokenDoclist;
  141030. struct TokenDoclist {
  141031. int bIgnore;
  141032. sqlite3_int64 iDocid;
  141033. char *pList;
  141034. int nList;
  141035. };
  141036. /*
  141037. ** Token pToken is an incrementally loaded token that is part of a
  141038. ** multi-token phrase. Advance it to the next matching document in the
  141039. ** database and populate output variable *p with the details of the new
  141040. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  141041. **
  141042. ** If an error occurs, return an SQLite error code. Otherwise, return
  141043. ** SQLITE_OK.
  141044. */
  141045. static int incrPhraseTokenNext(
  141046. Fts3Table *pTab, /* Virtual table handle */
  141047. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  141048. int iToken, /* Specific token to advance */
  141049. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  141050. u8 *pbEof /* OUT: True if iterator is at EOF */
  141051. ){
  141052. int rc = SQLITE_OK;
  141053. if( pPhrase->iDoclistToken==iToken ){
  141054. assert( p->bIgnore==0 );
  141055. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  141056. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  141057. p->pList = pPhrase->doclist.pList;
  141058. p->nList = pPhrase->doclist.nList;
  141059. p->iDocid = pPhrase->doclist.iDocid;
  141060. }else{
  141061. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  141062. assert( pToken->pDeferred==0 );
  141063. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  141064. if( pToken->pSegcsr ){
  141065. assert( p->bIgnore==0 );
  141066. rc = sqlite3Fts3MsrIncrNext(
  141067. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  141068. );
  141069. if( p->pList==0 ) *pbEof = 1;
  141070. }else{
  141071. p->bIgnore = 1;
  141072. }
  141073. }
  141074. return rc;
  141075. }
  141076. /*
  141077. ** The phrase iterator passed as the second argument:
  141078. **
  141079. ** * features at least one token that uses an incremental doclist, and
  141080. **
  141081. ** * does not contain any deferred tokens.
  141082. **
  141083. ** Advance it to the next matching documnent in the database and populate
  141084. ** the Fts3Doclist.pList and nList fields.
  141085. **
  141086. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  141087. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  141088. ** successfully advanced, *pbEof is set to 0.
  141089. **
  141090. ** If an error occurs, return an SQLite error code. Otherwise, return
  141091. ** SQLITE_OK.
  141092. */
  141093. static int fts3EvalIncrPhraseNext(
  141094. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141095. Fts3Phrase *p, /* Phrase object to advance to next docid */
  141096. u8 *pbEof /* OUT: Set to 1 if EOF */
  141097. ){
  141098. int rc = SQLITE_OK;
  141099. Fts3Doclist *pDL = &p->doclist;
  141100. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141101. u8 bEof = 0;
  141102. /* This is only called if it is guaranteed that the phrase has at least
  141103. ** one incremental token. In which case the bIncr flag is set. */
  141104. assert( p->bIncr==1 );
  141105. if( p->nToken==1 ){
  141106. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  141107. &pDL->iDocid, &pDL->pList, &pDL->nList
  141108. );
  141109. if( pDL->pList==0 ) bEof = 1;
  141110. }else{
  141111. int bDescDoclist = pCsr->bDesc;
  141112. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  141113. memset(a, 0, sizeof(a));
  141114. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  141115. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  141116. while( bEof==0 ){
  141117. int bMaxSet = 0;
  141118. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  141119. int i; /* Used to iterate through tokens */
  141120. /* Advance the iterator for each token in the phrase once. */
  141121. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  141122. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  141123. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  141124. iMax = a[i].iDocid;
  141125. bMaxSet = 1;
  141126. }
  141127. }
  141128. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  141129. assert( rc!=SQLITE_OK || bMaxSet );
  141130. /* Keep advancing iterators until they all point to the same document */
  141131. for(i=0; i<p->nToken; i++){
  141132. while( rc==SQLITE_OK && bEof==0
  141133. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  141134. ){
  141135. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  141136. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  141137. iMax = a[i].iDocid;
  141138. i = 0;
  141139. }
  141140. }
  141141. }
  141142. /* Check if the current entries really are a phrase match */
  141143. if( bEof==0 ){
  141144. int nList = 0;
  141145. int nByte = a[p->nToken-1].nList;
  141146. char *aDoclist = sqlite3_malloc(nByte+1);
  141147. if( !aDoclist ) return SQLITE_NOMEM;
  141148. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  141149. for(i=0; i<(p->nToken-1); i++){
  141150. if( a[i].bIgnore==0 ){
  141151. char *pL = a[i].pList;
  141152. char *pR = aDoclist;
  141153. char *pOut = aDoclist;
  141154. int nDist = p->nToken-1-i;
  141155. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  141156. if( res==0 ) break;
  141157. nList = (int)(pOut - aDoclist);
  141158. }
  141159. }
  141160. if( i==(p->nToken-1) ){
  141161. pDL->iDocid = iMax;
  141162. pDL->pList = aDoclist;
  141163. pDL->nList = nList;
  141164. pDL->bFreeList = 1;
  141165. break;
  141166. }
  141167. sqlite3_free(aDoclist);
  141168. }
  141169. }
  141170. }
  141171. *pbEof = bEof;
  141172. return rc;
  141173. }
  141174. /*
  141175. ** Attempt to move the phrase iterator to point to the next matching docid.
  141176. ** If an error occurs, return an SQLite error code. Otherwise, return
  141177. ** SQLITE_OK.
  141178. **
  141179. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  141180. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  141181. ** successfully advanced, *pbEof is set to 0.
  141182. */
  141183. static int fts3EvalPhraseNext(
  141184. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141185. Fts3Phrase *p, /* Phrase object to advance to next docid */
  141186. u8 *pbEof /* OUT: Set to 1 if EOF */
  141187. ){
  141188. int rc = SQLITE_OK;
  141189. Fts3Doclist *pDL = &p->doclist;
  141190. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141191. if( p->bIncr ){
  141192. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  141193. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  141194. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  141195. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  141196. );
  141197. pDL->pList = pDL->pNextDocid;
  141198. }else{
  141199. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  141200. }
  141201. return rc;
  141202. }
  141203. /*
  141204. **
  141205. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  141206. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  141207. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  141208. ** expressions for which all descendent tokens are deferred.
  141209. **
  141210. ** If parameter bOptOk is zero, then it is guaranteed that the
  141211. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  141212. ** each phrase in the expression (subject to deferred token processing).
  141213. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  141214. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  141215. **
  141216. ** If an error occurs within this function, *pRc is set to an SQLite error
  141217. ** code before returning.
  141218. */
  141219. static void fts3EvalStartReaders(
  141220. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141221. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  141222. int *pRc /* IN/OUT: Error code */
  141223. ){
  141224. if( pExpr && SQLITE_OK==*pRc ){
  141225. if( pExpr->eType==FTSQUERY_PHRASE ){
  141226. int nToken = pExpr->pPhrase->nToken;
  141227. if( nToken ){
  141228. int i;
  141229. for(i=0; i<nToken; i++){
  141230. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  141231. }
  141232. pExpr->bDeferred = (i==nToken);
  141233. }
  141234. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  141235. }else{
  141236. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  141237. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  141238. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  141239. }
  141240. }
  141241. }
  141242. /*
  141243. ** An array of the following structures is assembled as part of the process
  141244. ** of selecting tokens to defer before the query starts executing (as part
  141245. ** of the xFilter() method). There is one element in the array for each
  141246. ** token in the FTS expression.
  141247. **
  141248. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  141249. ** to phrases that are connected only by AND and NEAR operators (not OR or
  141250. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  141251. ** separately. The root of a tokens AND/NEAR cluster is stored in
  141252. ** Fts3TokenAndCost.pRoot.
  141253. */
  141254. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  141255. struct Fts3TokenAndCost {
  141256. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  141257. int iToken; /* Position of token in phrase */
  141258. Fts3PhraseToken *pToken; /* The token itself */
  141259. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  141260. int nOvfl; /* Number of overflow pages to load doclist */
  141261. int iCol; /* The column the token must match */
  141262. };
  141263. /*
  141264. ** This function is used to populate an allocated Fts3TokenAndCost array.
  141265. **
  141266. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  141267. ** Otherwise, if an error occurs during execution, *pRc is set to an
  141268. ** SQLite error code.
  141269. */
  141270. static void fts3EvalTokenCosts(
  141271. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141272. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  141273. Fts3Expr *pExpr, /* Expression to consider */
  141274. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  141275. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  141276. int *pRc /* IN/OUT: Error code */
  141277. ){
  141278. if( *pRc==SQLITE_OK ){
  141279. if( pExpr->eType==FTSQUERY_PHRASE ){
  141280. Fts3Phrase *pPhrase = pExpr->pPhrase;
  141281. int i;
  141282. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  141283. Fts3TokenAndCost *pTC = (*ppTC)++;
  141284. pTC->pPhrase = pPhrase;
  141285. pTC->iToken = i;
  141286. pTC->pRoot = pRoot;
  141287. pTC->pToken = &pPhrase->aToken[i];
  141288. pTC->iCol = pPhrase->iColumn;
  141289. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  141290. }
  141291. }else if( pExpr->eType!=FTSQUERY_NOT ){
  141292. assert( pExpr->eType==FTSQUERY_OR
  141293. || pExpr->eType==FTSQUERY_AND
  141294. || pExpr->eType==FTSQUERY_NEAR
  141295. );
  141296. assert( pExpr->pLeft && pExpr->pRight );
  141297. if( pExpr->eType==FTSQUERY_OR ){
  141298. pRoot = pExpr->pLeft;
  141299. **ppOr = pRoot;
  141300. (*ppOr)++;
  141301. }
  141302. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  141303. if( pExpr->eType==FTSQUERY_OR ){
  141304. pRoot = pExpr->pRight;
  141305. **ppOr = pRoot;
  141306. (*ppOr)++;
  141307. }
  141308. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  141309. }
  141310. }
  141311. }
  141312. /*
  141313. ** Determine the average document (row) size in pages. If successful,
  141314. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  141315. ** an SQLite error code.
  141316. **
  141317. ** The average document size in pages is calculated by first calculating
  141318. ** determining the average size in bytes, B. If B is less than the amount
  141319. ** of data that will fit on a single leaf page of an intkey table in
  141320. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  141321. ** the number of overflow pages consumed by a record B bytes in size.
  141322. */
  141323. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  141324. int rc = SQLITE_OK;
  141325. if( pCsr->nRowAvg==0 ){
  141326. /* The average document size, which is required to calculate the cost
  141327. ** of each doclist, has not yet been determined. Read the required
  141328. ** data from the %_stat table to calculate it.
  141329. **
  141330. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  141331. ** varints, where nCol is the number of columns in the FTS3 table.
  141332. ** The first varint is the number of documents currently stored in
  141333. ** the table. The following nCol varints contain the total amount of
  141334. ** data stored in all rows of each column of the table, from left
  141335. ** to right.
  141336. */
  141337. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  141338. sqlite3_stmt *pStmt;
  141339. sqlite3_int64 nDoc = 0;
  141340. sqlite3_int64 nByte = 0;
  141341. const char *pEnd;
  141342. const char *a;
  141343. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  141344. if( rc!=SQLITE_OK ) return rc;
  141345. a = sqlite3_column_blob(pStmt, 0);
  141346. assert( a );
  141347. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  141348. a += sqlite3Fts3GetVarint(a, &nDoc);
  141349. while( a<pEnd ){
  141350. a += sqlite3Fts3GetVarint(a, &nByte);
  141351. }
  141352. if( nDoc==0 || nByte==0 ){
  141353. sqlite3_reset(pStmt);
  141354. return FTS_CORRUPT_VTAB;
  141355. }
  141356. pCsr->nDoc = nDoc;
  141357. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  141358. assert( pCsr->nRowAvg>0 );
  141359. rc = sqlite3_reset(pStmt);
  141360. }
  141361. *pnPage = pCsr->nRowAvg;
  141362. return rc;
  141363. }
  141364. /*
  141365. ** This function is called to select the tokens (if any) that will be
  141366. ** deferred. The array aTC[] has already been populated when this is
  141367. ** called.
  141368. **
  141369. ** This function is called once for each AND/NEAR cluster in the
  141370. ** expression. Each invocation determines which tokens to defer within
  141371. ** the cluster with root node pRoot. See comments above the definition
  141372. ** of struct Fts3TokenAndCost for more details.
  141373. **
  141374. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  141375. ** called on each token to defer. Otherwise, an SQLite error code is
  141376. ** returned.
  141377. */
  141378. static int fts3EvalSelectDeferred(
  141379. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141380. Fts3Expr *pRoot, /* Consider tokens with this root node */
  141381. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  141382. int nTC /* Number of entries in aTC[] */
  141383. ){
  141384. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141385. int nDocSize = 0; /* Number of pages per doc loaded */
  141386. int rc = SQLITE_OK; /* Return code */
  141387. int ii; /* Iterator variable for various purposes */
  141388. int nOvfl = 0; /* Total overflow pages used by doclists */
  141389. int nToken = 0; /* Total number of tokens in cluster */
  141390. int nMinEst = 0; /* The minimum count for any phrase so far. */
  141391. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  141392. /* Tokens are never deferred for FTS tables created using the content=xxx
  141393. ** option. The reason being that it is not guaranteed that the content
  141394. ** table actually contains the same data as the index. To prevent this from
  141395. ** causing any problems, the deferred token optimization is completely
  141396. ** disabled for content=xxx tables. */
  141397. if( pTab->zContentTbl ){
  141398. return SQLITE_OK;
  141399. }
  141400. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  141401. ** associated with the tokens spill onto overflow pages, or if there is
  141402. ** only 1 token, exit early. No tokens to defer in this case. */
  141403. for(ii=0; ii<nTC; ii++){
  141404. if( aTC[ii].pRoot==pRoot ){
  141405. nOvfl += aTC[ii].nOvfl;
  141406. nToken++;
  141407. }
  141408. }
  141409. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  141410. /* Obtain the average docsize (in pages). */
  141411. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  141412. assert( rc!=SQLITE_OK || nDocSize>0 );
  141413. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  141414. ** of the number of overflow pages that will be loaded by the pager layer
  141415. ** to retrieve the entire doclist for the token from the full-text index.
  141416. ** Load the doclists for tokens that are either:
  141417. **
  141418. ** a. The cheapest token in the entire query (i.e. the one visited by the
  141419. ** first iteration of this loop), or
  141420. **
  141421. ** b. Part of a multi-token phrase.
  141422. **
  141423. ** After each token doclist is loaded, merge it with the others from the
  141424. ** same phrase and count the number of documents that the merged doclist
  141425. ** contains. Set variable "nMinEst" to the smallest number of documents in
  141426. ** any phrase doclist for which 1 or more token doclists have been loaded.
  141427. ** Let nOther be the number of other phrases for which it is certain that
  141428. ** one or more tokens will not be deferred.
  141429. **
  141430. ** Then, for each token, defer it if loading the doclist would result in
  141431. ** loading N or more overflow pages into memory, where N is computed as:
  141432. **
  141433. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  141434. */
  141435. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  141436. int iTC; /* Used to iterate through aTC[] array. */
  141437. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  141438. /* Set pTC to point to the cheapest remaining token. */
  141439. for(iTC=0; iTC<nTC; iTC++){
  141440. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  141441. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  141442. ){
  141443. pTC = &aTC[iTC];
  141444. }
  141445. }
  141446. assert( pTC );
  141447. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  141448. /* The number of overflow pages to load for this (and therefore all
  141449. ** subsequent) tokens is greater than the estimated number of pages
  141450. ** that will be loaded if all subsequent tokens are deferred.
  141451. */
  141452. Fts3PhraseToken *pToken = pTC->pToken;
  141453. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  141454. fts3SegReaderCursorFree(pToken->pSegcsr);
  141455. pToken->pSegcsr = 0;
  141456. }else{
  141457. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  141458. ** for-loop. Except, limit the value to 2^24 to prevent it from
  141459. ** overflowing the 32-bit integer it is stored in. */
  141460. if( ii<12 ) nLoad4 = nLoad4*4;
  141461. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  141462. /* Either this is the cheapest token in the entire query, or it is
  141463. ** part of a multi-token phrase. Either way, the entire doclist will
  141464. ** (eventually) be loaded into memory. It may as well be now. */
  141465. Fts3PhraseToken *pToken = pTC->pToken;
  141466. int nList = 0;
  141467. char *pList = 0;
  141468. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  141469. assert( rc==SQLITE_OK || pList==0 );
  141470. if( rc==SQLITE_OK ){
  141471. rc = fts3EvalPhraseMergeToken(
  141472. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  141473. );
  141474. }
  141475. if( rc==SQLITE_OK ){
  141476. int nCount;
  141477. nCount = fts3DoclistCountDocids(
  141478. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  141479. );
  141480. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  141481. }
  141482. }
  141483. }
  141484. pTC->pToken = 0;
  141485. }
  141486. return rc;
  141487. }
  141488. /*
  141489. ** This function is called from within the xFilter method. It initializes
  141490. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  141491. ** the results of a query, the caller does:
  141492. **
  141493. ** fts3EvalStart(pCsr);
  141494. ** while( 1 ){
  141495. ** fts3EvalNext(pCsr);
  141496. ** if( pCsr->bEof ) break;
  141497. ** ... return row pCsr->iPrevId to the caller ...
  141498. ** }
  141499. */
  141500. static int fts3EvalStart(Fts3Cursor *pCsr){
  141501. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141502. int rc = SQLITE_OK;
  141503. int nToken = 0;
  141504. int nOr = 0;
  141505. /* Allocate a MultiSegReader for each token in the expression. */
  141506. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  141507. /* Determine which, if any, tokens in the expression should be deferred. */
  141508. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  141509. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  141510. Fts3TokenAndCost *aTC;
  141511. Fts3Expr **apOr;
  141512. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  141513. sizeof(Fts3TokenAndCost) * nToken
  141514. + sizeof(Fts3Expr *) * nOr * 2
  141515. );
  141516. apOr = (Fts3Expr **)&aTC[nToken];
  141517. if( !aTC ){
  141518. rc = SQLITE_NOMEM;
  141519. }else{
  141520. int ii;
  141521. Fts3TokenAndCost *pTC = aTC;
  141522. Fts3Expr **ppOr = apOr;
  141523. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  141524. nToken = (int)(pTC-aTC);
  141525. nOr = (int)(ppOr-apOr);
  141526. if( rc==SQLITE_OK ){
  141527. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  141528. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  141529. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  141530. }
  141531. }
  141532. sqlite3_free(aTC);
  141533. }
  141534. }
  141535. #endif
  141536. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  141537. return rc;
  141538. }
  141539. /*
  141540. ** Invalidate the current position list for phrase pPhrase.
  141541. */
  141542. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  141543. if( pPhrase->doclist.bFreeList ){
  141544. sqlite3_free(pPhrase->doclist.pList);
  141545. }
  141546. pPhrase->doclist.pList = 0;
  141547. pPhrase->doclist.nList = 0;
  141548. pPhrase->doclist.bFreeList = 0;
  141549. }
  141550. /*
  141551. ** This function is called to edit the position list associated with
  141552. ** the phrase object passed as the fifth argument according to a NEAR
  141553. ** condition. For example:
  141554. **
  141555. ** abc NEAR/5 "def ghi"
  141556. **
  141557. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  141558. ** the example above). When this function is called, *paPoslist points to
  141559. ** the position list, and *pnToken is the number of phrase tokens in, the
  141560. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  141561. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  141562. ** the position list associated with phrase "abc".
  141563. **
  141564. ** All positions in the pPhrase position list that are not sufficiently
  141565. ** close to a position in the *paPoslist position list are removed. If this
  141566. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  141567. **
  141568. ** Before returning, *paPoslist is set to point to the position lsit
  141569. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  141570. ** pPhrase.
  141571. */
  141572. static int fts3EvalNearTrim(
  141573. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  141574. char *aTmp, /* Temporary space to use */
  141575. char **paPoslist, /* IN/OUT: Position list */
  141576. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  141577. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  141578. ){
  141579. int nParam1 = nNear + pPhrase->nToken;
  141580. int nParam2 = nNear + *pnToken;
  141581. int nNew;
  141582. char *p2;
  141583. char *pOut;
  141584. int res;
  141585. assert( pPhrase->doclist.pList );
  141586. p2 = pOut = pPhrase->doclist.pList;
  141587. res = fts3PoslistNearMerge(
  141588. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  141589. );
  141590. if( res ){
  141591. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  141592. assert( pPhrase->doclist.pList[nNew]=='\0' );
  141593. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  141594. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  141595. pPhrase->doclist.nList = nNew;
  141596. *paPoslist = pPhrase->doclist.pList;
  141597. *pnToken = pPhrase->nToken;
  141598. }
  141599. return res;
  141600. }
  141601. /*
  141602. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  141603. ** Otherwise, it advances the expression passed as the second argument to
  141604. ** point to the next matching row in the database. Expressions iterate through
  141605. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  141606. ** or descending if it is non-zero.
  141607. **
  141608. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  141609. ** successful, the following variables in pExpr are set:
  141610. **
  141611. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  141612. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  141613. **
  141614. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  141615. ** at EOF, then the following variables are populated with the position list
  141616. ** for the phrase for the visited row:
  141617. **
  141618. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  141619. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  141620. **
  141621. ** It says above that this function advances the expression to the next
  141622. ** matching row. This is usually true, but there are the following exceptions:
  141623. **
  141624. ** 1. Deferred tokens are not taken into account. If a phrase consists
  141625. ** entirely of deferred tokens, it is assumed to match every row in
  141626. ** the db. In this case the position-list is not populated at all.
  141627. **
  141628. ** Or, if a phrase contains one or more deferred tokens and one or
  141629. ** more non-deferred tokens, then the expression is advanced to the
  141630. ** next possible match, considering only non-deferred tokens. In other
  141631. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  141632. ** is advanced to the next row that contains an instance of "A * C",
  141633. ** where "*" may match any single token. The position list in this case
  141634. ** is populated as for "A * C" before returning.
  141635. **
  141636. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  141637. ** advanced to point to the next row that matches "x AND y".
  141638. **
  141639. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  141640. ** really a match, taking into account deferred tokens and NEAR operators.
  141641. */
  141642. static void fts3EvalNextRow(
  141643. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141644. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  141645. int *pRc /* IN/OUT: Error code */
  141646. ){
  141647. if( *pRc==SQLITE_OK ){
  141648. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  141649. assert( pExpr->bEof==0 );
  141650. pExpr->bStart = 1;
  141651. switch( pExpr->eType ){
  141652. case FTSQUERY_NEAR:
  141653. case FTSQUERY_AND: {
  141654. Fts3Expr *pLeft = pExpr->pLeft;
  141655. Fts3Expr *pRight = pExpr->pRight;
  141656. assert( !pLeft->bDeferred || !pRight->bDeferred );
  141657. if( pLeft->bDeferred ){
  141658. /* LHS is entirely deferred. So we assume it matches every row.
  141659. ** Advance the RHS iterator to find the next row visited. */
  141660. fts3EvalNextRow(pCsr, pRight, pRc);
  141661. pExpr->iDocid = pRight->iDocid;
  141662. pExpr->bEof = pRight->bEof;
  141663. }else if( pRight->bDeferred ){
  141664. /* RHS is entirely deferred. So we assume it matches every row.
  141665. ** Advance the LHS iterator to find the next row visited. */
  141666. fts3EvalNextRow(pCsr, pLeft, pRc);
  141667. pExpr->iDocid = pLeft->iDocid;
  141668. pExpr->bEof = pLeft->bEof;
  141669. }else{
  141670. /* Neither the RHS or LHS are deferred. */
  141671. fts3EvalNextRow(pCsr, pLeft, pRc);
  141672. fts3EvalNextRow(pCsr, pRight, pRc);
  141673. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  141674. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  141675. if( iDiff==0 ) break;
  141676. if( iDiff<0 ){
  141677. fts3EvalNextRow(pCsr, pLeft, pRc);
  141678. }else{
  141679. fts3EvalNextRow(pCsr, pRight, pRc);
  141680. }
  141681. }
  141682. pExpr->iDocid = pLeft->iDocid;
  141683. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  141684. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  141685. assert( pRight->eType==FTSQUERY_PHRASE );
  141686. if( pRight->pPhrase->doclist.aAll ){
  141687. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  141688. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  141689. memset(pDl->pList, 0, pDl->nList);
  141690. fts3EvalNextRow(pCsr, pRight, pRc);
  141691. }
  141692. }
  141693. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  141694. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  141695. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  141696. memset(pDl->pList, 0, pDl->nList);
  141697. fts3EvalNextRow(pCsr, pLeft, pRc);
  141698. }
  141699. }
  141700. }
  141701. }
  141702. break;
  141703. }
  141704. case FTSQUERY_OR: {
  141705. Fts3Expr *pLeft = pExpr->pLeft;
  141706. Fts3Expr *pRight = pExpr->pRight;
  141707. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  141708. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  141709. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  141710. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  141711. fts3EvalNextRow(pCsr, pLeft, pRc);
  141712. }else if( pLeft->bEof || iCmp>0 ){
  141713. fts3EvalNextRow(pCsr, pRight, pRc);
  141714. }else{
  141715. fts3EvalNextRow(pCsr, pLeft, pRc);
  141716. fts3EvalNextRow(pCsr, pRight, pRc);
  141717. }
  141718. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  141719. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  141720. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  141721. pExpr->iDocid = pLeft->iDocid;
  141722. }else{
  141723. pExpr->iDocid = pRight->iDocid;
  141724. }
  141725. break;
  141726. }
  141727. case FTSQUERY_NOT: {
  141728. Fts3Expr *pLeft = pExpr->pLeft;
  141729. Fts3Expr *pRight = pExpr->pRight;
  141730. if( pRight->bStart==0 ){
  141731. fts3EvalNextRow(pCsr, pRight, pRc);
  141732. assert( *pRc!=SQLITE_OK || pRight->bStart );
  141733. }
  141734. fts3EvalNextRow(pCsr, pLeft, pRc);
  141735. if( pLeft->bEof==0 ){
  141736. while( !*pRc
  141737. && !pRight->bEof
  141738. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  141739. ){
  141740. fts3EvalNextRow(pCsr, pRight, pRc);
  141741. }
  141742. }
  141743. pExpr->iDocid = pLeft->iDocid;
  141744. pExpr->bEof = pLeft->bEof;
  141745. break;
  141746. }
  141747. default: {
  141748. Fts3Phrase *pPhrase = pExpr->pPhrase;
  141749. fts3EvalInvalidatePoslist(pPhrase);
  141750. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  141751. pExpr->iDocid = pPhrase->doclist.iDocid;
  141752. break;
  141753. }
  141754. }
  141755. }
  141756. }
  141757. /*
  141758. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  141759. ** cluster, then this function returns 1 immediately.
  141760. **
  141761. ** Otherwise, it checks if the current row really does match the NEAR
  141762. ** expression, using the data currently stored in the position lists
  141763. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  141764. **
  141765. ** If the current row is a match, the position list associated with each
  141766. ** phrase in the NEAR expression is edited in place to contain only those
  141767. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  141768. ** constraints. In this case it returns 1. If the NEAR expression does not
  141769. ** match the current row, 0 is returned. The position lists may or may not
  141770. ** be edited if 0 is returned.
  141771. */
  141772. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  141773. int res = 1;
  141774. /* The following block runs if pExpr is the root of a NEAR query.
  141775. ** For example, the query:
  141776. **
  141777. ** "w" NEAR "x" NEAR "y" NEAR "z"
  141778. **
  141779. ** which is represented in tree form as:
  141780. **
  141781. ** |
  141782. ** +--NEAR--+ <-- root of NEAR query
  141783. ** | |
  141784. ** +--NEAR--+ "z"
  141785. ** | |
  141786. ** +--NEAR--+ "y"
  141787. ** | |
  141788. ** "w" "x"
  141789. **
  141790. ** The right-hand child of a NEAR node is always a phrase. The
  141791. ** left-hand child may be either a phrase or a NEAR node. There are
  141792. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  141793. */
  141794. if( *pRc==SQLITE_OK
  141795. && pExpr->eType==FTSQUERY_NEAR
  141796. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  141797. ){
  141798. Fts3Expr *p;
  141799. int nTmp = 0; /* Bytes of temp space */
  141800. char *aTmp; /* Temp space for PoslistNearMerge() */
  141801. /* Allocate temporary working space. */
  141802. for(p=pExpr; p->pLeft; p=p->pLeft){
  141803. assert( p->pRight->pPhrase->doclist.nList>0 );
  141804. nTmp += p->pRight->pPhrase->doclist.nList;
  141805. }
  141806. nTmp += p->pPhrase->doclist.nList;
  141807. aTmp = sqlite3_malloc(nTmp*2);
  141808. if( !aTmp ){
  141809. *pRc = SQLITE_NOMEM;
  141810. res = 0;
  141811. }else{
  141812. char *aPoslist = p->pPhrase->doclist.pList;
  141813. int nToken = p->pPhrase->nToken;
  141814. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  141815. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  141816. int nNear = p->nNear;
  141817. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  141818. }
  141819. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  141820. nToken = pExpr->pRight->pPhrase->nToken;
  141821. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  141822. int nNear;
  141823. Fts3Phrase *pPhrase;
  141824. assert( p->pParent && p->pParent->pLeft==p );
  141825. nNear = p->pParent->nNear;
  141826. pPhrase = (
  141827. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  141828. );
  141829. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  141830. }
  141831. }
  141832. sqlite3_free(aTmp);
  141833. }
  141834. return res;
  141835. }
  141836. /*
  141837. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  141838. ** Assuming no error occurs or has occurred, It returns non-zero if the
  141839. ** expression passed as the second argument matches the row that pCsr
  141840. ** currently points to, or zero if it does not.
  141841. **
  141842. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  141843. ** If an error occurs during execution of this function, *pRc is set to
  141844. ** the appropriate SQLite error code. In this case the returned value is
  141845. ** undefined.
  141846. */
  141847. static int fts3EvalTestExpr(
  141848. Fts3Cursor *pCsr, /* FTS cursor handle */
  141849. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  141850. int *pRc /* IN/OUT: Error code */
  141851. ){
  141852. int bHit = 1; /* Return value */
  141853. if( *pRc==SQLITE_OK ){
  141854. switch( pExpr->eType ){
  141855. case FTSQUERY_NEAR:
  141856. case FTSQUERY_AND:
  141857. bHit = (
  141858. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  141859. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  141860. && fts3EvalNearTest(pExpr, pRc)
  141861. );
  141862. /* If the NEAR expression does not match any rows, zero the doclist for
  141863. ** all phrases involved in the NEAR. This is because the snippet(),
  141864. ** offsets() and matchinfo() functions are not supposed to recognize
  141865. ** any instances of phrases that are part of unmatched NEAR queries.
  141866. ** For example if this expression:
  141867. **
  141868. ** ... MATCH 'a OR (b NEAR c)'
  141869. **
  141870. ** is matched against a row containing:
  141871. **
  141872. ** 'a b d e'
  141873. **
  141874. ** then any snippet() should ony highlight the "a" term, not the "b"
  141875. ** (as "b" is part of a non-matching NEAR clause).
  141876. */
  141877. if( bHit==0
  141878. && pExpr->eType==FTSQUERY_NEAR
  141879. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  141880. ){
  141881. Fts3Expr *p;
  141882. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  141883. if( p->pRight->iDocid==pCsr->iPrevId ){
  141884. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  141885. }
  141886. }
  141887. if( p->iDocid==pCsr->iPrevId ){
  141888. fts3EvalInvalidatePoslist(p->pPhrase);
  141889. }
  141890. }
  141891. break;
  141892. case FTSQUERY_OR: {
  141893. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  141894. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  141895. bHit = bHit1 || bHit2;
  141896. break;
  141897. }
  141898. case FTSQUERY_NOT:
  141899. bHit = (
  141900. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  141901. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  141902. );
  141903. break;
  141904. default: {
  141905. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  141906. if( pCsr->pDeferred
  141907. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  141908. ){
  141909. Fts3Phrase *pPhrase = pExpr->pPhrase;
  141910. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  141911. if( pExpr->bDeferred ){
  141912. fts3EvalInvalidatePoslist(pPhrase);
  141913. }
  141914. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  141915. bHit = (pPhrase->doclist.pList!=0);
  141916. pExpr->iDocid = pCsr->iPrevId;
  141917. }else
  141918. #endif
  141919. {
  141920. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  141921. }
  141922. break;
  141923. }
  141924. }
  141925. }
  141926. return bHit;
  141927. }
  141928. /*
  141929. ** This function is called as the second part of each xNext operation when
  141930. ** iterating through the results of a full-text query. At this point the
  141931. ** cursor points to a row that matches the query expression, with the
  141932. ** following caveats:
  141933. **
  141934. ** * Up until this point, "NEAR" operators in the expression have been
  141935. ** treated as "AND".
  141936. **
  141937. ** * Deferred tokens have not yet been considered.
  141938. **
  141939. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  141940. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  141941. ** operators and deferred tokens the current row is still a match for the
  141942. ** expression. It returns 1 if both of the following are true:
  141943. **
  141944. ** 1. *pRc is SQLITE_OK when this function returns, and
  141945. **
  141946. ** 2. After scanning the current FTS table row for the deferred tokens,
  141947. ** it is determined that the row does *not* match the query.
  141948. **
  141949. ** Or, if no error occurs and it seems the current row does match the FTS
  141950. ** query, return 0.
  141951. */
  141952. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  141953. int rc = *pRc;
  141954. int bMiss = 0;
  141955. if( rc==SQLITE_OK ){
  141956. /* If there are one or more deferred tokens, load the current row into
  141957. ** memory and scan it to determine the position list for each deferred
  141958. ** token. Then, see if this row is really a match, considering deferred
  141959. ** tokens and NEAR operators (neither of which were taken into account
  141960. ** earlier, by fts3EvalNextRow()).
  141961. */
  141962. if( pCsr->pDeferred ){
  141963. rc = fts3CursorSeek(0, pCsr);
  141964. if( rc==SQLITE_OK ){
  141965. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  141966. }
  141967. }
  141968. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  141969. /* Free the position-lists accumulated for each deferred token above. */
  141970. sqlite3Fts3FreeDeferredDoclists(pCsr);
  141971. *pRc = rc;
  141972. }
  141973. return (rc==SQLITE_OK && bMiss);
  141974. }
  141975. /*
  141976. ** Advance to the next document that matches the FTS expression in
  141977. ** Fts3Cursor.pExpr.
  141978. */
  141979. static int fts3EvalNext(Fts3Cursor *pCsr){
  141980. int rc = SQLITE_OK; /* Return Code */
  141981. Fts3Expr *pExpr = pCsr->pExpr;
  141982. assert( pCsr->isEof==0 );
  141983. if( pExpr==0 ){
  141984. pCsr->isEof = 1;
  141985. }else{
  141986. do {
  141987. if( pCsr->isRequireSeek==0 ){
  141988. sqlite3_reset(pCsr->pStmt);
  141989. }
  141990. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  141991. fts3EvalNextRow(pCsr, pExpr, &rc);
  141992. pCsr->isEof = pExpr->bEof;
  141993. pCsr->isRequireSeek = 1;
  141994. pCsr->isMatchinfoNeeded = 1;
  141995. pCsr->iPrevId = pExpr->iDocid;
  141996. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  141997. }
  141998. /* Check if the cursor is past the end of the docid range specified
  141999. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  142000. if( rc==SQLITE_OK && (
  142001. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  142002. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  142003. )){
  142004. pCsr->isEof = 1;
  142005. }
  142006. return rc;
  142007. }
  142008. /*
  142009. ** Restart interation for expression pExpr so that the next call to
  142010. ** fts3EvalNext() visits the first row. Do not allow incremental
  142011. ** loading or merging of phrase doclists for this iteration.
  142012. **
  142013. ** If *pRc is other than SQLITE_OK when this function is called, it is
  142014. ** a no-op. If an error occurs within this function, *pRc is set to an
  142015. ** SQLite error code before returning.
  142016. */
  142017. static void fts3EvalRestart(
  142018. Fts3Cursor *pCsr,
  142019. Fts3Expr *pExpr,
  142020. int *pRc
  142021. ){
  142022. if( pExpr && *pRc==SQLITE_OK ){
  142023. Fts3Phrase *pPhrase = pExpr->pPhrase;
  142024. if( pPhrase ){
  142025. fts3EvalInvalidatePoslist(pPhrase);
  142026. if( pPhrase->bIncr ){
  142027. int i;
  142028. for(i=0; i<pPhrase->nToken; i++){
  142029. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  142030. assert( pToken->pDeferred==0 );
  142031. if( pToken->pSegcsr ){
  142032. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  142033. }
  142034. }
  142035. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  142036. }
  142037. pPhrase->doclist.pNextDocid = 0;
  142038. pPhrase->doclist.iDocid = 0;
  142039. pPhrase->pOrPoslist = 0;
  142040. }
  142041. pExpr->iDocid = 0;
  142042. pExpr->bEof = 0;
  142043. pExpr->bStart = 0;
  142044. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  142045. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  142046. }
  142047. }
  142048. /*
  142049. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  142050. ** expression rooted at pExpr, the cursor iterates through all rows matched
  142051. ** by pExpr, calling this function for each row. This function increments
  142052. ** the values in Fts3Expr.aMI[] according to the position-list currently
  142053. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  142054. ** expression nodes.
  142055. */
  142056. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  142057. if( pExpr ){
  142058. Fts3Phrase *pPhrase = pExpr->pPhrase;
  142059. if( pPhrase && pPhrase->doclist.pList ){
  142060. int iCol = 0;
  142061. char *p = pPhrase->doclist.pList;
  142062. assert( *p );
  142063. while( 1 ){
  142064. u8 c = 0;
  142065. int iCnt = 0;
  142066. while( 0xFE & (*p | c) ){
  142067. if( (c&0x80)==0 ) iCnt++;
  142068. c = *p++ & 0x80;
  142069. }
  142070. /* aMI[iCol*3 + 1] = Number of occurrences
  142071. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  142072. */
  142073. pExpr->aMI[iCol*3 + 1] += iCnt;
  142074. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  142075. if( *p==0x00 ) break;
  142076. p++;
  142077. p += fts3GetVarint32(p, &iCol);
  142078. }
  142079. }
  142080. fts3EvalUpdateCounts(pExpr->pLeft);
  142081. fts3EvalUpdateCounts(pExpr->pRight);
  142082. }
  142083. }
  142084. /*
  142085. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  142086. **
  142087. ** If it is not already allocated and populated, this function allocates and
  142088. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  142089. ** of a NEAR expression, then it also allocates and populates the same array
  142090. ** for all other phrases that are part of the NEAR expression.
  142091. **
  142092. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  142093. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  142094. */
  142095. static int fts3EvalGatherStats(
  142096. Fts3Cursor *pCsr, /* Cursor object */
  142097. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  142098. ){
  142099. int rc = SQLITE_OK; /* Return code */
  142100. assert( pExpr->eType==FTSQUERY_PHRASE );
  142101. if( pExpr->aMI==0 ){
  142102. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142103. Fts3Expr *pRoot; /* Root of NEAR expression */
  142104. Fts3Expr *p; /* Iterator used for several purposes */
  142105. sqlite3_int64 iPrevId = pCsr->iPrevId;
  142106. sqlite3_int64 iDocid;
  142107. u8 bEof;
  142108. /* Find the root of the NEAR expression */
  142109. pRoot = pExpr;
  142110. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  142111. pRoot = pRoot->pParent;
  142112. }
  142113. iDocid = pRoot->iDocid;
  142114. bEof = pRoot->bEof;
  142115. assert( pRoot->bStart );
  142116. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  142117. for(p=pRoot; p; p=p->pLeft){
  142118. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  142119. assert( pE->aMI==0 );
  142120. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  142121. if( !pE->aMI ) return SQLITE_NOMEM;
  142122. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  142123. }
  142124. fts3EvalRestart(pCsr, pRoot, &rc);
  142125. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  142126. do {
  142127. /* Ensure the %_content statement is reset. */
  142128. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  142129. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  142130. /* Advance to the next document */
  142131. fts3EvalNextRow(pCsr, pRoot, &rc);
  142132. pCsr->isEof = pRoot->bEof;
  142133. pCsr->isRequireSeek = 1;
  142134. pCsr->isMatchinfoNeeded = 1;
  142135. pCsr->iPrevId = pRoot->iDocid;
  142136. }while( pCsr->isEof==0
  142137. && pRoot->eType==FTSQUERY_NEAR
  142138. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  142139. );
  142140. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  142141. fts3EvalUpdateCounts(pRoot);
  142142. }
  142143. }
  142144. pCsr->isEof = 0;
  142145. pCsr->iPrevId = iPrevId;
  142146. if( bEof ){
  142147. pRoot->bEof = bEof;
  142148. }else{
  142149. /* Caution: pRoot may iterate through docids in ascending or descending
  142150. ** order. For this reason, even though it seems more defensive, the
  142151. ** do loop can not be written:
  142152. **
  142153. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  142154. */
  142155. fts3EvalRestart(pCsr, pRoot, &rc);
  142156. do {
  142157. fts3EvalNextRow(pCsr, pRoot, &rc);
  142158. assert( pRoot->bEof==0 );
  142159. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  142160. }
  142161. }
  142162. return rc;
  142163. }
  142164. /*
  142165. ** This function is used by the matchinfo() module to query a phrase
  142166. ** expression node for the following information:
  142167. **
  142168. ** 1. The total number of occurrences of the phrase in each column of
  142169. ** the FTS table (considering all rows), and
  142170. **
  142171. ** 2. For each column, the number of rows in the table for which the
  142172. ** column contains at least one instance of the phrase.
  142173. **
  142174. ** If no error occurs, SQLITE_OK is returned and the values for each column
  142175. ** written into the array aiOut as follows:
  142176. **
  142177. ** aiOut[iCol*3 + 1] = Number of occurrences
  142178. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  142179. **
  142180. ** Caveats:
  142181. **
  142182. ** * If a phrase consists entirely of deferred tokens, then all output
  142183. ** values are set to the number of documents in the table. In other
  142184. ** words we assume that very common tokens occur exactly once in each
  142185. ** column of each row of the table.
  142186. **
  142187. ** * If a phrase contains some deferred tokens (and some non-deferred
  142188. ** tokens), count the potential occurrence identified by considering
  142189. ** the non-deferred tokens instead of actual phrase occurrences.
  142190. **
  142191. ** * If the phrase is part of a NEAR expression, then only phrase instances
  142192. ** that meet the NEAR constraint are included in the counts.
  142193. */
  142194. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  142195. Fts3Cursor *pCsr, /* FTS cursor handle */
  142196. Fts3Expr *pExpr, /* Phrase expression */
  142197. u32 *aiOut /* Array to write results into (see above) */
  142198. ){
  142199. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142200. int rc = SQLITE_OK;
  142201. int iCol;
  142202. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  142203. assert( pCsr->nDoc>0 );
  142204. for(iCol=0; iCol<pTab->nColumn; iCol++){
  142205. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  142206. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  142207. }
  142208. }else{
  142209. rc = fts3EvalGatherStats(pCsr, pExpr);
  142210. if( rc==SQLITE_OK ){
  142211. assert( pExpr->aMI );
  142212. for(iCol=0; iCol<pTab->nColumn; iCol++){
  142213. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  142214. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  142215. }
  142216. }
  142217. }
  142218. return rc;
  142219. }
  142220. /*
  142221. ** The expression pExpr passed as the second argument to this function
  142222. ** must be of type FTSQUERY_PHRASE.
  142223. **
  142224. ** The returned value is either NULL or a pointer to a buffer containing
  142225. ** a position-list indicating the occurrences of the phrase in column iCol
  142226. ** of the current row.
  142227. **
  142228. ** More specifically, the returned buffer contains 1 varint for each
  142229. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  142230. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  142231. ** if the requested column contains "a b X c d X X" and the position-list
  142232. ** for 'X' is requested, the buffer returned may contain:
  142233. **
  142234. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  142235. **
  142236. ** This function works regardless of whether or not the phrase is deferred,
  142237. ** incremental, or neither.
  142238. */
  142239. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  142240. Fts3Cursor *pCsr, /* FTS3 cursor object */
  142241. Fts3Expr *pExpr, /* Phrase to return doclist for */
  142242. int iCol, /* Column to return position list for */
  142243. char **ppOut /* OUT: Pointer to position list */
  142244. ){
  142245. Fts3Phrase *pPhrase = pExpr->pPhrase;
  142246. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142247. char *pIter;
  142248. int iThis;
  142249. sqlite3_int64 iDocid;
  142250. /* If this phrase is applies specifically to some column other than
  142251. ** column iCol, return a NULL pointer. */
  142252. *ppOut = 0;
  142253. assert( iCol>=0 && iCol<pTab->nColumn );
  142254. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  142255. return SQLITE_OK;
  142256. }
  142257. iDocid = pExpr->iDocid;
  142258. pIter = pPhrase->doclist.pList;
  142259. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  142260. int rc = SQLITE_OK;
  142261. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  142262. int bOr = 0;
  142263. u8 bTreeEof = 0;
  142264. Fts3Expr *p; /* Used to iterate from pExpr to root */
  142265. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  142266. int bMatch;
  142267. /* Check if this phrase descends from an OR expression node. If not,
  142268. ** return NULL. Otherwise, the entry that corresponds to docid
  142269. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  142270. ** tree that the node is part of has been marked as EOF, but the node
  142271. ** itself is not EOF, then it may point to an earlier entry. */
  142272. pNear = pExpr;
  142273. for(p=pExpr->pParent; p; p=p->pParent){
  142274. if( p->eType==FTSQUERY_OR ) bOr = 1;
  142275. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  142276. if( p->bEof ) bTreeEof = 1;
  142277. }
  142278. if( bOr==0 ) return SQLITE_OK;
  142279. /* This is the descendent of an OR node. In this case we cannot use
  142280. ** an incremental phrase. Load the entire doclist for the phrase
  142281. ** into memory in this case. */
  142282. if( pPhrase->bIncr ){
  142283. int bEofSave = pNear->bEof;
  142284. fts3EvalRestart(pCsr, pNear, &rc);
  142285. while( rc==SQLITE_OK && !pNear->bEof ){
  142286. fts3EvalNextRow(pCsr, pNear, &rc);
  142287. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  142288. }
  142289. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  142290. }
  142291. if( bTreeEof ){
  142292. while( rc==SQLITE_OK && !pNear->bEof ){
  142293. fts3EvalNextRow(pCsr, pNear, &rc);
  142294. }
  142295. }
  142296. if( rc!=SQLITE_OK ) return rc;
  142297. bMatch = 1;
  142298. for(p=pNear; p; p=p->pLeft){
  142299. u8 bEof = 0;
  142300. Fts3Expr *pTest = p;
  142301. Fts3Phrase *pPh;
  142302. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  142303. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  142304. assert( pTest->eType==FTSQUERY_PHRASE );
  142305. pPh = pTest->pPhrase;
  142306. pIter = pPh->pOrPoslist;
  142307. iDocid = pPh->iOrDocid;
  142308. if( pCsr->bDesc==bDescDoclist ){
  142309. bEof = !pPh->doclist.nAll ||
  142310. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  142311. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  142312. sqlite3Fts3DoclistNext(
  142313. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  142314. &pIter, &iDocid, &bEof
  142315. );
  142316. }
  142317. }else{
  142318. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  142319. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  142320. int dummy;
  142321. sqlite3Fts3DoclistPrev(
  142322. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  142323. &pIter, &iDocid, &dummy, &bEof
  142324. );
  142325. }
  142326. }
  142327. pPh->pOrPoslist = pIter;
  142328. pPh->iOrDocid = iDocid;
  142329. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  142330. }
  142331. if( bMatch ){
  142332. pIter = pPhrase->pOrPoslist;
  142333. }else{
  142334. pIter = 0;
  142335. }
  142336. }
  142337. if( pIter==0 ) return SQLITE_OK;
  142338. if( *pIter==0x01 ){
  142339. pIter++;
  142340. pIter += fts3GetVarint32(pIter, &iThis);
  142341. }else{
  142342. iThis = 0;
  142343. }
  142344. while( iThis<iCol ){
  142345. fts3ColumnlistCopy(0, &pIter);
  142346. if( *pIter==0x00 ) return SQLITE_OK;
  142347. pIter++;
  142348. pIter += fts3GetVarint32(pIter, &iThis);
  142349. }
  142350. if( *pIter==0x00 ){
  142351. pIter = 0;
  142352. }
  142353. *ppOut = ((iCol==iThis)?pIter:0);
  142354. return SQLITE_OK;
  142355. }
  142356. /*
  142357. ** Free all components of the Fts3Phrase structure that were allocated by
  142358. ** the eval module. Specifically, this means to free:
  142359. **
  142360. ** * the contents of pPhrase->doclist, and
  142361. ** * any Fts3MultiSegReader objects held by phrase tokens.
  142362. */
  142363. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  142364. if( pPhrase ){
  142365. int i;
  142366. sqlite3_free(pPhrase->doclist.aAll);
  142367. fts3EvalInvalidatePoslist(pPhrase);
  142368. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  142369. for(i=0; i<pPhrase->nToken; i++){
  142370. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  142371. pPhrase->aToken[i].pSegcsr = 0;
  142372. }
  142373. }
  142374. }
  142375. /*
  142376. ** Return SQLITE_CORRUPT_VTAB.
  142377. */
  142378. #ifdef SQLITE_DEBUG
  142379. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  142380. return SQLITE_CORRUPT_VTAB;
  142381. }
  142382. #endif
  142383. #if !SQLITE_CORE
  142384. /*
  142385. ** Initialize API pointer table, if required.
  142386. */
  142387. #ifdef _WIN32
  142388. __declspec(dllexport)
  142389. #endif
  142390. SQLITE_API int sqlite3_fts3_init(
  142391. sqlite3 *db,
  142392. char **pzErrMsg,
  142393. const sqlite3_api_routines *pApi
  142394. ){
  142395. SQLITE_EXTENSION_INIT2(pApi)
  142396. return sqlite3Fts3Init(db);
  142397. }
  142398. #endif
  142399. #endif
  142400. /************** End of fts3.c ************************************************/
  142401. /************** Begin file fts3_aux.c ****************************************/
  142402. /*
  142403. ** 2011 Jan 27
  142404. **
  142405. ** The author disclaims copyright to this source code. In place of
  142406. ** a legal notice, here is a blessing:
  142407. **
  142408. ** May you do good and not evil.
  142409. ** May you find forgiveness for yourself and forgive others.
  142410. ** May you share freely, never taking more than you give.
  142411. **
  142412. ******************************************************************************
  142413. **
  142414. */
  142415. /* #include "fts3Int.h" */
  142416. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  142417. /* #include <string.h> */
  142418. /* #include <assert.h> */
  142419. typedef struct Fts3auxTable Fts3auxTable;
  142420. typedef struct Fts3auxCursor Fts3auxCursor;
  142421. struct Fts3auxTable {
  142422. sqlite3_vtab base; /* Base class used by SQLite core */
  142423. Fts3Table *pFts3Tab;
  142424. };
  142425. struct Fts3auxCursor {
  142426. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  142427. Fts3MultiSegReader csr; /* Must be right after "base" */
  142428. Fts3SegFilter filter;
  142429. char *zStop;
  142430. int nStop; /* Byte-length of string zStop */
  142431. int iLangid; /* Language id to query */
  142432. int isEof; /* True if cursor is at EOF */
  142433. sqlite3_int64 iRowid; /* Current rowid */
  142434. int iCol; /* Current value of 'col' column */
  142435. int nStat; /* Size of aStat[] array */
  142436. struct Fts3auxColstats {
  142437. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  142438. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  142439. } *aStat;
  142440. };
  142441. /*
  142442. ** Schema of the terms table.
  142443. */
  142444. #define FTS3_AUX_SCHEMA \
  142445. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  142446. /*
  142447. ** This function does all the work for both the xConnect and xCreate methods.
  142448. ** These tables have no persistent representation of their own, so xConnect
  142449. ** and xCreate are identical operations.
  142450. */
  142451. static int fts3auxConnectMethod(
  142452. sqlite3 *db, /* Database connection */
  142453. void *pUnused, /* Unused */
  142454. int argc, /* Number of elements in argv array */
  142455. const char * const *argv, /* xCreate/xConnect argument array */
  142456. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  142457. char **pzErr /* OUT: sqlite3_malloc'd error message */
  142458. ){
  142459. char const *zDb; /* Name of database (e.g. "main") */
  142460. char const *zFts3; /* Name of fts3 table */
  142461. int nDb; /* Result of strlen(zDb) */
  142462. int nFts3; /* Result of strlen(zFts3) */
  142463. int nByte; /* Bytes of space to allocate here */
  142464. int rc; /* value returned by declare_vtab() */
  142465. Fts3auxTable *p; /* Virtual table object to return */
  142466. UNUSED_PARAMETER(pUnused);
  142467. /* The user should invoke this in one of two forms:
  142468. **
  142469. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  142470. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  142471. */
  142472. if( argc!=4 && argc!=5 ) goto bad_args;
  142473. zDb = argv[1];
  142474. nDb = (int)strlen(zDb);
  142475. if( argc==5 ){
  142476. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  142477. zDb = argv[3];
  142478. nDb = (int)strlen(zDb);
  142479. zFts3 = argv[4];
  142480. }else{
  142481. goto bad_args;
  142482. }
  142483. }else{
  142484. zFts3 = argv[3];
  142485. }
  142486. nFts3 = (int)strlen(zFts3);
  142487. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  142488. if( rc!=SQLITE_OK ) return rc;
  142489. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  142490. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  142491. if( !p ) return SQLITE_NOMEM;
  142492. memset(p, 0, nByte);
  142493. p->pFts3Tab = (Fts3Table *)&p[1];
  142494. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  142495. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  142496. p->pFts3Tab->db = db;
  142497. p->pFts3Tab->nIndex = 1;
  142498. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  142499. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  142500. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  142501. *ppVtab = (sqlite3_vtab *)p;
  142502. return SQLITE_OK;
  142503. bad_args:
  142504. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  142505. return SQLITE_ERROR;
  142506. }
  142507. /*
  142508. ** This function does the work for both the xDisconnect and xDestroy methods.
  142509. ** These tables have no persistent representation of their own, so xDisconnect
  142510. ** and xDestroy are identical operations.
  142511. */
  142512. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  142513. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  142514. Fts3Table *pFts3 = p->pFts3Tab;
  142515. int i;
  142516. /* Free any prepared statements held */
  142517. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  142518. sqlite3_finalize(pFts3->aStmt[i]);
  142519. }
  142520. sqlite3_free(pFts3->zSegmentsTbl);
  142521. sqlite3_free(p);
  142522. return SQLITE_OK;
  142523. }
  142524. #define FTS4AUX_EQ_CONSTRAINT 1
  142525. #define FTS4AUX_GE_CONSTRAINT 2
  142526. #define FTS4AUX_LE_CONSTRAINT 4
  142527. /*
  142528. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  142529. */
  142530. static int fts3auxBestIndexMethod(
  142531. sqlite3_vtab *pVTab,
  142532. sqlite3_index_info *pInfo
  142533. ){
  142534. int i;
  142535. int iEq = -1;
  142536. int iGe = -1;
  142537. int iLe = -1;
  142538. int iLangid = -1;
  142539. int iNext = 1; /* Next free argvIndex value */
  142540. UNUSED_PARAMETER(pVTab);
  142541. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  142542. if( pInfo->nOrderBy==1
  142543. && pInfo->aOrderBy[0].iColumn==0
  142544. && pInfo->aOrderBy[0].desc==0
  142545. ){
  142546. pInfo->orderByConsumed = 1;
  142547. }
  142548. /* Search for equality and range constraints on the "term" column.
  142549. ** And equality constraints on the hidden "languageid" column. */
  142550. for(i=0; i<pInfo->nConstraint; i++){
  142551. if( pInfo->aConstraint[i].usable ){
  142552. int op = pInfo->aConstraint[i].op;
  142553. int iCol = pInfo->aConstraint[i].iColumn;
  142554. if( iCol==0 ){
  142555. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  142556. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  142557. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  142558. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  142559. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  142560. }
  142561. if( iCol==4 ){
  142562. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  142563. }
  142564. }
  142565. }
  142566. if( iEq>=0 ){
  142567. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  142568. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  142569. pInfo->estimatedCost = 5;
  142570. }else{
  142571. pInfo->idxNum = 0;
  142572. pInfo->estimatedCost = 20000;
  142573. if( iGe>=0 ){
  142574. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  142575. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  142576. pInfo->estimatedCost /= 2;
  142577. }
  142578. if( iLe>=0 ){
  142579. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  142580. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  142581. pInfo->estimatedCost /= 2;
  142582. }
  142583. }
  142584. if( iLangid>=0 ){
  142585. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  142586. pInfo->estimatedCost--;
  142587. }
  142588. return SQLITE_OK;
  142589. }
  142590. /*
  142591. ** xOpen - Open a cursor.
  142592. */
  142593. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  142594. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  142595. UNUSED_PARAMETER(pVTab);
  142596. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  142597. if( !pCsr ) return SQLITE_NOMEM;
  142598. memset(pCsr, 0, sizeof(Fts3auxCursor));
  142599. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  142600. return SQLITE_OK;
  142601. }
  142602. /*
  142603. ** xClose - Close a cursor.
  142604. */
  142605. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  142606. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  142607. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142608. sqlite3Fts3SegmentsClose(pFts3);
  142609. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  142610. sqlite3_free((void *)pCsr->filter.zTerm);
  142611. sqlite3_free(pCsr->zStop);
  142612. sqlite3_free(pCsr->aStat);
  142613. sqlite3_free(pCsr);
  142614. return SQLITE_OK;
  142615. }
  142616. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  142617. if( nSize>pCsr->nStat ){
  142618. struct Fts3auxColstats *aNew;
  142619. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  142620. sizeof(struct Fts3auxColstats) * nSize
  142621. );
  142622. if( aNew==0 ) return SQLITE_NOMEM;
  142623. memset(&aNew[pCsr->nStat], 0,
  142624. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  142625. );
  142626. pCsr->aStat = aNew;
  142627. pCsr->nStat = nSize;
  142628. }
  142629. return SQLITE_OK;
  142630. }
  142631. /*
  142632. ** xNext - Advance the cursor to the next row, if any.
  142633. */
  142634. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  142635. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142636. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  142637. int rc;
  142638. /* Increment our pretend rowid value. */
  142639. pCsr->iRowid++;
  142640. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  142641. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  142642. }
  142643. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  142644. if( rc==SQLITE_ROW ){
  142645. int i = 0;
  142646. int nDoclist = pCsr->csr.nDoclist;
  142647. char *aDoclist = pCsr->csr.aDoclist;
  142648. int iCol;
  142649. int eState = 0;
  142650. if( pCsr->zStop ){
  142651. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  142652. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  142653. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  142654. pCsr->isEof = 1;
  142655. return SQLITE_OK;
  142656. }
  142657. }
  142658. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  142659. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  142660. iCol = 0;
  142661. while( i<nDoclist ){
  142662. sqlite3_int64 v = 0;
  142663. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  142664. switch( eState ){
  142665. /* State 0. In this state the integer just read was a docid. */
  142666. case 0:
  142667. pCsr->aStat[0].nDoc++;
  142668. eState = 1;
  142669. iCol = 0;
  142670. break;
  142671. /* State 1. In this state we are expecting either a 1, indicating
  142672. ** that the following integer will be a column number, or the
  142673. ** start of a position list for column 0.
  142674. **
  142675. ** The only difference between state 1 and state 2 is that if the
  142676. ** integer encountered in state 1 is not 0 or 1, then we need to
  142677. ** increment the column 0 "nDoc" count for this term.
  142678. */
  142679. case 1:
  142680. assert( iCol==0 );
  142681. if( v>1 ){
  142682. pCsr->aStat[1].nDoc++;
  142683. }
  142684. eState = 2;
  142685. /* fall through */
  142686. case 2:
  142687. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  142688. eState = 0;
  142689. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  142690. eState = 3;
  142691. }else{ /* 2 or greater. A position. */
  142692. pCsr->aStat[iCol+1].nOcc++;
  142693. pCsr->aStat[0].nOcc++;
  142694. }
  142695. break;
  142696. /* State 3. The integer just read is a column number. */
  142697. default: assert( eState==3 );
  142698. iCol = (int)v;
  142699. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  142700. pCsr->aStat[iCol+1].nDoc++;
  142701. eState = 2;
  142702. break;
  142703. }
  142704. }
  142705. pCsr->iCol = 0;
  142706. rc = SQLITE_OK;
  142707. }else{
  142708. pCsr->isEof = 1;
  142709. }
  142710. return rc;
  142711. }
  142712. /*
  142713. ** xFilter - Initialize a cursor to point at the start of its data.
  142714. */
  142715. static int fts3auxFilterMethod(
  142716. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  142717. int idxNum, /* Strategy index */
  142718. const char *idxStr, /* Unused */
  142719. int nVal, /* Number of elements in apVal */
  142720. sqlite3_value **apVal /* Arguments for the indexing scheme */
  142721. ){
  142722. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142723. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  142724. int rc;
  142725. int isScan = 0;
  142726. int iLangVal = 0; /* Language id to query */
  142727. int iEq = -1; /* Index of term=? value in apVal */
  142728. int iGe = -1; /* Index of term>=? value in apVal */
  142729. int iLe = -1; /* Index of term<=? value in apVal */
  142730. int iLangid = -1; /* Index of languageid=? value in apVal */
  142731. int iNext = 0;
  142732. UNUSED_PARAMETER(nVal);
  142733. UNUSED_PARAMETER(idxStr);
  142734. assert( idxStr==0 );
  142735. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  142736. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  142737. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  142738. );
  142739. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  142740. iEq = iNext++;
  142741. }else{
  142742. isScan = 1;
  142743. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  142744. iGe = iNext++;
  142745. }
  142746. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  142747. iLe = iNext++;
  142748. }
  142749. }
  142750. if( iNext<nVal ){
  142751. iLangid = iNext++;
  142752. }
  142753. /* In case this cursor is being reused, close and zero it. */
  142754. testcase(pCsr->filter.zTerm);
  142755. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  142756. sqlite3_free((void *)pCsr->filter.zTerm);
  142757. sqlite3_free(pCsr->aStat);
  142758. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  142759. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  142760. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  142761. if( iEq>=0 || iGe>=0 ){
  142762. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  142763. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  142764. if( zStr ){
  142765. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  142766. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  142767. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  142768. }
  142769. }
  142770. if( iLe>=0 ){
  142771. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  142772. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  142773. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  142774. }
  142775. if( iLangid>=0 ){
  142776. iLangVal = sqlite3_value_int(apVal[iLangid]);
  142777. /* If the user specified a negative value for the languageid, use zero
  142778. ** instead. This works, as the "languageid=?" constraint will also
  142779. ** be tested by the VDBE layer. The test will always be false (since
  142780. ** this module will not return a row with a negative languageid), and
  142781. ** so the overall query will return zero rows. */
  142782. if( iLangVal<0 ) iLangVal = 0;
  142783. }
  142784. pCsr->iLangid = iLangVal;
  142785. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  142786. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  142787. );
  142788. if( rc==SQLITE_OK ){
  142789. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  142790. }
  142791. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  142792. return rc;
  142793. }
  142794. /*
  142795. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  142796. */
  142797. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  142798. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142799. return pCsr->isEof;
  142800. }
  142801. /*
  142802. ** xColumn - Return a column value.
  142803. */
  142804. static int fts3auxColumnMethod(
  142805. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  142806. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  142807. int iCol /* Index of column to read value from */
  142808. ){
  142809. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  142810. assert( p->isEof==0 );
  142811. switch( iCol ){
  142812. case 0: /* term */
  142813. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  142814. break;
  142815. case 1: /* col */
  142816. if( p->iCol ){
  142817. sqlite3_result_int(pCtx, p->iCol-1);
  142818. }else{
  142819. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  142820. }
  142821. break;
  142822. case 2: /* documents */
  142823. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  142824. break;
  142825. case 3: /* occurrences */
  142826. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  142827. break;
  142828. default: /* languageid */
  142829. assert( iCol==4 );
  142830. sqlite3_result_int(pCtx, p->iLangid);
  142831. break;
  142832. }
  142833. return SQLITE_OK;
  142834. }
  142835. /*
  142836. ** xRowid - Return the current rowid for the cursor.
  142837. */
  142838. static int fts3auxRowidMethod(
  142839. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  142840. sqlite_int64 *pRowid /* OUT: Rowid value */
  142841. ){
  142842. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142843. *pRowid = pCsr->iRowid;
  142844. return SQLITE_OK;
  142845. }
  142846. /*
  142847. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  142848. ** if successful or an error code if sqlite3_create_module() fails.
  142849. */
  142850. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  142851. static const sqlite3_module fts3aux_module = {
  142852. 0, /* iVersion */
  142853. fts3auxConnectMethod, /* xCreate */
  142854. fts3auxConnectMethod, /* xConnect */
  142855. fts3auxBestIndexMethod, /* xBestIndex */
  142856. fts3auxDisconnectMethod, /* xDisconnect */
  142857. fts3auxDisconnectMethod, /* xDestroy */
  142858. fts3auxOpenMethod, /* xOpen */
  142859. fts3auxCloseMethod, /* xClose */
  142860. fts3auxFilterMethod, /* xFilter */
  142861. fts3auxNextMethod, /* xNext */
  142862. fts3auxEofMethod, /* xEof */
  142863. fts3auxColumnMethod, /* xColumn */
  142864. fts3auxRowidMethod, /* xRowid */
  142865. 0, /* xUpdate */
  142866. 0, /* xBegin */
  142867. 0, /* xSync */
  142868. 0, /* xCommit */
  142869. 0, /* xRollback */
  142870. 0, /* xFindFunction */
  142871. 0, /* xRename */
  142872. 0, /* xSavepoint */
  142873. 0, /* xRelease */
  142874. 0 /* xRollbackTo */
  142875. };
  142876. int rc; /* Return code */
  142877. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  142878. return rc;
  142879. }
  142880. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  142881. /************** End of fts3_aux.c ********************************************/
  142882. /************** Begin file fts3_expr.c ***************************************/
  142883. /*
  142884. ** 2008 Nov 28
  142885. **
  142886. ** The author disclaims copyright to this source code. In place of
  142887. ** a legal notice, here is a blessing:
  142888. **
  142889. ** May you do good and not evil.
  142890. ** May you find forgiveness for yourself and forgive others.
  142891. ** May you share freely, never taking more than you give.
  142892. **
  142893. ******************************************************************************
  142894. **
  142895. ** This module contains code that implements a parser for fts3 query strings
  142896. ** (the right-hand argument to the MATCH operator). Because the supported
  142897. ** syntax is relatively simple, the whole tokenizer/parser system is
  142898. ** hand-coded.
  142899. */
  142900. /* #include "fts3Int.h" */
  142901. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  142902. /*
  142903. ** By default, this module parses the legacy syntax that has been
  142904. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  142905. ** is defined, then it uses the new syntax. The differences between
  142906. ** the new and the old syntaxes are:
  142907. **
  142908. ** a) The new syntax supports parenthesis. The old does not.
  142909. **
  142910. ** b) The new syntax supports the AND and NOT operators. The old does not.
  142911. **
  142912. ** c) The old syntax supports the "-" token qualifier. This is not
  142913. ** supported by the new syntax (it is replaced by the NOT operator).
  142914. **
  142915. ** d) When using the old syntax, the OR operator has a greater precedence
  142916. ** than an implicit AND. When using the new, both implicity and explicit
  142917. ** AND operators have a higher precedence than OR.
  142918. **
  142919. ** If compiled with SQLITE_TEST defined, then this module exports the
  142920. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  142921. ** to zero causes the module to use the old syntax. If it is set to
  142922. ** non-zero the new syntax is activated. This is so both syntaxes can
  142923. ** be tested using a single build of testfixture.
  142924. **
  142925. ** The following describes the syntax supported by the fts3 MATCH
  142926. ** operator in a similar format to that used by the lemon parser
  142927. ** generator. This module does not use actually lemon, it uses a
  142928. ** custom parser.
  142929. **
  142930. ** query ::= andexpr (OR andexpr)*.
  142931. **
  142932. ** andexpr ::= notexpr (AND? notexpr)*.
  142933. **
  142934. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  142935. ** notexpr ::= LP query RP.
  142936. **
  142937. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  142938. **
  142939. ** distance_opt ::= .
  142940. ** distance_opt ::= / INTEGER.
  142941. **
  142942. ** phrase ::= TOKEN.
  142943. ** phrase ::= COLUMN:TOKEN.
  142944. ** phrase ::= "TOKEN TOKEN TOKEN...".
  142945. */
  142946. #ifdef SQLITE_TEST
  142947. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  142948. #else
  142949. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  142950. # define sqlite3_fts3_enable_parentheses 1
  142951. # else
  142952. # define sqlite3_fts3_enable_parentheses 0
  142953. # endif
  142954. #endif
  142955. /*
  142956. ** Default span for NEAR operators.
  142957. */
  142958. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  142959. /* #include <string.h> */
  142960. /* #include <assert.h> */
  142961. /*
  142962. ** isNot:
  142963. ** This variable is used by function getNextNode(). When getNextNode() is
  142964. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  142965. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  142966. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  142967. ** zero.
  142968. */
  142969. typedef struct ParseContext ParseContext;
  142970. struct ParseContext {
  142971. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  142972. int iLangid; /* Language id used with tokenizer */
  142973. const char **azCol; /* Array of column names for fts3 table */
  142974. int bFts4; /* True to allow FTS4-only syntax */
  142975. int nCol; /* Number of entries in azCol[] */
  142976. int iDefaultCol; /* Default column to query */
  142977. int isNot; /* True if getNextNode() sees a unary - */
  142978. sqlite3_context *pCtx; /* Write error message here */
  142979. int nNest; /* Number of nested brackets */
  142980. };
  142981. /*
  142982. ** This function is equivalent to the standard isspace() function.
  142983. **
  142984. ** The standard isspace() can be awkward to use safely, because although it
  142985. ** is defined to accept an argument of type int, its behavior when passed
  142986. ** an integer that falls outside of the range of the unsigned char type
  142987. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  142988. ** is defined to accept an argument of type char, and always returns 0 for
  142989. ** any values that fall outside of the range of the unsigned char type (i.e.
  142990. ** negative values).
  142991. */
  142992. static int fts3isspace(char c){
  142993. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  142994. }
  142995. /*
  142996. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  142997. ** zero the memory before returning a pointer to it. If unsuccessful,
  142998. ** return NULL.
  142999. */
  143000. static void *fts3MallocZero(int nByte){
  143001. void *pRet = sqlite3_malloc(nByte);
  143002. if( pRet ) memset(pRet, 0, nByte);
  143003. return pRet;
  143004. }
  143005. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  143006. sqlite3_tokenizer *pTokenizer,
  143007. int iLangid,
  143008. const char *z,
  143009. int n,
  143010. sqlite3_tokenizer_cursor **ppCsr
  143011. ){
  143012. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  143013. sqlite3_tokenizer_cursor *pCsr = 0;
  143014. int rc;
  143015. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  143016. assert( rc==SQLITE_OK || pCsr==0 );
  143017. if( rc==SQLITE_OK ){
  143018. pCsr->pTokenizer = pTokenizer;
  143019. if( pModule->iVersion>=1 ){
  143020. rc = pModule->xLanguageid(pCsr, iLangid);
  143021. if( rc!=SQLITE_OK ){
  143022. pModule->xClose(pCsr);
  143023. pCsr = 0;
  143024. }
  143025. }
  143026. }
  143027. *ppCsr = pCsr;
  143028. return rc;
  143029. }
  143030. /*
  143031. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  143032. ** call fts3ExprParse(). So this forward declaration is required.
  143033. */
  143034. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  143035. /*
  143036. ** Extract the next token from buffer z (length n) using the tokenizer
  143037. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  143038. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  143039. ** single token and set *ppExpr to point to it. If the end of the buffer is
  143040. ** reached before a token is found, set *ppExpr to zero. It is the
  143041. ** responsibility of the caller to eventually deallocate the allocated
  143042. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  143043. **
  143044. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  143045. ** fails.
  143046. */
  143047. static int getNextToken(
  143048. ParseContext *pParse, /* fts3 query parse context */
  143049. int iCol, /* Value for Fts3Phrase.iColumn */
  143050. const char *z, int n, /* Input string */
  143051. Fts3Expr **ppExpr, /* OUT: expression */
  143052. int *pnConsumed /* OUT: Number of bytes consumed */
  143053. ){
  143054. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  143055. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  143056. int rc;
  143057. sqlite3_tokenizer_cursor *pCursor;
  143058. Fts3Expr *pRet = 0;
  143059. int i = 0;
  143060. /* Set variable i to the maximum number of bytes of input to tokenize. */
  143061. for(i=0; i<n; i++){
  143062. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  143063. if( z[i]=='"' ) break;
  143064. }
  143065. *pnConsumed = i;
  143066. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  143067. if( rc==SQLITE_OK ){
  143068. const char *zToken;
  143069. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  143070. int nByte; /* total space to allocate */
  143071. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  143072. if( rc==SQLITE_OK ){
  143073. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  143074. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  143075. if( !pRet ){
  143076. rc = SQLITE_NOMEM;
  143077. }else{
  143078. pRet->eType = FTSQUERY_PHRASE;
  143079. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  143080. pRet->pPhrase->nToken = 1;
  143081. pRet->pPhrase->iColumn = iCol;
  143082. pRet->pPhrase->aToken[0].n = nToken;
  143083. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  143084. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  143085. if( iEnd<n && z[iEnd]=='*' ){
  143086. pRet->pPhrase->aToken[0].isPrefix = 1;
  143087. iEnd++;
  143088. }
  143089. while( 1 ){
  143090. if( !sqlite3_fts3_enable_parentheses
  143091. && iStart>0 && z[iStart-1]=='-'
  143092. ){
  143093. pParse->isNot = 1;
  143094. iStart--;
  143095. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  143096. pRet->pPhrase->aToken[0].bFirst = 1;
  143097. iStart--;
  143098. }else{
  143099. break;
  143100. }
  143101. }
  143102. }
  143103. *pnConsumed = iEnd;
  143104. }else if( i && rc==SQLITE_DONE ){
  143105. rc = SQLITE_OK;
  143106. }
  143107. pModule->xClose(pCursor);
  143108. }
  143109. *ppExpr = pRet;
  143110. return rc;
  143111. }
  143112. /*
  143113. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  143114. ** then free the old allocation.
  143115. */
  143116. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  143117. void *pRet = sqlite3_realloc(pOrig, nNew);
  143118. if( !pRet ){
  143119. sqlite3_free(pOrig);
  143120. }
  143121. return pRet;
  143122. }
  143123. /*
  143124. ** Buffer zInput, length nInput, contains the contents of a quoted string
  143125. ** that appeared as part of an fts3 query expression. Neither quote character
  143126. ** is included in the buffer. This function attempts to tokenize the entire
  143127. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  143128. ** containing the results.
  143129. **
  143130. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  143131. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  143132. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  143133. ** to 0.
  143134. */
  143135. static int getNextString(
  143136. ParseContext *pParse, /* fts3 query parse context */
  143137. const char *zInput, int nInput, /* Input string */
  143138. Fts3Expr **ppExpr /* OUT: expression */
  143139. ){
  143140. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  143141. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  143142. int rc;
  143143. Fts3Expr *p = 0;
  143144. sqlite3_tokenizer_cursor *pCursor = 0;
  143145. char *zTemp = 0;
  143146. int nTemp = 0;
  143147. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  143148. int nToken = 0;
  143149. /* The final Fts3Expr data structure, including the Fts3Phrase,
  143150. ** Fts3PhraseToken structures token buffers are all stored as a single
  143151. ** allocation so that the expression can be freed with a single call to
  143152. ** sqlite3_free(). Setting this up requires a two pass approach.
  143153. **
  143154. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  143155. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  143156. ** to assemble data in two dynamic buffers:
  143157. **
  143158. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  143159. ** structure, followed by the array of Fts3PhraseToken
  143160. ** structures. This pass only populates the Fts3PhraseToken array.
  143161. **
  143162. ** Buffer zTemp: Contains copies of all tokens.
  143163. **
  143164. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  143165. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  143166. ** structures.
  143167. */
  143168. rc = sqlite3Fts3OpenTokenizer(
  143169. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  143170. if( rc==SQLITE_OK ){
  143171. int ii;
  143172. for(ii=0; rc==SQLITE_OK; ii++){
  143173. const char *zByte;
  143174. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  143175. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  143176. if( rc==SQLITE_OK ){
  143177. Fts3PhraseToken *pToken;
  143178. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  143179. if( !p ) goto no_mem;
  143180. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  143181. if( !zTemp ) goto no_mem;
  143182. assert( nToken==ii );
  143183. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  143184. memset(pToken, 0, sizeof(Fts3PhraseToken));
  143185. memcpy(&zTemp[nTemp], zByte, nByte);
  143186. nTemp += nByte;
  143187. pToken->n = nByte;
  143188. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  143189. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  143190. nToken = ii+1;
  143191. }
  143192. }
  143193. pModule->xClose(pCursor);
  143194. pCursor = 0;
  143195. }
  143196. if( rc==SQLITE_DONE ){
  143197. int jj;
  143198. char *zBuf = 0;
  143199. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  143200. if( !p ) goto no_mem;
  143201. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  143202. p->eType = FTSQUERY_PHRASE;
  143203. p->pPhrase = (Fts3Phrase *)&p[1];
  143204. p->pPhrase->iColumn = pParse->iDefaultCol;
  143205. p->pPhrase->nToken = nToken;
  143206. zBuf = (char *)&p->pPhrase->aToken[nToken];
  143207. if( zTemp ){
  143208. memcpy(zBuf, zTemp, nTemp);
  143209. sqlite3_free(zTemp);
  143210. }else{
  143211. assert( nTemp==0 );
  143212. }
  143213. for(jj=0; jj<p->pPhrase->nToken; jj++){
  143214. p->pPhrase->aToken[jj].z = zBuf;
  143215. zBuf += p->pPhrase->aToken[jj].n;
  143216. }
  143217. rc = SQLITE_OK;
  143218. }
  143219. *ppExpr = p;
  143220. return rc;
  143221. no_mem:
  143222. if( pCursor ){
  143223. pModule->xClose(pCursor);
  143224. }
  143225. sqlite3_free(zTemp);
  143226. sqlite3_free(p);
  143227. *ppExpr = 0;
  143228. return SQLITE_NOMEM;
  143229. }
  143230. /*
  143231. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  143232. ** structure, or set to 0 if the end of the input buffer is reached.
  143233. **
  143234. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  143235. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  143236. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  143237. */
  143238. static int getNextNode(
  143239. ParseContext *pParse, /* fts3 query parse context */
  143240. const char *z, int n, /* Input string */
  143241. Fts3Expr **ppExpr, /* OUT: expression */
  143242. int *pnConsumed /* OUT: Number of bytes consumed */
  143243. ){
  143244. static const struct Fts3Keyword {
  143245. char *z; /* Keyword text */
  143246. unsigned char n; /* Length of the keyword */
  143247. unsigned char parenOnly; /* Only valid in paren mode */
  143248. unsigned char eType; /* Keyword code */
  143249. } aKeyword[] = {
  143250. { "OR" , 2, 0, FTSQUERY_OR },
  143251. { "AND", 3, 1, FTSQUERY_AND },
  143252. { "NOT", 3, 1, FTSQUERY_NOT },
  143253. { "NEAR", 4, 0, FTSQUERY_NEAR }
  143254. };
  143255. int ii;
  143256. int iCol;
  143257. int iColLen;
  143258. int rc;
  143259. Fts3Expr *pRet = 0;
  143260. const char *zInput = z;
  143261. int nInput = n;
  143262. pParse->isNot = 0;
  143263. /* Skip over any whitespace before checking for a keyword, an open or
  143264. ** close bracket, or a quoted string.
  143265. */
  143266. while( nInput>0 && fts3isspace(*zInput) ){
  143267. nInput--;
  143268. zInput++;
  143269. }
  143270. if( nInput==0 ){
  143271. return SQLITE_DONE;
  143272. }
  143273. /* See if we are dealing with a keyword. */
  143274. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  143275. const struct Fts3Keyword *pKey = &aKeyword[ii];
  143276. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  143277. continue;
  143278. }
  143279. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  143280. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  143281. int nKey = pKey->n;
  143282. char cNext;
  143283. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  143284. if( pKey->eType==FTSQUERY_NEAR ){
  143285. assert( nKey==4 );
  143286. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  143287. nNear = 0;
  143288. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  143289. nNear = nNear * 10 + (zInput[nKey] - '0');
  143290. }
  143291. }
  143292. }
  143293. /* At this point this is probably a keyword. But for that to be true,
  143294. ** the next byte must contain either whitespace, an open or close
  143295. ** parenthesis, a quote character, or EOF.
  143296. */
  143297. cNext = zInput[nKey];
  143298. if( fts3isspace(cNext)
  143299. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  143300. ){
  143301. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  143302. if( !pRet ){
  143303. return SQLITE_NOMEM;
  143304. }
  143305. pRet->eType = pKey->eType;
  143306. pRet->nNear = nNear;
  143307. *ppExpr = pRet;
  143308. *pnConsumed = (int)((zInput - z) + nKey);
  143309. return SQLITE_OK;
  143310. }
  143311. /* Turns out that wasn't a keyword after all. This happens if the
  143312. ** user has supplied a token such as "ORacle". Continue.
  143313. */
  143314. }
  143315. }
  143316. /* See if we are dealing with a quoted phrase. If this is the case, then
  143317. ** search for the closing quote and pass the whole string to getNextString()
  143318. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  143319. ** a quote character embedded in a string.
  143320. */
  143321. if( *zInput=='"' ){
  143322. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  143323. *pnConsumed = (int)((zInput - z) + ii + 1);
  143324. if( ii==nInput ){
  143325. return SQLITE_ERROR;
  143326. }
  143327. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  143328. }
  143329. if( sqlite3_fts3_enable_parentheses ){
  143330. if( *zInput=='(' ){
  143331. int nConsumed = 0;
  143332. pParse->nNest++;
  143333. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  143334. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  143335. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  143336. return rc;
  143337. }else if( *zInput==')' ){
  143338. pParse->nNest--;
  143339. *pnConsumed = (int)((zInput - z) + 1);
  143340. *ppExpr = 0;
  143341. return SQLITE_DONE;
  143342. }
  143343. }
  143344. /* If control flows to this point, this must be a regular token, or
  143345. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  143346. ** interface. Before doing so, figure out if there is an explicit
  143347. ** column specifier for the token.
  143348. **
  143349. ** TODO: Strangely, it is not possible to associate a column specifier
  143350. ** with a quoted phrase, only with a single token. Not sure if this was
  143351. ** an implementation artifact or an intentional decision when fts3 was
  143352. ** first implemented. Whichever it was, this module duplicates the
  143353. ** limitation.
  143354. */
  143355. iCol = pParse->iDefaultCol;
  143356. iColLen = 0;
  143357. for(ii=0; ii<pParse->nCol; ii++){
  143358. const char *zStr = pParse->azCol[ii];
  143359. int nStr = (int)strlen(zStr);
  143360. if( nInput>nStr && zInput[nStr]==':'
  143361. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  143362. ){
  143363. iCol = ii;
  143364. iColLen = (int)((zInput - z) + nStr + 1);
  143365. break;
  143366. }
  143367. }
  143368. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  143369. *pnConsumed += iColLen;
  143370. return rc;
  143371. }
  143372. /*
  143373. ** The argument is an Fts3Expr structure for a binary operator (any type
  143374. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  143375. ** precedence of the operator. Lower values have a higher precedence (i.e.
  143376. ** group more tightly). For example, in the C language, the == operator
  143377. ** groups more tightly than ||, and would therefore have a higher precedence.
  143378. **
  143379. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  143380. ** is defined), the order of the operators in precedence from highest to
  143381. ** lowest is:
  143382. **
  143383. ** NEAR
  143384. ** NOT
  143385. ** AND (including implicit ANDs)
  143386. ** OR
  143387. **
  143388. ** Note that when using the old query syntax, the OR operator has a higher
  143389. ** precedence than the AND operator.
  143390. */
  143391. static int opPrecedence(Fts3Expr *p){
  143392. assert( p->eType!=FTSQUERY_PHRASE );
  143393. if( sqlite3_fts3_enable_parentheses ){
  143394. return p->eType;
  143395. }else if( p->eType==FTSQUERY_NEAR ){
  143396. return 1;
  143397. }else if( p->eType==FTSQUERY_OR ){
  143398. return 2;
  143399. }
  143400. assert( p->eType==FTSQUERY_AND );
  143401. return 3;
  143402. }
  143403. /*
  143404. ** Argument ppHead contains a pointer to the current head of a query
  143405. ** expression tree being parsed. pPrev is the expression node most recently
  143406. ** inserted into the tree. This function adds pNew, which is always a binary
  143407. ** operator node, into the expression tree based on the relative precedence
  143408. ** of pNew and the existing nodes of the tree. This may result in the head
  143409. ** of the tree changing, in which case *ppHead is set to the new root node.
  143410. */
  143411. static void insertBinaryOperator(
  143412. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  143413. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  143414. Fts3Expr *pNew /* New binary node to insert into expression tree */
  143415. ){
  143416. Fts3Expr *pSplit = pPrev;
  143417. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  143418. pSplit = pSplit->pParent;
  143419. }
  143420. if( pSplit->pParent ){
  143421. assert( pSplit->pParent->pRight==pSplit );
  143422. pSplit->pParent->pRight = pNew;
  143423. pNew->pParent = pSplit->pParent;
  143424. }else{
  143425. *ppHead = pNew;
  143426. }
  143427. pNew->pLeft = pSplit;
  143428. pSplit->pParent = pNew;
  143429. }
  143430. /*
  143431. ** Parse the fts3 query expression found in buffer z, length n. This function
  143432. ** returns either when the end of the buffer is reached or an unmatched
  143433. ** closing bracket - ')' - is encountered.
  143434. **
  143435. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  143436. ** parsed form of the expression and *pnConsumed is set to the number of
  143437. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  143438. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  143439. */
  143440. static int fts3ExprParse(
  143441. ParseContext *pParse, /* fts3 query parse context */
  143442. const char *z, int n, /* Text of MATCH query */
  143443. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  143444. int *pnConsumed /* OUT: Number of bytes consumed */
  143445. ){
  143446. Fts3Expr *pRet = 0;
  143447. Fts3Expr *pPrev = 0;
  143448. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  143449. int nIn = n;
  143450. const char *zIn = z;
  143451. int rc = SQLITE_OK;
  143452. int isRequirePhrase = 1;
  143453. while( rc==SQLITE_OK ){
  143454. Fts3Expr *p = 0;
  143455. int nByte = 0;
  143456. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  143457. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  143458. if( rc==SQLITE_OK ){
  143459. if( p ){
  143460. int isPhrase;
  143461. if( !sqlite3_fts3_enable_parentheses
  143462. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  143463. ){
  143464. /* Create an implicit NOT operator. */
  143465. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  143466. if( !pNot ){
  143467. sqlite3Fts3ExprFree(p);
  143468. rc = SQLITE_NOMEM;
  143469. goto exprparse_out;
  143470. }
  143471. pNot->eType = FTSQUERY_NOT;
  143472. pNot->pRight = p;
  143473. p->pParent = pNot;
  143474. if( pNotBranch ){
  143475. pNot->pLeft = pNotBranch;
  143476. pNotBranch->pParent = pNot;
  143477. }
  143478. pNotBranch = pNot;
  143479. p = pPrev;
  143480. }else{
  143481. int eType = p->eType;
  143482. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  143483. /* The isRequirePhrase variable is set to true if a phrase or
  143484. ** an expression contained in parenthesis is required. If a
  143485. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  143486. ** isRequirePhrase is set, this is a syntax error.
  143487. */
  143488. if( !isPhrase && isRequirePhrase ){
  143489. sqlite3Fts3ExprFree(p);
  143490. rc = SQLITE_ERROR;
  143491. goto exprparse_out;
  143492. }
  143493. if( isPhrase && !isRequirePhrase ){
  143494. /* Insert an implicit AND operator. */
  143495. Fts3Expr *pAnd;
  143496. assert( pRet && pPrev );
  143497. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  143498. if( !pAnd ){
  143499. sqlite3Fts3ExprFree(p);
  143500. rc = SQLITE_NOMEM;
  143501. goto exprparse_out;
  143502. }
  143503. pAnd->eType = FTSQUERY_AND;
  143504. insertBinaryOperator(&pRet, pPrev, pAnd);
  143505. pPrev = pAnd;
  143506. }
  143507. /* This test catches attempts to make either operand of a NEAR
  143508. ** operator something other than a phrase. For example, either of
  143509. ** the following:
  143510. **
  143511. ** (bracketed expression) NEAR phrase
  143512. ** phrase NEAR (bracketed expression)
  143513. **
  143514. ** Return an error in either case.
  143515. */
  143516. if( pPrev && (
  143517. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  143518. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  143519. )){
  143520. sqlite3Fts3ExprFree(p);
  143521. rc = SQLITE_ERROR;
  143522. goto exprparse_out;
  143523. }
  143524. if( isPhrase ){
  143525. if( pRet ){
  143526. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  143527. pPrev->pRight = p;
  143528. p->pParent = pPrev;
  143529. }else{
  143530. pRet = p;
  143531. }
  143532. }else{
  143533. insertBinaryOperator(&pRet, pPrev, p);
  143534. }
  143535. isRequirePhrase = !isPhrase;
  143536. }
  143537. pPrev = p;
  143538. }
  143539. assert( nByte>0 );
  143540. }
  143541. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  143542. nIn -= nByte;
  143543. zIn += nByte;
  143544. }
  143545. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  143546. rc = SQLITE_ERROR;
  143547. }
  143548. if( rc==SQLITE_DONE ){
  143549. rc = SQLITE_OK;
  143550. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  143551. if( !pRet ){
  143552. rc = SQLITE_ERROR;
  143553. }else{
  143554. Fts3Expr *pIter = pNotBranch;
  143555. while( pIter->pLeft ){
  143556. pIter = pIter->pLeft;
  143557. }
  143558. pIter->pLeft = pRet;
  143559. pRet->pParent = pIter;
  143560. pRet = pNotBranch;
  143561. }
  143562. }
  143563. }
  143564. *pnConsumed = n - nIn;
  143565. exprparse_out:
  143566. if( rc!=SQLITE_OK ){
  143567. sqlite3Fts3ExprFree(pRet);
  143568. sqlite3Fts3ExprFree(pNotBranch);
  143569. pRet = 0;
  143570. }
  143571. *ppExpr = pRet;
  143572. return rc;
  143573. }
  143574. /*
  143575. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  143576. ** as the only argument is more than nMaxDepth.
  143577. */
  143578. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  143579. int rc = SQLITE_OK;
  143580. if( p ){
  143581. if( nMaxDepth<0 ){
  143582. rc = SQLITE_TOOBIG;
  143583. }else{
  143584. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  143585. if( rc==SQLITE_OK ){
  143586. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  143587. }
  143588. }
  143589. }
  143590. return rc;
  143591. }
  143592. /*
  143593. ** This function attempts to transform the expression tree at (*pp) to
  143594. ** an equivalent but more balanced form. The tree is modified in place.
  143595. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  143596. ** new root expression node.
  143597. **
  143598. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  143599. **
  143600. ** Otherwise, if an error occurs, an SQLite error code is returned and
  143601. ** expression (*pp) freed.
  143602. */
  143603. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  143604. int rc = SQLITE_OK; /* Return code */
  143605. Fts3Expr *pRoot = *pp; /* Initial root node */
  143606. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  143607. int eType = pRoot->eType; /* Type of node in this tree */
  143608. if( nMaxDepth==0 ){
  143609. rc = SQLITE_ERROR;
  143610. }
  143611. if( rc==SQLITE_OK ){
  143612. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  143613. Fts3Expr **apLeaf;
  143614. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  143615. if( 0==apLeaf ){
  143616. rc = SQLITE_NOMEM;
  143617. }else{
  143618. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  143619. }
  143620. if( rc==SQLITE_OK ){
  143621. int i;
  143622. Fts3Expr *p;
  143623. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  143624. for(p=pRoot; p->eType==eType; p=p->pLeft){
  143625. assert( p->pParent==0 || p->pParent->pLeft==p );
  143626. assert( p->pLeft && p->pRight );
  143627. }
  143628. /* This loop runs once for each leaf in the tree of eType nodes. */
  143629. while( 1 ){
  143630. int iLvl;
  143631. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  143632. assert( pParent==0 || pParent->pLeft==p );
  143633. p->pParent = 0;
  143634. if( pParent ){
  143635. pParent->pLeft = 0;
  143636. }else{
  143637. pRoot = 0;
  143638. }
  143639. rc = fts3ExprBalance(&p, nMaxDepth-1);
  143640. if( rc!=SQLITE_OK ) break;
  143641. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  143642. if( apLeaf[iLvl]==0 ){
  143643. apLeaf[iLvl] = p;
  143644. p = 0;
  143645. }else{
  143646. assert( pFree );
  143647. pFree->pLeft = apLeaf[iLvl];
  143648. pFree->pRight = p;
  143649. pFree->pLeft->pParent = pFree;
  143650. pFree->pRight->pParent = pFree;
  143651. p = pFree;
  143652. pFree = pFree->pParent;
  143653. p->pParent = 0;
  143654. apLeaf[iLvl] = 0;
  143655. }
  143656. }
  143657. if( p ){
  143658. sqlite3Fts3ExprFree(p);
  143659. rc = SQLITE_TOOBIG;
  143660. break;
  143661. }
  143662. /* If that was the last leaf node, break out of the loop */
  143663. if( pParent==0 ) break;
  143664. /* Set $p to point to the next leaf in the tree of eType nodes */
  143665. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  143666. /* Remove pParent from the original tree. */
  143667. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  143668. pParent->pRight->pParent = pParent->pParent;
  143669. if( pParent->pParent ){
  143670. pParent->pParent->pLeft = pParent->pRight;
  143671. }else{
  143672. assert( pParent==pRoot );
  143673. pRoot = pParent->pRight;
  143674. }
  143675. /* Link pParent into the free node list. It will be used as an
  143676. ** internal node of the new tree. */
  143677. pParent->pParent = pFree;
  143678. pFree = pParent;
  143679. }
  143680. if( rc==SQLITE_OK ){
  143681. p = 0;
  143682. for(i=0; i<nMaxDepth; i++){
  143683. if( apLeaf[i] ){
  143684. if( p==0 ){
  143685. p = apLeaf[i];
  143686. p->pParent = 0;
  143687. }else{
  143688. assert( pFree!=0 );
  143689. pFree->pRight = p;
  143690. pFree->pLeft = apLeaf[i];
  143691. pFree->pLeft->pParent = pFree;
  143692. pFree->pRight->pParent = pFree;
  143693. p = pFree;
  143694. pFree = pFree->pParent;
  143695. p->pParent = 0;
  143696. }
  143697. }
  143698. }
  143699. pRoot = p;
  143700. }else{
  143701. /* An error occurred. Delete the contents of the apLeaf[] array
  143702. ** and pFree list. Everything else is cleaned up by the call to
  143703. ** sqlite3Fts3ExprFree(pRoot) below. */
  143704. Fts3Expr *pDel;
  143705. for(i=0; i<nMaxDepth; i++){
  143706. sqlite3Fts3ExprFree(apLeaf[i]);
  143707. }
  143708. while( (pDel=pFree)!=0 ){
  143709. pFree = pDel->pParent;
  143710. sqlite3_free(pDel);
  143711. }
  143712. }
  143713. assert( pFree==0 );
  143714. sqlite3_free( apLeaf );
  143715. }
  143716. }else if( eType==FTSQUERY_NOT ){
  143717. Fts3Expr *pLeft = pRoot->pLeft;
  143718. Fts3Expr *pRight = pRoot->pRight;
  143719. pRoot->pLeft = 0;
  143720. pRoot->pRight = 0;
  143721. pLeft->pParent = 0;
  143722. pRight->pParent = 0;
  143723. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  143724. if( rc==SQLITE_OK ){
  143725. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  143726. }
  143727. if( rc!=SQLITE_OK ){
  143728. sqlite3Fts3ExprFree(pRight);
  143729. sqlite3Fts3ExprFree(pLeft);
  143730. }else{
  143731. assert( pLeft && pRight );
  143732. pRoot->pLeft = pLeft;
  143733. pLeft->pParent = pRoot;
  143734. pRoot->pRight = pRight;
  143735. pRight->pParent = pRoot;
  143736. }
  143737. }
  143738. }
  143739. if( rc!=SQLITE_OK ){
  143740. sqlite3Fts3ExprFree(pRoot);
  143741. pRoot = 0;
  143742. }
  143743. *pp = pRoot;
  143744. return rc;
  143745. }
  143746. /*
  143747. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  143748. ** differences:
  143749. **
  143750. ** 1. It does not do expression rebalancing.
  143751. ** 2. It does not check that the expression does not exceed the
  143752. ** maximum allowable depth.
  143753. ** 3. Even if it fails, *ppExpr may still be set to point to an
  143754. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  143755. ** in this case.
  143756. */
  143757. static int fts3ExprParseUnbalanced(
  143758. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  143759. int iLangid, /* Language id for tokenizer */
  143760. char **azCol, /* Array of column names for fts3 table */
  143761. int bFts4, /* True to allow FTS4-only syntax */
  143762. int nCol, /* Number of entries in azCol[] */
  143763. int iDefaultCol, /* Default column to query */
  143764. const char *z, int n, /* Text of MATCH query */
  143765. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  143766. ){
  143767. int nParsed;
  143768. int rc;
  143769. ParseContext sParse;
  143770. memset(&sParse, 0, sizeof(ParseContext));
  143771. sParse.pTokenizer = pTokenizer;
  143772. sParse.iLangid = iLangid;
  143773. sParse.azCol = (const char **)azCol;
  143774. sParse.nCol = nCol;
  143775. sParse.iDefaultCol = iDefaultCol;
  143776. sParse.bFts4 = bFts4;
  143777. if( z==0 ){
  143778. *ppExpr = 0;
  143779. return SQLITE_OK;
  143780. }
  143781. if( n<0 ){
  143782. n = (int)strlen(z);
  143783. }
  143784. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  143785. assert( rc==SQLITE_OK || *ppExpr==0 );
  143786. /* Check for mismatched parenthesis */
  143787. if( rc==SQLITE_OK && sParse.nNest ){
  143788. rc = SQLITE_ERROR;
  143789. }
  143790. return rc;
  143791. }
  143792. /*
  143793. ** Parameters z and n contain a pointer to and length of a buffer containing
  143794. ** an fts3 query expression, respectively. This function attempts to parse the
  143795. ** query expression and create a tree of Fts3Expr structures representing the
  143796. ** parsed expression. If successful, *ppExpr is set to point to the head
  143797. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  143798. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  143799. ** error) is returned and *ppExpr is set to 0.
  143800. **
  143801. ** If parameter n is a negative number, then z is assumed to point to a
  143802. ** nul-terminated string and the length is determined using strlen().
  143803. **
  143804. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  143805. ** use to normalize query tokens while parsing the expression. The azCol[]
  143806. ** array, which is assumed to contain nCol entries, should contain the names
  143807. ** of each column in the target fts3 table, in order from left to right.
  143808. ** Column names must be nul-terminated strings.
  143809. **
  143810. ** The iDefaultCol parameter should be passed the index of the table column
  143811. ** that appears on the left-hand-side of the MATCH operator (the default
  143812. ** column to match against for tokens for which a column name is not explicitly
  143813. ** specified as part of the query string), or -1 if tokens may by default
  143814. ** match any table column.
  143815. */
  143816. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  143817. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  143818. int iLangid, /* Language id for tokenizer */
  143819. char **azCol, /* Array of column names for fts3 table */
  143820. int bFts4, /* True to allow FTS4-only syntax */
  143821. int nCol, /* Number of entries in azCol[] */
  143822. int iDefaultCol, /* Default column to query */
  143823. const char *z, int n, /* Text of MATCH query */
  143824. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  143825. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  143826. ){
  143827. int rc = fts3ExprParseUnbalanced(
  143828. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  143829. );
  143830. /* Rebalance the expression. And check that its depth does not exceed
  143831. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  143832. if( rc==SQLITE_OK && *ppExpr ){
  143833. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  143834. if( rc==SQLITE_OK ){
  143835. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  143836. }
  143837. }
  143838. if( rc!=SQLITE_OK ){
  143839. sqlite3Fts3ExprFree(*ppExpr);
  143840. *ppExpr = 0;
  143841. if( rc==SQLITE_TOOBIG ){
  143842. sqlite3Fts3ErrMsg(pzErr,
  143843. "FTS expression tree is too large (maximum depth %d)",
  143844. SQLITE_FTS3_MAX_EXPR_DEPTH
  143845. );
  143846. rc = SQLITE_ERROR;
  143847. }else if( rc==SQLITE_ERROR ){
  143848. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  143849. }
  143850. }
  143851. return rc;
  143852. }
  143853. /*
  143854. ** Free a single node of an expression tree.
  143855. */
  143856. static void fts3FreeExprNode(Fts3Expr *p){
  143857. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  143858. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  143859. sqlite3_free(p->aMI);
  143860. sqlite3_free(p);
  143861. }
  143862. /*
  143863. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  143864. **
  143865. ** This function would be simpler if it recursively called itself. But
  143866. ** that would mean passing a sufficiently large expression to ExprParse()
  143867. ** could cause a stack overflow.
  143868. */
  143869. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  143870. Fts3Expr *p;
  143871. assert( pDel==0 || pDel->pParent==0 );
  143872. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  143873. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  143874. }
  143875. while( p ){
  143876. Fts3Expr *pParent = p->pParent;
  143877. fts3FreeExprNode(p);
  143878. if( pParent && p==pParent->pLeft && pParent->pRight ){
  143879. p = pParent->pRight;
  143880. while( p && (p->pLeft || p->pRight) ){
  143881. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  143882. p = (p->pLeft ? p->pLeft : p->pRight);
  143883. }
  143884. }else{
  143885. p = pParent;
  143886. }
  143887. }
  143888. }
  143889. /****************************************************************************
  143890. *****************************************************************************
  143891. ** Everything after this point is just test code.
  143892. */
  143893. #ifdef SQLITE_TEST
  143894. /* #include <stdio.h> */
  143895. /*
  143896. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  143897. */
  143898. static int queryTestTokenizer(
  143899. sqlite3 *db,
  143900. const char *zName,
  143901. const sqlite3_tokenizer_module **pp
  143902. ){
  143903. int rc;
  143904. sqlite3_stmt *pStmt;
  143905. const char zSql[] = "SELECT fts3_tokenizer(?)";
  143906. *pp = 0;
  143907. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  143908. if( rc!=SQLITE_OK ){
  143909. return rc;
  143910. }
  143911. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  143912. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  143913. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  143914. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  143915. }
  143916. }
  143917. return sqlite3_finalize(pStmt);
  143918. }
  143919. /*
  143920. ** Return a pointer to a buffer containing a text representation of the
  143921. ** expression passed as the first argument. The buffer is obtained from
  143922. ** sqlite3_malloc(). It is the responsibility of the caller to use
  143923. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  143924. ** NULL is returned.
  143925. **
  143926. ** If the second argument is not NULL, then its contents are prepended to
  143927. ** the returned expression text and then freed using sqlite3_free().
  143928. */
  143929. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  143930. if( pExpr==0 ){
  143931. return sqlite3_mprintf("");
  143932. }
  143933. switch( pExpr->eType ){
  143934. case FTSQUERY_PHRASE: {
  143935. Fts3Phrase *pPhrase = pExpr->pPhrase;
  143936. int i;
  143937. zBuf = sqlite3_mprintf(
  143938. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  143939. for(i=0; zBuf && i<pPhrase->nToken; i++){
  143940. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  143941. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  143942. (pPhrase->aToken[i].isPrefix?"+":"")
  143943. );
  143944. }
  143945. return zBuf;
  143946. }
  143947. case FTSQUERY_NEAR:
  143948. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  143949. break;
  143950. case FTSQUERY_NOT:
  143951. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  143952. break;
  143953. case FTSQUERY_AND:
  143954. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  143955. break;
  143956. case FTSQUERY_OR:
  143957. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  143958. break;
  143959. }
  143960. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  143961. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  143962. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  143963. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  143964. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  143965. return zBuf;
  143966. }
  143967. /*
  143968. ** This is the implementation of a scalar SQL function used to test the
  143969. ** expression parser. It should be called as follows:
  143970. **
  143971. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  143972. **
  143973. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  143974. ** to parse the query expression (see README.tokenizers). The second argument
  143975. ** is the query expression to parse. Each subsequent argument is the name
  143976. ** of a column of the fts3 table that the query expression may refer to.
  143977. ** For example:
  143978. **
  143979. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  143980. */
  143981. static void fts3ExprTest(
  143982. sqlite3_context *context,
  143983. int argc,
  143984. sqlite3_value **argv
  143985. ){
  143986. sqlite3_tokenizer_module const *pModule = 0;
  143987. sqlite3_tokenizer *pTokenizer = 0;
  143988. int rc;
  143989. char **azCol = 0;
  143990. const char *zExpr;
  143991. int nExpr;
  143992. int nCol;
  143993. int ii;
  143994. Fts3Expr *pExpr;
  143995. char *zBuf = 0;
  143996. sqlite3 *db = sqlite3_context_db_handle(context);
  143997. if( argc<3 ){
  143998. sqlite3_result_error(context,
  143999. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  144000. );
  144001. return;
  144002. }
  144003. rc = queryTestTokenizer(db,
  144004. (const char *)sqlite3_value_text(argv[0]), &pModule);
  144005. if( rc==SQLITE_NOMEM ){
  144006. sqlite3_result_error_nomem(context);
  144007. goto exprtest_out;
  144008. }else if( !pModule ){
  144009. sqlite3_result_error(context, "No such tokenizer module", -1);
  144010. goto exprtest_out;
  144011. }
  144012. rc = pModule->xCreate(0, 0, &pTokenizer);
  144013. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  144014. if( rc==SQLITE_NOMEM ){
  144015. sqlite3_result_error_nomem(context);
  144016. goto exprtest_out;
  144017. }
  144018. pTokenizer->pModule = pModule;
  144019. zExpr = (const char *)sqlite3_value_text(argv[1]);
  144020. nExpr = sqlite3_value_bytes(argv[1]);
  144021. nCol = argc-2;
  144022. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  144023. if( !azCol ){
  144024. sqlite3_result_error_nomem(context);
  144025. goto exprtest_out;
  144026. }
  144027. for(ii=0; ii<nCol; ii++){
  144028. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  144029. }
  144030. if( sqlite3_user_data(context) ){
  144031. char *zDummy = 0;
  144032. rc = sqlite3Fts3ExprParse(
  144033. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  144034. );
  144035. assert( rc==SQLITE_OK || pExpr==0 );
  144036. sqlite3_free(zDummy);
  144037. }else{
  144038. rc = fts3ExprParseUnbalanced(
  144039. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  144040. );
  144041. }
  144042. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  144043. sqlite3Fts3ExprFree(pExpr);
  144044. sqlite3_result_error(context, "Error parsing expression", -1);
  144045. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  144046. sqlite3_result_error_nomem(context);
  144047. }else{
  144048. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  144049. sqlite3_free(zBuf);
  144050. }
  144051. sqlite3Fts3ExprFree(pExpr);
  144052. exprtest_out:
  144053. if( pModule && pTokenizer ){
  144054. rc = pModule->xDestroy(pTokenizer);
  144055. }
  144056. sqlite3_free(azCol);
  144057. }
  144058. /*
  144059. ** Register the query expression parser test function fts3_exprtest()
  144060. ** with database connection db.
  144061. */
  144062. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  144063. int rc = sqlite3_create_function(
  144064. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  144065. );
  144066. if( rc==SQLITE_OK ){
  144067. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  144068. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  144069. );
  144070. }
  144071. return rc;
  144072. }
  144073. #endif
  144074. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  144075. /************** End of fts3_expr.c *******************************************/
  144076. /************** Begin file fts3_hash.c ***************************************/
  144077. /*
  144078. ** 2001 September 22
  144079. **
  144080. ** The author disclaims copyright to this source code. In place of
  144081. ** a legal notice, here is a blessing:
  144082. **
  144083. ** May you do good and not evil.
  144084. ** May you find forgiveness for yourself and forgive others.
  144085. ** May you share freely, never taking more than you give.
  144086. **
  144087. *************************************************************************
  144088. ** This is the implementation of generic hash-tables used in SQLite.
  144089. ** We've modified it slightly to serve as a standalone hash table
  144090. ** implementation for the full-text indexing module.
  144091. */
  144092. /*
  144093. ** The code in this file is only compiled if:
  144094. **
  144095. ** * The FTS3 module is being built as an extension
  144096. ** (in which case SQLITE_CORE is not defined), or
  144097. **
  144098. ** * The FTS3 module is being built into the core of
  144099. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  144100. */
  144101. /* #include "fts3Int.h" */
  144102. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  144103. /* #include <assert.h> */
  144104. /* #include <stdlib.h> */
  144105. /* #include <string.h> */
  144106. /* #include "fts3_hash.h" */
  144107. /*
  144108. ** Malloc and Free functions
  144109. */
  144110. static void *fts3HashMalloc(int n){
  144111. void *p = sqlite3_malloc(n);
  144112. if( p ){
  144113. memset(p, 0, n);
  144114. }
  144115. return p;
  144116. }
  144117. static void fts3HashFree(void *p){
  144118. sqlite3_free(p);
  144119. }
  144120. /* Turn bulk memory into a hash table object by initializing the
  144121. ** fields of the Hash structure.
  144122. **
  144123. ** "pNew" is a pointer to the hash table that is to be initialized.
  144124. ** keyClass is one of the constants
  144125. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  144126. ** determines what kind of key the hash table will use. "copyKey" is
  144127. ** true if the hash table should make its own private copy of keys and
  144128. ** false if it should just use the supplied pointer.
  144129. */
  144130. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  144131. assert( pNew!=0 );
  144132. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  144133. pNew->keyClass = keyClass;
  144134. pNew->copyKey = copyKey;
  144135. pNew->first = 0;
  144136. pNew->count = 0;
  144137. pNew->htsize = 0;
  144138. pNew->ht = 0;
  144139. }
  144140. /* Remove all entries from a hash table. Reclaim all memory.
  144141. ** Call this routine to delete a hash table or to reset a hash table
  144142. ** to the empty state.
  144143. */
  144144. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  144145. Fts3HashElem *elem; /* For looping over all elements of the table */
  144146. assert( pH!=0 );
  144147. elem = pH->first;
  144148. pH->first = 0;
  144149. fts3HashFree(pH->ht);
  144150. pH->ht = 0;
  144151. pH->htsize = 0;
  144152. while( elem ){
  144153. Fts3HashElem *next_elem = elem->next;
  144154. if( pH->copyKey && elem->pKey ){
  144155. fts3HashFree(elem->pKey);
  144156. }
  144157. fts3HashFree(elem);
  144158. elem = next_elem;
  144159. }
  144160. pH->count = 0;
  144161. }
  144162. /*
  144163. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  144164. */
  144165. static int fts3StrHash(const void *pKey, int nKey){
  144166. const char *z = (const char *)pKey;
  144167. unsigned h = 0;
  144168. if( nKey<=0 ) nKey = (int) strlen(z);
  144169. while( nKey > 0 ){
  144170. h = (h<<3) ^ h ^ *z++;
  144171. nKey--;
  144172. }
  144173. return (int)(h & 0x7fffffff);
  144174. }
  144175. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  144176. if( n1!=n2 ) return 1;
  144177. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  144178. }
  144179. /*
  144180. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  144181. */
  144182. static int fts3BinHash(const void *pKey, int nKey){
  144183. int h = 0;
  144184. const char *z = (const char *)pKey;
  144185. while( nKey-- > 0 ){
  144186. h = (h<<3) ^ h ^ *(z++);
  144187. }
  144188. return h & 0x7fffffff;
  144189. }
  144190. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  144191. if( n1!=n2 ) return 1;
  144192. return memcmp(pKey1,pKey2,n1);
  144193. }
  144194. /*
  144195. ** Return a pointer to the appropriate hash function given the key class.
  144196. **
  144197. ** The C syntax in this function definition may be unfamilar to some
  144198. ** programmers, so we provide the following additional explanation:
  144199. **
  144200. ** The name of the function is "ftsHashFunction". The function takes a
  144201. ** single parameter "keyClass". The return value of ftsHashFunction()
  144202. ** is a pointer to another function. Specifically, the return value
  144203. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  144204. ** with types "const void*" and "int" and returns an "int".
  144205. */
  144206. static int (*ftsHashFunction(int keyClass))(const void*,int){
  144207. if( keyClass==FTS3_HASH_STRING ){
  144208. return &fts3StrHash;
  144209. }else{
  144210. assert( keyClass==FTS3_HASH_BINARY );
  144211. return &fts3BinHash;
  144212. }
  144213. }
  144214. /*
  144215. ** Return a pointer to the appropriate hash function given the key class.
  144216. **
  144217. ** For help in interpreted the obscure C code in the function definition,
  144218. ** see the header comment on the previous function.
  144219. */
  144220. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  144221. if( keyClass==FTS3_HASH_STRING ){
  144222. return &fts3StrCompare;
  144223. }else{
  144224. assert( keyClass==FTS3_HASH_BINARY );
  144225. return &fts3BinCompare;
  144226. }
  144227. }
  144228. /* Link an element into the hash table
  144229. */
  144230. static void fts3HashInsertElement(
  144231. Fts3Hash *pH, /* The complete hash table */
  144232. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  144233. Fts3HashElem *pNew /* The element to be inserted */
  144234. ){
  144235. Fts3HashElem *pHead; /* First element already in pEntry */
  144236. pHead = pEntry->chain;
  144237. if( pHead ){
  144238. pNew->next = pHead;
  144239. pNew->prev = pHead->prev;
  144240. if( pHead->prev ){ pHead->prev->next = pNew; }
  144241. else { pH->first = pNew; }
  144242. pHead->prev = pNew;
  144243. }else{
  144244. pNew->next = pH->first;
  144245. if( pH->first ){ pH->first->prev = pNew; }
  144246. pNew->prev = 0;
  144247. pH->first = pNew;
  144248. }
  144249. pEntry->count++;
  144250. pEntry->chain = pNew;
  144251. }
  144252. /* Resize the hash table so that it cantains "new_size" buckets.
  144253. ** "new_size" must be a power of 2. The hash table might fail
  144254. ** to resize if sqliteMalloc() fails.
  144255. **
  144256. ** Return non-zero if a memory allocation error occurs.
  144257. */
  144258. static int fts3Rehash(Fts3Hash *pH, int new_size){
  144259. struct _fts3ht *new_ht; /* The new hash table */
  144260. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  144261. int (*xHash)(const void*,int); /* The hash function */
  144262. assert( (new_size & (new_size-1))==0 );
  144263. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  144264. if( new_ht==0 ) return 1;
  144265. fts3HashFree(pH->ht);
  144266. pH->ht = new_ht;
  144267. pH->htsize = new_size;
  144268. xHash = ftsHashFunction(pH->keyClass);
  144269. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  144270. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  144271. next_elem = elem->next;
  144272. fts3HashInsertElement(pH, &new_ht[h], elem);
  144273. }
  144274. return 0;
  144275. }
  144276. /* This function (for internal use only) locates an element in an
  144277. ** hash table that matches the given key. The hash for this key has
  144278. ** already been computed and is passed as the 4th parameter.
  144279. */
  144280. static Fts3HashElem *fts3FindElementByHash(
  144281. const Fts3Hash *pH, /* The pH to be searched */
  144282. const void *pKey, /* The key we are searching for */
  144283. int nKey,
  144284. int h /* The hash for this key. */
  144285. ){
  144286. Fts3HashElem *elem; /* Used to loop thru the element list */
  144287. int count; /* Number of elements left to test */
  144288. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  144289. if( pH->ht ){
  144290. struct _fts3ht *pEntry = &pH->ht[h];
  144291. elem = pEntry->chain;
  144292. count = pEntry->count;
  144293. xCompare = ftsCompareFunction(pH->keyClass);
  144294. while( count-- && elem ){
  144295. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  144296. return elem;
  144297. }
  144298. elem = elem->next;
  144299. }
  144300. }
  144301. return 0;
  144302. }
  144303. /* Remove a single entry from the hash table given a pointer to that
  144304. ** element and a hash on the element's key.
  144305. */
  144306. static void fts3RemoveElementByHash(
  144307. Fts3Hash *pH, /* The pH containing "elem" */
  144308. Fts3HashElem* elem, /* The element to be removed from the pH */
  144309. int h /* Hash value for the element */
  144310. ){
  144311. struct _fts3ht *pEntry;
  144312. if( elem->prev ){
  144313. elem->prev->next = elem->next;
  144314. }else{
  144315. pH->first = elem->next;
  144316. }
  144317. if( elem->next ){
  144318. elem->next->prev = elem->prev;
  144319. }
  144320. pEntry = &pH->ht[h];
  144321. if( pEntry->chain==elem ){
  144322. pEntry->chain = elem->next;
  144323. }
  144324. pEntry->count--;
  144325. if( pEntry->count<=0 ){
  144326. pEntry->chain = 0;
  144327. }
  144328. if( pH->copyKey && elem->pKey ){
  144329. fts3HashFree(elem->pKey);
  144330. }
  144331. fts3HashFree( elem );
  144332. pH->count--;
  144333. if( pH->count<=0 ){
  144334. assert( pH->first==0 );
  144335. assert( pH->count==0 );
  144336. fts3HashClear(pH);
  144337. }
  144338. }
  144339. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  144340. const Fts3Hash *pH,
  144341. const void *pKey,
  144342. int nKey
  144343. ){
  144344. int h; /* A hash on key */
  144345. int (*xHash)(const void*,int); /* The hash function */
  144346. if( pH==0 || pH->ht==0 ) return 0;
  144347. xHash = ftsHashFunction(pH->keyClass);
  144348. assert( xHash!=0 );
  144349. h = (*xHash)(pKey,nKey);
  144350. assert( (pH->htsize & (pH->htsize-1))==0 );
  144351. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  144352. }
  144353. /*
  144354. ** Attempt to locate an element of the hash table pH with a key
  144355. ** that matches pKey,nKey. Return the data for this element if it is
  144356. ** found, or NULL if there is no match.
  144357. */
  144358. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  144359. Fts3HashElem *pElem; /* The element that matches key (if any) */
  144360. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  144361. return pElem ? pElem->data : 0;
  144362. }
  144363. /* Insert an element into the hash table pH. The key is pKey,nKey
  144364. ** and the data is "data".
  144365. **
  144366. ** If no element exists with a matching key, then a new
  144367. ** element is created. A copy of the key is made if the copyKey
  144368. ** flag is set. NULL is returned.
  144369. **
  144370. ** If another element already exists with the same key, then the
  144371. ** new data replaces the old data and the old data is returned.
  144372. ** The key is not copied in this instance. If a malloc fails, then
  144373. ** the new data is returned and the hash table is unchanged.
  144374. **
  144375. ** If the "data" parameter to this function is NULL, then the
  144376. ** element corresponding to "key" is removed from the hash table.
  144377. */
  144378. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  144379. Fts3Hash *pH, /* The hash table to insert into */
  144380. const void *pKey, /* The key */
  144381. int nKey, /* Number of bytes in the key */
  144382. void *data /* The data */
  144383. ){
  144384. int hraw; /* Raw hash value of the key */
  144385. int h; /* the hash of the key modulo hash table size */
  144386. Fts3HashElem *elem; /* Used to loop thru the element list */
  144387. Fts3HashElem *new_elem; /* New element added to the pH */
  144388. int (*xHash)(const void*,int); /* The hash function */
  144389. assert( pH!=0 );
  144390. xHash = ftsHashFunction(pH->keyClass);
  144391. assert( xHash!=0 );
  144392. hraw = (*xHash)(pKey, nKey);
  144393. assert( (pH->htsize & (pH->htsize-1))==0 );
  144394. h = hraw & (pH->htsize-1);
  144395. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  144396. if( elem ){
  144397. void *old_data = elem->data;
  144398. if( data==0 ){
  144399. fts3RemoveElementByHash(pH,elem,h);
  144400. }else{
  144401. elem->data = data;
  144402. }
  144403. return old_data;
  144404. }
  144405. if( data==0 ) return 0;
  144406. if( (pH->htsize==0 && fts3Rehash(pH,8))
  144407. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  144408. ){
  144409. pH->count = 0;
  144410. return data;
  144411. }
  144412. assert( pH->htsize>0 );
  144413. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  144414. if( new_elem==0 ) return data;
  144415. if( pH->copyKey && pKey!=0 ){
  144416. new_elem->pKey = fts3HashMalloc( nKey );
  144417. if( new_elem->pKey==0 ){
  144418. fts3HashFree(new_elem);
  144419. return data;
  144420. }
  144421. memcpy((void*)new_elem->pKey, pKey, nKey);
  144422. }else{
  144423. new_elem->pKey = (void*)pKey;
  144424. }
  144425. new_elem->nKey = nKey;
  144426. pH->count++;
  144427. assert( pH->htsize>0 );
  144428. assert( (pH->htsize & (pH->htsize-1))==0 );
  144429. h = hraw & (pH->htsize-1);
  144430. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  144431. new_elem->data = data;
  144432. return 0;
  144433. }
  144434. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  144435. /************** End of fts3_hash.c *******************************************/
  144436. /************** Begin file fts3_porter.c *************************************/
  144437. /*
  144438. ** 2006 September 30
  144439. **
  144440. ** The author disclaims copyright to this source code. In place of
  144441. ** a legal notice, here is a blessing:
  144442. **
  144443. ** May you do good and not evil.
  144444. ** May you find forgiveness for yourself and forgive others.
  144445. ** May you share freely, never taking more than you give.
  144446. **
  144447. *************************************************************************
  144448. ** Implementation of the full-text-search tokenizer that implements
  144449. ** a Porter stemmer.
  144450. */
  144451. /*
  144452. ** The code in this file is only compiled if:
  144453. **
  144454. ** * The FTS3 module is being built as an extension
  144455. ** (in which case SQLITE_CORE is not defined), or
  144456. **
  144457. ** * The FTS3 module is being built into the core of
  144458. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  144459. */
  144460. /* #include "fts3Int.h" */
  144461. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  144462. /* #include <assert.h> */
  144463. /* #include <stdlib.h> */
  144464. /* #include <stdio.h> */
  144465. /* #include <string.h> */
  144466. /* #include "fts3_tokenizer.h" */
  144467. /*
  144468. ** Class derived from sqlite3_tokenizer
  144469. */
  144470. typedef struct porter_tokenizer {
  144471. sqlite3_tokenizer base; /* Base class */
  144472. } porter_tokenizer;
  144473. /*
  144474. ** Class derived from sqlite3_tokenizer_cursor
  144475. */
  144476. typedef struct porter_tokenizer_cursor {
  144477. sqlite3_tokenizer_cursor base;
  144478. const char *zInput; /* input we are tokenizing */
  144479. int nInput; /* size of the input */
  144480. int iOffset; /* current position in zInput */
  144481. int iToken; /* index of next token to be returned */
  144482. char *zToken; /* storage for current token */
  144483. int nAllocated; /* space allocated to zToken buffer */
  144484. } porter_tokenizer_cursor;
  144485. /*
  144486. ** Create a new tokenizer instance.
  144487. */
  144488. static int porterCreate(
  144489. int argc, const char * const *argv,
  144490. sqlite3_tokenizer **ppTokenizer
  144491. ){
  144492. porter_tokenizer *t;
  144493. UNUSED_PARAMETER(argc);
  144494. UNUSED_PARAMETER(argv);
  144495. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  144496. if( t==NULL ) return SQLITE_NOMEM;
  144497. memset(t, 0, sizeof(*t));
  144498. *ppTokenizer = &t->base;
  144499. return SQLITE_OK;
  144500. }
  144501. /*
  144502. ** Destroy a tokenizer
  144503. */
  144504. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  144505. sqlite3_free(pTokenizer);
  144506. return SQLITE_OK;
  144507. }
  144508. /*
  144509. ** Prepare to begin tokenizing a particular string. The input
  144510. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  144511. ** used to incrementally tokenize this string is returned in
  144512. ** *ppCursor.
  144513. */
  144514. static int porterOpen(
  144515. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  144516. const char *zInput, int nInput, /* String to be tokenized */
  144517. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  144518. ){
  144519. porter_tokenizer_cursor *c;
  144520. UNUSED_PARAMETER(pTokenizer);
  144521. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  144522. if( c==NULL ) return SQLITE_NOMEM;
  144523. c->zInput = zInput;
  144524. if( zInput==0 ){
  144525. c->nInput = 0;
  144526. }else if( nInput<0 ){
  144527. c->nInput = (int)strlen(zInput);
  144528. }else{
  144529. c->nInput = nInput;
  144530. }
  144531. c->iOffset = 0; /* start tokenizing at the beginning */
  144532. c->iToken = 0;
  144533. c->zToken = NULL; /* no space allocated, yet. */
  144534. c->nAllocated = 0;
  144535. *ppCursor = &c->base;
  144536. return SQLITE_OK;
  144537. }
  144538. /*
  144539. ** Close a tokenization cursor previously opened by a call to
  144540. ** porterOpen() above.
  144541. */
  144542. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  144543. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  144544. sqlite3_free(c->zToken);
  144545. sqlite3_free(c);
  144546. return SQLITE_OK;
  144547. }
  144548. /*
  144549. ** Vowel or consonant
  144550. */
  144551. static const char cType[] = {
  144552. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  144553. 1, 1, 1, 2, 1
  144554. };
  144555. /*
  144556. ** isConsonant() and isVowel() determine if their first character in
  144557. ** the string they point to is a consonant or a vowel, according
  144558. ** to Porter ruls.
  144559. **
  144560. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  144561. ** 'Y' is a consonant unless it follows another consonant,
  144562. ** in which case it is a vowel.
  144563. **
  144564. ** In these routine, the letters are in reverse order. So the 'y' rule
  144565. ** is that 'y' is a consonant unless it is followed by another
  144566. ** consonent.
  144567. */
  144568. static int isVowel(const char*);
  144569. static int isConsonant(const char *z){
  144570. int j;
  144571. char x = *z;
  144572. if( x==0 ) return 0;
  144573. assert( x>='a' && x<='z' );
  144574. j = cType[x-'a'];
  144575. if( j<2 ) return j;
  144576. return z[1]==0 || isVowel(z + 1);
  144577. }
  144578. static int isVowel(const char *z){
  144579. int j;
  144580. char x = *z;
  144581. if( x==0 ) return 0;
  144582. assert( x>='a' && x<='z' );
  144583. j = cType[x-'a'];
  144584. if( j<2 ) return 1-j;
  144585. return isConsonant(z + 1);
  144586. }
  144587. /*
  144588. ** Let any sequence of one or more vowels be represented by V and let
  144589. ** C be sequence of one or more consonants. Then every word can be
  144590. ** represented as:
  144591. **
  144592. ** [C] (VC){m} [V]
  144593. **
  144594. ** In prose: A word is an optional consonant followed by zero or
  144595. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  144596. ** number of vowel consonant pairs. This routine computes the value
  144597. ** of m for the first i bytes of a word.
  144598. **
  144599. ** Return true if the m-value for z is 1 or more. In other words,
  144600. ** return true if z contains at least one vowel that is followed
  144601. ** by a consonant.
  144602. **
  144603. ** In this routine z[] is in reverse order. So we are really looking
  144604. ** for an instance of a consonant followed by a vowel.
  144605. */
  144606. static int m_gt_0(const char *z){
  144607. while( isVowel(z) ){ z++; }
  144608. if( *z==0 ) return 0;
  144609. while( isConsonant(z) ){ z++; }
  144610. return *z!=0;
  144611. }
  144612. /* Like mgt0 above except we are looking for a value of m which is
  144613. ** exactly 1
  144614. */
  144615. static int m_eq_1(const char *z){
  144616. while( isVowel(z) ){ z++; }
  144617. if( *z==0 ) return 0;
  144618. while( isConsonant(z) ){ z++; }
  144619. if( *z==0 ) return 0;
  144620. while( isVowel(z) ){ z++; }
  144621. if( *z==0 ) return 1;
  144622. while( isConsonant(z) ){ z++; }
  144623. return *z==0;
  144624. }
  144625. /* Like mgt0 above except we are looking for a value of m>1 instead
  144626. ** or m>0
  144627. */
  144628. static int m_gt_1(const char *z){
  144629. while( isVowel(z) ){ z++; }
  144630. if( *z==0 ) return 0;
  144631. while( isConsonant(z) ){ z++; }
  144632. if( *z==0 ) return 0;
  144633. while( isVowel(z) ){ z++; }
  144634. if( *z==0 ) return 0;
  144635. while( isConsonant(z) ){ z++; }
  144636. return *z!=0;
  144637. }
  144638. /*
  144639. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  144640. */
  144641. static int hasVowel(const char *z){
  144642. while( isConsonant(z) ){ z++; }
  144643. return *z!=0;
  144644. }
  144645. /*
  144646. ** Return TRUE if the word ends in a double consonant.
  144647. **
  144648. ** The text is reversed here. So we are really looking at
  144649. ** the first two characters of z[].
  144650. */
  144651. static int doubleConsonant(const char *z){
  144652. return isConsonant(z) && z[0]==z[1];
  144653. }
  144654. /*
  144655. ** Return TRUE if the word ends with three letters which
  144656. ** are consonant-vowel-consonent and where the final consonant
  144657. ** is not 'w', 'x', or 'y'.
  144658. **
  144659. ** The word is reversed here. So we are really checking the
  144660. ** first three letters and the first one cannot be in [wxy].
  144661. */
  144662. static int star_oh(const char *z){
  144663. return
  144664. isConsonant(z) &&
  144665. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  144666. isVowel(z+1) &&
  144667. isConsonant(z+2);
  144668. }
  144669. /*
  144670. ** If the word ends with zFrom and xCond() is true for the stem
  144671. ** of the word that preceeds the zFrom ending, then change the
  144672. ** ending to zTo.
  144673. **
  144674. ** The input word *pz and zFrom are both in reverse order. zTo
  144675. ** is in normal order.
  144676. **
  144677. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  144678. ** match. Not that TRUE is returned even if xCond() fails and
  144679. ** no substitution occurs.
  144680. */
  144681. static int stem(
  144682. char **pz, /* The word being stemmed (Reversed) */
  144683. const char *zFrom, /* If the ending matches this... (Reversed) */
  144684. const char *zTo, /* ... change the ending to this (not reversed) */
  144685. int (*xCond)(const char*) /* Condition that must be true */
  144686. ){
  144687. char *z = *pz;
  144688. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  144689. if( *zFrom!=0 ) return 0;
  144690. if( xCond && !xCond(z) ) return 1;
  144691. while( *zTo ){
  144692. *(--z) = *(zTo++);
  144693. }
  144694. *pz = z;
  144695. return 1;
  144696. }
  144697. /*
  144698. ** This is the fallback stemmer used when the porter stemmer is
  144699. ** inappropriate. The input word is copied into the output with
  144700. ** US-ASCII case folding. If the input word is too long (more
  144701. ** than 20 bytes if it contains no digits or more than 6 bytes if
  144702. ** it contains digits) then word is truncated to 20 or 6 bytes
  144703. ** by taking 10 or 3 bytes from the beginning and end.
  144704. */
  144705. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  144706. int i, mx, j;
  144707. int hasDigit = 0;
  144708. for(i=0; i<nIn; i++){
  144709. char c = zIn[i];
  144710. if( c>='A' && c<='Z' ){
  144711. zOut[i] = c - 'A' + 'a';
  144712. }else{
  144713. if( c>='0' && c<='9' ) hasDigit = 1;
  144714. zOut[i] = c;
  144715. }
  144716. }
  144717. mx = hasDigit ? 3 : 10;
  144718. if( nIn>mx*2 ){
  144719. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  144720. zOut[j] = zOut[i];
  144721. }
  144722. i = j;
  144723. }
  144724. zOut[i] = 0;
  144725. *pnOut = i;
  144726. }
  144727. /*
  144728. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  144729. ** zOut is at least big enough to hold nIn bytes. Write the actual
  144730. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  144731. **
  144732. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  144733. ** are converted to lower case. Upper-case UTF characters are
  144734. ** unchanged.
  144735. **
  144736. ** Words that are longer than about 20 bytes are stemmed by retaining
  144737. ** a few bytes from the beginning and the end of the word. If the
  144738. ** word contains digits, 3 bytes are taken from the beginning and
  144739. ** 3 bytes from the end. For long words without digits, 10 bytes
  144740. ** are taken from each end. US-ASCII case folding still applies.
  144741. **
  144742. ** If the input word contains not digits but does characters not
  144743. ** in [a-zA-Z] then no stemming is attempted and this routine just
  144744. ** copies the input into the input into the output with US-ASCII
  144745. ** case folding.
  144746. **
  144747. ** Stemming never increases the length of the word. So there is
  144748. ** no chance of overflowing the zOut buffer.
  144749. */
  144750. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  144751. int i, j;
  144752. char zReverse[28];
  144753. char *z, *z2;
  144754. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  144755. /* The word is too big or too small for the porter stemmer.
  144756. ** Fallback to the copy stemmer */
  144757. copy_stemmer(zIn, nIn, zOut, pnOut);
  144758. return;
  144759. }
  144760. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  144761. char c = zIn[i];
  144762. if( c>='A' && c<='Z' ){
  144763. zReverse[j] = c + 'a' - 'A';
  144764. }else if( c>='a' && c<='z' ){
  144765. zReverse[j] = c;
  144766. }else{
  144767. /* The use of a character not in [a-zA-Z] means that we fallback
  144768. ** to the copy stemmer */
  144769. copy_stemmer(zIn, nIn, zOut, pnOut);
  144770. return;
  144771. }
  144772. }
  144773. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  144774. z = &zReverse[j+1];
  144775. /* Step 1a */
  144776. if( z[0]=='s' ){
  144777. if(
  144778. !stem(&z, "sess", "ss", 0) &&
  144779. !stem(&z, "sei", "i", 0) &&
  144780. !stem(&z, "ss", "ss", 0)
  144781. ){
  144782. z++;
  144783. }
  144784. }
  144785. /* Step 1b */
  144786. z2 = z;
  144787. if( stem(&z, "dee", "ee", m_gt_0) ){
  144788. /* Do nothing. The work was all in the test */
  144789. }else if(
  144790. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  144791. && z!=z2
  144792. ){
  144793. if( stem(&z, "ta", "ate", 0) ||
  144794. stem(&z, "lb", "ble", 0) ||
  144795. stem(&z, "zi", "ize", 0) ){
  144796. /* Do nothing. The work was all in the test */
  144797. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  144798. z++;
  144799. }else if( m_eq_1(z) && star_oh(z) ){
  144800. *(--z) = 'e';
  144801. }
  144802. }
  144803. /* Step 1c */
  144804. if( z[0]=='y' && hasVowel(z+1) ){
  144805. z[0] = 'i';
  144806. }
  144807. /* Step 2 */
  144808. switch( z[1] ){
  144809. case 'a':
  144810. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  144811. stem(&z, "lanoit", "tion", m_gt_0);
  144812. }
  144813. break;
  144814. case 'c':
  144815. if( !stem(&z, "icne", "ence", m_gt_0) ){
  144816. stem(&z, "icna", "ance", m_gt_0);
  144817. }
  144818. break;
  144819. case 'e':
  144820. stem(&z, "rezi", "ize", m_gt_0);
  144821. break;
  144822. case 'g':
  144823. stem(&z, "igol", "log", m_gt_0);
  144824. break;
  144825. case 'l':
  144826. if( !stem(&z, "ilb", "ble", m_gt_0)
  144827. && !stem(&z, "illa", "al", m_gt_0)
  144828. && !stem(&z, "iltne", "ent", m_gt_0)
  144829. && !stem(&z, "ile", "e", m_gt_0)
  144830. ){
  144831. stem(&z, "ilsuo", "ous", m_gt_0);
  144832. }
  144833. break;
  144834. case 'o':
  144835. if( !stem(&z, "noitazi", "ize", m_gt_0)
  144836. && !stem(&z, "noita", "ate", m_gt_0)
  144837. ){
  144838. stem(&z, "rota", "ate", m_gt_0);
  144839. }
  144840. break;
  144841. case 's':
  144842. if( !stem(&z, "msila", "al", m_gt_0)
  144843. && !stem(&z, "ssenevi", "ive", m_gt_0)
  144844. && !stem(&z, "ssenluf", "ful", m_gt_0)
  144845. ){
  144846. stem(&z, "ssensuo", "ous", m_gt_0);
  144847. }
  144848. break;
  144849. case 't':
  144850. if( !stem(&z, "itila", "al", m_gt_0)
  144851. && !stem(&z, "itivi", "ive", m_gt_0)
  144852. ){
  144853. stem(&z, "itilib", "ble", m_gt_0);
  144854. }
  144855. break;
  144856. }
  144857. /* Step 3 */
  144858. switch( z[0] ){
  144859. case 'e':
  144860. if( !stem(&z, "etaci", "ic", m_gt_0)
  144861. && !stem(&z, "evita", "", m_gt_0)
  144862. ){
  144863. stem(&z, "ezila", "al", m_gt_0);
  144864. }
  144865. break;
  144866. case 'i':
  144867. stem(&z, "itici", "ic", m_gt_0);
  144868. break;
  144869. case 'l':
  144870. if( !stem(&z, "laci", "ic", m_gt_0) ){
  144871. stem(&z, "luf", "", m_gt_0);
  144872. }
  144873. break;
  144874. case 's':
  144875. stem(&z, "ssen", "", m_gt_0);
  144876. break;
  144877. }
  144878. /* Step 4 */
  144879. switch( z[1] ){
  144880. case 'a':
  144881. if( z[0]=='l' && m_gt_1(z+2) ){
  144882. z += 2;
  144883. }
  144884. break;
  144885. case 'c':
  144886. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  144887. z += 4;
  144888. }
  144889. break;
  144890. case 'e':
  144891. if( z[0]=='r' && m_gt_1(z+2) ){
  144892. z += 2;
  144893. }
  144894. break;
  144895. case 'i':
  144896. if( z[0]=='c' && m_gt_1(z+2) ){
  144897. z += 2;
  144898. }
  144899. break;
  144900. case 'l':
  144901. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  144902. z += 4;
  144903. }
  144904. break;
  144905. case 'n':
  144906. if( z[0]=='t' ){
  144907. if( z[2]=='a' ){
  144908. if( m_gt_1(z+3) ){
  144909. z += 3;
  144910. }
  144911. }else if( z[2]=='e' ){
  144912. if( !stem(&z, "tneme", "", m_gt_1)
  144913. && !stem(&z, "tnem", "", m_gt_1)
  144914. ){
  144915. stem(&z, "tne", "", m_gt_1);
  144916. }
  144917. }
  144918. }
  144919. break;
  144920. case 'o':
  144921. if( z[0]=='u' ){
  144922. if( m_gt_1(z+2) ){
  144923. z += 2;
  144924. }
  144925. }else if( z[3]=='s' || z[3]=='t' ){
  144926. stem(&z, "noi", "", m_gt_1);
  144927. }
  144928. break;
  144929. case 's':
  144930. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  144931. z += 3;
  144932. }
  144933. break;
  144934. case 't':
  144935. if( !stem(&z, "eta", "", m_gt_1) ){
  144936. stem(&z, "iti", "", m_gt_1);
  144937. }
  144938. break;
  144939. case 'u':
  144940. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  144941. z += 3;
  144942. }
  144943. break;
  144944. case 'v':
  144945. case 'z':
  144946. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  144947. z += 3;
  144948. }
  144949. break;
  144950. }
  144951. /* Step 5a */
  144952. if( z[0]=='e' ){
  144953. if( m_gt_1(z+1) ){
  144954. z++;
  144955. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  144956. z++;
  144957. }
  144958. }
  144959. /* Step 5b */
  144960. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  144961. z++;
  144962. }
  144963. /* z[] is now the stemmed word in reverse order. Flip it back
  144964. ** around into forward order and return.
  144965. */
  144966. *pnOut = i = (int)strlen(z);
  144967. zOut[i] = 0;
  144968. while( *z ){
  144969. zOut[--i] = *(z++);
  144970. }
  144971. }
  144972. /*
  144973. ** Characters that can be part of a token. We assume any character
  144974. ** whose value is greater than 0x80 (any UTF character) can be
  144975. ** part of a token. In other words, delimiters all must have
  144976. ** values of 0x7f or lower.
  144977. */
  144978. static const char porterIdChar[] = {
  144979. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  144980. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  144981. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  144982. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  144983. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  144984. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  144985. };
  144986. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  144987. /*
  144988. ** Extract the next token from a tokenization cursor. The cursor must
  144989. ** have been opened by a prior call to porterOpen().
  144990. */
  144991. static int porterNext(
  144992. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  144993. const char **pzToken, /* OUT: *pzToken is the token text */
  144994. int *pnBytes, /* OUT: Number of bytes in token */
  144995. int *piStartOffset, /* OUT: Starting offset of token */
  144996. int *piEndOffset, /* OUT: Ending offset of token */
  144997. int *piPosition /* OUT: Position integer of token */
  144998. ){
  144999. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  145000. const char *z = c->zInput;
  145001. while( c->iOffset<c->nInput ){
  145002. int iStartOffset, ch;
  145003. /* Scan past delimiter characters */
  145004. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  145005. c->iOffset++;
  145006. }
  145007. /* Count non-delimiter characters. */
  145008. iStartOffset = c->iOffset;
  145009. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  145010. c->iOffset++;
  145011. }
  145012. if( c->iOffset>iStartOffset ){
  145013. int n = c->iOffset-iStartOffset;
  145014. if( n>c->nAllocated ){
  145015. char *pNew;
  145016. c->nAllocated = n+20;
  145017. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  145018. if( !pNew ) return SQLITE_NOMEM;
  145019. c->zToken = pNew;
  145020. }
  145021. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  145022. *pzToken = c->zToken;
  145023. *piStartOffset = iStartOffset;
  145024. *piEndOffset = c->iOffset;
  145025. *piPosition = c->iToken++;
  145026. return SQLITE_OK;
  145027. }
  145028. }
  145029. return SQLITE_DONE;
  145030. }
  145031. /*
  145032. ** The set of routines that implement the porter-stemmer tokenizer
  145033. */
  145034. static const sqlite3_tokenizer_module porterTokenizerModule = {
  145035. 0,
  145036. porterCreate,
  145037. porterDestroy,
  145038. porterOpen,
  145039. porterClose,
  145040. porterNext,
  145041. 0
  145042. };
  145043. /*
  145044. ** Allocate a new porter tokenizer. Return a pointer to the new
  145045. ** tokenizer in *ppModule
  145046. */
  145047. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  145048. sqlite3_tokenizer_module const**ppModule
  145049. ){
  145050. *ppModule = &porterTokenizerModule;
  145051. }
  145052. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  145053. /************** End of fts3_porter.c *****************************************/
  145054. /************** Begin file fts3_tokenizer.c **********************************/
  145055. /*
  145056. ** 2007 June 22
  145057. **
  145058. ** The author disclaims copyright to this source code. In place of
  145059. ** a legal notice, here is a blessing:
  145060. **
  145061. ** May you do good and not evil.
  145062. ** May you find forgiveness for yourself and forgive others.
  145063. ** May you share freely, never taking more than you give.
  145064. **
  145065. ******************************************************************************
  145066. **
  145067. ** This is part of an SQLite module implementing full-text search.
  145068. ** This particular file implements the generic tokenizer interface.
  145069. */
  145070. /*
  145071. ** The code in this file is only compiled if:
  145072. **
  145073. ** * The FTS3 module is being built as an extension
  145074. ** (in which case SQLITE_CORE is not defined), or
  145075. **
  145076. ** * The FTS3 module is being built into the core of
  145077. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  145078. */
  145079. /* #include "fts3Int.h" */
  145080. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  145081. /* #include <assert.h> */
  145082. /* #include <string.h> */
  145083. /*
  145084. ** Return true if the two-argument version of fts3_tokenizer()
  145085. ** has been activated via a prior call to sqlite3_db_config(db,
  145086. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  145087. */
  145088. static int fts3TokenizerEnabled(sqlite3_context *context){
  145089. sqlite3 *db = sqlite3_context_db_handle(context);
  145090. int isEnabled = 0;
  145091. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  145092. return isEnabled;
  145093. }
  145094. /*
  145095. ** Implementation of the SQL scalar function for accessing the underlying
  145096. ** hash table. This function may be called as follows:
  145097. **
  145098. ** SELECT <function-name>(<key-name>);
  145099. ** SELECT <function-name>(<key-name>, <pointer>);
  145100. **
  145101. ** where <function-name> is the name passed as the second argument
  145102. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  145103. **
  145104. ** If the <pointer> argument is specified, it must be a blob value
  145105. ** containing a pointer to be stored as the hash data corresponding
  145106. ** to the string <key-name>. If <pointer> is not specified, then
  145107. ** the string <key-name> must already exist in the has table. Otherwise,
  145108. ** an error is returned.
  145109. **
  145110. ** Whether or not the <pointer> argument is specified, the value returned
  145111. ** is a blob containing the pointer stored as the hash data corresponding
  145112. ** to string <key-name> (after the hash-table is updated, if applicable).
  145113. */
  145114. static void fts3TokenizerFunc(
  145115. sqlite3_context *context,
  145116. int argc,
  145117. sqlite3_value **argv
  145118. ){
  145119. Fts3Hash *pHash;
  145120. void *pPtr = 0;
  145121. const unsigned char *zName;
  145122. int nName;
  145123. assert( argc==1 || argc==2 );
  145124. pHash = (Fts3Hash *)sqlite3_user_data(context);
  145125. zName = sqlite3_value_text(argv[0]);
  145126. nName = sqlite3_value_bytes(argv[0])+1;
  145127. if( argc==2 ){
  145128. if( fts3TokenizerEnabled(context) ){
  145129. void *pOld;
  145130. int n = sqlite3_value_bytes(argv[1]);
  145131. if( zName==0 || n!=sizeof(pPtr) ){
  145132. sqlite3_result_error(context, "argument type mismatch", -1);
  145133. return;
  145134. }
  145135. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  145136. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  145137. if( pOld==pPtr ){
  145138. sqlite3_result_error(context, "out of memory", -1);
  145139. }
  145140. }else{
  145141. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  145142. return;
  145143. }
  145144. }else{
  145145. if( zName ){
  145146. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  145147. }
  145148. if( !pPtr ){
  145149. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  145150. sqlite3_result_error(context, zErr, -1);
  145151. sqlite3_free(zErr);
  145152. return;
  145153. }
  145154. }
  145155. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  145156. }
  145157. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  145158. static const char isFtsIdChar[] = {
  145159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  145160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  145161. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  145162. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  145163. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  145164. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  145165. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  145166. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  145167. };
  145168. return (c&0x80 || isFtsIdChar[(int)(c)]);
  145169. }
  145170. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  145171. const char *z1;
  145172. const char *z2 = 0;
  145173. /* Find the start of the next token. */
  145174. z1 = zStr;
  145175. while( z2==0 ){
  145176. char c = *z1;
  145177. switch( c ){
  145178. case '\0': return 0; /* No more tokens here */
  145179. case '\'':
  145180. case '"':
  145181. case '`': {
  145182. z2 = z1;
  145183. while( *++z2 && (*z2!=c || *++z2==c) );
  145184. break;
  145185. }
  145186. case '[':
  145187. z2 = &z1[1];
  145188. while( *z2 && z2[0]!=']' ) z2++;
  145189. if( *z2 ) z2++;
  145190. break;
  145191. default:
  145192. if( sqlite3Fts3IsIdChar(*z1) ){
  145193. z2 = &z1[1];
  145194. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  145195. }else{
  145196. z1++;
  145197. }
  145198. }
  145199. }
  145200. *pn = (int)(z2-z1);
  145201. return z1;
  145202. }
  145203. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  145204. Fts3Hash *pHash, /* Tokenizer hash table */
  145205. const char *zArg, /* Tokenizer name */
  145206. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  145207. char **pzErr /* OUT: Set to malloced error message */
  145208. ){
  145209. int rc;
  145210. char *z = (char *)zArg;
  145211. int n = 0;
  145212. char *zCopy;
  145213. char *zEnd; /* Pointer to nul-term of zCopy */
  145214. sqlite3_tokenizer_module *m;
  145215. zCopy = sqlite3_mprintf("%s", zArg);
  145216. if( !zCopy ) return SQLITE_NOMEM;
  145217. zEnd = &zCopy[strlen(zCopy)];
  145218. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  145219. if( z==0 ){
  145220. assert( n==0 );
  145221. z = zCopy;
  145222. }
  145223. z[n] = '\0';
  145224. sqlite3Fts3Dequote(z);
  145225. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  145226. if( !m ){
  145227. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  145228. rc = SQLITE_ERROR;
  145229. }else{
  145230. char const **aArg = 0;
  145231. int iArg = 0;
  145232. z = &z[n+1];
  145233. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  145234. int nNew = sizeof(char *)*(iArg+1);
  145235. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  145236. if( !aNew ){
  145237. sqlite3_free(zCopy);
  145238. sqlite3_free((void *)aArg);
  145239. return SQLITE_NOMEM;
  145240. }
  145241. aArg = aNew;
  145242. aArg[iArg++] = z;
  145243. z[n] = '\0';
  145244. sqlite3Fts3Dequote(z);
  145245. z = &z[n+1];
  145246. }
  145247. rc = m->xCreate(iArg, aArg, ppTok);
  145248. assert( rc!=SQLITE_OK || *ppTok );
  145249. if( rc!=SQLITE_OK ){
  145250. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  145251. }else{
  145252. (*ppTok)->pModule = m;
  145253. }
  145254. sqlite3_free((void *)aArg);
  145255. }
  145256. sqlite3_free(zCopy);
  145257. return rc;
  145258. }
  145259. #ifdef SQLITE_TEST
  145260. #if defined(INCLUDE_SQLITE_TCL_H)
  145261. # include "sqlite_tcl.h"
  145262. #else
  145263. # include "tcl.h"
  145264. #endif
  145265. /* #include <string.h> */
  145266. /*
  145267. ** Implementation of a special SQL scalar function for testing tokenizers
  145268. ** designed to be used in concert with the Tcl testing framework. This
  145269. ** function must be called with two or more arguments:
  145270. **
  145271. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  145272. **
  145273. ** where <function-name> is the name passed as the second argument
  145274. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  145275. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  145276. **
  145277. ** The return value is a string that may be interpreted as a Tcl
  145278. ** list. For each token in the <input-string>, three elements are
  145279. ** added to the returned list. The first is the token position, the
  145280. ** second is the token text (folded, stemmed, etc.) and the third is the
  145281. ** substring of <input-string> associated with the token. For example,
  145282. ** using the built-in "simple" tokenizer:
  145283. **
  145284. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  145285. **
  145286. ** will return the string:
  145287. **
  145288. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  145289. **
  145290. */
  145291. static void testFunc(
  145292. sqlite3_context *context,
  145293. int argc,
  145294. sqlite3_value **argv
  145295. ){
  145296. Fts3Hash *pHash;
  145297. sqlite3_tokenizer_module *p;
  145298. sqlite3_tokenizer *pTokenizer = 0;
  145299. sqlite3_tokenizer_cursor *pCsr = 0;
  145300. const char *zErr = 0;
  145301. const char *zName;
  145302. int nName;
  145303. const char *zInput;
  145304. int nInput;
  145305. const char *azArg[64];
  145306. const char *zToken;
  145307. int nToken = 0;
  145308. int iStart = 0;
  145309. int iEnd = 0;
  145310. int iPos = 0;
  145311. int i;
  145312. Tcl_Obj *pRet;
  145313. if( argc<2 ){
  145314. sqlite3_result_error(context, "insufficient arguments", -1);
  145315. return;
  145316. }
  145317. nName = sqlite3_value_bytes(argv[0]);
  145318. zName = (const char *)sqlite3_value_text(argv[0]);
  145319. nInput = sqlite3_value_bytes(argv[argc-1]);
  145320. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  145321. pHash = (Fts3Hash *)sqlite3_user_data(context);
  145322. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  145323. if( !p ){
  145324. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  145325. sqlite3_result_error(context, zErr2, -1);
  145326. sqlite3_free(zErr2);
  145327. return;
  145328. }
  145329. pRet = Tcl_NewObj();
  145330. Tcl_IncrRefCount(pRet);
  145331. for(i=1; i<argc-1; i++){
  145332. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  145333. }
  145334. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  145335. zErr = "error in xCreate()";
  145336. goto finish;
  145337. }
  145338. pTokenizer->pModule = p;
  145339. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  145340. zErr = "error in xOpen()";
  145341. goto finish;
  145342. }
  145343. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  145344. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  145345. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  145346. zToken = &zInput[iStart];
  145347. nToken = iEnd-iStart;
  145348. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  145349. }
  145350. if( SQLITE_OK!=p->xClose(pCsr) ){
  145351. zErr = "error in xClose()";
  145352. goto finish;
  145353. }
  145354. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  145355. zErr = "error in xDestroy()";
  145356. goto finish;
  145357. }
  145358. finish:
  145359. if( zErr ){
  145360. sqlite3_result_error(context, zErr, -1);
  145361. }else{
  145362. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  145363. }
  145364. Tcl_DecrRefCount(pRet);
  145365. }
  145366. static
  145367. int registerTokenizer(
  145368. sqlite3 *db,
  145369. char *zName,
  145370. const sqlite3_tokenizer_module *p
  145371. ){
  145372. int rc;
  145373. sqlite3_stmt *pStmt;
  145374. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  145375. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  145376. if( rc!=SQLITE_OK ){
  145377. return rc;
  145378. }
  145379. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  145380. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  145381. sqlite3_step(pStmt);
  145382. return sqlite3_finalize(pStmt);
  145383. }
  145384. static
  145385. int queryTokenizer(
  145386. sqlite3 *db,
  145387. char *zName,
  145388. const sqlite3_tokenizer_module **pp
  145389. ){
  145390. int rc;
  145391. sqlite3_stmt *pStmt;
  145392. const char zSql[] = "SELECT fts3_tokenizer(?)";
  145393. *pp = 0;
  145394. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  145395. if( rc!=SQLITE_OK ){
  145396. return rc;
  145397. }
  145398. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  145399. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  145400. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  145401. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  145402. }
  145403. }
  145404. return sqlite3_finalize(pStmt);
  145405. }
  145406. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  145407. /*
  145408. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  145409. ** This function is used for testing only, it is not included in the
  145410. ** build unless SQLITE_TEST is defined.
  145411. **
  145412. ** The purpose of this is to test that the fts3_tokenizer() function
  145413. ** can be used as designed by the C-code in the queryTokenizer and
  145414. ** registerTokenizer() functions above. These two functions are repeated
  145415. ** in the README.tokenizer file as an example, so it is important to
  145416. ** test them.
  145417. **
  145418. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  145419. ** function with no arguments. An assert() will fail if a problem is
  145420. ** detected. i.e.:
  145421. **
  145422. ** SELECT fts3_tokenizer_internal_test();
  145423. **
  145424. */
  145425. static void intTestFunc(
  145426. sqlite3_context *context,
  145427. int argc,
  145428. sqlite3_value **argv
  145429. ){
  145430. int rc;
  145431. const sqlite3_tokenizer_module *p1;
  145432. const sqlite3_tokenizer_module *p2;
  145433. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  145434. UNUSED_PARAMETER(argc);
  145435. UNUSED_PARAMETER(argv);
  145436. /* Test the query function */
  145437. sqlite3Fts3SimpleTokenizerModule(&p1);
  145438. rc = queryTokenizer(db, "simple", &p2);
  145439. assert( rc==SQLITE_OK );
  145440. assert( p1==p2 );
  145441. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  145442. assert( rc==SQLITE_ERROR );
  145443. assert( p2==0 );
  145444. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  145445. /* Test the storage function */
  145446. if( fts3TokenizerEnabled(context) ){
  145447. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  145448. assert( rc==SQLITE_OK );
  145449. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  145450. assert( rc==SQLITE_OK );
  145451. assert( p2==p1 );
  145452. }
  145453. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  145454. }
  145455. #endif
  145456. /*
  145457. ** Set up SQL objects in database db used to access the contents of
  145458. ** the hash table pointed to by argument pHash. The hash table must
  145459. ** been initialized to use string keys, and to take a private copy
  145460. ** of the key when a value is inserted. i.e. by a call similar to:
  145461. **
  145462. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  145463. **
  145464. ** This function adds a scalar function (see header comment above
  145465. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  145466. ** defined at compilation time, a temporary virtual table (see header
  145467. ** comment above struct HashTableVtab) to the database schema. Both
  145468. ** provide read/write access to the contents of *pHash.
  145469. **
  145470. ** The third argument to this function, zName, is used as the name
  145471. ** of both the scalar and, if created, the virtual table.
  145472. */
  145473. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  145474. sqlite3 *db,
  145475. Fts3Hash *pHash,
  145476. const char *zName
  145477. ){
  145478. int rc = SQLITE_OK;
  145479. void *p = (void *)pHash;
  145480. const int any = SQLITE_ANY;
  145481. #ifdef SQLITE_TEST
  145482. char *zTest = 0;
  145483. char *zTest2 = 0;
  145484. void *pdb = (void *)db;
  145485. zTest = sqlite3_mprintf("%s_test", zName);
  145486. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  145487. if( !zTest || !zTest2 ){
  145488. rc = SQLITE_NOMEM;
  145489. }
  145490. #endif
  145491. if( SQLITE_OK==rc ){
  145492. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  145493. }
  145494. if( SQLITE_OK==rc ){
  145495. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  145496. }
  145497. #ifdef SQLITE_TEST
  145498. if( SQLITE_OK==rc ){
  145499. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  145500. }
  145501. if( SQLITE_OK==rc ){
  145502. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  145503. }
  145504. #endif
  145505. #ifdef SQLITE_TEST
  145506. sqlite3_free(zTest);
  145507. sqlite3_free(zTest2);
  145508. #endif
  145509. return rc;
  145510. }
  145511. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  145512. /************** End of fts3_tokenizer.c **************************************/
  145513. /************** Begin file fts3_tokenizer1.c *********************************/
  145514. /*
  145515. ** 2006 Oct 10
  145516. **
  145517. ** The author disclaims copyright to this source code. In place of
  145518. ** a legal notice, here is a blessing:
  145519. **
  145520. ** May you do good and not evil.
  145521. ** May you find forgiveness for yourself and forgive others.
  145522. ** May you share freely, never taking more than you give.
  145523. **
  145524. ******************************************************************************
  145525. **
  145526. ** Implementation of the "simple" full-text-search tokenizer.
  145527. */
  145528. /*
  145529. ** The code in this file is only compiled if:
  145530. **
  145531. ** * The FTS3 module is being built as an extension
  145532. ** (in which case SQLITE_CORE is not defined), or
  145533. **
  145534. ** * The FTS3 module is being built into the core of
  145535. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  145536. */
  145537. /* #include "fts3Int.h" */
  145538. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  145539. /* #include <assert.h> */
  145540. /* #include <stdlib.h> */
  145541. /* #include <stdio.h> */
  145542. /* #include <string.h> */
  145543. /* #include "fts3_tokenizer.h" */
  145544. typedef struct simple_tokenizer {
  145545. sqlite3_tokenizer base;
  145546. char delim[128]; /* flag ASCII delimiters */
  145547. } simple_tokenizer;
  145548. typedef struct simple_tokenizer_cursor {
  145549. sqlite3_tokenizer_cursor base;
  145550. const char *pInput; /* input we are tokenizing */
  145551. int nBytes; /* size of the input */
  145552. int iOffset; /* current position in pInput */
  145553. int iToken; /* index of next token to be returned */
  145554. char *pToken; /* storage for current token */
  145555. int nTokenAllocated; /* space allocated to zToken buffer */
  145556. } simple_tokenizer_cursor;
  145557. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  145558. return c<0x80 && t->delim[c];
  145559. }
  145560. static int fts3_isalnum(int x){
  145561. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  145562. }
  145563. /*
  145564. ** Create a new tokenizer instance.
  145565. */
  145566. static int simpleCreate(
  145567. int argc, const char * const *argv,
  145568. sqlite3_tokenizer **ppTokenizer
  145569. ){
  145570. simple_tokenizer *t;
  145571. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  145572. if( t==NULL ) return SQLITE_NOMEM;
  145573. memset(t, 0, sizeof(*t));
  145574. /* TODO(shess) Delimiters need to remain the same from run to run,
  145575. ** else we need to reindex. One solution would be a meta-table to
  145576. ** track such information in the database, then we'd only want this
  145577. ** information on the initial create.
  145578. */
  145579. if( argc>1 ){
  145580. int i, n = (int)strlen(argv[1]);
  145581. for(i=0; i<n; i++){
  145582. unsigned char ch = argv[1][i];
  145583. /* We explicitly don't support UTF-8 delimiters for now. */
  145584. if( ch>=0x80 ){
  145585. sqlite3_free(t);
  145586. return SQLITE_ERROR;
  145587. }
  145588. t->delim[ch] = 1;
  145589. }
  145590. } else {
  145591. /* Mark non-alphanumeric ASCII characters as delimiters */
  145592. int i;
  145593. for(i=1; i<0x80; i++){
  145594. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  145595. }
  145596. }
  145597. *ppTokenizer = &t->base;
  145598. return SQLITE_OK;
  145599. }
  145600. /*
  145601. ** Destroy a tokenizer
  145602. */
  145603. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  145604. sqlite3_free(pTokenizer);
  145605. return SQLITE_OK;
  145606. }
  145607. /*
  145608. ** Prepare to begin tokenizing a particular string. The input
  145609. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  145610. ** used to incrementally tokenize this string is returned in
  145611. ** *ppCursor.
  145612. */
  145613. static int simpleOpen(
  145614. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  145615. const char *pInput, int nBytes, /* String to be tokenized */
  145616. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  145617. ){
  145618. simple_tokenizer_cursor *c;
  145619. UNUSED_PARAMETER(pTokenizer);
  145620. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  145621. if( c==NULL ) return SQLITE_NOMEM;
  145622. c->pInput = pInput;
  145623. if( pInput==0 ){
  145624. c->nBytes = 0;
  145625. }else if( nBytes<0 ){
  145626. c->nBytes = (int)strlen(pInput);
  145627. }else{
  145628. c->nBytes = nBytes;
  145629. }
  145630. c->iOffset = 0; /* start tokenizing at the beginning */
  145631. c->iToken = 0;
  145632. c->pToken = NULL; /* no space allocated, yet. */
  145633. c->nTokenAllocated = 0;
  145634. *ppCursor = &c->base;
  145635. return SQLITE_OK;
  145636. }
  145637. /*
  145638. ** Close a tokenization cursor previously opened by a call to
  145639. ** simpleOpen() above.
  145640. */
  145641. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  145642. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  145643. sqlite3_free(c->pToken);
  145644. sqlite3_free(c);
  145645. return SQLITE_OK;
  145646. }
  145647. /*
  145648. ** Extract the next token from a tokenization cursor. The cursor must
  145649. ** have been opened by a prior call to simpleOpen().
  145650. */
  145651. static int simpleNext(
  145652. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  145653. const char **ppToken, /* OUT: *ppToken is the token text */
  145654. int *pnBytes, /* OUT: Number of bytes in token */
  145655. int *piStartOffset, /* OUT: Starting offset of token */
  145656. int *piEndOffset, /* OUT: Ending offset of token */
  145657. int *piPosition /* OUT: Position integer of token */
  145658. ){
  145659. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  145660. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  145661. unsigned char *p = (unsigned char *)c->pInput;
  145662. while( c->iOffset<c->nBytes ){
  145663. int iStartOffset;
  145664. /* Scan past delimiter characters */
  145665. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  145666. c->iOffset++;
  145667. }
  145668. /* Count non-delimiter characters. */
  145669. iStartOffset = c->iOffset;
  145670. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  145671. c->iOffset++;
  145672. }
  145673. if( c->iOffset>iStartOffset ){
  145674. int i, n = c->iOffset-iStartOffset;
  145675. if( n>c->nTokenAllocated ){
  145676. char *pNew;
  145677. c->nTokenAllocated = n+20;
  145678. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  145679. if( !pNew ) return SQLITE_NOMEM;
  145680. c->pToken = pNew;
  145681. }
  145682. for(i=0; i<n; i++){
  145683. /* TODO(shess) This needs expansion to handle UTF-8
  145684. ** case-insensitivity.
  145685. */
  145686. unsigned char ch = p[iStartOffset+i];
  145687. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  145688. }
  145689. *ppToken = c->pToken;
  145690. *pnBytes = n;
  145691. *piStartOffset = iStartOffset;
  145692. *piEndOffset = c->iOffset;
  145693. *piPosition = c->iToken++;
  145694. return SQLITE_OK;
  145695. }
  145696. }
  145697. return SQLITE_DONE;
  145698. }
  145699. /*
  145700. ** The set of routines that implement the simple tokenizer
  145701. */
  145702. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  145703. 0,
  145704. simpleCreate,
  145705. simpleDestroy,
  145706. simpleOpen,
  145707. simpleClose,
  145708. simpleNext,
  145709. 0,
  145710. };
  145711. /*
  145712. ** Allocate a new simple tokenizer. Return a pointer to the new
  145713. ** tokenizer in *ppModule
  145714. */
  145715. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  145716. sqlite3_tokenizer_module const**ppModule
  145717. ){
  145718. *ppModule = &simpleTokenizerModule;
  145719. }
  145720. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  145721. /************** End of fts3_tokenizer1.c *************************************/
  145722. /************** Begin file fts3_tokenize_vtab.c ******************************/
  145723. /*
  145724. ** 2013 Apr 22
  145725. **
  145726. ** The author disclaims copyright to this source code. In place of
  145727. ** a legal notice, here is a blessing:
  145728. **
  145729. ** May you do good and not evil.
  145730. ** May you find forgiveness for yourself and forgive others.
  145731. ** May you share freely, never taking more than you give.
  145732. **
  145733. ******************************************************************************
  145734. **
  145735. ** This file contains code for the "fts3tokenize" virtual table module.
  145736. ** An fts3tokenize virtual table is created as follows:
  145737. **
  145738. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  145739. ** <tokenizer-name>, <arg-1>, ...
  145740. ** );
  145741. **
  145742. ** The table created has the following schema:
  145743. **
  145744. ** CREATE TABLE <tbl>(input, token, start, end, position)
  145745. **
  145746. ** When queried, the query must include a WHERE clause of type:
  145747. **
  145748. ** input = <string>
  145749. **
  145750. ** The virtual table module tokenizes this <string>, using the FTS3
  145751. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  145752. ** statement and returns one row for each token in the result. With
  145753. ** fields set as follows:
  145754. **
  145755. ** input: Always set to a copy of <string>
  145756. ** token: A token from the input.
  145757. ** start: Byte offset of the token within the input <string>.
  145758. ** end: Byte offset of the byte immediately following the end of the
  145759. ** token within the input string.
  145760. ** pos: Token offset of token within input.
  145761. **
  145762. */
  145763. /* #include "fts3Int.h" */
  145764. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  145765. /* #include <string.h> */
  145766. /* #include <assert.h> */
  145767. typedef struct Fts3tokTable Fts3tokTable;
  145768. typedef struct Fts3tokCursor Fts3tokCursor;
  145769. /*
  145770. ** Virtual table structure.
  145771. */
  145772. struct Fts3tokTable {
  145773. sqlite3_vtab base; /* Base class used by SQLite core */
  145774. const sqlite3_tokenizer_module *pMod;
  145775. sqlite3_tokenizer *pTok;
  145776. };
  145777. /*
  145778. ** Virtual table cursor structure.
  145779. */
  145780. struct Fts3tokCursor {
  145781. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  145782. char *zInput; /* Input string */
  145783. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  145784. int iRowid; /* Current 'rowid' value */
  145785. const char *zToken; /* Current 'token' value */
  145786. int nToken; /* Size of zToken in bytes */
  145787. int iStart; /* Current 'start' value */
  145788. int iEnd; /* Current 'end' value */
  145789. int iPos; /* Current 'pos' value */
  145790. };
  145791. /*
  145792. ** Query FTS for the tokenizer implementation named zName.
  145793. */
  145794. static int fts3tokQueryTokenizer(
  145795. Fts3Hash *pHash,
  145796. const char *zName,
  145797. const sqlite3_tokenizer_module **pp,
  145798. char **pzErr
  145799. ){
  145800. sqlite3_tokenizer_module *p;
  145801. int nName = (int)strlen(zName);
  145802. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  145803. if( !p ){
  145804. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  145805. return SQLITE_ERROR;
  145806. }
  145807. *pp = p;
  145808. return SQLITE_OK;
  145809. }
  145810. /*
  145811. ** The second argument, argv[], is an array of pointers to nul-terminated
  145812. ** strings. This function makes a copy of the array and strings into a
  145813. ** single block of memory. It then dequotes any of the strings that appear
  145814. ** to be quoted.
  145815. **
  145816. ** If successful, output parameter *pazDequote is set to point at the
  145817. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  145818. ** responsible for eventually calling sqlite3_free() to free the array
  145819. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  145820. ** The final value of *pazDequote is undefined in this case.
  145821. */
  145822. static int fts3tokDequoteArray(
  145823. int argc, /* Number of elements in argv[] */
  145824. const char * const *argv, /* Input array */
  145825. char ***pazDequote /* Output array */
  145826. ){
  145827. int rc = SQLITE_OK; /* Return code */
  145828. if( argc==0 ){
  145829. *pazDequote = 0;
  145830. }else{
  145831. int i;
  145832. int nByte = 0;
  145833. char **azDequote;
  145834. for(i=0; i<argc; i++){
  145835. nByte += (int)(strlen(argv[i]) + 1);
  145836. }
  145837. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  145838. if( azDequote==0 ){
  145839. rc = SQLITE_NOMEM;
  145840. }else{
  145841. char *pSpace = (char *)&azDequote[argc];
  145842. for(i=0; i<argc; i++){
  145843. int n = (int)strlen(argv[i]);
  145844. azDequote[i] = pSpace;
  145845. memcpy(pSpace, argv[i], n+1);
  145846. sqlite3Fts3Dequote(pSpace);
  145847. pSpace += (n+1);
  145848. }
  145849. }
  145850. }
  145851. return rc;
  145852. }
  145853. /*
  145854. ** Schema of the tokenizer table.
  145855. */
  145856. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  145857. /*
  145858. ** This function does all the work for both the xConnect and xCreate methods.
  145859. ** These tables have no persistent representation of their own, so xConnect
  145860. ** and xCreate are identical operations.
  145861. **
  145862. ** argv[0]: module name
  145863. ** argv[1]: database name
  145864. ** argv[2]: table name
  145865. ** argv[3]: first argument (tokenizer name)
  145866. */
  145867. static int fts3tokConnectMethod(
  145868. sqlite3 *db, /* Database connection */
  145869. void *pHash, /* Hash table of tokenizers */
  145870. int argc, /* Number of elements in argv array */
  145871. const char * const *argv, /* xCreate/xConnect argument array */
  145872. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  145873. char **pzErr /* OUT: sqlite3_malloc'd error message */
  145874. ){
  145875. Fts3tokTable *pTab = 0;
  145876. const sqlite3_tokenizer_module *pMod = 0;
  145877. sqlite3_tokenizer *pTok = 0;
  145878. int rc;
  145879. char **azDequote = 0;
  145880. int nDequote;
  145881. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  145882. if( rc!=SQLITE_OK ) return rc;
  145883. nDequote = argc-3;
  145884. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  145885. if( rc==SQLITE_OK ){
  145886. const char *zModule;
  145887. if( nDequote<1 ){
  145888. zModule = "simple";
  145889. }else{
  145890. zModule = azDequote[0];
  145891. }
  145892. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  145893. }
  145894. assert( (rc==SQLITE_OK)==(pMod!=0) );
  145895. if( rc==SQLITE_OK ){
  145896. const char * const *azArg = (const char * const *)&azDequote[1];
  145897. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  145898. }
  145899. if( rc==SQLITE_OK ){
  145900. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  145901. if( pTab==0 ){
  145902. rc = SQLITE_NOMEM;
  145903. }
  145904. }
  145905. if( rc==SQLITE_OK ){
  145906. memset(pTab, 0, sizeof(Fts3tokTable));
  145907. pTab->pMod = pMod;
  145908. pTab->pTok = pTok;
  145909. *ppVtab = &pTab->base;
  145910. }else{
  145911. if( pTok ){
  145912. pMod->xDestroy(pTok);
  145913. }
  145914. }
  145915. sqlite3_free(azDequote);
  145916. return rc;
  145917. }
  145918. /*
  145919. ** This function does the work for both the xDisconnect and xDestroy methods.
  145920. ** These tables have no persistent representation of their own, so xDisconnect
  145921. ** and xDestroy are identical operations.
  145922. */
  145923. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  145924. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  145925. pTab->pMod->xDestroy(pTab->pTok);
  145926. sqlite3_free(pTab);
  145927. return SQLITE_OK;
  145928. }
  145929. /*
  145930. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  145931. */
  145932. static int fts3tokBestIndexMethod(
  145933. sqlite3_vtab *pVTab,
  145934. sqlite3_index_info *pInfo
  145935. ){
  145936. int i;
  145937. UNUSED_PARAMETER(pVTab);
  145938. for(i=0; i<pInfo->nConstraint; i++){
  145939. if( pInfo->aConstraint[i].usable
  145940. && pInfo->aConstraint[i].iColumn==0
  145941. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  145942. ){
  145943. pInfo->idxNum = 1;
  145944. pInfo->aConstraintUsage[i].argvIndex = 1;
  145945. pInfo->aConstraintUsage[i].omit = 1;
  145946. pInfo->estimatedCost = 1;
  145947. return SQLITE_OK;
  145948. }
  145949. }
  145950. pInfo->idxNum = 0;
  145951. assert( pInfo->estimatedCost>1000000.0 );
  145952. return SQLITE_OK;
  145953. }
  145954. /*
  145955. ** xOpen - Open a cursor.
  145956. */
  145957. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  145958. Fts3tokCursor *pCsr;
  145959. UNUSED_PARAMETER(pVTab);
  145960. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  145961. if( pCsr==0 ){
  145962. return SQLITE_NOMEM;
  145963. }
  145964. memset(pCsr, 0, sizeof(Fts3tokCursor));
  145965. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  145966. return SQLITE_OK;
  145967. }
  145968. /*
  145969. ** Reset the tokenizer cursor passed as the only argument. As if it had
  145970. ** just been returned by fts3tokOpenMethod().
  145971. */
  145972. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  145973. if( pCsr->pCsr ){
  145974. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  145975. pTab->pMod->xClose(pCsr->pCsr);
  145976. pCsr->pCsr = 0;
  145977. }
  145978. sqlite3_free(pCsr->zInput);
  145979. pCsr->zInput = 0;
  145980. pCsr->zToken = 0;
  145981. pCsr->nToken = 0;
  145982. pCsr->iStart = 0;
  145983. pCsr->iEnd = 0;
  145984. pCsr->iPos = 0;
  145985. pCsr->iRowid = 0;
  145986. }
  145987. /*
  145988. ** xClose - Close a cursor.
  145989. */
  145990. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  145991. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  145992. fts3tokResetCursor(pCsr);
  145993. sqlite3_free(pCsr);
  145994. return SQLITE_OK;
  145995. }
  145996. /*
  145997. ** xNext - Advance the cursor to the next row, if any.
  145998. */
  145999. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  146000. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146001. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  146002. int rc; /* Return code */
  146003. pCsr->iRowid++;
  146004. rc = pTab->pMod->xNext(pCsr->pCsr,
  146005. &pCsr->zToken, &pCsr->nToken,
  146006. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  146007. );
  146008. if( rc!=SQLITE_OK ){
  146009. fts3tokResetCursor(pCsr);
  146010. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  146011. }
  146012. return rc;
  146013. }
  146014. /*
  146015. ** xFilter - Initialize a cursor to point at the start of its data.
  146016. */
  146017. static int fts3tokFilterMethod(
  146018. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  146019. int idxNum, /* Strategy index */
  146020. const char *idxStr, /* Unused */
  146021. int nVal, /* Number of elements in apVal */
  146022. sqlite3_value **apVal /* Arguments for the indexing scheme */
  146023. ){
  146024. int rc = SQLITE_ERROR;
  146025. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146026. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  146027. UNUSED_PARAMETER(idxStr);
  146028. UNUSED_PARAMETER(nVal);
  146029. fts3tokResetCursor(pCsr);
  146030. if( idxNum==1 ){
  146031. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  146032. int nByte = sqlite3_value_bytes(apVal[0]);
  146033. pCsr->zInput = sqlite3_malloc(nByte+1);
  146034. if( pCsr->zInput==0 ){
  146035. rc = SQLITE_NOMEM;
  146036. }else{
  146037. memcpy(pCsr->zInput, zByte, nByte);
  146038. pCsr->zInput[nByte] = 0;
  146039. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  146040. if( rc==SQLITE_OK ){
  146041. pCsr->pCsr->pTokenizer = pTab->pTok;
  146042. }
  146043. }
  146044. }
  146045. if( rc!=SQLITE_OK ) return rc;
  146046. return fts3tokNextMethod(pCursor);
  146047. }
  146048. /*
  146049. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  146050. */
  146051. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  146052. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146053. return (pCsr->zToken==0);
  146054. }
  146055. /*
  146056. ** xColumn - Return a column value.
  146057. */
  146058. static int fts3tokColumnMethod(
  146059. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  146060. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  146061. int iCol /* Index of column to read value from */
  146062. ){
  146063. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146064. /* CREATE TABLE x(input, token, start, end, position) */
  146065. switch( iCol ){
  146066. case 0:
  146067. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  146068. break;
  146069. case 1:
  146070. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  146071. break;
  146072. case 2:
  146073. sqlite3_result_int(pCtx, pCsr->iStart);
  146074. break;
  146075. case 3:
  146076. sqlite3_result_int(pCtx, pCsr->iEnd);
  146077. break;
  146078. default:
  146079. assert( iCol==4 );
  146080. sqlite3_result_int(pCtx, pCsr->iPos);
  146081. break;
  146082. }
  146083. return SQLITE_OK;
  146084. }
  146085. /*
  146086. ** xRowid - Return the current rowid for the cursor.
  146087. */
  146088. static int fts3tokRowidMethod(
  146089. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  146090. sqlite_int64 *pRowid /* OUT: Rowid value */
  146091. ){
  146092. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146093. *pRowid = (sqlite3_int64)pCsr->iRowid;
  146094. return SQLITE_OK;
  146095. }
  146096. /*
  146097. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  146098. ** if successful or an error code if sqlite3_create_module() fails.
  146099. */
  146100. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  146101. static const sqlite3_module fts3tok_module = {
  146102. 0, /* iVersion */
  146103. fts3tokConnectMethod, /* xCreate */
  146104. fts3tokConnectMethod, /* xConnect */
  146105. fts3tokBestIndexMethod, /* xBestIndex */
  146106. fts3tokDisconnectMethod, /* xDisconnect */
  146107. fts3tokDisconnectMethod, /* xDestroy */
  146108. fts3tokOpenMethod, /* xOpen */
  146109. fts3tokCloseMethod, /* xClose */
  146110. fts3tokFilterMethod, /* xFilter */
  146111. fts3tokNextMethod, /* xNext */
  146112. fts3tokEofMethod, /* xEof */
  146113. fts3tokColumnMethod, /* xColumn */
  146114. fts3tokRowidMethod, /* xRowid */
  146115. 0, /* xUpdate */
  146116. 0, /* xBegin */
  146117. 0, /* xSync */
  146118. 0, /* xCommit */
  146119. 0, /* xRollback */
  146120. 0, /* xFindFunction */
  146121. 0, /* xRename */
  146122. 0, /* xSavepoint */
  146123. 0, /* xRelease */
  146124. 0 /* xRollbackTo */
  146125. };
  146126. int rc; /* Return code */
  146127. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  146128. return rc;
  146129. }
  146130. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  146131. /************** End of fts3_tokenize_vtab.c **********************************/
  146132. /************** Begin file fts3_write.c **************************************/
  146133. /*
  146134. ** 2009 Oct 23
  146135. **
  146136. ** The author disclaims copyright to this source code. In place of
  146137. ** a legal notice, here is a blessing:
  146138. **
  146139. ** May you do good and not evil.
  146140. ** May you find forgiveness for yourself and forgive others.
  146141. ** May you share freely, never taking more than you give.
  146142. **
  146143. ******************************************************************************
  146144. **
  146145. ** This file is part of the SQLite FTS3 extension module. Specifically,
  146146. ** this file contains code to insert, update and delete rows from FTS3
  146147. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  146148. ** of the sub-routines used to merge segments are also used by the query
  146149. ** code in fts3.c.
  146150. */
  146151. /* #include "fts3Int.h" */
  146152. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  146153. /* #include <string.h> */
  146154. /* #include <assert.h> */
  146155. /* #include <stdlib.h> */
  146156. #define FTS_MAX_APPENDABLE_HEIGHT 16
  146157. /*
  146158. ** When full-text index nodes are loaded from disk, the buffer that they
  146159. ** are loaded into has the following number of bytes of padding at the end
  146160. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  146161. ** of 920 bytes is allocated for it.
  146162. **
  146163. ** This means that if we have a pointer into a buffer containing node data,
  146164. ** it is always safe to read up to two varints from it without risking an
  146165. ** overread, even if the node data is corrupted.
  146166. */
  146167. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  146168. /*
  146169. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  146170. ** memory incrementally instead of all at once. This can be a big performance
  146171. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  146172. ** method before retrieving all query results (as may happen, for example,
  146173. ** if a query has a LIMIT clause).
  146174. **
  146175. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  146176. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  146177. ** The code is written so that the hard lower-limit for each of these values
  146178. ** is 1. Clearly such small values would be inefficient, but can be useful
  146179. ** for testing purposes.
  146180. **
  146181. ** If this module is built with SQLITE_TEST defined, these constants may
  146182. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  146183. ** a Tcl interface to read and write the values.
  146184. */
  146185. #ifdef SQLITE_TEST
  146186. int test_fts3_node_chunksize = (4*1024);
  146187. int test_fts3_node_chunk_threshold = (4*1024)*4;
  146188. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  146189. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  146190. #else
  146191. # define FTS3_NODE_CHUNKSIZE (4*1024)
  146192. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  146193. #endif
  146194. /*
  146195. ** The two values that may be meaningfully bound to the :1 parameter in
  146196. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  146197. */
  146198. #define FTS_STAT_DOCTOTAL 0
  146199. #define FTS_STAT_INCRMERGEHINT 1
  146200. #define FTS_STAT_AUTOINCRMERGE 2
  146201. /*
  146202. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  146203. ** and incremental merge operation that takes place. This is used for
  146204. ** debugging FTS only, it should not usually be turned on in production
  146205. ** systems.
  146206. */
  146207. #ifdef FTS3_LOG_MERGES
  146208. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  146209. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  146210. }
  146211. #else
  146212. #define fts3LogMerge(x, y)
  146213. #endif
  146214. typedef struct PendingList PendingList;
  146215. typedef struct SegmentNode SegmentNode;
  146216. typedef struct SegmentWriter SegmentWriter;
  146217. /*
  146218. ** An instance of the following data structure is used to build doclists
  146219. ** incrementally. See function fts3PendingListAppend() for details.
  146220. */
  146221. struct PendingList {
  146222. int nData;
  146223. char *aData;
  146224. int nSpace;
  146225. sqlite3_int64 iLastDocid;
  146226. sqlite3_int64 iLastCol;
  146227. sqlite3_int64 iLastPos;
  146228. };
  146229. /*
  146230. ** Each cursor has a (possibly empty) linked list of the following objects.
  146231. */
  146232. struct Fts3DeferredToken {
  146233. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  146234. int iCol; /* Column token must occur in */
  146235. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  146236. PendingList *pList; /* Doclist is assembled here */
  146237. };
  146238. /*
  146239. ** An instance of this structure is used to iterate through the terms on
  146240. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  146241. ** this structure are only manipulated by code in this file, opaque handles
  146242. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  146243. ** terms when querying the full-text index. See functions:
  146244. **
  146245. ** sqlite3Fts3SegReaderNew()
  146246. ** sqlite3Fts3SegReaderFree()
  146247. ** sqlite3Fts3SegReaderIterate()
  146248. **
  146249. ** Methods used to manipulate Fts3SegReader structures:
  146250. **
  146251. ** fts3SegReaderNext()
  146252. ** fts3SegReaderFirstDocid()
  146253. ** fts3SegReaderNextDocid()
  146254. */
  146255. struct Fts3SegReader {
  146256. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  146257. u8 bLookup; /* True for a lookup only */
  146258. u8 rootOnly; /* True for a root-only reader */
  146259. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  146260. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  146261. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  146262. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  146263. char *aNode; /* Pointer to node data (or NULL) */
  146264. int nNode; /* Size of buffer at aNode (or 0) */
  146265. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  146266. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  146267. Fts3HashElem **ppNextElem;
  146268. /* Variables set by fts3SegReaderNext(). These may be read directly
  146269. ** by the caller. They are valid from the time SegmentReaderNew() returns
  146270. ** until SegmentReaderNext() returns something other than SQLITE_OK
  146271. ** (i.e. SQLITE_DONE).
  146272. */
  146273. int nTerm; /* Number of bytes in current term */
  146274. char *zTerm; /* Pointer to current term */
  146275. int nTermAlloc; /* Allocated size of zTerm buffer */
  146276. char *aDoclist; /* Pointer to doclist of current entry */
  146277. int nDoclist; /* Size of doclist in current entry */
  146278. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  146279. ** through the current doclist (aDoclist/nDoclist).
  146280. */
  146281. char *pOffsetList;
  146282. int nOffsetList; /* For descending pending seg-readers only */
  146283. sqlite3_int64 iDocid;
  146284. };
  146285. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  146286. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  146287. /*
  146288. ** An instance of this structure is used to create a segment b-tree in the
  146289. ** database. The internal details of this type are only accessed by the
  146290. ** following functions:
  146291. **
  146292. ** fts3SegWriterAdd()
  146293. ** fts3SegWriterFlush()
  146294. ** fts3SegWriterFree()
  146295. */
  146296. struct SegmentWriter {
  146297. SegmentNode *pTree; /* Pointer to interior tree structure */
  146298. sqlite3_int64 iFirst; /* First slot in %_segments written */
  146299. sqlite3_int64 iFree; /* Next free slot in %_segments */
  146300. char *zTerm; /* Pointer to previous term buffer */
  146301. int nTerm; /* Number of bytes in zTerm */
  146302. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  146303. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  146304. int nSize; /* Size of allocation at aData */
  146305. int nData; /* Bytes of data in aData */
  146306. char *aData; /* Pointer to block from malloc() */
  146307. i64 nLeafData; /* Number of bytes of leaf data written */
  146308. };
  146309. /*
  146310. ** Type SegmentNode is used by the following three functions to create
  146311. ** the interior part of the segment b+-tree structures (everything except
  146312. ** the leaf nodes). These functions and type are only ever used by code
  146313. ** within the fts3SegWriterXXX() family of functions described above.
  146314. **
  146315. ** fts3NodeAddTerm()
  146316. ** fts3NodeWrite()
  146317. ** fts3NodeFree()
  146318. **
  146319. ** When a b+tree is written to the database (either as a result of a merge
  146320. ** or the pending-terms table being flushed), leaves are written into the
  146321. ** database file as soon as they are completely populated. The interior of
  146322. ** the tree is assembled in memory and written out only once all leaves have
  146323. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  146324. ** very large, meaning that the interior of the tree consumes relatively
  146325. ** little memory.
  146326. */
  146327. struct SegmentNode {
  146328. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  146329. SegmentNode *pRight; /* Pointer to right-sibling */
  146330. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  146331. int nEntry; /* Number of terms written to node so far */
  146332. char *zTerm; /* Pointer to previous term buffer */
  146333. int nTerm; /* Number of bytes in zTerm */
  146334. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  146335. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  146336. int nData; /* Bytes of valid data so far */
  146337. char *aData; /* Node data */
  146338. };
  146339. /*
  146340. ** Valid values for the second argument to fts3SqlStmt().
  146341. */
  146342. #define SQL_DELETE_CONTENT 0
  146343. #define SQL_IS_EMPTY 1
  146344. #define SQL_DELETE_ALL_CONTENT 2
  146345. #define SQL_DELETE_ALL_SEGMENTS 3
  146346. #define SQL_DELETE_ALL_SEGDIR 4
  146347. #define SQL_DELETE_ALL_DOCSIZE 5
  146348. #define SQL_DELETE_ALL_STAT 6
  146349. #define SQL_SELECT_CONTENT_BY_ROWID 7
  146350. #define SQL_NEXT_SEGMENT_INDEX 8
  146351. #define SQL_INSERT_SEGMENTS 9
  146352. #define SQL_NEXT_SEGMENTS_ID 10
  146353. #define SQL_INSERT_SEGDIR 11
  146354. #define SQL_SELECT_LEVEL 12
  146355. #define SQL_SELECT_LEVEL_RANGE 13
  146356. #define SQL_SELECT_LEVEL_COUNT 14
  146357. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  146358. #define SQL_DELETE_SEGDIR_LEVEL 16
  146359. #define SQL_DELETE_SEGMENTS_RANGE 17
  146360. #define SQL_CONTENT_INSERT 18
  146361. #define SQL_DELETE_DOCSIZE 19
  146362. #define SQL_REPLACE_DOCSIZE 20
  146363. #define SQL_SELECT_DOCSIZE 21
  146364. #define SQL_SELECT_STAT 22
  146365. #define SQL_REPLACE_STAT 23
  146366. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  146367. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  146368. #define SQL_DELETE_SEGDIR_RANGE 26
  146369. #define SQL_SELECT_ALL_LANGID 27
  146370. #define SQL_FIND_MERGE_LEVEL 28
  146371. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  146372. #define SQL_DELETE_SEGDIR_ENTRY 30
  146373. #define SQL_SHIFT_SEGDIR_ENTRY 31
  146374. #define SQL_SELECT_SEGDIR 32
  146375. #define SQL_CHOMP_SEGDIR 33
  146376. #define SQL_SEGMENT_IS_APPENDABLE 34
  146377. #define SQL_SELECT_INDEXES 35
  146378. #define SQL_SELECT_MXLEVEL 36
  146379. #define SQL_SELECT_LEVEL_RANGE2 37
  146380. #define SQL_UPDATE_LEVEL_IDX 38
  146381. #define SQL_UPDATE_LEVEL 39
  146382. /*
  146383. ** This function is used to obtain an SQLite prepared statement handle
  146384. ** for the statement identified by the second argument. If successful,
  146385. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  146386. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  146387. **
  146388. ** If argument apVal is not NULL, then it must point to an array with
  146389. ** at least as many entries as the requested statement has bound
  146390. ** parameters. The values are bound to the statements parameters before
  146391. ** returning.
  146392. */
  146393. static int fts3SqlStmt(
  146394. Fts3Table *p, /* Virtual table handle */
  146395. int eStmt, /* One of the SQL_XXX constants above */
  146396. sqlite3_stmt **pp, /* OUT: Statement handle */
  146397. sqlite3_value **apVal /* Values to bind to statement */
  146398. ){
  146399. const char *azSql[] = {
  146400. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  146401. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  146402. /* 2 */ "DELETE FROM %Q.'%q_content'",
  146403. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  146404. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  146405. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  146406. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  146407. /* 7 */ "SELECT %s WHERE rowid=?",
  146408. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  146409. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  146410. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  146411. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  146412. /* Return segments in order from oldest to newest.*/
  146413. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  146414. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  146415. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  146416. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  146417. "ORDER BY level DESC, idx ASC",
  146418. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  146419. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  146420. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  146421. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  146422. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  146423. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  146424. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  146425. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  146426. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  146427. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  146428. /* 24 */ "",
  146429. /* 25 */ "",
  146430. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  146431. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  146432. /* This statement is used to determine which level to read the input from
  146433. ** when performing an incremental merge. It returns the absolute level number
  146434. ** of the oldest level in the db that contains at least ? segments. Or,
  146435. ** if no level in the FTS index contains more than ? segments, the statement
  146436. ** returns zero rows. */
  146437. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  146438. " GROUP BY level HAVING cnt>=?"
  146439. " ORDER BY (level %% 1024) ASC LIMIT 1",
  146440. /* Estimate the upper limit on the number of leaf nodes in a new segment
  146441. ** created by merging the oldest :2 segments from absolute level :1. See
  146442. ** function sqlite3Fts3Incrmerge() for details. */
  146443. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  146444. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  146445. /* SQL_DELETE_SEGDIR_ENTRY
  146446. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  146447. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  146448. /* SQL_SHIFT_SEGDIR_ENTRY
  146449. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  146450. ** to :1. */
  146451. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  146452. /* SQL_SELECT_SEGDIR
  146453. ** Read a single entry from the %_segdir table. The entry from absolute
  146454. ** level :1 with index value :2. */
  146455. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  146456. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  146457. /* SQL_CHOMP_SEGDIR
  146458. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  146459. ** entry located on absolute level :3 with index :4. */
  146460. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  146461. "WHERE level = ? AND idx = ?",
  146462. /* SQL_SEGMENT_IS_APPENDABLE
  146463. ** Return a single row if the segment with end_block=? is appendable. Or
  146464. ** no rows otherwise. */
  146465. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  146466. /* SQL_SELECT_INDEXES
  146467. ** Return the list of valid segment indexes for absolute level ? */
  146468. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  146469. /* SQL_SELECT_MXLEVEL
  146470. ** Return the largest relative level in the FTS index or indexes. */
  146471. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  146472. /* Return segments in order from oldest to newest.*/
  146473. /* 37 */ "SELECT level, idx, end_block "
  146474. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  146475. "ORDER BY level DESC, idx ASC",
  146476. /* Update statements used while promoting segments */
  146477. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  146478. "WHERE level=? AND idx=?",
  146479. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  146480. };
  146481. int rc = SQLITE_OK;
  146482. sqlite3_stmt *pStmt;
  146483. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  146484. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  146485. pStmt = p->aStmt[eStmt];
  146486. if( !pStmt ){
  146487. char *zSql;
  146488. if( eStmt==SQL_CONTENT_INSERT ){
  146489. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  146490. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  146491. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  146492. }else{
  146493. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  146494. }
  146495. if( !zSql ){
  146496. rc = SQLITE_NOMEM;
  146497. }else{
  146498. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  146499. sqlite3_free(zSql);
  146500. assert( rc==SQLITE_OK || pStmt==0 );
  146501. p->aStmt[eStmt] = pStmt;
  146502. }
  146503. }
  146504. if( apVal ){
  146505. int i;
  146506. int nParam = sqlite3_bind_parameter_count(pStmt);
  146507. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  146508. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  146509. }
  146510. }
  146511. *pp = pStmt;
  146512. return rc;
  146513. }
  146514. static int fts3SelectDocsize(
  146515. Fts3Table *pTab, /* FTS3 table handle */
  146516. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  146517. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  146518. ){
  146519. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  146520. int rc; /* Return code */
  146521. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  146522. if( rc==SQLITE_OK ){
  146523. sqlite3_bind_int64(pStmt, 1, iDocid);
  146524. rc = sqlite3_step(pStmt);
  146525. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  146526. rc = sqlite3_reset(pStmt);
  146527. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  146528. pStmt = 0;
  146529. }else{
  146530. rc = SQLITE_OK;
  146531. }
  146532. }
  146533. *ppStmt = pStmt;
  146534. return rc;
  146535. }
  146536. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  146537. Fts3Table *pTab, /* Fts3 table handle */
  146538. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  146539. ){
  146540. sqlite3_stmt *pStmt = 0;
  146541. int rc;
  146542. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  146543. if( rc==SQLITE_OK ){
  146544. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  146545. if( sqlite3_step(pStmt)!=SQLITE_ROW
  146546. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  146547. ){
  146548. rc = sqlite3_reset(pStmt);
  146549. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  146550. pStmt = 0;
  146551. }
  146552. }
  146553. *ppStmt = pStmt;
  146554. return rc;
  146555. }
  146556. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  146557. Fts3Table *pTab, /* Fts3 table handle */
  146558. sqlite3_int64 iDocid, /* Docid to read size data for */
  146559. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  146560. ){
  146561. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  146562. }
  146563. /*
  146564. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  146565. ** array apVal[] to the SQL statement identified by eStmt, the statement
  146566. ** is executed.
  146567. **
  146568. ** Returns SQLITE_OK if the statement is successfully executed, or an
  146569. ** SQLite error code otherwise.
  146570. */
  146571. static void fts3SqlExec(
  146572. int *pRC, /* Result code */
  146573. Fts3Table *p, /* The FTS3 table */
  146574. int eStmt, /* Index of statement to evaluate */
  146575. sqlite3_value **apVal /* Parameters to bind */
  146576. ){
  146577. sqlite3_stmt *pStmt;
  146578. int rc;
  146579. if( *pRC ) return;
  146580. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  146581. if( rc==SQLITE_OK ){
  146582. sqlite3_step(pStmt);
  146583. rc = sqlite3_reset(pStmt);
  146584. }
  146585. *pRC = rc;
  146586. }
  146587. /*
  146588. ** This function ensures that the caller has obtained an exclusive
  146589. ** shared-cache table-lock on the %_segdir table. This is required before
  146590. ** writing data to the fts3 table. If this lock is not acquired first, then
  146591. ** the caller may end up attempting to take this lock as part of committing
  146592. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  146593. ** LOCKED_SHAREDCACHEto a COMMIT command.
  146594. **
  146595. ** It is best to avoid this because if FTS3 returns any error when
  146596. ** committing a transaction, the whole transaction will be rolled back.
  146597. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  146598. ** It can still happen if the user locks the underlying tables directly
  146599. ** instead of accessing them via FTS.
  146600. */
  146601. static int fts3Writelock(Fts3Table *p){
  146602. int rc = SQLITE_OK;
  146603. if( p->nPendingData==0 ){
  146604. sqlite3_stmt *pStmt;
  146605. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  146606. if( rc==SQLITE_OK ){
  146607. sqlite3_bind_null(pStmt, 1);
  146608. sqlite3_step(pStmt);
  146609. rc = sqlite3_reset(pStmt);
  146610. }
  146611. }
  146612. return rc;
  146613. }
  146614. /*
  146615. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  146616. ** Within each language id, a separate index is maintained to store the
  146617. ** document terms, and each configured prefix size (configured the FTS
  146618. ** "prefix=" option). And each index consists of multiple levels ("relative
  146619. ** levels").
  146620. **
  146621. ** All three of these values (the language id, the specific index and the
  146622. ** level within the index) are encoded in 64-bit integer values stored
  146623. ** in the %_segdir table on disk. This function is used to convert three
  146624. ** separate component values into the single 64-bit integer value that
  146625. ** can be used to query the %_segdir table.
  146626. **
  146627. ** Specifically, each language-id/index combination is allocated 1024
  146628. ** 64-bit integer level values ("absolute levels"). The main terms index
  146629. ** for language-id 0 is allocate values 0-1023. The first prefix index
  146630. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  146631. ** Language 1 indexes are allocated immediately following language 0.
  146632. **
  146633. ** So, for a system with nPrefix prefix indexes configured, the block of
  146634. ** absolute levels that corresponds to language-id iLangid and index
  146635. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  146636. */
  146637. static sqlite3_int64 getAbsoluteLevel(
  146638. Fts3Table *p, /* FTS3 table handle */
  146639. int iLangid, /* Language id */
  146640. int iIndex, /* Index in p->aIndex[] */
  146641. int iLevel /* Level of segments */
  146642. ){
  146643. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  146644. assert( iLangid>=0 );
  146645. assert( p->nIndex>0 );
  146646. assert( iIndex>=0 && iIndex<p->nIndex );
  146647. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  146648. return iBase + iLevel;
  146649. }
  146650. /*
  146651. ** Set *ppStmt to a statement handle that may be used to iterate through
  146652. ** all rows in the %_segdir table, from oldest to newest. If successful,
  146653. ** return SQLITE_OK. If an error occurs while preparing the statement,
  146654. ** return an SQLite error code.
  146655. **
  146656. ** There is only ever one instance of this SQL statement compiled for
  146657. ** each FTS3 table.
  146658. **
  146659. ** The statement returns the following columns from the %_segdir table:
  146660. **
  146661. ** 0: idx
  146662. ** 1: start_block
  146663. ** 2: leaves_end_block
  146664. ** 3: end_block
  146665. ** 4: root
  146666. */
  146667. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  146668. Fts3Table *p, /* FTS3 table */
  146669. int iLangid, /* Language being queried */
  146670. int iIndex, /* Index for p->aIndex[] */
  146671. int iLevel, /* Level to select (relative level) */
  146672. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  146673. ){
  146674. int rc;
  146675. sqlite3_stmt *pStmt = 0;
  146676. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  146677. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  146678. assert( iIndex>=0 && iIndex<p->nIndex );
  146679. if( iLevel<0 ){
  146680. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  146681. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  146682. if( rc==SQLITE_OK ){
  146683. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  146684. sqlite3_bind_int64(pStmt, 2,
  146685. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  146686. );
  146687. }
  146688. }else{
  146689. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  146690. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  146691. if( rc==SQLITE_OK ){
  146692. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  146693. }
  146694. }
  146695. *ppStmt = pStmt;
  146696. return rc;
  146697. }
  146698. /*
  146699. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  146700. ** if successful, or an SQLite error code otherwise.
  146701. **
  146702. ** This function also serves to allocate the PendingList structure itself.
  146703. ** For example, to create a new PendingList structure containing two
  146704. ** varints:
  146705. **
  146706. ** PendingList *p = 0;
  146707. ** fts3PendingListAppendVarint(&p, 1);
  146708. ** fts3PendingListAppendVarint(&p, 2);
  146709. */
  146710. static int fts3PendingListAppendVarint(
  146711. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  146712. sqlite3_int64 i /* Value to append to data */
  146713. ){
  146714. PendingList *p = *pp;
  146715. /* Allocate or grow the PendingList as required. */
  146716. if( !p ){
  146717. p = sqlite3_malloc(sizeof(*p) + 100);
  146718. if( !p ){
  146719. return SQLITE_NOMEM;
  146720. }
  146721. p->nSpace = 100;
  146722. p->aData = (char *)&p[1];
  146723. p->nData = 0;
  146724. }
  146725. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  146726. int nNew = p->nSpace * 2;
  146727. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  146728. if( !p ){
  146729. sqlite3_free(*pp);
  146730. *pp = 0;
  146731. return SQLITE_NOMEM;
  146732. }
  146733. p->nSpace = nNew;
  146734. p->aData = (char *)&p[1];
  146735. }
  146736. /* Append the new serialized varint to the end of the list. */
  146737. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  146738. p->aData[p->nData] = '\0';
  146739. *pp = p;
  146740. return SQLITE_OK;
  146741. }
  146742. /*
  146743. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  146744. ** is returned if the structure is sqlite3_realloced as part of adding
  146745. ** the entry. Otherwise, zero.
  146746. **
  146747. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  146748. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  146749. ** it is set to SQLITE_OK.
  146750. */
  146751. static int fts3PendingListAppend(
  146752. PendingList **pp, /* IN/OUT: PendingList structure */
  146753. sqlite3_int64 iDocid, /* Docid for entry to add */
  146754. sqlite3_int64 iCol, /* Column for entry to add */
  146755. sqlite3_int64 iPos, /* Position of term for entry to add */
  146756. int *pRc /* OUT: Return code */
  146757. ){
  146758. PendingList *p = *pp;
  146759. int rc = SQLITE_OK;
  146760. assert( !p || p->iLastDocid<=iDocid );
  146761. if( !p || p->iLastDocid!=iDocid ){
  146762. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  146763. if( p ){
  146764. assert( p->nData<p->nSpace );
  146765. assert( p->aData[p->nData]==0 );
  146766. p->nData++;
  146767. }
  146768. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  146769. goto pendinglistappend_out;
  146770. }
  146771. p->iLastCol = -1;
  146772. p->iLastPos = 0;
  146773. p->iLastDocid = iDocid;
  146774. }
  146775. if( iCol>0 && p->iLastCol!=iCol ){
  146776. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  146777. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  146778. ){
  146779. goto pendinglistappend_out;
  146780. }
  146781. p->iLastCol = iCol;
  146782. p->iLastPos = 0;
  146783. }
  146784. if( iCol>=0 ){
  146785. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  146786. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  146787. if( rc==SQLITE_OK ){
  146788. p->iLastPos = iPos;
  146789. }
  146790. }
  146791. pendinglistappend_out:
  146792. *pRc = rc;
  146793. if( p!=*pp ){
  146794. *pp = p;
  146795. return 1;
  146796. }
  146797. return 0;
  146798. }
  146799. /*
  146800. ** Free a PendingList object allocated by fts3PendingListAppend().
  146801. */
  146802. static void fts3PendingListDelete(PendingList *pList){
  146803. sqlite3_free(pList);
  146804. }
  146805. /*
  146806. ** Add an entry to one of the pending-terms hash tables.
  146807. */
  146808. static int fts3PendingTermsAddOne(
  146809. Fts3Table *p,
  146810. int iCol,
  146811. int iPos,
  146812. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  146813. const char *zToken,
  146814. int nToken
  146815. ){
  146816. PendingList *pList;
  146817. int rc = SQLITE_OK;
  146818. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  146819. if( pList ){
  146820. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  146821. }
  146822. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  146823. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  146824. /* Malloc failed while inserting the new entry. This can only
  146825. ** happen if there was no previous entry for this token.
  146826. */
  146827. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  146828. sqlite3_free(pList);
  146829. rc = SQLITE_NOMEM;
  146830. }
  146831. }
  146832. if( rc==SQLITE_OK ){
  146833. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  146834. }
  146835. return rc;
  146836. }
  146837. /*
  146838. ** Tokenize the nul-terminated string zText and add all tokens to the
  146839. ** pending-terms hash-table. The docid used is that currently stored in
  146840. ** p->iPrevDocid, and the column is specified by argument iCol.
  146841. **
  146842. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  146843. */
  146844. static int fts3PendingTermsAdd(
  146845. Fts3Table *p, /* Table into which text will be inserted */
  146846. int iLangid, /* Language id to use */
  146847. const char *zText, /* Text of document to be inserted */
  146848. int iCol, /* Column into which text is being inserted */
  146849. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  146850. ){
  146851. int rc;
  146852. int iStart = 0;
  146853. int iEnd = 0;
  146854. int iPos = 0;
  146855. int nWord = 0;
  146856. char const *zToken;
  146857. int nToken = 0;
  146858. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  146859. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  146860. sqlite3_tokenizer_cursor *pCsr;
  146861. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  146862. const char**,int*,int*,int*,int*);
  146863. assert( pTokenizer && pModule );
  146864. /* If the user has inserted a NULL value, this function may be called with
  146865. ** zText==0. In this case, add zero token entries to the hash table and
  146866. ** return early. */
  146867. if( zText==0 ){
  146868. *pnWord = 0;
  146869. return SQLITE_OK;
  146870. }
  146871. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  146872. if( rc!=SQLITE_OK ){
  146873. return rc;
  146874. }
  146875. xNext = pModule->xNext;
  146876. while( SQLITE_OK==rc
  146877. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  146878. ){
  146879. int i;
  146880. if( iPos>=nWord ) nWord = iPos+1;
  146881. /* Positions cannot be negative; we use -1 as a terminator internally.
  146882. ** Tokens must have a non-zero length.
  146883. */
  146884. if( iPos<0 || !zToken || nToken<=0 ){
  146885. rc = SQLITE_ERROR;
  146886. break;
  146887. }
  146888. /* Add the term to the terms index */
  146889. rc = fts3PendingTermsAddOne(
  146890. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  146891. );
  146892. /* Add the term to each of the prefix indexes that it is not too
  146893. ** short for. */
  146894. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  146895. struct Fts3Index *pIndex = &p->aIndex[i];
  146896. if( nToken<pIndex->nPrefix ) continue;
  146897. rc = fts3PendingTermsAddOne(
  146898. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  146899. );
  146900. }
  146901. }
  146902. pModule->xClose(pCsr);
  146903. *pnWord += nWord;
  146904. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  146905. }
  146906. /*
  146907. ** Calling this function indicates that subsequent calls to
  146908. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  146909. ** contents of the document with docid iDocid.
  146910. */
  146911. static int fts3PendingTermsDocid(
  146912. Fts3Table *p, /* Full-text table handle */
  146913. int bDelete, /* True if this op is a delete */
  146914. int iLangid, /* Language id of row being written */
  146915. sqlite_int64 iDocid /* Docid of row being written */
  146916. ){
  146917. assert( iLangid>=0 );
  146918. assert( bDelete==1 || bDelete==0 );
  146919. /* TODO(shess) Explore whether partially flushing the buffer on
  146920. ** forced-flush would provide better performance. I suspect that if
  146921. ** we ordered the doclists by size and flushed the largest until the
  146922. ** buffer was half empty, that would let the less frequent terms
  146923. ** generate longer doclists.
  146924. */
  146925. if( iDocid<p->iPrevDocid
  146926. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  146927. || p->iPrevLangid!=iLangid
  146928. || p->nPendingData>p->nMaxPendingData
  146929. ){
  146930. int rc = sqlite3Fts3PendingTermsFlush(p);
  146931. if( rc!=SQLITE_OK ) return rc;
  146932. }
  146933. p->iPrevDocid = iDocid;
  146934. p->iPrevLangid = iLangid;
  146935. p->bPrevDelete = bDelete;
  146936. return SQLITE_OK;
  146937. }
  146938. /*
  146939. ** Discard the contents of the pending-terms hash tables.
  146940. */
  146941. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  146942. int i;
  146943. for(i=0; i<p->nIndex; i++){
  146944. Fts3HashElem *pElem;
  146945. Fts3Hash *pHash = &p->aIndex[i].hPending;
  146946. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  146947. PendingList *pList = (PendingList *)fts3HashData(pElem);
  146948. fts3PendingListDelete(pList);
  146949. }
  146950. fts3HashClear(pHash);
  146951. }
  146952. p->nPendingData = 0;
  146953. }
  146954. /*
  146955. ** This function is called by the xUpdate() method as part of an INSERT
  146956. ** operation. It adds entries for each term in the new record to the
  146957. ** pendingTerms hash table.
  146958. **
  146959. ** Argument apVal is the same as the similarly named argument passed to
  146960. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  146961. */
  146962. static int fts3InsertTerms(
  146963. Fts3Table *p,
  146964. int iLangid,
  146965. sqlite3_value **apVal,
  146966. u32 *aSz
  146967. ){
  146968. int i; /* Iterator variable */
  146969. for(i=2; i<p->nColumn+2; i++){
  146970. int iCol = i-2;
  146971. if( p->abNotindexed[iCol]==0 ){
  146972. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  146973. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  146974. if( rc!=SQLITE_OK ){
  146975. return rc;
  146976. }
  146977. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  146978. }
  146979. }
  146980. return SQLITE_OK;
  146981. }
  146982. /*
  146983. ** This function is called by the xUpdate() method for an INSERT operation.
  146984. ** The apVal parameter is passed a copy of the apVal argument passed by
  146985. ** SQLite to the xUpdate() method. i.e:
  146986. **
  146987. ** apVal[0] Not used for INSERT.
  146988. ** apVal[1] rowid
  146989. ** apVal[2] Left-most user-defined column
  146990. ** ...
  146991. ** apVal[p->nColumn+1] Right-most user-defined column
  146992. ** apVal[p->nColumn+2] Hidden column with same name as table
  146993. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  146994. ** apVal[p->nColumn+4] Hidden languageid column
  146995. */
  146996. static int fts3InsertData(
  146997. Fts3Table *p, /* Full-text table */
  146998. sqlite3_value **apVal, /* Array of values to insert */
  146999. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  147000. ){
  147001. int rc; /* Return code */
  147002. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  147003. if( p->zContentTbl ){
  147004. sqlite3_value *pRowid = apVal[p->nColumn+3];
  147005. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  147006. pRowid = apVal[1];
  147007. }
  147008. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  147009. return SQLITE_CONSTRAINT;
  147010. }
  147011. *piDocid = sqlite3_value_int64(pRowid);
  147012. return SQLITE_OK;
  147013. }
  147014. /* Locate the statement handle used to insert data into the %_content
  147015. ** table. The SQL for this statement is:
  147016. **
  147017. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  147018. **
  147019. ** The statement features N '?' variables, where N is the number of user
  147020. ** defined columns in the FTS3 table, plus one for the docid field.
  147021. */
  147022. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  147023. if( rc==SQLITE_OK && p->zLanguageid ){
  147024. rc = sqlite3_bind_int(
  147025. pContentInsert, p->nColumn+2,
  147026. sqlite3_value_int(apVal[p->nColumn+4])
  147027. );
  147028. }
  147029. if( rc!=SQLITE_OK ) return rc;
  147030. /* There is a quirk here. The users INSERT statement may have specified
  147031. ** a value for the "rowid" field, for the "docid" field, or for both.
  147032. ** Which is a problem, since "rowid" and "docid" are aliases for the
  147033. ** same value. For example:
  147034. **
  147035. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  147036. **
  147037. ** In FTS3, this is an error. It is an error to specify non-NULL values
  147038. ** for both docid and some other rowid alias.
  147039. */
  147040. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  147041. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  147042. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  147043. ){
  147044. /* A rowid/docid conflict. */
  147045. return SQLITE_ERROR;
  147046. }
  147047. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  147048. if( rc!=SQLITE_OK ) return rc;
  147049. }
  147050. /* Execute the statement to insert the record. Set *piDocid to the
  147051. ** new docid value.
  147052. */
  147053. sqlite3_step(pContentInsert);
  147054. rc = sqlite3_reset(pContentInsert);
  147055. *piDocid = sqlite3_last_insert_rowid(p->db);
  147056. return rc;
  147057. }
  147058. /*
  147059. ** Remove all data from the FTS3 table. Clear the hash table containing
  147060. ** pending terms.
  147061. */
  147062. static int fts3DeleteAll(Fts3Table *p, int bContent){
  147063. int rc = SQLITE_OK; /* Return code */
  147064. /* Discard the contents of the pending-terms hash table. */
  147065. sqlite3Fts3PendingTermsClear(p);
  147066. /* Delete everything from the shadow tables. Except, leave %_content as
  147067. ** is if bContent is false. */
  147068. assert( p->zContentTbl==0 || bContent==0 );
  147069. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  147070. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  147071. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  147072. if( p->bHasDocsize ){
  147073. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  147074. }
  147075. if( p->bHasStat ){
  147076. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  147077. }
  147078. return rc;
  147079. }
  147080. /*
  147081. **
  147082. */
  147083. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  147084. int iLangid = 0;
  147085. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  147086. return iLangid;
  147087. }
  147088. /*
  147089. ** The first element in the apVal[] array is assumed to contain the docid
  147090. ** (an integer) of a row about to be deleted. Remove all terms from the
  147091. ** full-text index.
  147092. */
  147093. static void fts3DeleteTerms(
  147094. int *pRC, /* Result code */
  147095. Fts3Table *p, /* The FTS table to delete from */
  147096. sqlite3_value *pRowid, /* The docid to be deleted */
  147097. u32 *aSz, /* Sizes of deleted document written here */
  147098. int *pbFound /* OUT: Set to true if row really does exist */
  147099. ){
  147100. int rc;
  147101. sqlite3_stmt *pSelect;
  147102. assert( *pbFound==0 );
  147103. if( *pRC ) return;
  147104. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  147105. if( rc==SQLITE_OK ){
  147106. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  147107. int i;
  147108. int iLangid = langidFromSelect(p, pSelect);
  147109. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  147110. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  147111. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  147112. int iCol = i-1;
  147113. if( p->abNotindexed[iCol]==0 ){
  147114. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  147115. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  147116. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  147117. }
  147118. }
  147119. if( rc!=SQLITE_OK ){
  147120. sqlite3_reset(pSelect);
  147121. *pRC = rc;
  147122. return;
  147123. }
  147124. *pbFound = 1;
  147125. }
  147126. rc = sqlite3_reset(pSelect);
  147127. }else{
  147128. sqlite3_reset(pSelect);
  147129. }
  147130. *pRC = rc;
  147131. }
  147132. /*
  147133. ** Forward declaration to account for the circular dependency between
  147134. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  147135. */
  147136. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  147137. /*
  147138. ** This function allocates a new level iLevel index in the segdir table.
  147139. ** Usually, indexes are allocated within a level sequentially starting
  147140. ** with 0, so the allocated index is one greater than the value returned
  147141. ** by:
  147142. **
  147143. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  147144. **
  147145. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  147146. ** level, they are merged into a single level (iLevel+1) segment and the
  147147. ** allocated index is 0.
  147148. **
  147149. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  147150. ** returned. Otherwise, an SQLite error code is returned.
  147151. */
  147152. static int fts3AllocateSegdirIdx(
  147153. Fts3Table *p,
  147154. int iLangid, /* Language id */
  147155. int iIndex, /* Index for p->aIndex */
  147156. int iLevel,
  147157. int *piIdx
  147158. ){
  147159. int rc; /* Return Code */
  147160. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  147161. int iNext = 0; /* Result of query pNextIdx */
  147162. assert( iLangid>=0 );
  147163. assert( p->nIndex>=1 );
  147164. /* Set variable iNext to the next available segdir index at level iLevel. */
  147165. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  147166. if( rc==SQLITE_OK ){
  147167. sqlite3_bind_int64(
  147168. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  147169. );
  147170. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  147171. iNext = sqlite3_column_int(pNextIdx, 0);
  147172. }
  147173. rc = sqlite3_reset(pNextIdx);
  147174. }
  147175. if( rc==SQLITE_OK ){
  147176. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  147177. ** full, merge all segments in level iLevel into a single iLevel+1
  147178. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  147179. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  147180. */
  147181. if( iNext>=FTS3_MERGE_COUNT ){
  147182. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  147183. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  147184. *piIdx = 0;
  147185. }else{
  147186. *piIdx = iNext;
  147187. }
  147188. }
  147189. return rc;
  147190. }
  147191. /*
  147192. ** The %_segments table is declared as follows:
  147193. **
  147194. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  147195. **
  147196. ** This function reads data from a single row of the %_segments table. The
  147197. ** specific row is identified by the iBlockid parameter. If paBlob is not
  147198. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  147199. ** with the contents of the blob stored in the "block" column of the
  147200. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  147201. ** to the size of the blob in bytes before returning.
  147202. **
  147203. ** If an error occurs, or the table does not contain the specified row,
  147204. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  147205. ** paBlob is non-NULL, then it is the responsibility of the caller to
  147206. ** eventually free the returned buffer.
  147207. **
  147208. ** This function may leave an open sqlite3_blob* handle in the
  147209. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  147210. ** to this function. The handle may be closed by calling the
  147211. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  147212. ** performance improvement, but the blob handle should always be closed
  147213. ** before control is returned to the user (to prevent a lock being held
  147214. ** on the database file for longer than necessary). Thus, any virtual table
  147215. ** method (xFilter etc.) that may directly or indirectly call this function
  147216. ** must call sqlite3Fts3SegmentsClose() before returning.
  147217. */
  147218. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  147219. Fts3Table *p, /* FTS3 table handle */
  147220. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  147221. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  147222. int *pnBlob, /* OUT: Size of blob data */
  147223. int *pnLoad /* OUT: Bytes actually loaded */
  147224. ){
  147225. int rc; /* Return code */
  147226. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  147227. assert( pnBlob );
  147228. if( p->pSegments ){
  147229. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  147230. }else{
  147231. if( 0==p->zSegmentsTbl ){
  147232. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  147233. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  147234. }
  147235. rc = sqlite3_blob_open(
  147236. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  147237. );
  147238. }
  147239. if( rc==SQLITE_OK ){
  147240. int nByte = sqlite3_blob_bytes(p->pSegments);
  147241. *pnBlob = nByte;
  147242. if( paBlob ){
  147243. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  147244. if( !aByte ){
  147245. rc = SQLITE_NOMEM;
  147246. }else{
  147247. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  147248. nByte = FTS3_NODE_CHUNKSIZE;
  147249. *pnLoad = nByte;
  147250. }
  147251. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  147252. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  147253. if( rc!=SQLITE_OK ){
  147254. sqlite3_free(aByte);
  147255. aByte = 0;
  147256. }
  147257. }
  147258. *paBlob = aByte;
  147259. }
  147260. }
  147261. return rc;
  147262. }
  147263. /*
  147264. ** Close the blob handle at p->pSegments, if it is open. See comments above
  147265. ** the sqlite3Fts3ReadBlock() function for details.
  147266. */
  147267. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  147268. sqlite3_blob_close(p->pSegments);
  147269. p->pSegments = 0;
  147270. }
  147271. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  147272. int nRead; /* Number of bytes to read */
  147273. int rc; /* Return code */
  147274. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  147275. rc = sqlite3_blob_read(
  147276. pReader->pBlob,
  147277. &pReader->aNode[pReader->nPopulate],
  147278. nRead,
  147279. pReader->nPopulate
  147280. );
  147281. if( rc==SQLITE_OK ){
  147282. pReader->nPopulate += nRead;
  147283. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  147284. if( pReader->nPopulate==pReader->nNode ){
  147285. sqlite3_blob_close(pReader->pBlob);
  147286. pReader->pBlob = 0;
  147287. pReader->nPopulate = 0;
  147288. }
  147289. }
  147290. return rc;
  147291. }
  147292. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  147293. int rc = SQLITE_OK;
  147294. assert( !pReader->pBlob
  147295. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  147296. );
  147297. while( pReader->pBlob && rc==SQLITE_OK
  147298. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  147299. ){
  147300. rc = fts3SegReaderIncrRead(pReader);
  147301. }
  147302. return rc;
  147303. }
  147304. /*
  147305. ** Set an Fts3SegReader cursor to point at EOF.
  147306. */
  147307. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  147308. if( !fts3SegReaderIsRootOnly(pSeg) ){
  147309. sqlite3_free(pSeg->aNode);
  147310. sqlite3_blob_close(pSeg->pBlob);
  147311. pSeg->pBlob = 0;
  147312. }
  147313. pSeg->aNode = 0;
  147314. }
  147315. /*
  147316. ** Move the iterator passed as the first argument to the next term in the
  147317. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  147318. ** SQLITE_DONE. Otherwise, an SQLite error code.
  147319. */
  147320. static int fts3SegReaderNext(
  147321. Fts3Table *p,
  147322. Fts3SegReader *pReader,
  147323. int bIncr
  147324. ){
  147325. int rc; /* Return code of various sub-routines */
  147326. char *pNext; /* Cursor variable */
  147327. int nPrefix; /* Number of bytes in term prefix */
  147328. int nSuffix; /* Number of bytes in term suffix */
  147329. if( !pReader->aDoclist ){
  147330. pNext = pReader->aNode;
  147331. }else{
  147332. pNext = &pReader->aDoclist[pReader->nDoclist];
  147333. }
  147334. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  147335. if( fts3SegReaderIsPending(pReader) ){
  147336. Fts3HashElem *pElem = *(pReader->ppNextElem);
  147337. sqlite3_free(pReader->aNode);
  147338. pReader->aNode = 0;
  147339. if( pElem ){
  147340. char *aCopy;
  147341. PendingList *pList = (PendingList *)fts3HashData(pElem);
  147342. int nCopy = pList->nData+1;
  147343. pReader->zTerm = (char *)fts3HashKey(pElem);
  147344. pReader->nTerm = fts3HashKeysize(pElem);
  147345. aCopy = (char*)sqlite3_malloc(nCopy);
  147346. if( !aCopy ) return SQLITE_NOMEM;
  147347. memcpy(aCopy, pList->aData, nCopy);
  147348. pReader->nNode = pReader->nDoclist = nCopy;
  147349. pReader->aNode = pReader->aDoclist = aCopy;
  147350. pReader->ppNextElem++;
  147351. assert( pReader->aNode );
  147352. }
  147353. return SQLITE_OK;
  147354. }
  147355. fts3SegReaderSetEof(pReader);
  147356. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  147357. ** blocks have already been traversed. */
  147358. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  147359. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  147360. return SQLITE_OK;
  147361. }
  147362. rc = sqlite3Fts3ReadBlock(
  147363. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  147364. (bIncr ? &pReader->nPopulate : 0)
  147365. );
  147366. if( rc!=SQLITE_OK ) return rc;
  147367. assert( pReader->pBlob==0 );
  147368. if( bIncr && pReader->nPopulate<pReader->nNode ){
  147369. pReader->pBlob = p->pSegments;
  147370. p->pSegments = 0;
  147371. }
  147372. pNext = pReader->aNode;
  147373. }
  147374. assert( !fts3SegReaderIsPending(pReader) );
  147375. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  147376. if( rc!=SQLITE_OK ) return rc;
  147377. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  147378. ** safe (no risk of overread) even if the node data is corrupted. */
  147379. pNext += fts3GetVarint32(pNext, &nPrefix);
  147380. pNext += fts3GetVarint32(pNext, &nSuffix);
  147381. if( nPrefix<0 || nSuffix<=0
  147382. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  147383. ){
  147384. return FTS_CORRUPT_VTAB;
  147385. }
  147386. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  147387. int nNew = (nPrefix+nSuffix)*2;
  147388. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  147389. if( !zNew ){
  147390. return SQLITE_NOMEM;
  147391. }
  147392. pReader->zTerm = zNew;
  147393. pReader->nTermAlloc = nNew;
  147394. }
  147395. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  147396. if( rc!=SQLITE_OK ) return rc;
  147397. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  147398. pReader->nTerm = nPrefix+nSuffix;
  147399. pNext += nSuffix;
  147400. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  147401. pReader->aDoclist = pNext;
  147402. pReader->pOffsetList = 0;
  147403. /* Check that the doclist does not appear to extend past the end of the
  147404. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  147405. ** of these statements is untrue, then the data structure is corrupt.
  147406. */
  147407. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  147408. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  147409. ){
  147410. return FTS_CORRUPT_VTAB;
  147411. }
  147412. return SQLITE_OK;
  147413. }
  147414. /*
  147415. ** Set the SegReader to point to the first docid in the doclist associated
  147416. ** with the current term.
  147417. */
  147418. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  147419. int rc = SQLITE_OK;
  147420. assert( pReader->aDoclist );
  147421. assert( !pReader->pOffsetList );
  147422. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  147423. u8 bEof = 0;
  147424. pReader->iDocid = 0;
  147425. pReader->nOffsetList = 0;
  147426. sqlite3Fts3DoclistPrev(0,
  147427. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  147428. &pReader->iDocid, &pReader->nOffsetList, &bEof
  147429. );
  147430. }else{
  147431. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  147432. if( rc==SQLITE_OK ){
  147433. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  147434. pReader->pOffsetList = &pReader->aDoclist[n];
  147435. }
  147436. }
  147437. return rc;
  147438. }
  147439. /*
  147440. ** Advance the SegReader to point to the next docid in the doclist
  147441. ** associated with the current term.
  147442. **
  147443. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  147444. ** *ppOffsetList is set to point to the first column-offset list
  147445. ** in the doclist entry (i.e. immediately past the docid varint).
  147446. ** *pnOffsetList is set to the length of the set of column-offset
  147447. ** lists, not including the nul-terminator byte. For example:
  147448. */
  147449. static int fts3SegReaderNextDocid(
  147450. Fts3Table *pTab,
  147451. Fts3SegReader *pReader, /* Reader to advance to next docid */
  147452. char **ppOffsetList, /* OUT: Pointer to current position-list */
  147453. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  147454. ){
  147455. int rc = SQLITE_OK;
  147456. char *p = pReader->pOffsetList;
  147457. char c = 0;
  147458. assert( p );
  147459. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  147460. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  147461. ** Pending-terms doclists are always built up in ascending order, so
  147462. ** we have to iterate through them backwards here. */
  147463. u8 bEof = 0;
  147464. if( ppOffsetList ){
  147465. *ppOffsetList = pReader->pOffsetList;
  147466. *pnOffsetList = pReader->nOffsetList - 1;
  147467. }
  147468. sqlite3Fts3DoclistPrev(0,
  147469. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  147470. &pReader->nOffsetList, &bEof
  147471. );
  147472. if( bEof ){
  147473. pReader->pOffsetList = 0;
  147474. }else{
  147475. pReader->pOffsetList = p;
  147476. }
  147477. }else{
  147478. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  147479. /* Pointer p currently points at the first byte of an offset list. The
  147480. ** following block advances it to point one byte past the end of
  147481. ** the same offset list. */
  147482. while( 1 ){
  147483. /* The following line of code (and the "p++" below the while() loop) is
  147484. ** normally all that is required to move pointer p to the desired
  147485. ** position. The exception is if this node is being loaded from disk
  147486. ** incrementally and pointer "p" now points to the first byte past
  147487. ** the populated part of pReader->aNode[].
  147488. */
  147489. while( *p | c ) c = *p++ & 0x80;
  147490. assert( *p==0 );
  147491. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  147492. rc = fts3SegReaderIncrRead(pReader);
  147493. if( rc!=SQLITE_OK ) return rc;
  147494. }
  147495. p++;
  147496. /* If required, populate the output variables with a pointer to and the
  147497. ** size of the previous offset-list.
  147498. */
  147499. if( ppOffsetList ){
  147500. *ppOffsetList = pReader->pOffsetList;
  147501. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  147502. }
  147503. /* List may have been edited in place by fts3EvalNearTrim() */
  147504. while( p<pEnd && *p==0 ) p++;
  147505. /* If there are no more entries in the doclist, set pOffsetList to
  147506. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  147507. ** Fts3SegReader.pOffsetList to point to the next offset list before
  147508. ** returning.
  147509. */
  147510. if( p>=pEnd ){
  147511. pReader->pOffsetList = 0;
  147512. }else{
  147513. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  147514. if( rc==SQLITE_OK ){
  147515. sqlite3_int64 iDelta;
  147516. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  147517. if( pTab->bDescIdx ){
  147518. pReader->iDocid -= iDelta;
  147519. }else{
  147520. pReader->iDocid += iDelta;
  147521. }
  147522. }
  147523. }
  147524. }
  147525. return SQLITE_OK;
  147526. }
  147527. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  147528. Fts3Cursor *pCsr,
  147529. Fts3MultiSegReader *pMsr,
  147530. int *pnOvfl
  147531. ){
  147532. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  147533. int nOvfl = 0;
  147534. int ii;
  147535. int rc = SQLITE_OK;
  147536. int pgsz = p->nPgsz;
  147537. assert( p->bFts4 );
  147538. assert( pgsz>0 );
  147539. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  147540. Fts3SegReader *pReader = pMsr->apSegment[ii];
  147541. if( !fts3SegReaderIsPending(pReader)
  147542. && !fts3SegReaderIsRootOnly(pReader)
  147543. ){
  147544. sqlite3_int64 jj;
  147545. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  147546. int nBlob;
  147547. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  147548. if( rc!=SQLITE_OK ) break;
  147549. if( (nBlob+35)>pgsz ){
  147550. nOvfl += (nBlob + 34)/pgsz;
  147551. }
  147552. }
  147553. }
  147554. }
  147555. *pnOvfl = nOvfl;
  147556. return rc;
  147557. }
  147558. /*
  147559. ** Free all allocations associated with the iterator passed as the
  147560. ** second argument.
  147561. */
  147562. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  147563. if( pReader ){
  147564. if( !fts3SegReaderIsPending(pReader) ){
  147565. sqlite3_free(pReader->zTerm);
  147566. }
  147567. if( !fts3SegReaderIsRootOnly(pReader) ){
  147568. sqlite3_free(pReader->aNode);
  147569. }
  147570. sqlite3_blob_close(pReader->pBlob);
  147571. }
  147572. sqlite3_free(pReader);
  147573. }
  147574. /*
  147575. ** Allocate a new SegReader object.
  147576. */
  147577. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  147578. int iAge, /* Segment "age". */
  147579. int bLookup, /* True for a lookup only */
  147580. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  147581. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  147582. sqlite3_int64 iEndBlock, /* Final block of segment */
  147583. const char *zRoot, /* Buffer containing root node */
  147584. int nRoot, /* Size of buffer containing root node */
  147585. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  147586. ){
  147587. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  147588. int nExtra = 0; /* Bytes to allocate segment root node */
  147589. assert( iStartLeaf<=iEndLeaf );
  147590. if( iStartLeaf==0 ){
  147591. nExtra = nRoot + FTS3_NODE_PADDING;
  147592. }
  147593. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  147594. if( !pReader ){
  147595. return SQLITE_NOMEM;
  147596. }
  147597. memset(pReader, 0, sizeof(Fts3SegReader));
  147598. pReader->iIdx = iAge;
  147599. pReader->bLookup = bLookup!=0;
  147600. pReader->iStartBlock = iStartLeaf;
  147601. pReader->iLeafEndBlock = iEndLeaf;
  147602. pReader->iEndBlock = iEndBlock;
  147603. if( nExtra ){
  147604. /* The entire segment is stored in the root node. */
  147605. pReader->aNode = (char *)&pReader[1];
  147606. pReader->rootOnly = 1;
  147607. pReader->nNode = nRoot;
  147608. memcpy(pReader->aNode, zRoot, nRoot);
  147609. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  147610. }else{
  147611. pReader->iCurrentBlock = iStartLeaf-1;
  147612. }
  147613. *ppReader = pReader;
  147614. return SQLITE_OK;
  147615. }
  147616. /*
  147617. ** This is a comparison function used as a qsort() callback when sorting
  147618. ** an array of pending terms by term. This occurs as part of flushing
  147619. ** the contents of the pending-terms hash table to the database.
  147620. */
  147621. static int SQLITE_CDECL fts3CompareElemByTerm(
  147622. const void *lhs,
  147623. const void *rhs
  147624. ){
  147625. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  147626. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  147627. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  147628. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  147629. int n = (n1<n2 ? n1 : n2);
  147630. int c = memcmp(z1, z2, n);
  147631. if( c==0 ){
  147632. c = n1 - n2;
  147633. }
  147634. return c;
  147635. }
  147636. /*
  147637. ** This function is used to allocate an Fts3SegReader that iterates through
  147638. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  147639. **
  147640. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  147641. ** through each term in the pending-terms table. Or, if isPrefixIter is
  147642. ** non-zero, it iterates through each term and its prefixes. For example, if
  147643. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  147644. ** "firebird", then the iterator visits the following 'terms' (in the order
  147645. ** shown):
  147646. **
  147647. ** f fi fir fire fireb firebi firebir firebird
  147648. ** m my mys mysq mysql
  147649. ** s sq sql sqli sqlit sqlite
  147650. **
  147651. ** Whereas if isPrefixIter is zero, the terms visited are:
  147652. **
  147653. ** firebird mysql sqlite
  147654. */
  147655. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  147656. Fts3Table *p, /* Virtual table handle */
  147657. int iIndex, /* Index for p->aIndex */
  147658. const char *zTerm, /* Term to search for */
  147659. int nTerm, /* Size of buffer zTerm */
  147660. int bPrefix, /* True for a prefix iterator */
  147661. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  147662. ){
  147663. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  147664. Fts3HashElem *pE; /* Iterator variable */
  147665. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  147666. int nElem = 0; /* Size of array at aElem */
  147667. int rc = SQLITE_OK; /* Return Code */
  147668. Fts3Hash *pHash;
  147669. pHash = &p->aIndex[iIndex].hPending;
  147670. if( bPrefix ){
  147671. int nAlloc = 0; /* Size of allocated array at aElem */
  147672. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  147673. char *zKey = (char *)fts3HashKey(pE);
  147674. int nKey = fts3HashKeysize(pE);
  147675. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  147676. if( nElem==nAlloc ){
  147677. Fts3HashElem **aElem2;
  147678. nAlloc += 16;
  147679. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  147680. aElem, nAlloc*sizeof(Fts3HashElem *)
  147681. );
  147682. if( !aElem2 ){
  147683. rc = SQLITE_NOMEM;
  147684. nElem = 0;
  147685. break;
  147686. }
  147687. aElem = aElem2;
  147688. }
  147689. aElem[nElem++] = pE;
  147690. }
  147691. }
  147692. /* If more than one term matches the prefix, sort the Fts3HashElem
  147693. ** objects in term order using qsort(). This uses the same comparison
  147694. ** callback as is used when flushing terms to disk.
  147695. */
  147696. if( nElem>1 ){
  147697. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  147698. }
  147699. }else{
  147700. /* The query is a simple term lookup that matches at most one term in
  147701. ** the index. All that is required is a straight hash-lookup.
  147702. **
  147703. ** Because the stack address of pE may be accessed via the aElem pointer
  147704. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  147705. ** within this entire function, not just this "else{...}" block.
  147706. */
  147707. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  147708. if( pE ){
  147709. aElem = &pE;
  147710. nElem = 1;
  147711. }
  147712. }
  147713. if( nElem>0 ){
  147714. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  147715. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  147716. if( !pReader ){
  147717. rc = SQLITE_NOMEM;
  147718. }else{
  147719. memset(pReader, 0, nByte);
  147720. pReader->iIdx = 0x7FFFFFFF;
  147721. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  147722. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  147723. }
  147724. }
  147725. if( bPrefix ){
  147726. sqlite3_free(aElem);
  147727. }
  147728. *ppReader = pReader;
  147729. return rc;
  147730. }
  147731. /*
  147732. ** Compare the entries pointed to by two Fts3SegReader structures.
  147733. ** Comparison is as follows:
  147734. **
  147735. ** 1) EOF is greater than not EOF.
  147736. **
  147737. ** 2) The current terms (if any) are compared using memcmp(). If one
  147738. ** term is a prefix of another, the longer term is considered the
  147739. ** larger.
  147740. **
  147741. ** 3) By segment age. An older segment is considered larger.
  147742. */
  147743. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  147744. int rc;
  147745. if( pLhs->aNode && pRhs->aNode ){
  147746. int rc2 = pLhs->nTerm - pRhs->nTerm;
  147747. if( rc2<0 ){
  147748. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  147749. }else{
  147750. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  147751. }
  147752. if( rc==0 ){
  147753. rc = rc2;
  147754. }
  147755. }else{
  147756. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  147757. }
  147758. if( rc==0 ){
  147759. rc = pRhs->iIdx - pLhs->iIdx;
  147760. }
  147761. assert( rc!=0 );
  147762. return rc;
  147763. }
  147764. /*
  147765. ** A different comparison function for SegReader structures. In this
  147766. ** version, it is assumed that each SegReader points to an entry in
  147767. ** a doclist for identical terms. Comparison is made as follows:
  147768. **
  147769. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  147770. **
  147771. ** 2) By current docid.
  147772. **
  147773. ** 3) By segment age. An older segment is considered larger.
  147774. */
  147775. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  147776. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  147777. if( rc==0 ){
  147778. if( pLhs->iDocid==pRhs->iDocid ){
  147779. rc = pRhs->iIdx - pLhs->iIdx;
  147780. }else{
  147781. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  147782. }
  147783. }
  147784. assert( pLhs->aNode && pRhs->aNode );
  147785. return rc;
  147786. }
  147787. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  147788. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  147789. if( rc==0 ){
  147790. if( pLhs->iDocid==pRhs->iDocid ){
  147791. rc = pRhs->iIdx - pLhs->iIdx;
  147792. }else{
  147793. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  147794. }
  147795. }
  147796. assert( pLhs->aNode && pRhs->aNode );
  147797. return rc;
  147798. }
  147799. /*
  147800. ** Compare the term that the Fts3SegReader object passed as the first argument
  147801. ** points to with the term specified by arguments zTerm and nTerm.
  147802. **
  147803. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  147804. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  147805. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  147806. */
  147807. static int fts3SegReaderTermCmp(
  147808. Fts3SegReader *pSeg, /* Segment reader object */
  147809. const char *zTerm, /* Term to compare to */
  147810. int nTerm /* Size of term zTerm in bytes */
  147811. ){
  147812. int res = 0;
  147813. if( pSeg->aNode ){
  147814. if( pSeg->nTerm>nTerm ){
  147815. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  147816. }else{
  147817. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  147818. }
  147819. if( res==0 ){
  147820. res = pSeg->nTerm-nTerm;
  147821. }
  147822. }
  147823. return res;
  147824. }
  147825. /*
  147826. ** Argument apSegment is an array of nSegment elements. It is known that
  147827. ** the final (nSegment-nSuspect) members are already in sorted order
  147828. ** (according to the comparison function provided). This function shuffles
  147829. ** the array around until all entries are in sorted order.
  147830. */
  147831. static void fts3SegReaderSort(
  147832. Fts3SegReader **apSegment, /* Array to sort entries of */
  147833. int nSegment, /* Size of apSegment array */
  147834. int nSuspect, /* Unsorted entry count */
  147835. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  147836. ){
  147837. int i; /* Iterator variable */
  147838. assert( nSuspect<=nSegment );
  147839. if( nSuspect==nSegment ) nSuspect--;
  147840. for(i=nSuspect-1; i>=0; i--){
  147841. int j;
  147842. for(j=i; j<(nSegment-1); j++){
  147843. Fts3SegReader *pTmp;
  147844. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  147845. pTmp = apSegment[j+1];
  147846. apSegment[j+1] = apSegment[j];
  147847. apSegment[j] = pTmp;
  147848. }
  147849. }
  147850. #ifndef NDEBUG
  147851. /* Check that the list really is sorted now. */
  147852. for(i=0; i<(nSuspect-1); i++){
  147853. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  147854. }
  147855. #endif
  147856. }
  147857. /*
  147858. ** Insert a record into the %_segments table.
  147859. */
  147860. static int fts3WriteSegment(
  147861. Fts3Table *p, /* Virtual table handle */
  147862. sqlite3_int64 iBlock, /* Block id for new block */
  147863. char *z, /* Pointer to buffer containing block data */
  147864. int n /* Size of buffer z in bytes */
  147865. ){
  147866. sqlite3_stmt *pStmt;
  147867. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  147868. if( rc==SQLITE_OK ){
  147869. sqlite3_bind_int64(pStmt, 1, iBlock);
  147870. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  147871. sqlite3_step(pStmt);
  147872. rc = sqlite3_reset(pStmt);
  147873. }
  147874. return rc;
  147875. }
  147876. /*
  147877. ** Find the largest relative level number in the table. If successful, set
  147878. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  147879. ** set *pnMax to zero and return an SQLite error code.
  147880. */
  147881. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  147882. int rc;
  147883. int mxLevel = 0;
  147884. sqlite3_stmt *pStmt = 0;
  147885. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  147886. if( rc==SQLITE_OK ){
  147887. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  147888. mxLevel = sqlite3_column_int(pStmt, 0);
  147889. }
  147890. rc = sqlite3_reset(pStmt);
  147891. }
  147892. *pnMax = mxLevel;
  147893. return rc;
  147894. }
  147895. /*
  147896. ** Insert a record into the %_segdir table.
  147897. */
  147898. static int fts3WriteSegdir(
  147899. Fts3Table *p, /* Virtual table handle */
  147900. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  147901. int iIdx, /* Value for "idx" field */
  147902. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  147903. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  147904. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  147905. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  147906. char *zRoot, /* Blob value for "root" field */
  147907. int nRoot /* Number of bytes in buffer zRoot */
  147908. ){
  147909. sqlite3_stmt *pStmt;
  147910. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  147911. if( rc==SQLITE_OK ){
  147912. sqlite3_bind_int64(pStmt, 1, iLevel);
  147913. sqlite3_bind_int(pStmt, 2, iIdx);
  147914. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  147915. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  147916. if( nLeafData==0 ){
  147917. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  147918. }else{
  147919. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  147920. if( !zEnd ) return SQLITE_NOMEM;
  147921. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  147922. }
  147923. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  147924. sqlite3_step(pStmt);
  147925. rc = sqlite3_reset(pStmt);
  147926. }
  147927. return rc;
  147928. }
  147929. /*
  147930. ** Return the size of the common prefix (if any) shared by zPrev and
  147931. ** zNext, in bytes. For example,
  147932. **
  147933. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  147934. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  147935. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  147936. */
  147937. static int fts3PrefixCompress(
  147938. const char *zPrev, /* Buffer containing previous term */
  147939. int nPrev, /* Size of buffer zPrev in bytes */
  147940. const char *zNext, /* Buffer containing next term */
  147941. int nNext /* Size of buffer zNext in bytes */
  147942. ){
  147943. int n;
  147944. UNUSED_PARAMETER(nNext);
  147945. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  147946. return n;
  147947. }
  147948. /*
  147949. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  147950. ** (according to memcmp) than the previous term.
  147951. */
  147952. static int fts3NodeAddTerm(
  147953. Fts3Table *p, /* Virtual table handle */
  147954. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  147955. int isCopyTerm, /* True if zTerm/nTerm is transient */
  147956. const char *zTerm, /* Pointer to buffer containing term */
  147957. int nTerm /* Size of term in bytes */
  147958. ){
  147959. SegmentNode *pTree = *ppTree;
  147960. int rc;
  147961. SegmentNode *pNew;
  147962. /* First try to append the term to the current node. Return early if
  147963. ** this is possible.
  147964. */
  147965. if( pTree ){
  147966. int nData = pTree->nData; /* Current size of node in bytes */
  147967. int nReq = nData; /* Required space after adding zTerm */
  147968. int nPrefix; /* Number of bytes of prefix compression */
  147969. int nSuffix; /* Suffix length */
  147970. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  147971. nSuffix = nTerm-nPrefix;
  147972. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  147973. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  147974. if( nReq>p->nNodeSize ){
  147975. /* An unusual case: this is the first term to be added to the node
  147976. ** and the static node buffer (p->nNodeSize bytes) is not large
  147977. ** enough. Use a separately malloced buffer instead This wastes
  147978. ** p->nNodeSize bytes, but since this scenario only comes about when
  147979. ** the database contain two terms that share a prefix of almost 2KB,
  147980. ** this is not expected to be a serious problem.
  147981. */
  147982. assert( pTree->aData==(char *)&pTree[1] );
  147983. pTree->aData = (char *)sqlite3_malloc(nReq);
  147984. if( !pTree->aData ){
  147985. return SQLITE_NOMEM;
  147986. }
  147987. }
  147988. if( pTree->zTerm ){
  147989. /* There is no prefix-length field for first term in a node */
  147990. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  147991. }
  147992. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  147993. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  147994. pTree->nData = nData + nSuffix;
  147995. pTree->nEntry++;
  147996. if( isCopyTerm ){
  147997. if( pTree->nMalloc<nTerm ){
  147998. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  147999. if( !zNew ){
  148000. return SQLITE_NOMEM;
  148001. }
  148002. pTree->nMalloc = nTerm*2;
  148003. pTree->zMalloc = zNew;
  148004. }
  148005. pTree->zTerm = pTree->zMalloc;
  148006. memcpy(pTree->zTerm, zTerm, nTerm);
  148007. pTree->nTerm = nTerm;
  148008. }else{
  148009. pTree->zTerm = (char *)zTerm;
  148010. pTree->nTerm = nTerm;
  148011. }
  148012. return SQLITE_OK;
  148013. }
  148014. }
  148015. /* If control flows to here, it was not possible to append zTerm to the
  148016. ** current node. Create a new node (a right-sibling of the current node).
  148017. ** If this is the first node in the tree, the term is added to it.
  148018. **
  148019. ** Otherwise, the term is not added to the new node, it is left empty for
  148020. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  148021. ** has no parent, one is created here.
  148022. */
  148023. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  148024. if( !pNew ){
  148025. return SQLITE_NOMEM;
  148026. }
  148027. memset(pNew, 0, sizeof(SegmentNode));
  148028. pNew->nData = 1 + FTS3_VARINT_MAX;
  148029. pNew->aData = (char *)&pNew[1];
  148030. if( pTree ){
  148031. SegmentNode *pParent = pTree->pParent;
  148032. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  148033. if( pTree->pParent==0 ){
  148034. pTree->pParent = pParent;
  148035. }
  148036. pTree->pRight = pNew;
  148037. pNew->pLeftmost = pTree->pLeftmost;
  148038. pNew->pParent = pParent;
  148039. pNew->zMalloc = pTree->zMalloc;
  148040. pNew->nMalloc = pTree->nMalloc;
  148041. pTree->zMalloc = 0;
  148042. }else{
  148043. pNew->pLeftmost = pNew;
  148044. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  148045. }
  148046. *ppTree = pNew;
  148047. return rc;
  148048. }
  148049. /*
  148050. ** Helper function for fts3NodeWrite().
  148051. */
  148052. static int fts3TreeFinishNode(
  148053. SegmentNode *pTree,
  148054. int iHeight,
  148055. sqlite3_int64 iLeftChild
  148056. ){
  148057. int nStart;
  148058. assert( iHeight>=1 && iHeight<128 );
  148059. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  148060. pTree->aData[nStart] = (char)iHeight;
  148061. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  148062. return nStart;
  148063. }
  148064. /*
  148065. ** Write the buffer for the segment node pTree and all of its peers to the
  148066. ** database. Then call this function recursively to write the parent of
  148067. ** pTree and its peers to the database.
  148068. **
  148069. ** Except, if pTree is a root node, do not write it to the database. Instead,
  148070. ** set output variables *paRoot and *pnRoot to contain the root node.
  148071. **
  148072. ** If successful, SQLITE_OK is returned and output variable *piLast is
  148073. ** set to the largest blockid written to the database (or zero if no
  148074. ** blocks were written to the db). Otherwise, an SQLite error code is
  148075. ** returned.
  148076. */
  148077. static int fts3NodeWrite(
  148078. Fts3Table *p, /* Virtual table handle */
  148079. SegmentNode *pTree, /* SegmentNode handle */
  148080. int iHeight, /* Height of this node in tree */
  148081. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  148082. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  148083. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  148084. char **paRoot, /* OUT: Data for root node */
  148085. int *pnRoot /* OUT: Size of root node in bytes */
  148086. ){
  148087. int rc = SQLITE_OK;
  148088. if( !pTree->pParent ){
  148089. /* Root node of the tree. */
  148090. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  148091. *piLast = iFree-1;
  148092. *pnRoot = pTree->nData - nStart;
  148093. *paRoot = &pTree->aData[nStart];
  148094. }else{
  148095. SegmentNode *pIter;
  148096. sqlite3_int64 iNextFree = iFree;
  148097. sqlite3_int64 iNextLeaf = iLeaf;
  148098. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  148099. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  148100. int nWrite = pIter->nData - nStart;
  148101. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  148102. iNextFree++;
  148103. iNextLeaf += (pIter->nEntry+1);
  148104. }
  148105. if( rc==SQLITE_OK ){
  148106. assert( iNextLeaf==iFree );
  148107. rc = fts3NodeWrite(
  148108. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  148109. );
  148110. }
  148111. }
  148112. return rc;
  148113. }
  148114. /*
  148115. ** Free all memory allocations associated with the tree pTree.
  148116. */
  148117. static void fts3NodeFree(SegmentNode *pTree){
  148118. if( pTree ){
  148119. SegmentNode *p = pTree->pLeftmost;
  148120. fts3NodeFree(p->pParent);
  148121. while( p ){
  148122. SegmentNode *pRight = p->pRight;
  148123. if( p->aData!=(char *)&p[1] ){
  148124. sqlite3_free(p->aData);
  148125. }
  148126. assert( pRight==0 || p->zMalloc==0 );
  148127. sqlite3_free(p->zMalloc);
  148128. sqlite3_free(p);
  148129. p = pRight;
  148130. }
  148131. }
  148132. }
  148133. /*
  148134. ** Add a term to the segment being constructed by the SegmentWriter object
  148135. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  148136. ** be passed NULL. This function will allocate a new SegmentWriter object
  148137. ** and return it via the input/output variable *ppWriter in this case.
  148138. **
  148139. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  148140. */
  148141. static int fts3SegWriterAdd(
  148142. Fts3Table *p, /* Virtual table handle */
  148143. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  148144. int isCopyTerm, /* True if buffer zTerm must be copied */
  148145. const char *zTerm, /* Pointer to buffer containing term */
  148146. int nTerm, /* Size of term in bytes */
  148147. const char *aDoclist, /* Pointer to buffer containing doclist */
  148148. int nDoclist /* Size of doclist in bytes */
  148149. ){
  148150. int nPrefix; /* Size of term prefix in bytes */
  148151. int nSuffix; /* Size of term suffix in bytes */
  148152. int nReq; /* Number of bytes required on leaf page */
  148153. int nData;
  148154. SegmentWriter *pWriter = *ppWriter;
  148155. if( !pWriter ){
  148156. int rc;
  148157. sqlite3_stmt *pStmt;
  148158. /* Allocate the SegmentWriter structure */
  148159. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  148160. if( !pWriter ) return SQLITE_NOMEM;
  148161. memset(pWriter, 0, sizeof(SegmentWriter));
  148162. *ppWriter = pWriter;
  148163. /* Allocate a buffer in which to accumulate data */
  148164. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  148165. if( !pWriter->aData ) return SQLITE_NOMEM;
  148166. pWriter->nSize = p->nNodeSize;
  148167. /* Find the next free blockid in the %_segments table */
  148168. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  148169. if( rc!=SQLITE_OK ) return rc;
  148170. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148171. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  148172. pWriter->iFirst = pWriter->iFree;
  148173. }
  148174. rc = sqlite3_reset(pStmt);
  148175. if( rc!=SQLITE_OK ) return rc;
  148176. }
  148177. nData = pWriter->nData;
  148178. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  148179. nSuffix = nTerm-nPrefix;
  148180. /* Figure out how many bytes are required by this new entry */
  148181. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  148182. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  148183. nSuffix + /* Term suffix */
  148184. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  148185. nDoclist; /* Doclist data */
  148186. if( nData>0 && nData+nReq>p->nNodeSize ){
  148187. int rc;
  148188. /* The current leaf node is full. Write it out to the database. */
  148189. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  148190. if( rc!=SQLITE_OK ) return rc;
  148191. p->nLeafAdd++;
  148192. /* Add the current term to the interior node tree. The term added to
  148193. ** the interior tree must:
  148194. **
  148195. ** a) be greater than the largest term on the leaf node just written
  148196. ** to the database (still available in pWriter->zTerm), and
  148197. **
  148198. ** b) be less than or equal to the term about to be added to the new
  148199. ** leaf node (zTerm/nTerm).
  148200. **
  148201. ** In other words, it must be the prefix of zTerm 1 byte longer than
  148202. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  148203. */
  148204. assert( nPrefix<nTerm );
  148205. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  148206. if( rc!=SQLITE_OK ) return rc;
  148207. nData = 0;
  148208. pWriter->nTerm = 0;
  148209. nPrefix = 0;
  148210. nSuffix = nTerm;
  148211. nReq = 1 + /* varint containing prefix size */
  148212. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  148213. nTerm + /* Term suffix */
  148214. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  148215. nDoclist; /* Doclist data */
  148216. }
  148217. /* Increase the total number of bytes written to account for the new entry. */
  148218. pWriter->nLeafData += nReq;
  148219. /* If the buffer currently allocated is too small for this entry, realloc
  148220. ** the buffer to make it large enough.
  148221. */
  148222. if( nReq>pWriter->nSize ){
  148223. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  148224. if( !aNew ) return SQLITE_NOMEM;
  148225. pWriter->aData = aNew;
  148226. pWriter->nSize = nReq;
  148227. }
  148228. assert( nData+nReq<=pWriter->nSize );
  148229. /* Append the prefix-compressed term and doclist to the buffer. */
  148230. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  148231. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  148232. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  148233. nData += nSuffix;
  148234. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  148235. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  148236. pWriter->nData = nData + nDoclist;
  148237. /* Save the current term so that it can be used to prefix-compress the next.
  148238. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  148239. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  148240. ** store a copy of the pointer.
  148241. */
  148242. if( isCopyTerm ){
  148243. if( nTerm>pWriter->nMalloc ){
  148244. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  148245. if( !zNew ){
  148246. return SQLITE_NOMEM;
  148247. }
  148248. pWriter->nMalloc = nTerm*2;
  148249. pWriter->zMalloc = zNew;
  148250. pWriter->zTerm = zNew;
  148251. }
  148252. assert( pWriter->zTerm==pWriter->zMalloc );
  148253. memcpy(pWriter->zTerm, zTerm, nTerm);
  148254. }else{
  148255. pWriter->zTerm = (char *)zTerm;
  148256. }
  148257. pWriter->nTerm = nTerm;
  148258. return SQLITE_OK;
  148259. }
  148260. /*
  148261. ** Flush all data associated with the SegmentWriter object pWriter to the
  148262. ** database. This function must be called after all terms have been added
  148263. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  148264. ** returned. Otherwise, an SQLite error code.
  148265. */
  148266. static int fts3SegWriterFlush(
  148267. Fts3Table *p, /* Virtual table handle */
  148268. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  148269. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  148270. int iIdx /* Value for 'idx' column of %_segdir */
  148271. ){
  148272. int rc; /* Return code */
  148273. if( pWriter->pTree ){
  148274. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  148275. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  148276. char *zRoot = NULL; /* Pointer to buffer containing root node */
  148277. int nRoot = 0; /* Size of buffer zRoot */
  148278. iLastLeaf = pWriter->iFree;
  148279. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  148280. if( rc==SQLITE_OK ){
  148281. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  148282. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  148283. }
  148284. if( rc==SQLITE_OK ){
  148285. rc = fts3WriteSegdir(p, iLevel, iIdx,
  148286. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  148287. }
  148288. }else{
  148289. /* The entire tree fits on the root node. Write it to the segdir table. */
  148290. rc = fts3WriteSegdir(p, iLevel, iIdx,
  148291. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  148292. }
  148293. p->nLeafAdd++;
  148294. return rc;
  148295. }
  148296. /*
  148297. ** Release all memory held by the SegmentWriter object passed as the
  148298. ** first argument.
  148299. */
  148300. static void fts3SegWriterFree(SegmentWriter *pWriter){
  148301. if( pWriter ){
  148302. sqlite3_free(pWriter->aData);
  148303. sqlite3_free(pWriter->zMalloc);
  148304. fts3NodeFree(pWriter->pTree);
  148305. sqlite3_free(pWriter);
  148306. }
  148307. }
  148308. /*
  148309. ** The first value in the apVal[] array is assumed to contain an integer.
  148310. ** This function tests if there exist any documents with docid values that
  148311. ** are different from that integer. i.e. if deleting the document with docid
  148312. ** pRowid would mean the FTS3 table were empty.
  148313. **
  148314. ** If successful, *pisEmpty is set to true if the table is empty except for
  148315. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  148316. ** error occurs, an SQLite error code is returned.
  148317. */
  148318. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  148319. sqlite3_stmt *pStmt;
  148320. int rc;
  148321. if( p->zContentTbl ){
  148322. /* If using the content=xxx option, assume the table is never empty */
  148323. *pisEmpty = 0;
  148324. rc = SQLITE_OK;
  148325. }else{
  148326. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  148327. if( rc==SQLITE_OK ){
  148328. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148329. *pisEmpty = sqlite3_column_int(pStmt, 0);
  148330. }
  148331. rc = sqlite3_reset(pStmt);
  148332. }
  148333. }
  148334. return rc;
  148335. }
  148336. /*
  148337. ** Set *pnMax to the largest segment level in the database for the index
  148338. ** iIndex.
  148339. **
  148340. ** Segment levels are stored in the 'level' column of the %_segdir table.
  148341. **
  148342. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  148343. */
  148344. static int fts3SegmentMaxLevel(
  148345. Fts3Table *p,
  148346. int iLangid,
  148347. int iIndex,
  148348. sqlite3_int64 *pnMax
  148349. ){
  148350. sqlite3_stmt *pStmt;
  148351. int rc;
  148352. assert( iIndex>=0 && iIndex<p->nIndex );
  148353. /* Set pStmt to the compiled version of:
  148354. **
  148355. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  148356. **
  148357. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  148358. */
  148359. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  148360. if( rc!=SQLITE_OK ) return rc;
  148361. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  148362. sqlite3_bind_int64(pStmt, 2,
  148363. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  148364. );
  148365. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148366. *pnMax = sqlite3_column_int64(pStmt, 0);
  148367. }
  148368. return sqlite3_reset(pStmt);
  148369. }
  148370. /*
  148371. ** iAbsLevel is an absolute level that may be assumed to exist within
  148372. ** the database. This function checks if it is the largest level number
  148373. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  148374. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  148375. ** is returned. If an error occurs, an error code is returned and the
  148376. ** final value of *pbMax is undefined.
  148377. */
  148378. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  148379. /* Set pStmt to the compiled version of:
  148380. **
  148381. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  148382. **
  148383. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  148384. */
  148385. sqlite3_stmt *pStmt;
  148386. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  148387. if( rc!=SQLITE_OK ) return rc;
  148388. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  148389. sqlite3_bind_int64(pStmt, 2,
  148390. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  148391. );
  148392. *pbMax = 0;
  148393. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148394. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  148395. }
  148396. return sqlite3_reset(pStmt);
  148397. }
  148398. /*
  148399. ** Delete all entries in the %_segments table associated with the segment
  148400. ** opened with seg-reader pSeg. This function does not affect the contents
  148401. ** of the %_segdir table.
  148402. */
  148403. static int fts3DeleteSegment(
  148404. Fts3Table *p, /* FTS table handle */
  148405. Fts3SegReader *pSeg /* Segment to delete */
  148406. ){
  148407. int rc = SQLITE_OK; /* Return code */
  148408. if( pSeg->iStartBlock ){
  148409. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  148410. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  148411. if( rc==SQLITE_OK ){
  148412. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  148413. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  148414. sqlite3_step(pDelete);
  148415. rc = sqlite3_reset(pDelete);
  148416. }
  148417. }
  148418. return rc;
  148419. }
  148420. /*
  148421. ** This function is used after merging multiple segments into a single large
  148422. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  148423. ** it:
  148424. **
  148425. ** 1) Deletes all %_segments entries for the segments associated with
  148426. ** each of the SegReader objects in the array passed as the third
  148427. ** argument, and
  148428. **
  148429. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  148430. ** entries regardless of level if (iLevel<0).
  148431. **
  148432. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  148433. */
  148434. static int fts3DeleteSegdir(
  148435. Fts3Table *p, /* Virtual table handle */
  148436. int iLangid, /* Language id */
  148437. int iIndex, /* Index for p->aIndex */
  148438. int iLevel, /* Level of %_segdir entries to delete */
  148439. Fts3SegReader **apSegment, /* Array of SegReader objects */
  148440. int nReader /* Size of array apSegment */
  148441. ){
  148442. int rc = SQLITE_OK; /* Return Code */
  148443. int i; /* Iterator variable */
  148444. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  148445. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  148446. rc = fts3DeleteSegment(p, apSegment[i]);
  148447. }
  148448. if( rc!=SQLITE_OK ){
  148449. return rc;
  148450. }
  148451. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  148452. if( iLevel==FTS3_SEGCURSOR_ALL ){
  148453. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  148454. if( rc==SQLITE_OK ){
  148455. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  148456. sqlite3_bind_int64(pDelete, 2,
  148457. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  148458. );
  148459. }
  148460. }else{
  148461. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  148462. if( rc==SQLITE_OK ){
  148463. sqlite3_bind_int64(
  148464. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  148465. );
  148466. }
  148467. }
  148468. if( rc==SQLITE_OK ){
  148469. sqlite3_step(pDelete);
  148470. rc = sqlite3_reset(pDelete);
  148471. }
  148472. return rc;
  148473. }
  148474. /*
  148475. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  148476. ** a position list that may (or may not) feature multiple columns. This
  148477. ** function adjusts the pointer *ppList and the length *pnList so that they
  148478. ** identify the subset of the position list that corresponds to column iCol.
  148479. **
  148480. ** If there are no entries in the input position list for column iCol, then
  148481. ** *pnList is set to zero before returning.
  148482. **
  148483. ** If parameter bZero is non-zero, then any part of the input list following
  148484. ** the end of the output list is zeroed before returning.
  148485. */
  148486. static void fts3ColumnFilter(
  148487. int iCol, /* Column to filter on */
  148488. int bZero, /* Zero out anything following *ppList */
  148489. char **ppList, /* IN/OUT: Pointer to position list */
  148490. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  148491. ){
  148492. char *pList = *ppList;
  148493. int nList = *pnList;
  148494. char *pEnd = &pList[nList];
  148495. int iCurrent = 0;
  148496. char *p = pList;
  148497. assert( iCol>=0 );
  148498. while( 1 ){
  148499. char c = 0;
  148500. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  148501. if( iCol==iCurrent ){
  148502. nList = (int)(p - pList);
  148503. break;
  148504. }
  148505. nList -= (int)(p - pList);
  148506. pList = p;
  148507. if( nList==0 ){
  148508. break;
  148509. }
  148510. p = &pList[1];
  148511. p += fts3GetVarint32(p, &iCurrent);
  148512. }
  148513. if( bZero && &pList[nList]!=pEnd ){
  148514. memset(&pList[nList], 0, pEnd - &pList[nList]);
  148515. }
  148516. *ppList = pList;
  148517. *pnList = nList;
  148518. }
  148519. /*
  148520. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  148521. ** existing data). Grow the buffer if required.
  148522. **
  148523. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  148524. ** trying to resize the buffer, return SQLITE_NOMEM.
  148525. */
  148526. static int fts3MsrBufferData(
  148527. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  148528. char *pList,
  148529. int nList
  148530. ){
  148531. if( nList>pMsr->nBuffer ){
  148532. char *pNew;
  148533. pMsr->nBuffer = nList*2;
  148534. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  148535. if( !pNew ) return SQLITE_NOMEM;
  148536. pMsr->aBuffer = pNew;
  148537. }
  148538. memcpy(pMsr->aBuffer, pList, nList);
  148539. return SQLITE_OK;
  148540. }
  148541. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  148542. Fts3Table *p, /* Virtual table handle */
  148543. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  148544. sqlite3_int64 *piDocid, /* OUT: Docid value */
  148545. char **paPoslist, /* OUT: Pointer to position list */
  148546. int *pnPoslist /* OUT: Size of position list in bytes */
  148547. ){
  148548. int nMerge = pMsr->nAdvance;
  148549. Fts3SegReader **apSegment = pMsr->apSegment;
  148550. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  148551. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  148552. );
  148553. if( nMerge==0 ){
  148554. *paPoslist = 0;
  148555. return SQLITE_OK;
  148556. }
  148557. while( 1 ){
  148558. Fts3SegReader *pSeg;
  148559. pSeg = pMsr->apSegment[0];
  148560. if( pSeg->pOffsetList==0 ){
  148561. *paPoslist = 0;
  148562. break;
  148563. }else{
  148564. int rc;
  148565. char *pList;
  148566. int nList;
  148567. int j;
  148568. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  148569. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  148570. j = 1;
  148571. while( rc==SQLITE_OK
  148572. && j<nMerge
  148573. && apSegment[j]->pOffsetList
  148574. && apSegment[j]->iDocid==iDocid
  148575. ){
  148576. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  148577. j++;
  148578. }
  148579. if( rc!=SQLITE_OK ) return rc;
  148580. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  148581. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  148582. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  148583. if( rc!=SQLITE_OK ) return rc;
  148584. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  148585. pList = pMsr->aBuffer;
  148586. }
  148587. if( pMsr->iColFilter>=0 ){
  148588. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  148589. }
  148590. if( nList>0 ){
  148591. *paPoslist = pList;
  148592. *piDocid = iDocid;
  148593. *pnPoslist = nList;
  148594. break;
  148595. }
  148596. }
  148597. }
  148598. return SQLITE_OK;
  148599. }
  148600. static int fts3SegReaderStart(
  148601. Fts3Table *p, /* Virtual table handle */
  148602. Fts3MultiSegReader *pCsr, /* Cursor object */
  148603. const char *zTerm, /* Term searched for (or NULL) */
  148604. int nTerm /* Length of zTerm in bytes */
  148605. ){
  148606. int i;
  148607. int nSeg = pCsr->nSegment;
  148608. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  148609. ** for, then advance each segment iterator until it points to a term of
  148610. ** equal or greater value than the specified term. This prevents many
  148611. ** unnecessary merge/sort operations for the case where single segment
  148612. ** b-tree leaf nodes contain more than one term.
  148613. */
  148614. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  148615. int res = 0;
  148616. Fts3SegReader *pSeg = pCsr->apSegment[i];
  148617. do {
  148618. int rc = fts3SegReaderNext(p, pSeg, 0);
  148619. if( rc!=SQLITE_OK ) return rc;
  148620. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  148621. if( pSeg->bLookup && res!=0 ){
  148622. fts3SegReaderSetEof(pSeg);
  148623. }
  148624. }
  148625. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  148626. return SQLITE_OK;
  148627. }
  148628. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  148629. Fts3Table *p, /* Virtual table handle */
  148630. Fts3MultiSegReader *pCsr, /* Cursor object */
  148631. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  148632. ){
  148633. pCsr->pFilter = pFilter;
  148634. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  148635. }
  148636. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  148637. Fts3Table *p, /* Virtual table handle */
  148638. Fts3MultiSegReader *pCsr, /* Cursor object */
  148639. int iCol, /* Column to match on. */
  148640. const char *zTerm, /* Term to iterate through a doclist for */
  148641. int nTerm /* Number of bytes in zTerm */
  148642. ){
  148643. int i;
  148644. int rc;
  148645. int nSegment = pCsr->nSegment;
  148646. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  148647. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  148648. );
  148649. assert( pCsr->pFilter==0 );
  148650. assert( zTerm && nTerm>0 );
  148651. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  148652. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  148653. if( rc!=SQLITE_OK ) return rc;
  148654. /* Determine how many of the segments actually point to zTerm/nTerm. */
  148655. for(i=0; i<nSegment; i++){
  148656. Fts3SegReader *pSeg = pCsr->apSegment[i];
  148657. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  148658. break;
  148659. }
  148660. }
  148661. pCsr->nAdvance = i;
  148662. /* Advance each of the segments to point to the first docid. */
  148663. for(i=0; i<pCsr->nAdvance; i++){
  148664. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  148665. if( rc!=SQLITE_OK ) return rc;
  148666. }
  148667. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  148668. assert( iCol<0 || iCol<p->nColumn );
  148669. pCsr->iColFilter = iCol;
  148670. return SQLITE_OK;
  148671. }
  148672. /*
  148673. ** This function is called on a MultiSegReader that has been started using
  148674. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  148675. ** have been made. Calling this function puts the MultiSegReader in such
  148676. ** a state that if the next two calls are:
  148677. **
  148678. ** sqlite3Fts3SegReaderStart()
  148679. ** sqlite3Fts3SegReaderStep()
  148680. **
  148681. ** then the entire doclist for the term is available in
  148682. ** MultiSegReader.aDoclist/nDoclist.
  148683. */
  148684. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  148685. int i; /* Used to iterate through segment-readers */
  148686. assert( pCsr->zTerm==0 );
  148687. assert( pCsr->nTerm==0 );
  148688. assert( pCsr->aDoclist==0 );
  148689. assert( pCsr->nDoclist==0 );
  148690. pCsr->nAdvance = 0;
  148691. pCsr->bRestart = 1;
  148692. for(i=0; i<pCsr->nSegment; i++){
  148693. pCsr->apSegment[i]->pOffsetList = 0;
  148694. pCsr->apSegment[i]->nOffsetList = 0;
  148695. pCsr->apSegment[i]->iDocid = 0;
  148696. }
  148697. return SQLITE_OK;
  148698. }
  148699. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  148700. Fts3Table *p, /* Virtual table handle */
  148701. Fts3MultiSegReader *pCsr /* Cursor object */
  148702. ){
  148703. int rc = SQLITE_OK;
  148704. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  148705. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  148706. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  148707. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  148708. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  148709. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  148710. Fts3SegReader **apSegment = pCsr->apSegment;
  148711. int nSegment = pCsr->nSegment;
  148712. Fts3SegFilter *pFilter = pCsr->pFilter;
  148713. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  148714. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  148715. );
  148716. if( pCsr->nSegment==0 ) return SQLITE_OK;
  148717. do {
  148718. int nMerge;
  148719. int i;
  148720. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  148721. ** forward. Then sort the list in order of current term again.
  148722. */
  148723. for(i=0; i<pCsr->nAdvance; i++){
  148724. Fts3SegReader *pSeg = apSegment[i];
  148725. if( pSeg->bLookup ){
  148726. fts3SegReaderSetEof(pSeg);
  148727. }else{
  148728. rc = fts3SegReaderNext(p, pSeg, 0);
  148729. }
  148730. if( rc!=SQLITE_OK ) return rc;
  148731. }
  148732. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  148733. pCsr->nAdvance = 0;
  148734. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  148735. assert( rc==SQLITE_OK );
  148736. if( apSegment[0]->aNode==0 ) break;
  148737. pCsr->nTerm = apSegment[0]->nTerm;
  148738. pCsr->zTerm = apSegment[0]->zTerm;
  148739. /* If this is a prefix-search, and if the term that apSegment[0] points
  148740. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  148741. ** required callbacks have been made. In this case exit early.
  148742. **
  148743. ** Similarly, if this is a search for an exact match, and the first term
  148744. ** of segment apSegment[0] is not a match, exit early.
  148745. */
  148746. if( pFilter->zTerm && !isScan ){
  148747. if( pCsr->nTerm<pFilter->nTerm
  148748. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  148749. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  148750. ){
  148751. break;
  148752. }
  148753. }
  148754. nMerge = 1;
  148755. while( nMerge<nSegment
  148756. && apSegment[nMerge]->aNode
  148757. && apSegment[nMerge]->nTerm==pCsr->nTerm
  148758. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  148759. ){
  148760. nMerge++;
  148761. }
  148762. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  148763. if( nMerge==1
  148764. && !isIgnoreEmpty
  148765. && !isFirst
  148766. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  148767. ){
  148768. pCsr->nDoclist = apSegment[0]->nDoclist;
  148769. if( fts3SegReaderIsPending(apSegment[0]) ){
  148770. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  148771. pCsr->aDoclist = pCsr->aBuffer;
  148772. }else{
  148773. pCsr->aDoclist = apSegment[0]->aDoclist;
  148774. }
  148775. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  148776. }else{
  148777. int nDoclist = 0; /* Size of doclist */
  148778. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  148779. /* The current term of the first nMerge entries in the array
  148780. ** of Fts3SegReader objects is the same. The doclists must be merged
  148781. ** and a single term returned with the merged doclist.
  148782. */
  148783. for(i=0; i<nMerge; i++){
  148784. fts3SegReaderFirstDocid(p, apSegment[i]);
  148785. }
  148786. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  148787. while( apSegment[0]->pOffsetList ){
  148788. int j; /* Number of segments that share a docid */
  148789. char *pList = 0;
  148790. int nList = 0;
  148791. int nByte;
  148792. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  148793. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  148794. j = 1;
  148795. while( j<nMerge
  148796. && apSegment[j]->pOffsetList
  148797. && apSegment[j]->iDocid==iDocid
  148798. ){
  148799. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  148800. j++;
  148801. }
  148802. if( isColFilter ){
  148803. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  148804. }
  148805. if( !isIgnoreEmpty || nList>0 ){
  148806. /* Calculate the 'docid' delta value to write into the merged
  148807. ** doclist. */
  148808. sqlite3_int64 iDelta;
  148809. if( p->bDescIdx && nDoclist>0 ){
  148810. iDelta = iPrev - iDocid;
  148811. }else{
  148812. iDelta = iDocid - iPrev;
  148813. }
  148814. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  148815. assert( nDoclist>0 || iDelta==iDocid );
  148816. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  148817. if( nDoclist+nByte>pCsr->nBuffer ){
  148818. char *aNew;
  148819. pCsr->nBuffer = (nDoclist+nByte)*2;
  148820. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  148821. if( !aNew ){
  148822. return SQLITE_NOMEM;
  148823. }
  148824. pCsr->aBuffer = aNew;
  148825. }
  148826. if( isFirst ){
  148827. char *a = &pCsr->aBuffer[nDoclist];
  148828. int nWrite;
  148829. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  148830. if( nWrite ){
  148831. iPrev = iDocid;
  148832. nDoclist += nWrite;
  148833. }
  148834. }else{
  148835. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  148836. iPrev = iDocid;
  148837. if( isRequirePos ){
  148838. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  148839. nDoclist += nList;
  148840. pCsr->aBuffer[nDoclist++] = '\0';
  148841. }
  148842. }
  148843. }
  148844. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  148845. }
  148846. if( nDoclist>0 ){
  148847. pCsr->aDoclist = pCsr->aBuffer;
  148848. pCsr->nDoclist = nDoclist;
  148849. rc = SQLITE_ROW;
  148850. }
  148851. }
  148852. pCsr->nAdvance = nMerge;
  148853. }while( rc==SQLITE_OK );
  148854. return rc;
  148855. }
  148856. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  148857. Fts3MultiSegReader *pCsr /* Cursor object */
  148858. ){
  148859. if( pCsr ){
  148860. int i;
  148861. for(i=0; i<pCsr->nSegment; i++){
  148862. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  148863. }
  148864. sqlite3_free(pCsr->apSegment);
  148865. sqlite3_free(pCsr->aBuffer);
  148866. pCsr->nSegment = 0;
  148867. pCsr->apSegment = 0;
  148868. pCsr->aBuffer = 0;
  148869. }
  148870. }
  148871. /*
  148872. ** Decode the "end_block" field, selected by column iCol of the SELECT
  148873. ** statement passed as the first argument.
  148874. **
  148875. ** The "end_block" field may contain either an integer, or a text field
  148876. ** containing the text representation of two non-negative integers separated
  148877. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  148878. ** to the integer value and *pnByte to zero before returning. In the second,
  148879. ** set *piEndBlock to the first value and *pnByte to the second.
  148880. */
  148881. static void fts3ReadEndBlockField(
  148882. sqlite3_stmt *pStmt,
  148883. int iCol,
  148884. i64 *piEndBlock,
  148885. i64 *pnByte
  148886. ){
  148887. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  148888. if( zText ){
  148889. int i;
  148890. int iMul = 1;
  148891. i64 iVal = 0;
  148892. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  148893. iVal = iVal*10 + (zText[i] - '0');
  148894. }
  148895. *piEndBlock = iVal;
  148896. while( zText[i]==' ' ) i++;
  148897. iVal = 0;
  148898. if( zText[i]=='-' ){
  148899. i++;
  148900. iMul = -1;
  148901. }
  148902. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  148903. iVal = iVal*10 + (zText[i] - '0');
  148904. }
  148905. *pnByte = (iVal * (i64)iMul);
  148906. }
  148907. }
  148908. /*
  148909. ** A segment of size nByte bytes has just been written to absolute level
  148910. ** iAbsLevel. Promote any segments that should be promoted as a result.
  148911. */
  148912. static int fts3PromoteSegments(
  148913. Fts3Table *p, /* FTS table handle */
  148914. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  148915. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  148916. ){
  148917. int rc = SQLITE_OK;
  148918. sqlite3_stmt *pRange;
  148919. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  148920. if( rc==SQLITE_OK ){
  148921. int bOk = 0;
  148922. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  148923. i64 nLimit = (nByte*3)/2;
  148924. /* Loop through all entries in the %_segdir table corresponding to
  148925. ** segments in this index on levels greater than iAbsLevel. If there is
  148926. ** at least one such segment, and it is possible to determine that all
  148927. ** such segments are smaller than nLimit bytes in size, they will be
  148928. ** promoted to level iAbsLevel. */
  148929. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  148930. sqlite3_bind_int64(pRange, 2, iLast);
  148931. while( SQLITE_ROW==sqlite3_step(pRange) ){
  148932. i64 nSize = 0, dummy;
  148933. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  148934. if( nSize<=0 || nSize>nLimit ){
  148935. /* If nSize==0, then the %_segdir.end_block field does not not
  148936. ** contain a size value. This happens if it was written by an
  148937. ** old version of FTS. In this case it is not possible to determine
  148938. ** the size of the segment, and so segment promotion does not
  148939. ** take place. */
  148940. bOk = 0;
  148941. break;
  148942. }
  148943. bOk = 1;
  148944. }
  148945. rc = sqlite3_reset(pRange);
  148946. if( bOk ){
  148947. int iIdx = 0;
  148948. sqlite3_stmt *pUpdate1 = 0;
  148949. sqlite3_stmt *pUpdate2 = 0;
  148950. if( rc==SQLITE_OK ){
  148951. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  148952. }
  148953. if( rc==SQLITE_OK ){
  148954. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  148955. }
  148956. if( rc==SQLITE_OK ){
  148957. /* Loop through all %_segdir entries for segments in this index with
  148958. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  148959. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  148960. ** oldest segment in the range, 1 for the next oldest, and so on.
  148961. **
  148962. ** In other words, move all segments being promoted to level -1,
  148963. ** setting the "idx" fields as appropriate to keep them in the same
  148964. ** order. The contents of level -1 (which is never used, except
  148965. ** transiently here), will be moved back to level iAbsLevel below. */
  148966. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  148967. while( SQLITE_ROW==sqlite3_step(pRange) ){
  148968. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  148969. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  148970. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  148971. sqlite3_step(pUpdate1);
  148972. rc = sqlite3_reset(pUpdate1);
  148973. if( rc!=SQLITE_OK ){
  148974. sqlite3_reset(pRange);
  148975. break;
  148976. }
  148977. }
  148978. }
  148979. if( rc==SQLITE_OK ){
  148980. rc = sqlite3_reset(pRange);
  148981. }
  148982. /* Move level -1 to level iAbsLevel */
  148983. if( rc==SQLITE_OK ){
  148984. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  148985. sqlite3_step(pUpdate2);
  148986. rc = sqlite3_reset(pUpdate2);
  148987. }
  148988. }
  148989. }
  148990. return rc;
  148991. }
  148992. /*
  148993. ** Merge all level iLevel segments in the database into a single
  148994. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  148995. ** single segment with a level equal to the numerically largest level
  148996. ** currently present in the database.
  148997. **
  148998. ** If this function is called with iLevel<0, but there is only one
  148999. ** segment in the database, SQLITE_DONE is returned immediately.
  149000. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  149001. ** an SQLite error code is returned.
  149002. */
  149003. static int fts3SegmentMerge(
  149004. Fts3Table *p,
  149005. int iLangid, /* Language id to merge */
  149006. int iIndex, /* Index in p->aIndex[] to merge */
  149007. int iLevel /* Level to merge */
  149008. ){
  149009. int rc; /* Return code */
  149010. int iIdx = 0; /* Index of new segment */
  149011. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  149012. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  149013. Fts3SegFilter filter; /* Segment term filter condition */
  149014. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  149015. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  149016. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  149017. assert( iLevel==FTS3_SEGCURSOR_ALL
  149018. || iLevel==FTS3_SEGCURSOR_PENDING
  149019. || iLevel>=0
  149020. );
  149021. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  149022. assert( iIndex>=0 && iIndex<p->nIndex );
  149023. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  149024. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  149025. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  149026. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  149027. if( rc!=SQLITE_OK ) goto finished;
  149028. }
  149029. if( iLevel==FTS3_SEGCURSOR_ALL ){
  149030. /* This call is to merge all segments in the database to a single
  149031. ** segment. The level of the new segment is equal to the numerically
  149032. ** greatest segment level currently present in the database for this
  149033. ** index. The idx of the new segment is always 0. */
  149034. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  149035. rc = SQLITE_DONE;
  149036. goto finished;
  149037. }
  149038. iNewLevel = iMaxLevel;
  149039. bIgnoreEmpty = 1;
  149040. }else{
  149041. /* This call is to merge all segments at level iLevel. find the next
  149042. ** available segment index at level iLevel+1. The call to
  149043. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  149044. ** a single iLevel+2 segment if necessary. */
  149045. assert( FTS3_SEGCURSOR_PENDING==-1 );
  149046. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  149047. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  149048. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  149049. }
  149050. if( rc!=SQLITE_OK ) goto finished;
  149051. assert( csr.nSegment>0 );
  149052. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  149053. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  149054. memset(&filter, 0, sizeof(Fts3SegFilter));
  149055. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  149056. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  149057. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  149058. while( SQLITE_OK==rc ){
  149059. rc = sqlite3Fts3SegReaderStep(p, &csr);
  149060. if( rc!=SQLITE_ROW ) break;
  149061. rc = fts3SegWriterAdd(p, &pWriter, 1,
  149062. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  149063. }
  149064. if( rc!=SQLITE_OK ) goto finished;
  149065. assert( pWriter || bIgnoreEmpty );
  149066. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  149067. rc = fts3DeleteSegdir(
  149068. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  149069. );
  149070. if( rc!=SQLITE_OK ) goto finished;
  149071. }
  149072. if( pWriter ){
  149073. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  149074. if( rc==SQLITE_OK ){
  149075. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  149076. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  149077. }
  149078. }
  149079. }
  149080. finished:
  149081. fts3SegWriterFree(pWriter);
  149082. sqlite3Fts3SegReaderFinish(&csr);
  149083. return rc;
  149084. }
  149085. /*
  149086. ** Flush the contents of pendingTerms to level 0 segments.
  149087. */
  149088. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  149089. int rc = SQLITE_OK;
  149090. int i;
  149091. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  149092. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  149093. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  149094. }
  149095. sqlite3Fts3PendingTermsClear(p);
  149096. /* Determine the auto-incr-merge setting if unknown. If enabled,
  149097. ** estimate the number of leaf blocks of content to be written
  149098. */
  149099. if( rc==SQLITE_OK && p->bHasStat
  149100. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  149101. ){
  149102. sqlite3_stmt *pStmt = 0;
  149103. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  149104. if( rc==SQLITE_OK ){
  149105. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  149106. rc = sqlite3_step(pStmt);
  149107. if( rc==SQLITE_ROW ){
  149108. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  149109. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  149110. }else if( rc==SQLITE_DONE ){
  149111. p->nAutoincrmerge = 0;
  149112. }
  149113. rc = sqlite3_reset(pStmt);
  149114. }
  149115. }
  149116. return rc;
  149117. }
  149118. /*
  149119. ** Encode N integers as varints into a blob.
  149120. */
  149121. static void fts3EncodeIntArray(
  149122. int N, /* The number of integers to encode */
  149123. u32 *a, /* The integer values */
  149124. char *zBuf, /* Write the BLOB here */
  149125. int *pNBuf /* Write number of bytes if zBuf[] used here */
  149126. ){
  149127. int i, j;
  149128. for(i=j=0; i<N; i++){
  149129. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  149130. }
  149131. *pNBuf = j;
  149132. }
  149133. /*
  149134. ** Decode a blob of varints into N integers
  149135. */
  149136. static void fts3DecodeIntArray(
  149137. int N, /* The number of integers to decode */
  149138. u32 *a, /* Write the integer values */
  149139. const char *zBuf, /* The BLOB containing the varints */
  149140. int nBuf /* size of the BLOB */
  149141. ){
  149142. int i, j;
  149143. UNUSED_PARAMETER(nBuf);
  149144. for(i=j=0; i<N; i++){
  149145. sqlite3_int64 x;
  149146. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  149147. assert(j<=nBuf);
  149148. a[i] = (u32)(x & 0xffffffff);
  149149. }
  149150. }
  149151. /*
  149152. ** Insert the sizes (in tokens) for each column of the document
  149153. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  149154. ** a blob of varints.
  149155. */
  149156. static void fts3InsertDocsize(
  149157. int *pRC, /* Result code */
  149158. Fts3Table *p, /* Table into which to insert */
  149159. u32 *aSz /* Sizes of each column, in tokens */
  149160. ){
  149161. char *pBlob; /* The BLOB encoding of the document size */
  149162. int nBlob; /* Number of bytes in the BLOB */
  149163. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  149164. int rc; /* Result code from subfunctions */
  149165. if( *pRC ) return;
  149166. pBlob = sqlite3_malloc( 10*p->nColumn );
  149167. if( pBlob==0 ){
  149168. *pRC = SQLITE_NOMEM;
  149169. return;
  149170. }
  149171. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  149172. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  149173. if( rc ){
  149174. sqlite3_free(pBlob);
  149175. *pRC = rc;
  149176. return;
  149177. }
  149178. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  149179. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  149180. sqlite3_step(pStmt);
  149181. *pRC = sqlite3_reset(pStmt);
  149182. }
  149183. /*
  149184. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  149185. ** where N is the number of user defined columns in the fts3 table plus
  149186. ** two. If nCol is the number of user defined columns, then values of the
  149187. ** varints are set as follows:
  149188. **
  149189. ** Varint 0: Total number of rows in the table.
  149190. **
  149191. ** Varint 1..nCol: For each column, the total number of tokens stored in
  149192. ** the column for all rows of the table.
  149193. **
  149194. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  149195. ** columns of all rows of the table.
  149196. **
  149197. */
  149198. static void fts3UpdateDocTotals(
  149199. int *pRC, /* The result code */
  149200. Fts3Table *p, /* Table being updated */
  149201. u32 *aSzIns, /* Size increases */
  149202. u32 *aSzDel, /* Size decreases */
  149203. int nChng /* Change in the number of documents */
  149204. ){
  149205. char *pBlob; /* Storage for BLOB written into %_stat */
  149206. int nBlob; /* Size of BLOB written into %_stat */
  149207. u32 *a; /* Array of integers that becomes the BLOB */
  149208. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  149209. int i; /* Loop counter */
  149210. int rc; /* Result code from subfunctions */
  149211. const int nStat = p->nColumn+2;
  149212. if( *pRC ) return;
  149213. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  149214. if( a==0 ){
  149215. *pRC = SQLITE_NOMEM;
  149216. return;
  149217. }
  149218. pBlob = (char*)&a[nStat];
  149219. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  149220. if( rc ){
  149221. sqlite3_free(a);
  149222. *pRC = rc;
  149223. return;
  149224. }
  149225. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  149226. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  149227. fts3DecodeIntArray(nStat, a,
  149228. sqlite3_column_blob(pStmt, 0),
  149229. sqlite3_column_bytes(pStmt, 0));
  149230. }else{
  149231. memset(a, 0, sizeof(u32)*(nStat) );
  149232. }
  149233. rc = sqlite3_reset(pStmt);
  149234. if( rc!=SQLITE_OK ){
  149235. sqlite3_free(a);
  149236. *pRC = rc;
  149237. return;
  149238. }
  149239. if( nChng<0 && a[0]<(u32)(-nChng) ){
  149240. a[0] = 0;
  149241. }else{
  149242. a[0] += nChng;
  149243. }
  149244. for(i=0; i<p->nColumn+1; i++){
  149245. u32 x = a[i+1];
  149246. if( x+aSzIns[i] < aSzDel[i] ){
  149247. x = 0;
  149248. }else{
  149249. x = x + aSzIns[i] - aSzDel[i];
  149250. }
  149251. a[i+1] = x;
  149252. }
  149253. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  149254. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  149255. if( rc ){
  149256. sqlite3_free(a);
  149257. *pRC = rc;
  149258. return;
  149259. }
  149260. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  149261. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  149262. sqlite3_step(pStmt);
  149263. *pRC = sqlite3_reset(pStmt);
  149264. sqlite3_free(a);
  149265. }
  149266. /*
  149267. ** Merge the entire database so that there is one segment for each
  149268. ** iIndex/iLangid combination.
  149269. */
  149270. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  149271. int bSeenDone = 0;
  149272. int rc;
  149273. sqlite3_stmt *pAllLangid = 0;
  149274. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  149275. if( rc==SQLITE_OK ){
  149276. int rc2;
  149277. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  149278. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  149279. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  149280. int i;
  149281. int iLangid = sqlite3_column_int(pAllLangid, 0);
  149282. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  149283. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  149284. if( rc==SQLITE_DONE ){
  149285. bSeenDone = 1;
  149286. rc = SQLITE_OK;
  149287. }
  149288. }
  149289. }
  149290. rc2 = sqlite3_reset(pAllLangid);
  149291. if( rc==SQLITE_OK ) rc = rc2;
  149292. }
  149293. sqlite3Fts3SegmentsClose(p);
  149294. sqlite3Fts3PendingTermsClear(p);
  149295. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  149296. }
  149297. /*
  149298. ** This function is called when the user executes the following statement:
  149299. **
  149300. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  149301. **
  149302. ** The entire FTS index is discarded and rebuilt. If the table is one
  149303. ** created using the content=xxx option, then the new index is based on
  149304. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  149305. ** on the contents of the %_content table.
  149306. */
  149307. static int fts3DoRebuild(Fts3Table *p){
  149308. int rc; /* Return Code */
  149309. rc = fts3DeleteAll(p, 0);
  149310. if( rc==SQLITE_OK ){
  149311. u32 *aSz = 0;
  149312. u32 *aSzIns = 0;
  149313. u32 *aSzDel = 0;
  149314. sqlite3_stmt *pStmt = 0;
  149315. int nEntry = 0;
  149316. /* Compose and prepare an SQL statement to loop through the content table */
  149317. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  149318. if( !zSql ){
  149319. rc = SQLITE_NOMEM;
  149320. }else{
  149321. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  149322. sqlite3_free(zSql);
  149323. }
  149324. if( rc==SQLITE_OK ){
  149325. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  149326. aSz = (u32 *)sqlite3_malloc(nByte);
  149327. if( aSz==0 ){
  149328. rc = SQLITE_NOMEM;
  149329. }else{
  149330. memset(aSz, 0, nByte);
  149331. aSzIns = &aSz[p->nColumn+1];
  149332. aSzDel = &aSzIns[p->nColumn+1];
  149333. }
  149334. }
  149335. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  149336. int iCol;
  149337. int iLangid = langidFromSelect(p, pStmt);
  149338. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  149339. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  149340. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  149341. if( p->abNotindexed[iCol]==0 ){
  149342. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  149343. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  149344. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  149345. }
  149346. }
  149347. if( p->bHasDocsize ){
  149348. fts3InsertDocsize(&rc, p, aSz);
  149349. }
  149350. if( rc!=SQLITE_OK ){
  149351. sqlite3_finalize(pStmt);
  149352. pStmt = 0;
  149353. }else{
  149354. nEntry++;
  149355. for(iCol=0; iCol<=p->nColumn; iCol++){
  149356. aSzIns[iCol] += aSz[iCol];
  149357. }
  149358. }
  149359. }
  149360. if( p->bFts4 ){
  149361. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  149362. }
  149363. sqlite3_free(aSz);
  149364. if( pStmt ){
  149365. int rc2 = sqlite3_finalize(pStmt);
  149366. if( rc==SQLITE_OK ){
  149367. rc = rc2;
  149368. }
  149369. }
  149370. }
  149371. return rc;
  149372. }
  149373. /*
  149374. ** This function opens a cursor used to read the input data for an
  149375. ** incremental merge operation. Specifically, it opens a cursor to scan
  149376. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  149377. ** level iAbsLevel.
  149378. */
  149379. static int fts3IncrmergeCsr(
  149380. Fts3Table *p, /* FTS3 table handle */
  149381. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  149382. int nSeg, /* Number of segments to merge */
  149383. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  149384. ){
  149385. int rc; /* Return Code */
  149386. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  149387. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  149388. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  149389. memset(pCsr, 0, sizeof(*pCsr));
  149390. nByte = sizeof(Fts3SegReader *) * nSeg;
  149391. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  149392. if( pCsr->apSegment==0 ){
  149393. rc = SQLITE_NOMEM;
  149394. }else{
  149395. memset(pCsr->apSegment, 0, nByte);
  149396. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  149397. }
  149398. if( rc==SQLITE_OK ){
  149399. int i;
  149400. int rc2;
  149401. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  149402. assert( pCsr->nSegment==0 );
  149403. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  149404. rc = sqlite3Fts3SegReaderNew(i, 0,
  149405. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  149406. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  149407. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  149408. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  149409. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  149410. &pCsr->apSegment[i]
  149411. );
  149412. pCsr->nSegment++;
  149413. }
  149414. rc2 = sqlite3_reset(pStmt);
  149415. if( rc==SQLITE_OK ) rc = rc2;
  149416. }
  149417. return rc;
  149418. }
  149419. typedef struct IncrmergeWriter IncrmergeWriter;
  149420. typedef struct NodeWriter NodeWriter;
  149421. typedef struct Blob Blob;
  149422. typedef struct NodeReader NodeReader;
  149423. /*
  149424. ** An instance of the following structure is used as a dynamic buffer
  149425. ** to build up nodes or other blobs of data in.
  149426. **
  149427. ** The function blobGrowBuffer() is used to extend the allocation.
  149428. */
  149429. struct Blob {
  149430. char *a; /* Pointer to allocation */
  149431. int n; /* Number of valid bytes of data in a[] */
  149432. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  149433. };
  149434. /*
  149435. ** This structure is used to build up buffers containing segment b-tree
  149436. ** nodes (blocks).
  149437. */
  149438. struct NodeWriter {
  149439. sqlite3_int64 iBlock; /* Current block id */
  149440. Blob key; /* Last key written to the current block */
  149441. Blob block; /* Current block image */
  149442. };
  149443. /*
  149444. ** An object of this type contains the state required to create or append
  149445. ** to an appendable b-tree segment.
  149446. */
  149447. struct IncrmergeWriter {
  149448. int nLeafEst; /* Space allocated for leaf blocks */
  149449. int nWork; /* Number of leaf pages flushed */
  149450. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  149451. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  149452. sqlite3_int64 iStart; /* Block number of first allocated block */
  149453. sqlite3_int64 iEnd; /* Block number of last allocated block */
  149454. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  149455. u8 bNoLeafData; /* If true, store 0 for segment size */
  149456. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  149457. };
  149458. /*
  149459. ** An object of the following type is used to read data from a single
  149460. ** FTS segment node. See the following functions:
  149461. **
  149462. ** nodeReaderInit()
  149463. ** nodeReaderNext()
  149464. ** nodeReaderRelease()
  149465. */
  149466. struct NodeReader {
  149467. const char *aNode;
  149468. int nNode;
  149469. int iOff; /* Current offset within aNode[] */
  149470. /* Output variables. Containing the current node entry. */
  149471. sqlite3_int64 iChild; /* Pointer to child node */
  149472. Blob term; /* Current term */
  149473. const char *aDoclist; /* Pointer to doclist */
  149474. int nDoclist; /* Size of doclist in bytes */
  149475. };
  149476. /*
  149477. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  149478. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  149479. ** bytes in size, extend (realloc) it to be so.
  149480. **
  149481. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  149482. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  149483. ** to reflect the new size of the pBlob->a[] buffer.
  149484. */
  149485. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  149486. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  149487. int nAlloc = nMin;
  149488. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  149489. if( a ){
  149490. pBlob->nAlloc = nAlloc;
  149491. pBlob->a = a;
  149492. }else{
  149493. *pRc = SQLITE_NOMEM;
  149494. }
  149495. }
  149496. }
  149497. /*
  149498. ** Attempt to advance the node-reader object passed as the first argument to
  149499. ** the next entry on the node.
  149500. **
  149501. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  149502. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  149503. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  149504. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  149505. ** variables for the new entry.
  149506. */
  149507. static int nodeReaderNext(NodeReader *p){
  149508. int bFirst = (p->term.n==0); /* True for first term on the node */
  149509. int nPrefix = 0; /* Bytes to copy from previous term */
  149510. int nSuffix = 0; /* Bytes to append to the prefix */
  149511. int rc = SQLITE_OK; /* Return code */
  149512. assert( p->aNode );
  149513. if( p->iChild && bFirst==0 ) p->iChild++;
  149514. if( p->iOff>=p->nNode ){
  149515. /* EOF */
  149516. p->aNode = 0;
  149517. }else{
  149518. if( bFirst==0 ){
  149519. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  149520. }
  149521. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  149522. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  149523. if( rc==SQLITE_OK ){
  149524. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  149525. p->term.n = nPrefix+nSuffix;
  149526. p->iOff += nSuffix;
  149527. if( p->iChild==0 ){
  149528. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  149529. p->aDoclist = &p->aNode[p->iOff];
  149530. p->iOff += p->nDoclist;
  149531. }
  149532. }
  149533. }
  149534. assert( p->iOff<=p->nNode );
  149535. return rc;
  149536. }
  149537. /*
  149538. ** Release all dynamic resources held by node-reader object *p.
  149539. */
  149540. static void nodeReaderRelease(NodeReader *p){
  149541. sqlite3_free(p->term.a);
  149542. }
  149543. /*
  149544. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  149545. **
  149546. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  149547. ** point to the first entry on the node (if any). Otherwise, an SQLite
  149548. ** error code is returned.
  149549. */
  149550. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  149551. memset(p, 0, sizeof(NodeReader));
  149552. p->aNode = aNode;
  149553. p->nNode = nNode;
  149554. /* Figure out if this is a leaf or an internal node. */
  149555. if( p->aNode[0] ){
  149556. /* An internal node. */
  149557. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  149558. }else{
  149559. p->iOff = 1;
  149560. }
  149561. return nodeReaderNext(p);
  149562. }
  149563. /*
  149564. ** This function is called while writing an FTS segment each time a leaf o
  149565. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  149566. ** to be greater than the largest key on the node just written, but smaller
  149567. ** than or equal to the first key that will be written to the next leaf
  149568. ** node.
  149569. **
  149570. ** The block id of the leaf node just written to disk may be found in
  149571. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  149572. */
  149573. static int fts3IncrmergePush(
  149574. Fts3Table *p, /* Fts3 table handle */
  149575. IncrmergeWriter *pWriter, /* Writer object */
  149576. const char *zTerm, /* Term to write to internal node */
  149577. int nTerm /* Bytes at zTerm */
  149578. ){
  149579. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  149580. int iLayer;
  149581. assert( nTerm>0 );
  149582. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  149583. sqlite3_int64 iNextPtr = 0;
  149584. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  149585. int rc = SQLITE_OK;
  149586. int nPrefix;
  149587. int nSuffix;
  149588. int nSpace;
  149589. /* Figure out how much space the key will consume if it is written to
  149590. ** the current node of layer iLayer. Due to the prefix compression,
  149591. ** the space required changes depending on which node the key is to
  149592. ** be added to. */
  149593. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  149594. nSuffix = nTerm - nPrefix;
  149595. nSpace = sqlite3Fts3VarintLen(nPrefix);
  149596. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  149597. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  149598. /* If the current node of layer iLayer contains zero keys, or if adding
  149599. ** the key to it will not cause it to grow to larger than nNodeSize
  149600. ** bytes in size, write the key here. */
  149601. Blob *pBlk = &pNode->block;
  149602. if( pBlk->n==0 ){
  149603. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  149604. if( rc==SQLITE_OK ){
  149605. pBlk->a[0] = (char)iLayer;
  149606. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  149607. }
  149608. }
  149609. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  149610. blobGrowBuffer(&pNode->key, nTerm, &rc);
  149611. if( rc==SQLITE_OK ){
  149612. if( pNode->key.n ){
  149613. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  149614. }
  149615. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  149616. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  149617. pBlk->n += nSuffix;
  149618. memcpy(pNode->key.a, zTerm, nTerm);
  149619. pNode->key.n = nTerm;
  149620. }
  149621. }else{
  149622. /* Otherwise, flush the current node of layer iLayer to disk.
  149623. ** Then allocate a new, empty sibling node. The key will be written
  149624. ** into the parent of this node. */
  149625. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  149626. assert( pNode->block.nAlloc>=p->nNodeSize );
  149627. pNode->block.a[0] = (char)iLayer;
  149628. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  149629. iNextPtr = pNode->iBlock;
  149630. pNode->iBlock++;
  149631. pNode->key.n = 0;
  149632. }
  149633. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  149634. iPtr = iNextPtr;
  149635. }
  149636. assert( 0 );
  149637. return 0;
  149638. }
  149639. /*
  149640. ** Append a term and (optionally) doclist to the FTS segment node currently
  149641. ** stored in blob *pNode. The node need not contain any terms, but the
  149642. ** header must be written before this function is called.
  149643. **
  149644. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  149645. ** followed by the left-hand-child varint for an internal node.
  149646. **
  149647. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  149648. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  149649. ** node, both aDoclist and nDoclist must be passed 0.
  149650. **
  149651. ** If the size of the value in blob pPrev is zero, then this is the first
  149652. ** term written to the node. Otherwise, pPrev contains a copy of the
  149653. ** previous term. Before this function returns, it is updated to contain a
  149654. ** copy of zTerm/nTerm.
  149655. **
  149656. ** It is assumed that the buffer associated with pNode is already large
  149657. ** enough to accommodate the new entry. The buffer associated with pPrev
  149658. ** is extended by this function if requrired.
  149659. **
  149660. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  149661. ** returned. Otherwise, SQLITE_OK.
  149662. */
  149663. static int fts3AppendToNode(
  149664. Blob *pNode, /* Current node image to append to */
  149665. Blob *pPrev, /* Buffer containing previous term written */
  149666. const char *zTerm, /* New term to write */
  149667. int nTerm, /* Size of zTerm in bytes */
  149668. const char *aDoclist, /* Doclist (or NULL) to write */
  149669. int nDoclist /* Size of aDoclist in bytes */
  149670. ){
  149671. int rc = SQLITE_OK; /* Return code */
  149672. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  149673. int nPrefix; /* Size of term prefix in bytes */
  149674. int nSuffix; /* Size of term suffix in bytes */
  149675. /* Node must have already been started. There must be a doclist for a
  149676. ** leaf node, and there must not be a doclist for an internal node. */
  149677. assert( pNode->n>0 );
  149678. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  149679. blobGrowBuffer(pPrev, nTerm, &rc);
  149680. if( rc!=SQLITE_OK ) return rc;
  149681. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  149682. nSuffix = nTerm - nPrefix;
  149683. memcpy(pPrev->a, zTerm, nTerm);
  149684. pPrev->n = nTerm;
  149685. if( bFirst==0 ){
  149686. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  149687. }
  149688. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  149689. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  149690. pNode->n += nSuffix;
  149691. if( aDoclist ){
  149692. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  149693. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  149694. pNode->n += nDoclist;
  149695. }
  149696. assert( pNode->n<=pNode->nAlloc );
  149697. return SQLITE_OK;
  149698. }
  149699. /*
  149700. ** Append the current term and doclist pointed to by cursor pCsr to the
  149701. ** appendable b-tree segment opened for writing by pWriter.
  149702. **
  149703. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  149704. */
  149705. static int fts3IncrmergeAppend(
  149706. Fts3Table *p, /* Fts3 table handle */
  149707. IncrmergeWriter *pWriter, /* Writer object */
  149708. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  149709. ){
  149710. const char *zTerm = pCsr->zTerm;
  149711. int nTerm = pCsr->nTerm;
  149712. const char *aDoclist = pCsr->aDoclist;
  149713. int nDoclist = pCsr->nDoclist;
  149714. int rc = SQLITE_OK; /* Return code */
  149715. int nSpace; /* Total space in bytes required on leaf */
  149716. int nPrefix; /* Size of prefix shared with previous term */
  149717. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  149718. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  149719. pLeaf = &pWriter->aNodeWriter[0];
  149720. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  149721. nSuffix = nTerm - nPrefix;
  149722. nSpace = sqlite3Fts3VarintLen(nPrefix);
  149723. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  149724. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  149725. /* If the current block is not empty, and if adding this term/doclist
  149726. ** to the current block would make it larger than Fts3Table.nNodeSize
  149727. ** bytes, write this block out to the database. */
  149728. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  149729. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  149730. pWriter->nWork++;
  149731. /* Add the current term to the parent node. The term added to the
  149732. ** parent must:
  149733. **
  149734. ** a) be greater than the largest term on the leaf node just written
  149735. ** to the database (still available in pLeaf->key), and
  149736. **
  149737. ** b) be less than or equal to the term about to be added to the new
  149738. ** leaf node (zTerm/nTerm).
  149739. **
  149740. ** In other words, it must be the prefix of zTerm 1 byte longer than
  149741. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  149742. */
  149743. if( rc==SQLITE_OK ){
  149744. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  149745. }
  149746. /* Advance to the next output block */
  149747. pLeaf->iBlock++;
  149748. pLeaf->key.n = 0;
  149749. pLeaf->block.n = 0;
  149750. nSuffix = nTerm;
  149751. nSpace = 1;
  149752. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  149753. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  149754. }
  149755. pWriter->nLeafData += nSpace;
  149756. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  149757. if( rc==SQLITE_OK ){
  149758. if( pLeaf->block.n==0 ){
  149759. pLeaf->block.n = 1;
  149760. pLeaf->block.a[0] = '\0';
  149761. }
  149762. rc = fts3AppendToNode(
  149763. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  149764. );
  149765. }
  149766. return rc;
  149767. }
  149768. /*
  149769. ** This function is called to release all dynamic resources held by the
  149770. ** merge-writer object pWriter, and if no error has occurred, to flush
  149771. ** all outstanding node buffers held by pWriter to disk.
  149772. **
  149773. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  149774. ** is made to write any data to disk. Instead, this function serves only
  149775. ** to release outstanding resources.
  149776. **
  149777. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  149778. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  149779. ** returning.
  149780. */
  149781. static void fts3IncrmergeRelease(
  149782. Fts3Table *p, /* FTS3 table handle */
  149783. IncrmergeWriter *pWriter, /* Merge-writer object */
  149784. int *pRc /* IN/OUT: Error code */
  149785. ){
  149786. int i; /* Used to iterate through non-root layers */
  149787. int iRoot; /* Index of root in pWriter->aNodeWriter */
  149788. NodeWriter *pRoot; /* NodeWriter for root node */
  149789. int rc = *pRc; /* Error code */
  149790. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  149791. ** root node. If the segment fits entirely on a single leaf node, iRoot
  149792. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  149793. ** will be 1. And so on. */
  149794. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  149795. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  149796. if( pNode->block.n>0 ) break;
  149797. assert( *pRc || pNode->block.nAlloc==0 );
  149798. assert( *pRc || pNode->key.nAlloc==0 );
  149799. sqlite3_free(pNode->block.a);
  149800. sqlite3_free(pNode->key.a);
  149801. }
  149802. /* Empty output segment. This is a no-op. */
  149803. if( iRoot<0 ) return;
  149804. /* The entire output segment fits on a single node. Normally, this means
  149805. ** the node would be stored as a blob in the "root" column of the %_segdir
  149806. ** table. However, this is not permitted in this case. The problem is that
  149807. ** space has already been reserved in the %_segments table, and so the
  149808. ** start_block and end_block fields of the %_segdir table must be populated.
  149809. ** And, by design or by accident, released versions of FTS cannot handle
  149810. ** segments that fit entirely on the root node with start_block!=0.
  149811. **
  149812. ** Instead, create a synthetic root node that contains nothing but a
  149813. ** pointer to the single content node. So that the segment consists of a
  149814. ** single leaf and a single interior (root) node.
  149815. **
  149816. ** Todo: Better might be to defer allocating space in the %_segments
  149817. ** table until we are sure it is needed.
  149818. */
  149819. if( iRoot==0 ){
  149820. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  149821. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  149822. if( rc==SQLITE_OK ){
  149823. pBlock->a[0] = 0x01;
  149824. pBlock->n = 1 + sqlite3Fts3PutVarint(
  149825. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  149826. );
  149827. }
  149828. iRoot = 1;
  149829. }
  149830. pRoot = &pWriter->aNodeWriter[iRoot];
  149831. /* Flush all currently outstanding nodes to disk. */
  149832. for(i=0; i<iRoot; i++){
  149833. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  149834. if( pNode->block.n>0 && rc==SQLITE_OK ){
  149835. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  149836. }
  149837. sqlite3_free(pNode->block.a);
  149838. sqlite3_free(pNode->key.a);
  149839. }
  149840. /* Write the %_segdir record. */
  149841. if( rc==SQLITE_OK ){
  149842. rc = fts3WriteSegdir(p,
  149843. pWriter->iAbsLevel+1, /* level */
  149844. pWriter->iIdx, /* idx */
  149845. pWriter->iStart, /* start_block */
  149846. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  149847. pWriter->iEnd, /* end_block */
  149848. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  149849. pRoot->block.a, pRoot->block.n /* root */
  149850. );
  149851. }
  149852. sqlite3_free(pRoot->block.a);
  149853. sqlite3_free(pRoot->key.a);
  149854. *pRc = rc;
  149855. }
  149856. /*
  149857. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  149858. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  149859. ** the other, it is considered to be smaller than the other.
  149860. **
  149861. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  149862. ** if it is greater.
  149863. */
  149864. static int fts3TermCmp(
  149865. const char *zLhs, int nLhs, /* LHS of comparison */
  149866. const char *zRhs, int nRhs /* RHS of comparison */
  149867. ){
  149868. int nCmp = MIN(nLhs, nRhs);
  149869. int res;
  149870. res = memcmp(zLhs, zRhs, nCmp);
  149871. if( res==0 ) res = nLhs - nRhs;
  149872. return res;
  149873. }
  149874. /*
  149875. ** Query to see if the entry in the %_segments table with blockid iEnd is
  149876. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  149877. ** returning. Otherwise, set *pbRes to 0.
  149878. **
  149879. ** Or, if an error occurs while querying the database, return an SQLite
  149880. ** error code. The final value of *pbRes is undefined in this case.
  149881. **
  149882. ** This is used to test if a segment is an "appendable" segment. If it
  149883. ** is, then a NULL entry has been inserted into the %_segments table
  149884. ** with blockid %_segdir.end_block.
  149885. */
  149886. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  149887. int bRes = 0; /* Result to set *pbRes to */
  149888. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  149889. int rc; /* Return code */
  149890. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  149891. if( rc==SQLITE_OK ){
  149892. sqlite3_bind_int64(pCheck, 1, iEnd);
  149893. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  149894. rc = sqlite3_reset(pCheck);
  149895. }
  149896. *pbRes = bRes;
  149897. return rc;
  149898. }
  149899. /*
  149900. ** This function is called when initializing an incremental-merge operation.
  149901. ** It checks if the existing segment with index value iIdx at absolute level
  149902. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  149903. ** merge-writer object *pWriter is initialized to write to it.
  149904. **
  149905. ** An existing segment can be appended to by an incremental merge if:
  149906. **
  149907. ** * It was initially created as an appendable segment (with all required
  149908. ** space pre-allocated), and
  149909. **
  149910. ** * The first key read from the input (arguments zKey and nKey) is
  149911. ** greater than the largest key currently stored in the potential
  149912. ** output segment.
  149913. */
  149914. static int fts3IncrmergeLoad(
  149915. Fts3Table *p, /* Fts3 table handle */
  149916. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  149917. int iIdx, /* Index of candidate output segment */
  149918. const char *zKey, /* First key to write */
  149919. int nKey, /* Number of bytes in nKey */
  149920. IncrmergeWriter *pWriter /* Populate this object */
  149921. ){
  149922. int rc; /* Return code */
  149923. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  149924. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  149925. if( rc==SQLITE_OK ){
  149926. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  149927. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  149928. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  149929. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  149930. int nRoot = 0; /* Size of aRoot[] in bytes */
  149931. int rc2; /* Return code from sqlite3_reset() */
  149932. int bAppendable = 0; /* Set to true if segment is appendable */
  149933. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  149934. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  149935. sqlite3_bind_int(pSelect, 2, iIdx);
  149936. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  149937. iStart = sqlite3_column_int64(pSelect, 1);
  149938. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  149939. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  149940. if( pWriter->nLeafData<0 ){
  149941. pWriter->nLeafData = pWriter->nLeafData * -1;
  149942. }
  149943. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  149944. nRoot = sqlite3_column_bytes(pSelect, 4);
  149945. aRoot = sqlite3_column_blob(pSelect, 4);
  149946. }else{
  149947. return sqlite3_reset(pSelect);
  149948. }
  149949. /* Check for the zero-length marker in the %_segments table */
  149950. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  149951. /* Check that zKey/nKey is larger than the largest key the candidate */
  149952. if( rc==SQLITE_OK && bAppendable ){
  149953. char *aLeaf = 0;
  149954. int nLeaf = 0;
  149955. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  149956. if( rc==SQLITE_OK ){
  149957. NodeReader reader;
  149958. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  149959. rc==SQLITE_OK && reader.aNode;
  149960. rc = nodeReaderNext(&reader)
  149961. ){
  149962. assert( reader.aNode );
  149963. }
  149964. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  149965. bAppendable = 0;
  149966. }
  149967. nodeReaderRelease(&reader);
  149968. }
  149969. sqlite3_free(aLeaf);
  149970. }
  149971. if( rc==SQLITE_OK && bAppendable ){
  149972. /* It is possible to append to this segment. Set up the IncrmergeWriter
  149973. ** object to do so. */
  149974. int i;
  149975. int nHeight = (int)aRoot[0];
  149976. NodeWriter *pNode;
  149977. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  149978. pWriter->iStart = iStart;
  149979. pWriter->iEnd = iEnd;
  149980. pWriter->iAbsLevel = iAbsLevel;
  149981. pWriter->iIdx = iIdx;
  149982. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  149983. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  149984. }
  149985. pNode = &pWriter->aNodeWriter[nHeight];
  149986. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  149987. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  149988. if( rc==SQLITE_OK ){
  149989. memcpy(pNode->block.a, aRoot, nRoot);
  149990. pNode->block.n = nRoot;
  149991. }
  149992. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  149993. NodeReader reader;
  149994. pNode = &pWriter->aNodeWriter[i];
  149995. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  149996. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  149997. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  149998. if( rc==SQLITE_OK ){
  149999. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  150000. pNode->key.n = reader.term.n;
  150001. if( i>0 ){
  150002. char *aBlock = 0;
  150003. int nBlock = 0;
  150004. pNode = &pWriter->aNodeWriter[i-1];
  150005. pNode->iBlock = reader.iChild;
  150006. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  150007. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  150008. if( rc==SQLITE_OK ){
  150009. memcpy(pNode->block.a, aBlock, nBlock);
  150010. pNode->block.n = nBlock;
  150011. }
  150012. sqlite3_free(aBlock);
  150013. }
  150014. }
  150015. nodeReaderRelease(&reader);
  150016. }
  150017. }
  150018. rc2 = sqlite3_reset(pSelect);
  150019. if( rc==SQLITE_OK ) rc = rc2;
  150020. }
  150021. return rc;
  150022. }
  150023. /*
  150024. ** Determine the largest segment index value that exists within absolute
  150025. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  150026. ** one before returning SQLITE_OK. Or, if there are no segments at all
  150027. ** within level iAbsLevel, set *piIdx to zero.
  150028. **
  150029. ** If an error occurs, return an SQLite error code. The final value of
  150030. ** *piIdx is undefined in this case.
  150031. */
  150032. static int fts3IncrmergeOutputIdx(
  150033. Fts3Table *p, /* FTS Table handle */
  150034. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  150035. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  150036. ){
  150037. int rc;
  150038. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  150039. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  150040. if( rc==SQLITE_OK ){
  150041. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  150042. sqlite3_step(pOutputIdx);
  150043. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  150044. rc = sqlite3_reset(pOutputIdx);
  150045. }
  150046. return rc;
  150047. }
  150048. /*
  150049. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  150050. ** with idx value iIdx.
  150051. **
  150052. ** In the %_segdir table, a segment is defined by the values in three
  150053. ** columns:
  150054. **
  150055. ** start_block
  150056. ** leaves_end_block
  150057. ** end_block
  150058. **
  150059. ** When an appendable segment is allocated, it is estimated that the
  150060. ** maximum number of leaf blocks that may be required is the sum of the
  150061. ** number of leaf blocks consumed by the input segments, plus the number
  150062. ** of input segments, multiplied by two. This value is stored in stack
  150063. ** variable nLeafEst.
  150064. **
  150065. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  150066. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  150067. ** array of leaf nodes starts at the first block allocated. The array
  150068. ** of interior nodes that are parents of the leaf nodes start at block
  150069. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  150070. **
  150071. ** In the actual code below, the value "16" is replaced with the
  150072. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  150073. */
  150074. static int fts3IncrmergeWriter(
  150075. Fts3Table *p, /* Fts3 table handle */
  150076. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  150077. int iIdx, /* Index of new output segment */
  150078. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  150079. IncrmergeWriter *pWriter /* Populate this object */
  150080. ){
  150081. int rc; /* Return Code */
  150082. int i; /* Iterator variable */
  150083. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  150084. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  150085. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  150086. /* Calculate nLeafEst. */
  150087. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  150088. if( rc==SQLITE_OK ){
  150089. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  150090. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  150091. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  150092. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  150093. }
  150094. rc = sqlite3_reset(pLeafEst);
  150095. }
  150096. if( rc!=SQLITE_OK ) return rc;
  150097. /* Calculate the first block to use in the output segment */
  150098. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  150099. if( rc==SQLITE_OK ){
  150100. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  150101. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  150102. pWriter->iEnd = pWriter->iStart - 1;
  150103. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  150104. }
  150105. rc = sqlite3_reset(pFirstBlock);
  150106. }
  150107. if( rc!=SQLITE_OK ) return rc;
  150108. /* Insert the marker in the %_segments table to make sure nobody tries
  150109. ** to steal the space just allocated. This is also used to identify
  150110. ** appendable segments. */
  150111. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  150112. if( rc!=SQLITE_OK ) return rc;
  150113. pWriter->iAbsLevel = iAbsLevel;
  150114. pWriter->nLeafEst = nLeafEst;
  150115. pWriter->iIdx = iIdx;
  150116. /* Set up the array of NodeWriter objects */
  150117. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  150118. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  150119. }
  150120. return SQLITE_OK;
  150121. }
  150122. /*
  150123. ** Remove an entry from the %_segdir table. This involves running the
  150124. ** following two statements:
  150125. **
  150126. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  150127. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  150128. **
  150129. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  150130. ** statement ensures that the remaining segments have contiguously allocated
  150131. ** idx values.
  150132. */
  150133. static int fts3RemoveSegdirEntry(
  150134. Fts3Table *p, /* FTS3 table handle */
  150135. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  150136. int iIdx /* Index of %_segdir entry to delete */
  150137. ){
  150138. int rc; /* Return code */
  150139. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  150140. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  150141. if( rc==SQLITE_OK ){
  150142. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  150143. sqlite3_bind_int(pDelete, 2, iIdx);
  150144. sqlite3_step(pDelete);
  150145. rc = sqlite3_reset(pDelete);
  150146. }
  150147. return rc;
  150148. }
  150149. /*
  150150. ** One or more segments have just been removed from absolute level iAbsLevel.
  150151. ** Update the 'idx' values of the remaining segments in the level so that
  150152. ** the idx values are a contiguous sequence starting from 0.
  150153. */
  150154. static int fts3RepackSegdirLevel(
  150155. Fts3Table *p, /* FTS3 table handle */
  150156. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  150157. ){
  150158. int rc; /* Return code */
  150159. int *aIdx = 0; /* Array of remaining idx values */
  150160. int nIdx = 0; /* Valid entries in aIdx[] */
  150161. int nAlloc = 0; /* Allocated size of aIdx[] */
  150162. int i; /* Iterator variable */
  150163. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  150164. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  150165. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  150166. if( rc==SQLITE_OK ){
  150167. int rc2;
  150168. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  150169. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  150170. if( nIdx>=nAlloc ){
  150171. int *aNew;
  150172. nAlloc += 16;
  150173. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  150174. if( !aNew ){
  150175. rc = SQLITE_NOMEM;
  150176. break;
  150177. }
  150178. aIdx = aNew;
  150179. }
  150180. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  150181. }
  150182. rc2 = sqlite3_reset(pSelect);
  150183. if( rc==SQLITE_OK ) rc = rc2;
  150184. }
  150185. if( rc==SQLITE_OK ){
  150186. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  150187. }
  150188. if( rc==SQLITE_OK ){
  150189. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  150190. }
  150191. assert( p->bIgnoreSavepoint==0 );
  150192. p->bIgnoreSavepoint = 1;
  150193. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  150194. if( aIdx[i]!=i ){
  150195. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  150196. sqlite3_bind_int(pUpdate, 1, i);
  150197. sqlite3_step(pUpdate);
  150198. rc = sqlite3_reset(pUpdate);
  150199. }
  150200. }
  150201. p->bIgnoreSavepoint = 0;
  150202. sqlite3_free(aIdx);
  150203. return rc;
  150204. }
  150205. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  150206. pNode->a[0] = (char)iHeight;
  150207. if( iChild ){
  150208. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  150209. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  150210. }else{
  150211. assert( pNode->nAlloc>=1 );
  150212. pNode->n = 1;
  150213. }
  150214. }
  150215. /*
  150216. ** The first two arguments are a pointer to and the size of a segment b-tree
  150217. ** node. The node may be a leaf or an internal node.
  150218. **
  150219. ** This function creates a new node image in blob object *pNew by copying
  150220. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  150221. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  150222. */
  150223. static int fts3TruncateNode(
  150224. const char *aNode, /* Current node image */
  150225. int nNode, /* Size of aNode in bytes */
  150226. Blob *pNew, /* OUT: Write new node image here */
  150227. const char *zTerm, /* Omit all terms smaller than this */
  150228. int nTerm, /* Size of zTerm in bytes */
  150229. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  150230. ){
  150231. NodeReader reader; /* Reader object */
  150232. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  150233. int rc = SQLITE_OK; /* Return code */
  150234. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  150235. /* Allocate required output space */
  150236. blobGrowBuffer(pNew, nNode, &rc);
  150237. if( rc!=SQLITE_OK ) return rc;
  150238. pNew->n = 0;
  150239. /* Populate new node buffer */
  150240. for(rc = nodeReaderInit(&reader, aNode, nNode);
  150241. rc==SQLITE_OK && reader.aNode;
  150242. rc = nodeReaderNext(&reader)
  150243. ){
  150244. if( pNew->n==0 ){
  150245. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  150246. if( res<0 || (bLeaf==0 && res==0) ) continue;
  150247. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  150248. *piBlock = reader.iChild;
  150249. }
  150250. rc = fts3AppendToNode(
  150251. pNew, &prev, reader.term.a, reader.term.n,
  150252. reader.aDoclist, reader.nDoclist
  150253. );
  150254. if( rc!=SQLITE_OK ) break;
  150255. }
  150256. if( pNew->n==0 ){
  150257. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  150258. *piBlock = reader.iChild;
  150259. }
  150260. assert( pNew->n<=pNew->nAlloc );
  150261. nodeReaderRelease(&reader);
  150262. sqlite3_free(prev.a);
  150263. return rc;
  150264. }
  150265. /*
  150266. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  150267. ** level iAbsLevel. This may involve deleting entries from the %_segments
  150268. ** table, and modifying existing entries in both the %_segments and %_segdir
  150269. ** tables.
  150270. **
  150271. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  150272. ** SQLite error code otherwise.
  150273. */
  150274. static int fts3TruncateSegment(
  150275. Fts3Table *p, /* FTS3 table handle */
  150276. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  150277. int iIdx, /* Index within level of segment to modify */
  150278. const char *zTerm, /* Remove terms smaller than this */
  150279. int nTerm /* Number of bytes in buffer zTerm */
  150280. ){
  150281. int rc = SQLITE_OK; /* Return code */
  150282. Blob root = {0,0,0}; /* New root page image */
  150283. Blob block = {0,0,0}; /* Buffer used for any other block */
  150284. sqlite3_int64 iBlock = 0; /* Block id */
  150285. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  150286. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  150287. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  150288. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  150289. if( rc==SQLITE_OK ){
  150290. int rc2; /* sqlite3_reset() return code */
  150291. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  150292. sqlite3_bind_int(pFetch, 2, iIdx);
  150293. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  150294. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  150295. int nRoot = sqlite3_column_bytes(pFetch, 4);
  150296. iOldStart = sqlite3_column_int64(pFetch, 1);
  150297. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  150298. }
  150299. rc2 = sqlite3_reset(pFetch);
  150300. if( rc==SQLITE_OK ) rc = rc2;
  150301. }
  150302. while( rc==SQLITE_OK && iBlock ){
  150303. char *aBlock = 0;
  150304. int nBlock = 0;
  150305. iNewStart = iBlock;
  150306. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  150307. if( rc==SQLITE_OK ){
  150308. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  150309. }
  150310. if( rc==SQLITE_OK ){
  150311. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  150312. }
  150313. sqlite3_free(aBlock);
  150314. }
  150315. /* Variable iNewStart now contains the first valid leaf node. */
  150316. if( rc==SQLITE_OK && iNewStart ){
  150317. sqlite3_stmt *pDel = 0;
  150318. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  150319. if( rc==SQLITE_OK ){
  150320. sqlite3_bind_int64(pDel, 1, iOldStart);
  150321. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  150322. sqlite3_step(pDel);
  150323. rc = sqlite3_reset(pDel);
  150324. }
  150325. }
  150326. if( rc==SQLITE_OK ){
  150327. sqlite3_stmt *pChomp = 0;
  150328. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  150329. if( rc==SQLITE_OK ){
  150330. sqlite3_bind_int64(pChomp, 1, iNewStart);
  150331. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  150332. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  150333. sqlite3_bind_int(pChomp, 4, iIdx);
  150334. sqlite3_step(pChomp);
  150335. rc = sqlite3_reset(pChomp);
  150336. }
  150337. }
  150338. sqlite3_free(root.a);
  150339. sqlite3_free(block.a);
  150340. return rc;
  150341. }
  150342. /*
  150343. ** This function is called after an incrmental-merge operation has run to
  150344. ** merge (or partially merge) two or more segments from absolute level
  150345. ** iAbsLevel.
  150346. **
  150347. ** Each input segment is either removed from the db completely (if all of
  150348. ** its data was copied to the output segment by the incrmerge operation)
  150349. ** or modified in place so that it no longer contains those entries that
  150350. ** have been duplicated in the output segment.
  150351. */
  150352. static int fts3IncrmergeChomp(
  150353. Fts3Table *p, /* FTS table handle */
  150354. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  150355. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  150356. int *pnRem /* Number of segments not deleted */
  150357. ){
  150358. int i;
  150359. int nRem = 0;
  150360. int rc = SQLITE_OK;
  150361. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  150362. Fts3SegReader *pSeg = 0;
  150363. int j;
  150364. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  150365. ** somewhere in the pCsr->apSegment[] array. */
  150366. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  150367. pSeg = pCsr->apSegment[j];
  150368. if( pSeg->iIdx==i ) break;
  150369. }
  150370. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  150371. if( pSeg->aNode==0 ){
  150372. /* Seg-reader is at EOF. Remove the entire input segment. */
  150373. rc = fts3DeleteSegment(p, pSeg);
  150374. if( rc==SQLITE_OK ){
  150375. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  150376. }
  150377. *pnRem = 0;
  150378. }else{
  150379. /* The incremental merge did not copy all the data from this
  150380. ** segment to the upper level. The segment is modified in place
  150381. ** so that it contains no keys smaller than zTerm/nTerm. */
  150382. const char *zTerm = pSeg->zTerm;
  150383. int nTerm = pSeg->nTerm;
  150384. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  150385. nRem++;
  150386. }
  150387. }
  150388. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  150389. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  150390. }
  150391. *pnRem = nRem;
  150392. return rc;
  150393. }
  150394. /*
  150395. ** Store an incr-merge hint in the database.
  150396. */
  150397. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  150398. sqlite3_stmt *pReplace = 0;
  150399. int rc; /* Return code */
  150400. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  150401. if( rc==SQLITE_OK ){
  150402. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  150403. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  150404. sqlite3_step(pReplace);
  150405. rc = sqlite3_reset(pReplace);
  150406. }
  150407. return rc;
  150408. }
  150409. /*
  150410. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  150411. ** exists, is stored in the rowid==1 row of the %_stat table.
  150412. **
  150413. ** If successful, populate blob *pHint with the value read from the %_stat
  150414. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  150415. ** SQLite error code.
  150416. */
  150417. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  150418. sqlite3_stmt *pSelect = 0;
  150419. int rc;
  150420. pHint->n = 0;
  150421. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  150422. if( rc==SQLITE_OK ){
  150423. int rc2;
  150424. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  150425. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  150426. const char *aHint = sqlite3_column_blob(pSelect, 0);
  150427. int nHint = sqlite3_column_bytes(pSelect, 0);
  150428. if( aHint ){
  150429. blobGrowBuffer(pHint, nHint, &rc);
  150430. if( rc==SQLITE_OK ){
  150431. memcpy(pHint->a, aHint, nHint);
  150432. pHint->n = nHint;
  150433. }
  150434. }
  150435. }
  150436. rc2 = sqlite3_reset(pSelect);
  150437. if( rc==SQLITE_OK ) rc = rc2;
  150438. }
  150439. return rc;
  150440. }
  150441. /*
  150442. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  150443. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  150444. ** consists of two varints, the absolute level number of the input segments
  150445. ** and the number of input segments.
  150446. **
  150447. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  150448. ** set *pRc to an SQLite error code before returning.
  150449. */
  150450. static void fts3IncrmergeHintPush(
  150451. Blob *pHint, /* Hint blob to append to */
  150452. i64 iAbsLevel, /* First varint to store in hint */
  150453. int nInput, /* Second varint to store in hint */
  150454. int *pRc /* IN/OUT: Error code */
  150455. ){
  150456. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  150457. if( *pRc==SQLITE_OK ){
  150458. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  150459. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  150460. }
  150461. }
  150462. /*
  150463. ** Read the last entry (most recently pushed) from the hint blob *pHint
  150464. ** and then remove the entry. Write the two values read to *piAbsLevel and
  150465. ** *pnInput before returning.
  150466. **
  150467. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  150468. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  150469. */
  150470. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  150471. const int nHint = pHint->n;
  150472. int i;
  150473. i = pHint->n-2;
  150474. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  150475. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  150476. pHint->n = i;
  150477. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  150478. i += fts3GetVarint32(&pHint->a[i], pnInput);
  150479. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  150480. return SQLITE_OK;
  150481. }
  150482. /*
  150483. ** Attempt an incremental merge that writes nMerge leaf blocks.
  150484. **
  150485. ** Incremental merges happen nMin segments at a time. The segments
  150486. ** to be merged are the nMin oldest segments (the ones with the smallest
  150487. ** values for the _segdir.idx field) in the highest level that contains
  150488. ** at least nMin segments. Multiple merges might occur in an attempt to
  150489. ** write the quota of nMerge leaf blocks.
  150490. */
  150491. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  150492. int rc; /* Return code */
  150493. int nRem = nMerge; /* Number of leaf pages yet to be written */
  150494. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  150495. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  150496. IncrmergeWriter *pWriter; /* Writer object */
  150497. int nSeg = 0; /* Number of input segments */
  150498. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  150499. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  150500. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  150501. /* Allocate space for the cursor, filter and writer objects */
  150502. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  150503. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  150504. if( !pWriter ) return SQLITE_NOMEM;
  150505. pFilter = (Fts3SegFilter *)&pWriter[1];
  150506. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  150507. rc = fts3IncrmergeHintLoad(p, &hint);
  150508. while( rc==SQLITE_OK && nRem>0 ){
  150509. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  150510. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  150511. int bUseHint = 0; /* True if attempting to append */
  150512. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  150513. /* Search the %_segdir table for the absolute level with the smallest
  150514. ** relative level number that contains at least nMin segments, if any.
  150515. ** If one is found, set iAbsLevel to the absolute level number and
  150516. ** nSeg to nMin. If no level with at least nMin segments can be found,
  150517. ** set nSeg to -1.
  150518. */
  150519. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  150520. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  150521. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  150522. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  150523. nSeg = sqlite3_column_int(pFindLevel, 1);
  150524. assert( nSeg>=2 );
  150525. }else{
  150526. nSeg = -1;
  150527. }
  150528. rc = sqlite3_reset(pFindLevel);
  150529. /* If the hint read from the %_stat table is not empty, check if the
  150530. ** last entry in it specifies a relative level smaller than or equal
  150531. ** to the level identified by the block above (if any). If so, this
  150532. ** iteration of the loop will work on merging at the hinted level.
  150533. */
  150534. if( rc==SQLITE_OK && hint.n ){
  150535. int nHint = hint.n;
  150536. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  150537. int nHintSeg = 0; /* Hint number of segments */
  150538. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  150539. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  150540. iAbsLevel = iHintAbsLevel;
  150541. nSeg = nHintSeg;
  150542. bUseHint = 1;
  150543. bDirtyHint = 1;
  150544. }else{
  150545. /* This undoes the effect of the HintPop() above - so that no entry
  150546. ** is removed from the hint blob. */
  150547. hint.n = nHint;
  150548. }
  150549. }
  150550. /* If nSeg is less that zero, then there is no level with at least
  150551. ** nMin segments and no hint in the %_stat table. No work to do.
  150552. ** Exit early in this case. */
  150553. if( nSeg<0 ) break;
  150554. /* Open a cursor to iterate through the contents of the oldest nSeg
  150555. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  150556. ** the 'hint' parameters, it is possible that there are less than nSeg
  150557. ** segments available in level iAbsLevel. In this case, no work is
  150558. ** done on iAbsLevel - fall through to the next iteration of the loop
  150559. ** to start work on some other level. */
  150560. memset(pWriter, 0, nAlloc);
  150561. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  150562. if( rc==SQLITE_OK ){
  150563. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  150564. assert( bUseHint==1 || bUseHint==0 );
  150565. if( iIdx==0 || (bUseHint && iIdx==1) ){
  150566. int bIgnore = 0;
  150567. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  150568. if( bIgnore ){
  150569. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  150570. }
  150571. }
  150572. }
  150573. if( rc==SQLITE_OK ){
  150574. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  150575. }
  150576. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  150577. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  150578. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  150579. ){
  150580. if( bUseHint && iIdx>0 ){
  150581. const char *zKey = pCsr->zTerm;
  150582. int nKey = pCsr->nTerm;
  150583. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  150584. }else{
  150585. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  150586. }
  150587. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  150588. fts3LogMerge(nSeg, iAbsLevel);
  150589. do {
  150590. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  150591. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  150592. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  150593. }while( rc==SQLITE_ROW );
  150594. /* Update or delete the input segments */
  150595. if( rc==SQLITE_OK ){
  150596. nRem -= (1 + pWriter->nWork);
  150597. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  150598. if( nSeg!=0 ){
  150599. bDirtyHint = 1;
  150600. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  150601. }
  150602. }
  150603. }
  150604. if( nSeg!=0 ){
  150605. pWriter->nLeafData = pWriter->nLeafData * -1;
  150606. }
  150607. fts3IncrmergeRelease(p, pWriter, &rc);
  150608. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  150609. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  150610. }
  150611. }
  150612. sqlite3Fts3SegReaderFinish(pCsr);
  150613. }
  150614. /* Write the hint values into the %_stat table for the next incr-merger */
  150615. if( bDirtyHint && rc==SQLITE_OK ){
  150616. rc = fts3IncrmergeHintStore(p, &hint);
  150617. }
  150618. sqlite3_free(pWriter);
  150619. sqlite3_free(hint.a);
  150620. return rc;
  150621. }
  150622. /*
  150623. ** Convert the text beginning at *pz into an integer and return
  150624. ** its value. Advance *pz to point to the first character past
  150625. ** the integer.
  150626. **
  150627. ** This function used for parameters to merge= and incrmerge=
  150628. ** commands.
  150629. */
  150630. static int fts3Getint(const char **pz){
  150631. const char *z = *pz;
  150632. int i = 0;
  150633. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  150634. *pz = z;
  150635. return i;
  150636. }
  150637. /*
  150638. ** Process statements of the form:
  150639. **
  150640. ** INSERT INTO table(table) VALUES('merge=A,B');
  150641. **
  150642. ** A and B are integers that decode to be the number of leaf pages
  150643. ** written for the merge, and the minimum number of segments on a level
  150644. ** before it will be selected for a merge, respectively.
  150645. */
  150646. static int fts3DoIncrmerge(
  150647. Fts3Table *p, /* FTS3 table handle */
  150648. const char *zParam /* Nul-terminated string containing "A,B" */
  150649. ){
  150650. int rc;
  150651. int nMin = (FTS3_MERGE_COUNT / 2);
  150652. int nMerge = 0;
  150653. const char *z = zParam;
  150654. /* Read the first integer value */
  150655. nMerge = fts3Getint(&z);
  150656. /* If the first integer value is followed by a ',', read the second
  150657. ** integer value. */
  150658. if( z[0]==',' && z[1]!='\0' ){
  150659. z++;
  150660. nMin = fts3Getint(&z);
  150661. }
  150662. if( z[0]!='\0' || nMin<2 ){
  150663. rc = SQLITE_ERROR;
  150664. }else{
  150665. rc = SQLITE_OK;
  150666. if( !p->bHasStat ){
  150667. assert( p->bFts4==0 );
  150668. sqlite3Fts3CreateStatTable(&rc, p);
  150669. }
  150670. if( rc==SQLITE_OK ){
  150671. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  150672. }
  150673. sqlite3Fts3SegmentsClose(p);
  150674. }
  150675. return rc;
  150676. }
  150677. /*
  150678. ** Process statements of the form:
  150679. **
  150680. ** INSERT INTO table(table) VALUES('automerge=X');
  150681. **
  150682. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  150683. ** turn it on. The setting is persistent.
  150684. */
  150685. static int fts3DoAutoincrmerge(
  150686. Fts3Table *p, /* FTS3 table handle */
  150687. const char *zParam /* Nul-terminated string containing boolean */
  150688. ){
  150689. int rc = SQLITE_OK;
  150690. sqlite3_stmt *pStmt = 0;
  150691. p->nAutoincrmerge = fts3Getint(&zParam);
  150692. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  150693. p->nAutoincrmerge = 8;
  150694. }
  150695. if( !p->bHasStat ){
  150696. assert( p->bFts4==0 );
  150697. sqlite3Fts3CreateStatTable(&rc, p);
  150698. if( rc ) return rc;
  150699. }
  150700. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  150701. if( rc ) return rc;
  150702. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  150703. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  150704. sqlite3_step(pStmt);
  150705. rc = sqlite3_reset(pStmt);
  150706. return rc;
  150707. }
  150708. /*
  150709. ** Return a 64-bit checksum for the FTS index entry specified by the
  150710. ** arguments to this function.
  150711. */
  150712. static u64 fts3ChecksumEntry(
  150713. const char *zTerm, /* Pointer to buffer containing term */
  150714. int nTerm, /* Size of zTerm in bytes */
  150715. int iLangid, /* Language id for current row */
  150716. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  150717. i64 iDocid, /* Docid for current row. */
  150718. int iCol, /* Column number */
  150719. int iPos /* Position */
  150720. ){
  150721. int i;
  150722. u64 ret = (u64)iDocid;
  150723. ret += (ret<<3) + iLangid;
  150724. ret += (ret<<3) + iIndex;
  150725. ret += (ret<<3) + iCol;
  150726. ret += (ret<<3) + iPos;
  150727. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  150728. return ret;
  150729. }
  150730. /*
  150731. ** Return a checksum of all entries in the FTS index that correspond to
  150732. ** language id iLangid. The checksum is calculated by XORing the checksums
  150733. ** of each individual entry (see fts3ChecksumEntry()) together.
  150734. **
  150735. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  150736. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  150737. ** return value is undefined in this case.
  150738. */
  150739. static u64 fts3ChecksumIndex(
  150740. Fts3Table *p, /* FTS3 table handle */
  150741. int iLangid, /* Language id to return cksum for */
  150742. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  150743. int *pRc /* OUT: Return code */
  150744. ){
  150745. Fts3SegFilter filter;
  150746. Fts3MultiSegReader csr;
  150747. int rc;
  150748. u64 cksum = 0;
  150749. assert( *pRc==SQLITE_OK );
  150750. memset(&filter, 0, sizeof(filter));
  150751. memset(&csr, 0, sizeof(csr));
  150752. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  150753. filter.flags |= FTS3_SEGMENT_SCAN;
  150754. rc = sqlite3Fts3SegReaderCursor(
  150755. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  150756. );
  150757. if( rc==SQLITE_OK ){
  150758. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  150759. }
  150760. if( rc==SQLITE_OK ){
  150761. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  150762. char *pCsr = csr.aDoclist;
  150763. char *pEnd = &pCsr[csr.nDoclist];
  150764. i64 iDocid = 0;
  150765. i64 iCol = 0;
  150766. i64 iPos = 0;
  150767. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  150768. while( pCsr<pEnd ){
  150769. i64 iVal = 0;
  150770. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  150771. if( pCsr<pEnd ){
  150772. if( iVal==0 || iVal==1 ){
  150773. iCol = 0;
  150774. iPos = 0;
  150775. if( iVal ){
  150776. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  150777. }else{
  150778. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  150779. iDocid += iVal;
  150780. }
  150781. }else{
  150782. iPos += (iVal - 2);
  150783. cksum = cksum ^ fts3ChecksumEntry(
  150784. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  150785. (int)iCol, (int)iPos
  150786. );
  150787. }
  150788. }
  150789. }
  150790. }
  150791. }
  150792. sqlite3Fts3SegReaderFinish(&csr);
  150793. *pRc = rc;
  150794. return cksum;
  150795. }
  150796. /*
  150797. ** Check if the contents of the FTS index match the current contents of the
  150798. ** content table. If no error occurs and the contents do match, set *pbOk
  150799. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  150800. ** to false before returning.
  150801. **
  150802. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  150803. ** code. The final value of *pbOk is undefined in this case.
  150804. */
  150805. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  150806. int rc = SQLITE_OK; /* Return code */
  150807. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  150808. u64 cksum2 = 0; /* Checksum based on %_content contents */
  150809. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  150810. /* This block calculates the checksum according to the FTS index. */
  150811. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  150812. if( rc==SQLITE_OK ){
  150813. int rc2;
  150814. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  150815. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  150816. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  150817. int iLangid = sqlite3_column_int(pAllLangid, 0);
  150818. int i;
  150819. for(i=0; i<p->nIndex; i++){
  150820. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  150821. }
  150822. }
  150823. rc2 = sqlite3_reset(pAllLangid);
  150824. if( rc==SQLITE_OK ) rc = rc2;
  150825. }
  150826. /* This block calculates the checksum according to the %_content table */
  150827. if( rc==SQLITE_OK ){
  150828. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  150829. sqlite3_stmt *pStmt = 0;
  150830. char *zSql;
  150831. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  150832. if( !zSql ){
  150833. rc = SQLITE_NOMEM;
  150834. }else{
  150835. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  150836. sqlite3_free(zSql);
  150837. }
  150838. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  150839. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  150840. int iLang = langidFromSelect(p, pStmt);
  150841. int iCol;
  150842. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  150843. if( p->abNotindexed[iCol]==0 ){
  150844. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  150845. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  150846. sqlite3_tokenizer_cursor *pT = 0;
  150847. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  150848. while( rc==SQLITE_OK ){
  150849. char const *zToken; /* Buffer containing token */
  150850. int nToken = 0; /* Number of bytes in token */
  150851. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  150852. int iPos = 0; /* Position of token in zText */
  150853. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  150854. if( rc==SQLITE_OK ){
  150855. int i;
  150856. cksum2 = cksum2 ^ fts3ChecksumEntry(
  150857. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  150858. );
  150859. for(i=1; i<p->nIndex; i++){
  150860. if( p->aIndex[i].nPrefix<=nToken ){
  150861. cksum2 = cksum2 ^ fts3ChecksumEntry(
  150862. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  150863. );
  150864. }
  150865. }
  150866. }
  150867. }
  150868. if( pT ) pModule->xClose(pT);
  150869. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  150870. }
  150871. }
  150872. }
  150873. sqlite3_finalize(pStmt);
  150874. }
  150875. *pbOk = (cksum1==cksum2);
  150876. return rc;
  150877. }
  150878. /*
  150879. ** Run the integrity-check. If no error occurs and the current contents of
  150880. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  150881. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  150882. **
  150883. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  150884. ** error code.
  150885. **
  150886. ** The integrity-check works as follows. For each token and indexed token
  150887. ** prefix in the document set, a 64-bit checksum is calculated (by code
  150888. ** in fts3ChecksumEntry()) based on the following:
  150889. **
  150890. ** + The index number (0 for the main index, 1 for the first prefix
  150891. ** index etc.),
  150892. ** + The token (or token prefix) text itself,
  150893. ** + The language-id of the row it appears in,
  150894. ** + The docid of the row it appears in,
  150895. ** + The column it appears in, and
  150896. ** + The tokens position within that column.
  150897. **
  150898. ** The checksums for all entries in the index are XORed together to create
  150899. ** a single checksum for the entire index.
  150900. **
  150901. ** The integrity-check code calculates the same checksum in two ways:
  150902. **
  150903. ** 1. By scanning the contents of the FTS index, and
  150904. ** 2. By scanning and tokenizing the content table.
  150905. **
  150906. ** If the two checksums are identical, the integrity-check is deemed to have
  150907. ** passed.
  150908. */
  150909. static int fts3DoIntegrityCheck(
  150910. Fts3Table *p /* FTS3 table handle */
  150911. ){
  150912. int rc;
  150913. int bOk = 0;
  150914. rc = fts3IntegrityCheck(p, &bOk);
  150915. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  150916. return rc;
  150917. }
  150918. /*
  150919. ** Handle a 'special' INSERT of the form:
  150920. **
  150921. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  150922. **
  150923. ** Argument pVal contains the result of <expr>. Currently the only
  150924. ** meaningful value to insert is the text 'optimize'.
  150925. */
  150926. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  150927. int rc; /* Return Code */
  150928. const char *zVal = (const char *)sqlite3_value_text(pVal);
  150929. int nVal = sqlite3_value_bytes(pVal);
  150930. if( !zVal ){
  150931. return SQLITE_NOMEM;
  150932. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  150933. rc = fts3DoOptimize(p, 0);
  150934. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  150935. rc = fts3DoRebuild(p);
  150936. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  150937. rc = fts3DoIntegrityCheck(p);
  150938. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  150939. rc = fts3DoIncrmerge(p, &zVal[6]);
  150940. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  150941. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  150942. #ifdef SQLITE_TEST
  150943. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  150944. p->nNodeSize = atoi(&zVal[9]);
  150945. rc = SQLITE_OK;
  150946. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  150947. p->nMaxPendingData = atoi(&zVal[11]);
  150948. rc = SQLITE_OK;
  150949. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  150950. p->bNoIncrDoclist = atoi(&zVal[21]);
  150951. rc = SQLITE_OK;
  150952. #endif
  150953. }else{
  150954. rc = SQLITE_ERROR;
  150955. }
  150956. return rc;
  150957. }
  150958. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  150959. /*
  150960. ** Delete all cached deferred doclists. Deferred doclists are cached
  150961. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  150962. */
  150963. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  150964. Fts3DeferredToken *pDef;
  150965. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  150966. fts3PendingListDelete(pDef->pList);
  150967. pDef->pList = 0;
  150968. }
  150969. }
  150970. /*
  150971. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  150972. ** this list using sqlite3Fts3DeferToken().
  150973. */
  150974. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  150975. Fts3DeferredToken *pDef;
  150976. Fts3DeferredToken *pNext;
  150977. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  150978. pNext = pDef->pNext;
  150979. fts3PendingListDelete(pDef->pList);
  150980. sqlite3_free(pDef);
  150981. }
  150982. pCsr->pDeferred = 0;
  150983. }
  150984. /*
  150985. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  150986. ** based on the row that pCsr currently points to.
  150987. **
  150988. ** A deferred-doclist is like any other doclist with position information
  150989. ** included, except that it only contains entries for a single row of the
  150990. ** table, not for all rows.
  150991. */
  150992. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  150993. int rc = SQLITE_OK; /* Return code */
  150994. if( pCsr->pDeferred ){
  150995. int i; /* Used to iterate through table columns */
  150996. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  150997. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  150998. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  150999. sqlite3_tokenizer *pT = p->pTokenizer;
  151000. sqlite3_tokenizer_module const *pModule = pT->pModule;
  151001. assert( pCsr->isRequireSeek==0 );
  151002. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  151003. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  151004. if( p->abNotindexed[i]==0 ){
  151005. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  151006. sqlite3_tokenizer_cursor *pTC = 0;
  151007. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  151008. while( rc==SQLITE_OK ){
  151009. char const *zToken; /* Buffer containing token */
  151010. int nToken = 0; /* Number of bytes in token */
  151011. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  151012. int iPos = 0; /* Position of token in zText */
  151013. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  151014. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  151015. Fts3PhraseToken *pPT = pDef->pToken;
  151016. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  151017. && (pPT->bFirst==0 || iPos==0)
  151018. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  151019. && (0==memcmp(zToken, pPT->z, pPT->n))
  151020. ){
  151021. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  151022. }
  151023. }
  151024. }
  151025. if( pTC ) pModule->xClose(pTC);
  151026. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  151027. }
  151028. }
  151029. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  151030. if( pDef->pList ){
  151031. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  151032. }
  151033. }
  151034. }
  151035. return rc;
  151036. }
  151037. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  151038. Fts3DeferredToken *p,
  151039. char **ppData,
  151040. int *pnData
  151041. ){
  151042. char *pRet;
  151043. int nSkip;
  151044. sqlite3_int64 dummy;
  151045. *ppData = 0;
  151046. *pnData = 0;
  151047. if( p->pList==0 ){
  151048. return SQLITE_OK;
  151049. }
  151050. pRet = (char *)sqlite3_malloc(p->pList->nData);
  151051. if( !pRet ) return SQLITE_NOMEM;
  151052. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  151053. *pnData = p->pList->nData - nSkip;
  151054. *ppData = pRet;
  151055. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  151056. return SQLITE_OK;
  151057. }
  151058. /*
  151059. ** Add an entry for token pToken to the pCsr->pDeferred list.
  151060. */
  151061. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  151062. Fts3Cursor *pCsr, /* Fts3 table cursor */
  151063. Fts3PhraseToken *pToken, /* Token to defer */
  151064. int iCol /* Column that token must appear in (or -1) */
  151065. ){
  151066. Fts3DeferredToken *pDeferred;
  151067. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  151068. if( !pDeferred ){
  151069. return SQLITE_NOMEM;
  151070. }
  151071. memset(pDeferred, 0, sizeof(*pDeferred));
  151072. pDeferred->pToken = pToken;
  151073. pDeferred->pNext = pCsr->pDeferred;
  151074. pDeferred->iCol = iCol;
  151075. pCsr->pDeferred = pDeferred;
  151076. assert( pToken->pDeferred==0 );
  151077. pToken->pDeferred = pDeferred;
  151078. return SQLITE_OK;
  151079. }
  151080. #endif
  151081. /*
  151082. ** SQLite value pRowid contains the rowid of a row that may or may not be
  151083. ** present in the FTS3 table. If it is, delete it and adjust the contents
  151084. ** of subsiduary data structures accordingly.
  151085. */
  151086. static int fts3DeleteByRowid(
  151087. Fts3Table *p,
  151088. sqlite3_value *pRowid,
  151089. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  151090. u32 *aSzDel
  151091. ){
  151092. int rc = SQLITE_OK; /* Return code */
  151093. int bFound = 0; /* True if *pRowid really is in the table */
  151094. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  151095. if( bFound && rc==SQLITE_OK ){
  151096. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  151097. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  151098. if( rc==SQLITE_OK ){
  151099. if( isEmpty ){
  151100. /* Deleting this row means the whole table is empty. In this case
  151101. ** delete the contents of all three tables and throw away any
  151102. ** data in the pendingTerms hash table. */
  151103. rc = fts3DeleteAll(p, 1);
  151104. *pnChng = 0;
  151105. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  151106. }else{
  151107. *pnChng = *pnChng - 1;
  151108. if( p->zContentTbl==0 ){
  151109. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  151110. }
  151111. if( p->bHasDocsize ){
  151112. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  151113. }
  151114. }
  151115. }
  151116. }
  151117. return rc;
  151118. }
  151119. /*
  151120. ** This function does the work for the xUpdate method of FTS3 virtual
  151121. ** tables. The schema of the virtual table being:
  151122. **
  151123. ** CREATE TABLE <table name>(
  151124. ** <user columns>,
  151125. ** <table name> HIDDEN,
  151126. ** docid HIDDEN,
  151127. ** <langid> HIDDEN
  151128. ** );
  151129. **
  151130. **
  151131. */
  151132. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  151133. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  151134. int nArg, /* Size of argument array */
  151135. sqlite3_value **apVal, /* Array of arguments */
  151136. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  151137. ){
  151138. Fts3Table *p = (Fts3Table *)pVtab;
  151139. int rc = SQLITE_OK; /* Return Code */
  151140. int isRemove = 0; /* True for an UPDATE or DELETE */
  151141. u32 *aSzIns = 0; /* Sizes of inserted documents */
  151142. u32 *aSzDel = 0; /* Sizes of deleted documents */
  151143. int nChng = 0; /* Net change in number of documents */
  151144. int bInsertDone = 0;
  151145. /* At this point it must be known if the %_stat table exists or not.
  151146. ** So bHasStat may not be 2. */
  151147. assert( p->bHasStat==0 || p->bHasStat==1 );
  151148. assert( p->pSegments==0 );
  151149. assert(
  151150. nArg==1 /* DELETE operations */
  151151. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  151152. );
  151153. /* Check for a "special" INSERT operation. One of the form:
  151154. **
  151155. ** INSERT INTO xyz(xyz) VALUES('command');
  151156. */
  151157. if( nArg>1
  151158. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  151159. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  151160. ){
  151161. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  151162. goto update_out;
  151163. }
  151164. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  151165. rc = SQLITE_CONSTRAINT;
  151166. goto update_out;
  151167. }
  151168. /* Allocate space to hold the change in document sizes */
  151169. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  151170. if( aSzDel==0 ){
  151171. rc = SQLITE_NOMEM;
  151172. goto update_out;
  151173. }
  151174. aSzIns = &aSzDel[p->nColumn+1];
  151175. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  151176. rc = fts3Writelock(p);
  151177. if( rc!=SQLITE_OK ) goto update_out;
  151178. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  151179. ** value, then this operation requires constraint handling.
  151180. **
  151181. ** If the on-conflict mode is REPLACE, this means that the existing row
  151182. ** should be deleted from the database before inserting the new row. Or,
  151183. ** if the on-conflict mode is other than REPLACE, then this method must
  151184. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  151185. ** modify the database file.
  151186. */
  151187. if( nArg>1 && p->zContentTbl==0 ){
  151188. /* Find the value object that holds the new rowid value. */
  151189. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  151190. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  151191. pNewRowid = apVal[1];
  151192. }
  151193. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  151194. sqlite3_value_type(apVal[0])==SQLITE_NULL
  151195. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  151196. )){
  151197. /* The new rowid is not NULL (in this case the rowid will be
  151198. ** automatically assigned and there is no chance of a conflict), and
  151199. ** the statement is either an INSERT or an UPDATE that modifies the
  151200. ** rowid column. So if the conflict mode is REPLACE, then delete any
  151201. ** existing row with rowid=pNewRowid.
  151202. **
  151203. ** Or, if the conflict mode is not REPLACE, insert the new record into
  151204. ** the %_content table. If we hit the duplicate rowid constraint (or any
  151205. ** other error) while doing so, return immediately.
  151206. **
  151207. ** This branch may also run if pNewRowid contains a value that cannot
  151208. ** be losslessly converted to an integer. In this case, the eventual
  151209. ** call to fts3InsertData() (either just below or further on in this
  151210. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  151211. ** invoked, it will delete zero rows (since no row will have
  151212. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  151213. */
  151214. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  151215. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  151216. }else{
  151217. rc = fts3InsertData(p, apVal, pRowid);
  151218. bInsertDone = 1;
  151219. }
  151220. }
  151221. }
  151222. if( rc!=SQLITE_OK ){
  151223. goto update_out;
  151224. }
  151225. /* If this is a DELETE or UPDATE operation, remove the old record. */
  151226. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  151227. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  151228. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  151229. isRemove = 1;
  151230. }
  151231. /* If this is an INSERT or UPDATE operation, insert the new record. */
  151232. if( nArg>1 && rc==SQLITE_OK ){
  151233. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  151234. if( bInsertDone==0 ){
  151235. rc = fts3InsertData(p, apVal, pRowid);
  151236. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  151237. rc = FTS_CORRUPT_VTAB;
  151238. }
  151239. }
  151240. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  151241. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  151242. }
  151243. if( rc==SQLITE_OK ){
  151244. assert( p->iPrevDocid==*pRowid );
  151245. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  151246. }
  151247. if( p->bHasDocsize ){
  151248. fts3InsertDocsize(&rc, p, aSzIns);
  151249. }
  151250. nChng++;
  151251. }
  151252. if( p->bFts4 ){
  151253. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  151254. }
  151255. update_out:
  151256. sqlite3_free(aSzDel);
  151257. sqlite3Fts3SegmentsClose(p);
  151258. return rc;
  151259. }
  151260. /*
  151261. ** Flush any data in the pending-terms hash table to disk. If successful,
  151262. ** merge all segments in the database (including the new segment, if
  151263. ** there was any data to flush) into a single segment.
  151264. */
  151265. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  151266. int rc;
  151267. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  151268. if( rc==SQLITE_OK ){
  151269. rc = fts3DoOptimize(p, 1);
  151270. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  151271. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  151272. if( rc2!=SQLITE_OK ) rc = rc2;
  151273. }else{
  151274. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  151275. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  151276. }
  151277. }
  151278. sqlite3Fts3SegmentsClose(p);
  151279. return rc;
  151280. }
  151281. #endif
  151282. /************** End of fts3_write.c ******************************************/
  151283. /************** Begin file fts3_snippet.c ************************************/
  151284. /*
  151285. ** 2009 Oct 23
  151286. **
  151287. ** The author disclaims copyright to this source code. In place of
  151288. ** a legal notice, here is a blessing:
  151289. **
  151290. ** May you do good and not evil.
  151291. ** May you find forgiveness for yourself and forgive others.
  151292. ** May you share freely, never taking more than you give.
  151293. **
  151294. ******************************************************************************
  151295. */
  151296. /* #include "fts3Int.h" */
  151297. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  151298. /* #include <string.h> */
  151299. /* #include <assert.h> */
  151300. /*
  151301. ** Characters that may appear in the second argument to matchinfo().
  151302. */
  151303. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  151304. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  151305. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  151306. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  151307. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  151308. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  151309. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  151310. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  151311. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  151312. /*
  151313. ** The default value for the second argument to matchinfo().
  151314. */
  151315. #define FTS3_MATCHINFO_DEFAULT "pcx"
  151316. /*
  151317. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  151318. ** Fts3Expr.aDoclist[]/nDoclist.
  151319. */
  151320. typedef struct LoadDoclistCtx LoadDoclistCtx;
  151321. struct LoadDoclistCtx {
  151322. Fts3Cursor *pCsr; /* FTS3 Cursor */
  151323. int nPhrase; /* Number of phrases seen so far */
  151324. int nToken; /* Number of tokens seen so far */
  151325. };
  151326. /*
  151327. ** The following types are used as part of the implementation of the
  151328. ** fts3BestSnippet() routine.
  151329. */
  151330. typedef struct SnippetIter SnippetIter;
  151331. typedef struct SnippetPhrase SnippetPhrase;
  151332. typedef struct SnippetFragment SnippetFragment;
  151333. struct SnippetIter {
  151334. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  151335. int iCol; /* Extract snippet from this column */
  151336. int nSnippet; /* Requested snippet length (in tokens) */
  151337. int nPhrase; /* Number of phrases in query */
  151338. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  151339. int iCurrent; /* First token of current snippet */
  151340. };
  151341. struct SnippetPhrase {
  151342. int nToken; /* Number of tokens in phrase */
  151343. char *pList; /* Pointer to start of phrase position list */
  151344. int iHead; /* Next value in position list */
  151345. char *pHead; /* Position list data following iHead */
  151346. int iTail; /* Next value in trailing position list */
  151347. char *pTail; /* Position list data following iTail */
  151348. };
  151349. struct SnippetFragment {
  151350. int iCol; /* Column snippet is extracted from */
  151351. int iPos; /* Index of first token in snippet */
  151352. u64 covered; /* Mask of query phrases covered */
  151353. u64 hlmask; /* Mask of snippet terms to highlight */
  151354. };
  151355. /*
  151356. ** This type is used as an fts3ExprIterate() context object while
  151357. ** accumulating the data returned by the matchinfo() function.
  151358. */
  151359. typedef struct MatchInfo MatchInfo;
  151360. struct MatchInfo {
  151361. Fts3Cursor *pCursor; /* FTS3 Cursor */
  151362. int nCol; /* Number of columns in table */
  151363. int nPhrase; /* Number of matchable phrases in query */
  151364. sqlite3_int64 nDoc; /* Number of docs in database */
  151365. char flag;
  151366. u32 *aMatchinfo; /* Pre-allocated buffer */
  151367. };
  151368. /*
  151369. ** An instance of this structure is used to manage a pair of buffers, each
  151370. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  151371. ** for details.
  151372. */
  151373. struct MatchinfoBuffer {
  151374. u8 aRef[3];
  151375. int nElem;
  151376. int bGlobal; /* Set if global data is loaded */
  151377. char *zMatchinfo;
  151378. u32 aMatchinfo[1];
  151379. };
  151380. /*
  151381. ** The snippet() and offsets() functions both return text values. An instance
  151382. ** of the following structure is used to accumulate those values while the
  151383. ** functions are running. See fts3StringAppend() for details.
  151384. */
  151385. typedef struct StrBuffer StrBuffer;
  151386. struct StrBuffer {
  151387. char *z; /* Pointer to buffer containing string */
  151388. int n; /* Length of z in bytes (excl. nul-term) */
  151389. int nAlloc; /* Allocated size of buffer z in bytes */
  151390. };
  151391. /*************************************************************************
  151392. ** Start of MatchinfoBuffer code.
  151393. */
  151394. /*
  151395. ** Allocate a two-slot MatchinfoBuffer object.
  151396. */
  151397. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  151398. MatchinfoBuffer *pRet;
  151399. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  151400. int nStr = (int)strlen(zMatchinfo);
  151401. pRet = sqlite3_malloc(nByte + nStr+1);
  151402. if( pRet ){
  151403. memset(pRet, 0, nByte);
  151404. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  151405. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  151406. pRet->nElem = nElem;
  151407. pRet->zMatchinfo = ((char*)pRet) + nByte;
  151408. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  151409. pRet->aRef[0] = 1;
  151410. }
  151411. return pRet;
  151412. }
  151413. static void fts3MIBufferFree(void *p){
  151414. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  151415. assert( (u32*)p==&pBuf->aMatchinfo[1]
  151416. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  151417. );
  151418. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  151419. pBuf->aRef[1] = 0;
  151420. }else{
  151421. pBuf->aRef[2] = 0;
  151422. }
  151423. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  151424. sqlite3_free(pBuf);
  151425. }
  151426. }
  151427. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  151428. void (*xRet)(void*) = 0;
  151429. u32 *aOut = 0;
  151430. if( p->aRef[1]==0 ){
  151431. p->aRef[1] = 1;
  151432. aOut = &p->aMatchinfo[1];
  151433. xRet = fts3MIBufferFree;
  151434. }
  151435. else if( p->aRef[2]==0 ){
  151436. p->aRef[2] = 1;
  151437. aOut = &p->aMatchinfo[p->nElem+2];
  151438. xRet = fts3MIBufferFree;
  151439. }else{
  151440. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  151441. if( aOut ){
  151442. xRet = sqlite3_free;
  151443. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  151444. }
  151445. }
  151446. *paOut = aOut;
  151447. return xRet;
  151448. }
  151449. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  151450. p->bGlobal = 1;
  151451. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  151452. }
  151453. /*
  151454. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  151455. */
  151456. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  151457. if( p ){
  151458. assert( p->aRef[0]==1 );
  151459. p->aRef[0] = 0;
  151460. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  151461. sqlite3_free(p);
  151462. }
  151463. }
  151464. }
  151465. /*
  151466. ** End of MatchinfoBuffer code.
  151467. *************************************************************************/
  151468. /*
  151469. ** This function is used to help iterate through a position-list. A position
  151470. ** list is a list of unique integers, sorted from smallest to largest. Each
  151471. ** element of the list is represented by an FTS3 varint that takes the value
  151472. ** of the difference between the current element and the previous one plus
  151473. ** two. For example, to store the position-list:
  151474. **
  151475. ** 4 9 113
  151476. **
  151477. ** the three varints:
  151478. **
  151479. ** 6 7 106
  151480. **
  151481. ** are encoded.
  151482. **
  151483. ** When this function is called, *pp points to the start of an element of
  151484. ** the list. *piPos contains the value of the previous entry in the list.
  151485. ** After it returns, *piPos contains the value of the next element of the
  151486. ** list and *pp is advanced to the following varint.
  151487. */
  151488. static void fts3GetDeltaPosition(char **pp, int *piPos){
  151489. int iVal;
  151490. *pp += fts3GetVarint32(*pp, &iVal);
  151491. *piPos += (iVal-2);
  151492. }
  151493. /*
  151494. ** Helper function for fts3ExprIterate() (see below).
  151495. */
  151496. static int fts3ExprIterate2(
  151497. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  151498. int *piPhrase, /* Pointer to phrase counter */
  151499. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  151500. void *pCtx /* Second argument to pass to callback */
  151501. ){
  151502. int rc; /* Return code */
  151503. int eType = pExpr->eType; /* Type of expression node pExpr */
  151504. if( eType!=FTSQUERY_PHRASE ){
  151505. assert( pExpr->pLeft && pExpr->pRight );
  151506. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  151507. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  151508. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  151509. }
  151510. }else{
  151511. rc = x(pExpr, *piPhrase, pCtx);
  151512. (*piPhrase)++;
  151513. }
  151514. return rc;
  151515. }
  151516. /*
  151517. ** Iterate through all phrase nodes in an FTS3 query, except those that
  151518. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  151519. ** For each phrase node found, the supplied callback function is invoked.
  151520. **
  151521. ** If the callback function returns anything other than SQLITE_OK,
  151522. ** the iteration is abandoned and the error code returned immediately.
  151523. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  151524. ** all eligible phrase nodes.
  151525. */
  151526. static int fts3ExprIterate(
  151527. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  151528. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  151529. void *pCtx /* Second argument to pass to callback */
  151530. ){
  151531. int iPhrase = 0; /* Variable used as the phrase counter */
  151532. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  151533. }
  151534. /*
  151535. ** This is an fts3ExprIterate() callback used while loading the doclists
  151536. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  151537. ** fts3ExprLoadDoclists().
  151538. */
  151539. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  151540. int rc = SQLITE_OK;
  151541. Fts3Phrase *pPhrase = pExpr->pPhrase;
  151542. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  151543. UNUSED_PARAMETER(iPhrase);
  151544. p->nPhrase++;
  151545. p->nToken += pPhrase->nToken;
  151546. return rc;
  151547. }
  151548. /*
  151549. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  151550. ** pCsr.
  151551. **
  151552. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  151553. ** phrases in the expression (all phrases except those directly or
  151554. ** indirectly descended from the right-hand-side of a NOT operator). If
  151555. ** pnToken is not NULL, then it is set to the number of tokens in all
  151556. ** matchable phrases of the expression.
  151557. */
  151558. static int fts3ExprLoadDoclists(
  151559. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  151560. int *pnPhrase, /* OUT: Number of phrases in query */
  151561. int *pnToken /* OUT: Number of tokens in query */
  151562. ){
  151563. int rc; /* Return Code */
  151564. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  151565. sCtx.pCsr = pCsr;
  151566. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  151567. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  151568. if( pnToken ) *pnToken = sCtx.nToken;
  151569. return rc;
  151570. }
  151571. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  151572. (*(int *)ctx)++;
  151573. pExpr->iPhrase = iPhrase;
  151574. return SQLITE_OK;
  151575. }
  151576. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  151577. int nPhrase = 0;
  151578. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  151579. return nPhrase;
  151580. }
  151581. /*
  151582. ** Advance the position list iterator specified by the first two
  151583. ** arguments so that it points to the first element with a value greater
  151584. ** than or equal to parameter iNext.
  151585. */
  151586. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  151587. char *pIter = *ppIter;
  151588. if( pIter ){
  151589. int iIter = *piIter;
  151590. while( iIter<iNext ){
  151591. if( 0==(*pIter & 0xFE) ){
  151592. iIter = -1;
  151593. pIter = 0;
  151594. break;
  151595. }
  151596. fts3GetDeltaPosition(&pIter, &iIter);
  151597. }
  151598. *piIter = iIter;
  151599. *ppIter = pIter;
  151600. }
  151601. }
  151602. /*
  151603. ** Advance the snippet iterator to the next candidate snippet.
  151604. */
  151605. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  151606. int i; /* Loop counter */
  151607. if( pIter->iCurrent<0 ){
  151608. /* The SnippetIter object has just been initialized. The first snippet
  151609. ** candidate always starts at offset 0 (even if this candidate has a
  151610. ** score of 0.0).
  151611. */
  151612. pIter->iCurrent = 0;
  151613. /* Advance the 'head' iterator of each phrase to the first offset that
  151614. ** is greater than or equal to (iNext+nSnippet).
  151615. */
  151616. for(i=0; i<pIter->nPhrase; i++){
  151617. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  151618. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  151619. }
  151620. }else{
  151621. int iStart;
  151622. int iEnd = 0x7FFFFFFF;
  151623. for(i=0; i<pIter->nPhrase; i++){
  151624. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  151625. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  151626. iEnd = pPhrase->iHead;
  151627. }
  151628. }
  151629. if( iEnd==0x7FFFFFFF ){
  151630. return 1;
  151631. }
  151632. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  151633. for(i=0; i<pIter->nPhrase; i++){
  151634. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  151635. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  151636. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  151637. }
  151638. }
  151639. return 0;
  151640. }
  151641. /*
  151642. ** Retrieve information about the current candidate snippet of snippet
  151643. ** iterator pIter.
  151644. */
  151645. static void fts3SnippetDetails(
  151646. SnippetIter *pIter, /* Snippet iterator */
  151647. u64 mCovered, /* Bitmask of phrases already covered */
  151648. int *piToken, /* OUT: First token of proposed snippet */
  151649. int *piScore, /* OUT: "Score" for this snippet */
  151650. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  151651. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  151652. ){
  151653. int iStart = pIter->iCurrent; /* First token of snippet */
  151654. int iScore = 0; /* Score of this snippet */
  151655. int i; /* Loop counter */
  151656. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  151657. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  151658. for(i=0; i<pIter->nPhrase; i++){
  151659. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  151660. if( pPhrase->pTail ){
  151661. char *pCsr = pPhrase->pTail;
  151662. int iCsr = pPhrase->iTail;
  151663. while( iCsr<(iStart+pIter->nSnippet) ){
  151664. int j;
  151665. u64 mPhrase = (u64)1 << i;
  151666. u64 mPos = (u64)1 << (iCsr - iStart);
  151667. assert( iCsr>=iStart );
  151668. if( (mCover|mCovered)&mPhrase ){
  151669. iScore++;
  151670. }else{
  151671. iScore += 1000;
  151672. }
  151673. mCover |= mPhrase;
  151674. for(j=0; j<pPhrase->nToken; j++){
  151675. mHighlight |= (mPos>>j);
  151676. }
  151677. if( 0==(*pCsr & 0x0FE) ) break;
  151678. fts3GetDeltaPosition(&pCsr, &iCsr);
  151679. }
  151680. }
  151681. }
  151682. /* Set the output variables before returning. */
  151683. *piToken = iStart;
  151684. *piScore = iScore;
  151685. *pmCover = mCover;
  151686. *pmHighlight = mHighlight;
  151687. }
  151688. /*
  151689. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  151690. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  151691. */
  151692. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  151693. SnippetIter *p = (SnippetIter *)ctx;
  151694. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  151695. char *pCsr;
  151696. int rc;
  151697. pPhrase->nToken = pExpr->pPhrase->nToken;
  151698. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  151699. assert( rc==SQLITE_OK || pCsr==0 );
  151700. if( pCsr ){
  151701. int iFirst = 0;
  151702. pPhrase->pList = pCsr;
  151703. fts3GetDeltaPosition(&pCsr, &iFirst);
  151704. assert( iFirst>=0 );
  151705. pPhrase->pHead = pCsr;
  151706. pPhrase->pTail = pCsr;
  151707. pPhrase->iHead = iFirst;
  151708. pPhrase->iTail = iFirst;
  151709. }else{
  151710. assert( rc!=SQLITE_OK || (
  151711. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  151712. ));
  151713. }
  151714. return rc;
  151715. }
  151716. /*
  151717. ** Select the fragment of text consisting of nFragment contiguous tokens
  151718. ** from column iCol that represent the "best" snippet. The best snippet
  151719. ** is the snippet with the highest score, where scores are calculated
  151720. ** by adding:
  151721. **
  151722. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  151723. **
  151724. ** (b) +1000 points for the first occurrence of each matchable phrase in
  151725. ** the snippet for which the corresponding mCovered bit is not set.
  151726. **
  151727. ** The selected snippet parameters are stored in structure *pFragment before
  151728. ** returning. The score of the selected snippet is stored in *piScore
  151729. ** before returning.
  151730. */
  151731. static int fts3BestSnippet(
  151732. int nSnippet, /* Desired snippet length */
  151733. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  151734. int iCol, /* Index of column to create snippet from */
  151735. u64 mCovered, /* Mask of phrases already covered */
  151736. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  151737. SnippetFragment *pFragment, /* OUT: Best snippet found */
  151738. int *piScore /* OUT: Score of snippet pFragment */
  151739. ){
  151740. int rc; /* Return Code */
  151741. int nList; /* Number of phrases in expression */
  151742. SnippetIter sIter; /* Iterates through snippet candidates */
  151743. int nByte; /* Number of bytes of space to allocate */
  151744. int iBestScore = -1; /* Best snippet score found so far */
  151745. int i; /* Loop counter */
  151746. memset(&sIter, 0, sizeof(sIter));
  151747. /* Iterate through the phrases in the expression to count them. The same
  151748. ** callback makes sure the doclists are loaded for each phrase.
  151749. */
  151750. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  151751. if( rc!=SQLITE_OK ){
  151752. return rc;
  151753. }
  151754. /* Now that it is known how many phrases there are, allocate and zero
  151755. ** the required space using malloc().
  151756. */
  151757. nByte = sizeof(SnippetPhrase) * nList;
  151758. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  151759. if( !sIter.aPhrase ){
  151760. return SQLITE_NOMEM;
  151761. }
  151762. memset(sIter.aPhrase, 0, nByte);
  151763. /* Initialize the contents of the SnippetIter object. Then iterate through
  151764. ** the set of phrases in the expression to populate the aPhrase[] array.
  151765. */
  151766. sIter.pCsr = pCsr;
  151767. sIter.iCol = iCol;
  151768. sIter.nSnippet = nSnippet;
  151769. sIter.nPhrase = nList;
  151770. sIter.iCurrent = -1;
  151771. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  151772. if( rc==SQLITE_OK ){
  151773. /* Set the *pmSeen output variable. */
  151774. for(i=0; i<nList; i++){
  151775. if( sIter.aPhrase[i].pHead ){
  151776. *pmSeen |= (u64)1 << i;
  151777. }
  151778. }
  151779. /* Loop through all candidate snippets. Store the best snippet in
  151780. ** *pFragment. Store its associated 'score' in iBestScore.
  151781. */
  151782. pFragment->iCol = iCol;
  151783. while( !fts3SnippetNextCandidate(&sIter) ){
  151784. int iPos;
  151785. int iScore;
  151786. u64 mCover;
  151787. u64 mHighlite;
  151788. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  151789. assert( iScore>=0 );
  151790. if( iScore>iBestScore ){
  151791. pFragment->iPos = iPos;
  151792. pFragment->hlmask = mHighlite;
  151793. pFragment->covered = mCover;
  151794. iBestScore = iScore;
  151795. }
  151796. }
  151797. *piScore = iBestScore;
  151798. }
  151799. sqlite3_free(sIter.aPhrase);
  151800. return rc;
  151801. }
  151802. /*
  151803. ** Append a string to the string-buffer passed as the first argument.
  151804. **
  151805. ** If nAppend is negative, then the length of the string zAppend is
  151806. ** determined using strlen().
  151807. */
  151808. static int fts3StringAppend(
  151809. StrBuffer *pStr, /* Buffer to append to */
  151810. const char *zAppend, /* Pointer to data to append to buffer */
  151811. int nAppend /* Size of zAppend in bytes (or -1) */
  151812. ){
  151813. if( nAppend<0 ){
  151814. nAppend = (int)strlen(zAppend);
  151815. }
  151816. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  151817. ** to grow the buffer until so that it is big enough to accomadate the
  151818. ** appended data.
  151819. */
  151820. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  151821. int nAlloc = pStr->nAlloc+nAppend+100;
  151822. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  151823. if( !zNew ){
  151824. return SQLITE_NOMEM;
  151825. }
  151826. pStr->z = zNew;
  151827. pStr->nAlloc = nAlloc;
  151828. }
  151829. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  151830. /* Append the data to the string buffer. */
  151831. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  151832. pStr->n += nAppend;
  151833. pStr->z[pStr->n] = '\0';
  151834. return SQLITE_OK;
  151835. }
  151836. /*
  151837. ** The fts3BestSnippet() function often selects snippets that end with a
  151838. ** query term. That is, the final term of the snippet is always a term
  151839. ** that requires highlighting. For example, if 'X' is a highlighted term
  151840. ** and '.' is a non-highlighted term, BestSnippet() may select:
  151841. **
  151842. ** ........X.....X
  151843. **
  151844. ** This function "shifts" the beginning of the snippet forward in the
  151845. ** document so that there are approximately the same number of
  151846. ** non-highlighted terms to the right of the final highlighted term as there
  151847. ** are to the left of the first highlighted term. For example, to this:
  151848. **
  151849. ** ....X.....X....
  151850. **
  151851. ** This is done as part of extracting the snippet text, not when selecting
  151852. ** the snippet. Snippet selection is done based on doclists only, so there
  151853. ** is no way for fts3BestSnippet() to know whether or not the document
  151854. ** actually contains terms that follow the final highlighted term.
  151855. */
  151856. static int fts3SnippetShift(
  151857. Fts3Table *pTab, /* FTS3 table snippet comes from */
  151858. int iLangid, /* Language id to use in tokenizing */
  151859. int nSnippet, /* Number of tokens desired for snippet */
  151860. const char *zDoc, /* Document text to extract snippet from */
  151861. int nDoc, /* Size of buffer zDoc in bytes */
  151862. int *piPos, /* IN/OUT: First token of snippet */
  151863. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  151864. ){
  151865. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  151866. if( hlmask ){
  151867. int nLeft; /* Tokens to the left of first highlight */
  151868. int nRight; /* Tokens to the right of last highlight */
  151869. int nDesired; /* Ideal number of tokens to shift forward */
  151870. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  151871. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  151872. nDesired = (nLeft-nRight)/2;
  151873. /* Ideally, the start of the snippet should be pushed forward in the
  151874. ** document nDesired tokens. This block checks if there are actually
  151875. ** nDesired tokens to the right of the snippet. If so, *piPos and
  151876. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  151877. ** right. Otherwise, the snippet is shifted by the number of tokens
  151878. ** available.
  151879. */
  151880. if( nDesired>0 ){
  151881. int nShift; /* Number of tokens to shift snippet by */
  151882. int iCurrent = 0; /* Token counter */
  151883. int rc; /* Return Code */
  151884. sqlite3_tokenizer_module *pMod;
  151885. sqlite3_tokenizer_cursor *pC;
  151886. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  151887. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  151888. ** or more tokens in zDoc/nDoc.
  151889. */
  151890. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  151891. if( rc!=SQLITE_OK ){
  151892. return rc;
  151893. }
  151894. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  151895. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  151896. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  151897. }
  151898. pMod->xClose(pC);
  151899. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  151900. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  151901. assert( nShift<=nDesired );
  151902. if( nShift>0 ){
  151903. *piPos += nShift;
  151904. *pHlmask = hlmask >> nShift;
  151905. }
  151906. }
  151907. }
  151908. return SQLITE_OK;
  151909. }
  151910. /*
  151911. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  151912. ** append it to string buffer pOut.
  151913. */
  151914. static int fts3SnippetText(
  151915. Fts3Cursor *pCsr, /* FTS3 Cursor */
  151916. SnippetFragment *pFragment, /* Snippet to extract */
  151917. int iFragment, /* Fragment number */
  151918. int isLast, /* True for final fragment in snippet */
  151919. int nSnippet, /* Number of tokens in extracted snippet */
  151920. const char *zOpen, /* String inserted before highlighted term */
  151921. const char *zClose, /* String inserted after highlighted term */
  151922. const char *zEllipsis, /* String inserted between snippets */
  151923. StrBuffer *pOut /* Write output here */
  151924. ){
  151925. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  151926. int rc; /* Return code */
  151927. const char *zDoc; /* Document text to extract snippet from */
  151928. int nDoc; /* Size of zDoc in bytes */
  151929. int iCurrent = 0; /* Current token number of document */
  151930. int iEnd = 0; /* Byte offset of end of current token */
  151931. int isShiftDone = 0; /* True after snippet is shifted */
  151932. int iPos = pFragment->iPos; /* First token of snippet */
  151933. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  151934. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  151935. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  151936. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  151937. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  151938. if( zDoc==0 ){
  151939. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  151940. return SQLITE_NOMEM;
  151941. }
  151942. return SQLITE_OK;
  151943. }
  151944. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  151945. /* Open a token cursor on the document. */
  151946. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  151947. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  151948. if( rc!=SQLITE_OK ){
  151949. return rc;
  151950. }
  151951. while( rc==SQLITE_OK ){
  151952. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  151953. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  151954. int iBegin = 0; /* Offset in zDoc of start of token */
  151955. int iFin = 0; /* Offset in zDoc of end of token */
  151956. int isHighlight = 0; /* True for highlighted terms */
  151957. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  151958. ** in the FTS code the variable that the third argument to xNext points to
  151959. ** is initialized to zero before the first (*but not necessarily
  151960. ** subsequent*) call to xNext(). This is done for a particular application
  151961. ** that needs to know whether or not the tokenizer is being used for
  151962. ** snippet generation or for some other purpose.
  151963. **
  151964. ** Extreme care is required when writing code to depend on this
  151965. ** initialization. It is not a documented part of the tokenizer interface.
  151966. ** If a tokenizer is used directly by any code outside of FTS, this
  151967. ** convention might not be respected. */
  151968. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  151969. if( rc!=SQLITE_OK ){
  151970. if( rc==SQLITE_DONE ){
  151971. /* Special case - the last token of the snippet is also the last token
  151972. ** of the column. Append any punctuation that occurred between the end
  151973. ** of the previous token and the end of the document to the output.
  151974. ** Then break out of the loop. */
  151975. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  151976. }
  151977. break;
  151978. }
  151979. if( iCurrent<iPos ){ continue; }
  151980. if( !isShiftDone ){
  151981. int n = nDoc - iBegin;
  151982. rc = fts3SnippetShift(
  151983. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  151984. );
  151985. isShiftDone = 1;
  151986. /* Now that the shift has been done, check if the initial "..." are
  151987. ** required. They are required if (a) this is not the first fragment,
  151988. ** or (b) this fragment does not begin at position 0 of its column.
  151989. */
  151990. if( rc==SQLITE_OK ){
  151991. if( iPos>0 || iFragment>0 ){
  151992. rc = fts3StringAppend(pOut, zEllipsis, -1);
  151993. }else if( iBegin ){
  151994. rc = fts3StringAppend(pOut, zDoc, iBegin);
  151995. }
  151996. }
  151997. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  151998. }
  151999. if( iCurrent>=(iPos+nSnippet) ){
  152000. if( isLast ){
  152001. rc = fts3StringAppend(pOut, zEllipsis, -1);
  152002. }
  152003. break;
  152004. }
  152005. /* Set isHighlight to true if this term should be highlighted. */
  152006. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  152007. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  152008. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  152009. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  152010. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  152011. iEnd = iFin;
  152012. }
  152013. pMod->xClose(pC);
  152014. return rc;
  152015. }
  152016. /*
  152017. ** This function is used to count the entries in a column-list (a
  152018. ** delta-encoded list of term offsets within a single column of a single
  152019. ** row). When this function is called, *ppCollist should point to the
  152020. ** beginning of the first varint in the column-list (the varint that
  152021. ** contains the position of the first matching term in the column data).
  152022. ** Before returning, *ppCollist is set to point to the first byte after
  152023. ** the last varint in the column-list (either the 0x00 signifying the end
  152024. ** of the position-list, or the 0x01 that precedes the column number of
  152025. ** the next column in the position-list).
  152026. **
  152027. ** The number of elements in the column-list is returned.
  152028. */
  152029. static int fts3ColumnlistCount(char **ppCollist){
  152030. char *pEnd = *ppCollist;
  152031. char c = 0;
  152032. int nEntry = 0;
  152033. /* A column-list is terminated by either a 0x01 or 0x00. */
  152034. while( 0xFE & (*pEnd | c) ){
  152035. c = *pEnd++ & 0x80;
  152036. if( !c ) nEntry++;
  152037. }
  152038. *ppCollist = pEnd;
  152039. return nEntry;
  152040. }
  152041. /*
  152042. ** This function gathers 'y' or 'b' data for a single phrase.
  152043. */
  152044. static void fts3ExprLHits(
  152045. Fts3Expr *pExpr, /* Phrase expression node */
  152046. MatchInfo *p /* Matchinfo context */
  152047. ){
  152048. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  152049. int iStart;
  152050. Fts3Phrase *pPhrase = pExpr->pPhrase;
  152051. char *pIter = pPhrase->doclist.pList;
  152052. int iCol = 0;
  152053. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  152054. if( p->flag==FTS3_MATCHINFO_LHITS ){
  152055. iStart = pExpr->iPhrase * p->nCol;
  152056. }else{
  152057. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  152058. }
  152059. while( 1 ){
  152060. int nHit = fts3ColumnlistCount(&pIter);
  152061. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  152062. if( p->flag==FTS3_MATCHINFO_LHITS ){
  152063. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  152064. }else if( nHit ){
  152065. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  152066. }
  152067. }
  152068. assert( *pIter==0x00 || *pIter==0x01 );
  152069. if( *pIter!=0x01 ) break;
  152070. pIter++;
  152071. pIter += fts3GetVarint32(pIter, &iCol);
  152072. }
  152073. }
  152074. /*
  152075. ** Gather the results for matchinfo directives 'y' and 'b'.
  152076. */
  152077. static void fts3ExprLHitGather(
  152078. Fts3Expr *pExpr,
  152079. MatchInfo *p
  152080. ){
  152081. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  152082. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  152083. if( pExpr->pLeft ){
  152084. fts3ExprLHitGather(pExpr->pLeft, p);
  152085. fts3ExprLHitGather(pExpr->pRight, p);
  152086. }else{
  152087. fts3ExprLHits(pExpr, p);
  152088. }
  152089. }
  152090. }
  152091. /*
  152092. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  152093. ** for a single query.
  152094. **
  152095. ** fts3ExprIterate() callback to load the 'global' elements of a
  152096. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  152097. ** of the matchinfo array that are constant for all rows returned by the
  152098. ** current query.
  152099. **
  152100. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  152101. ** function populates Matchinfo.aMatchinfo[] as follows:
  152102. **
  152103. ** for(iCol=0; iCol<nCol; iCol++){
  152104. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  152105. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  152106. ** }
  152107. **
  152108. ** where X is the number of matches for phrase iPhrase is column iCol of all
  152109. ** rows of the table. Y is the number of rows for which column iCol contains
  152110. ** at least one instance of phrase iPhrase.
  152111. **
  152112. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  152113. ** Y values are set to nDoc, where nDoc is the number of documents in the
  152114. ** file system. This is done because the full-text index doclist is required
  152115. ** to calculate these values properly, and the full-text index doclist is
  152116. ** not available for deferred tokens.
  152117. */
  152118. static int fts3ExprGlobalHitsCb(
  152119. Fts3Expr *pExpr, /* Phrase expression node */
  152120. int iPhrase, /* Phrase number (numbered from zero) */
  152121. void *pCtx /* Pointer to MatchInfo structure */
  152122. ){
  152123. MatchInfo *p = (MatchInfo *)pCtx;
  152124. return sqlite3Fts3EvalPhraseStats(
  152125. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  152126. );
  152127. }
  152128. /*
  152129. ** fts3ExprIterate() callback used to collect the "local" part of the
  152130. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  152131. ** array that are different for each row returned by the query.
  152132. */
  152133. static int fts3ExprLocalHitsCb(
  152134. Fts3Expr *pExpr, /* Phrase expression node */
  152135. int iPhrase, /* Phrase number */
  152136. void *pCtx /* Pointer to MatchInfo structure */
  152137. ){
  152138. int rc = SQLITE_OK;
  152139. MatchInfo *p = (MatchInfo *)pCtx;
  152140. int iStart = iPhrase * p->nCol * 3;
  152141. int i;
  152142. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  152143. char *pCsr;
  152144. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  152145. if( pCsr ){
  152146. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  152147. }else{
  152148. p->aMatchinfo[iStart+i*3] = 0;
  152149. }
  152150. }
  152151. return rc;
  152152. }
  152153. static int fts3MatchinfoCheck(
  152154. Fts3Table *pTab,
  152155. char cArg,
  152156. char **pzErr
  152157. ){
  152158. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  152159. || (cArg==FTS3_MATCHINFO_NCOL)
  152160. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  152161. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  152162. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  152163. || (cArg==FTS3_MATCHINFO_LCS)
  152164. || (cArg==FTS3_MATCHINFO_HITS)
  152165. || (cArg==FTS3_MATCHINFO_LHITS)
  152166. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  152167. ){
  152168. return SQLITE_OK;
  152169. }
  152170. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  152171. return SQLITE_ERROR;
  152172. }
  152173. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  152174. int nVal; /* Number of integers output by cArg */
  152175. switch( cArg ){
  152176. case FTS3_MATCHINFO_NDOC:
  152177. case FTS3_MATCHINFO_NPHRASE:
  152178. case FTS3_MATCHINFO_NCOL:
  152179. nVal = 1;
  152180. break;
  152181. case FTS3_MATCHINFO_AVGLENGTH:
  152182. case FTS3_MATCHINFO_LENGTH:
  152183. case FTS3_MATCHINFO_LCS:
  152184. nVal = pInfo->nCol;
  152185. break;
  152186. case FTS3_MATCHINFO_LHITS:
  152187. nVal = pInfo->nCol * pInfo->nPhrase;
  152188. break;
  152189. case FTS3_MATCHINFO_LHITS_BM:
  152190. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  152191. break;
  152192. default:
  152193. assert( cArg==FTS3_MATCHINFO_HITS );
  152194. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  152195. break;
  152196. }
  152197. return nVal;
  152198. }
  152199. static int fts3MatchinfoSelectDoctotal(
  152200. Fts3Table *pTab,
  152201. sqlite3_stmt **ppStmt,
  152202. sqlite3_int64 *pnDoc,
  152203. const char **paLen
  152204. ){
  152205. sqlite3_stmt *pStmt;
  152206. const char *a;
  152207. sqlite3_int64 nDoc;
  152208. if( !*ppStmt ){
  152209. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  152210. if( rc!=SQLITE_OK ) return rc;
  152211. }
  152212. pStmt = *ppStmt;
  152213. assert( sqlite3_data_count(pStmt)==1 );
  152214. a = sqlite3_column_blob(pStmt, 0);
  152215. a += sqlite3Fts3GetVarint(a, &nDoc);
  152216. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  152217. *pnDoc = (u32)nDoc;
  152218. if( paLen ) *paLen = a;
  152219. return SQLITE_OK;
  152220. }
  152221. /*
  152222. ** An instance of the following structure is used to store state while
  152223. ** iterating through a multi-column position-list corresponding to the
  152224. ** hits for a single phrase on a single row in order to calculate the
  152225. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  152226. */
  152227. typedef struct LcsIterator LcsIterator;
  152228. struct LcsIterator {
  152229. Fts3Expr *pExpr; /* Pointer to phrase expression */
  152230. int iPosOffset; /* Tokens count up to end of this phrase */
  152231. char *pRead; /* Cursor used to iterate through aDoclist */
  152232. int iPos; /* Current position */
  152233. };
  152234. /*
  152235. ** If LcsIterator.iCol is set to the following value, the iterator has
  152236. ** finished iterating through all offsets for all columns.
  152237. */
  152238. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  152239. static int fts3MatchinfoLcsCb(
  152240. Fts3Expr *pExpr, /* Phrase expression node */
  152241. int iPhrase, /* Phrase number (numbered from zero) */
  152242. void *pCtx /* Pointer to MatchInfo structure */
  152243. ){
  152244. LcsIterator *aIter = (LcsIterator *)pCtx;
  152245. aIter[iPhrase].pExpr = pExpr;
  152246. return SQLITE_OK;
  152247. }
  152248. /*
  152249. ** Advance the iterator passed as an argument to the next position. Return
  152250. ** 1 if the iterator is at EOF or if it now points to the start of the
  152251. ** position list for the next column.
  152252. */
  152253. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  152254. char *pRead = pIter->pRead;
  152255. sqlite3_int64 iRead;
  152256. int rc = 0;
  152257. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  152258. if( iRead==0 || iRead==1 ){
  152259. pRead = 0;
  152260. rc = 1;
  152261. }else{
  152262. pIter->iPos += (int)(iRead-2);
  152263. }
  152264. pIter->pRead = pRead;
  152265. return rc;
  152266. }
  152267. /*
  152268. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  152269. **
  152270. ** If the call is successful, the longest-common-substring lengths for each
  152271. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  152272. ** array before returning. SQLITE_OK is returned in this case.
  152273. **
  152274. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  152275. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  152276. ** undefined.
  152277. */
  152278. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  152279. LcsIterator *aIter;
  152280. int i;
  152281. int iCol;
  152282. int nToken = 0;
  152283. /* Allocate and populate the array of LcsIterator objects. The array
  152284. ** contains one element for each matchable phrase in the query.
  152285. **/
  152286. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  152287. if( !aIter ) return SQLITE_NOMEM;
  152288. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  152289. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  152290. for(i=0; i<pInfo->nPhrase; i++){
  152291. LcsIterator *pIter = &aIter[i];
  152292. nToken -= pIter->pExpr->pPhrase->nToken;
  152293. pIter->iPosOffset = nToken;
  152294. }
  152295. for(iCol=0; iCol<pInfo->nCol; iCol++){
  152296. int nLcs = 0; /* LCS value for this column */
  152297. int nLive = 0; /* Number of iterators in aIter not at EOF */
  152298. for(i=0; i<pInfo->nPhrase; i++){
  152299. int rc;
  152300. LcsIterator *pIt = &aIter[i];
  152301. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  152302. if( rc!=SQLITE_OK ) return rc;
  152303. if( pIt->pRead ){
  152304. pIt->iPos = pIt->iPosOffset;
  152305. fts3LcsIteratorAdvance(&aIter[i]);
  152306. nLive++;
  152307. }
  152308. }
  152309. while( nLive>0 ){
  152310. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  152311. int nThisLcs = 0; /* LCS for the current iterator positions */
  152312. for(i=0; i<pInfo->nPhrase; i++){
  152313. LcsIterator *pIter = &aIter[i];
  152314. if( pIter->pRead==0 ){
  152315. /* This iterator is already at EOF for this column. */
  152316. nThisLcs = 0;
  152317. }else{
  152318. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  152319. pAdv = pIter;
  152320. }
  152321. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  152322. nThisLcs++;
  152323. }else{
  152324. nThisLcs = 1;
  152325. }
  152326. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  152327. }
  152328. }
  152329. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  152330. }
  152331. pInfo->aMatchinfo[iCol] = nLcs;
  152332. }
  152333. sqlite3_free(aIter);
  152334. return SQLITE_OK;
  152335. }
  152336. /*
  152337. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  152338. ** be returned by the matchinfo() function. Argument zArg contains the
  152339. ** format string passed as the second argument to matchinfo (or the
  152340. ** default value "pcx" if no second argument was specified). The format
  152341. ** string has already been validated and the pInfo->aMatchinfo[] array
  152342. ** is guaranteed to be large enough for the output.
  152343. **
  152344. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  152345. ** If it is false, then assume that those fields that do not change between
  152346. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  152347. ** have already been populated.
  152348. **
  152349. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  152350. ** occurs. If a value other than SQLITE_OK is returned, the state the
  152351. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  152352. */
  152353. static int fts3MatchinfoValues(
  152354. Fts3Cursor *pCsr, /* FTS3 cursor object */
  152355. int bGlobal, /* True to grab the global stats */
  152356. MatchInfo *pInfo, /* Matchinfo context object */
  152357. const char *zArg /* Matchinfo format string */
  152358. ){
  152359. int rc = SQLITE_OK;
  152360. int i;
  152361. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152362. sqlite3_stmt *pSelect = 0;
  152363. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  152364. pInfo->flag = zArg[i];
  152365. switch( zArg[i] ){
  152366. case FTS3_MATCHINFO_NPHRASE:
  152367. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  152368. break;
  152369. case FTS3_MATCHINFO_NCOL:
  152370. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  152371. break;
  152372. case FTS3_MATCHINFO_NDOC:
  152373. if( bGlobal ){
  152374. sqlite3_int64 nDoc = 0;
  152375. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  152376. pInfo->aMatchinfo[0] = (u32)nDoc;
  152377. }
  152378. break;
  152379. case FTS3_MATCHINFO_AVGLENGTH:
  152380. if( bGlobal ){
  152381. sqlite3_int64 nDoc; /* Number of rows in table */
  152382. const char *a; /* Aggregate column length array */
  152383. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  152384. if( rc==SQLITE_OK ){
  152385. int iCol;
  152386. for(iCol=0; iCol<pInfo->nCol; iCol++){
  152387. u32 iVal;
  152388. sqlite3_int64 nToken;
  152389. a += sqlite3Fts3GetVarint(a, &nToken);
  152390. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  152391. pInfo->aMatchinfo[iCol] = iVal;
  152392. }
  152393. }
  152394. }
  152395. break;
  152396. case FTS3_MATCHINFO_LENGTH: {
  152397. sqlite3_stmt *pSelectDocsize = 0;
  152398. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  152399. if( rc==SQLITE_OK ){
  152400. int iCol;
  152401. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  152402. for(iCol=0; iCol<pInfo->nCol; iCol++){
  152403. sqlite3_int64 nToken;
  152404. a += sqlite3Fts3GetVarint(a, &nToken);
  152405. pInfo->aMatchinfo[iCol] = (u32)nToken;
  152406. }
  152407. }
  152408. sqlite3_reset(pSelectDocsize);
  152409. break;
  152410. }
  152411. case FTS3_MATCHINFO_LCS:
  152412. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  152413. if( rc==SQLITE_OK ){
  152414. rc = fts3MatchinfoLcs(pCsr, pInfo);
  152415. }
  152416. break;
  152417. case FTS3_MATCHINFO_LHITS_BM:
  152418. case FTS3_MATCHINFO_LHITS: {
  152419. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  152420. memset(pInfo->aMatchinfo, 0, nZero);
  152421. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  152422. break;
  152423. }
  152424. default: {
  152425. Fts3Expr *pExpr;
  152426. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  152427. pExpr = pCsr->pExpr;
  152428. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  152429. if( rc!=SQLITE_OK ) break;
  152430. if( bGlobal ){
  152431. if( pCsr->pDeferred ){
  152432. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  152433. if( rc!=SQLITE_OK ) break;
  152434. }
  152435. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  152436. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  152437. if( rc!=SQLITE_OK ) break;
  152438. }
  152439. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  152440. break;
  152441. }
  152442. }
  152443. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  152444. }
  152445. sqlite3_reset(pSelect);
  152446. return rc;
  152447. }
  152448. /*
  152449. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  152450. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  152451. */
  152452. static void fts3GetMatchinfo(
  152453. sqlite3_context *pCtx, /* Return results here */
  152454. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  152455. const char *zArg /* Second argument to matchinfo() function */
  152456. ){
  152457. MatchInfo sInfo;
  152458. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152459. int rc = SQLITE_OK;
  152460. int bGlobal = 0; /* Collect 'global' stats as well as local */
  152461. u32 *aOut = 0;
  152462. void (*xDestroyOut)(void*) = 0;
  152463. memset(&sInfo, 0, sizeof(MatchInfo));
  152464. sInfo.pCursor = pCsr;
  152465. sInfo.nCol = pTab->nColumn;
  152466. /* If there is cached matchinfo() data, but the format string for the
  152467. ** cache does not match the format string for this request, discard
  152468. ** the cached data. */
  152469. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  152470. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  152471. pCsr->pMIBuffer = 0;
  152472. }
  152473. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  152474. ** matchinfo function has been called for this query. In this case
  152475. ** allocate the array used to accumulate the matchinfo data and
  152476. ** initialize those elements that are constant for every row.
  152477. */
  152478. if( pCsr->pMIBuffer==0 ){
  152479. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  152480. int i; /* Used to iterate through zArg */
  152481. /* Determine the number of phrases in the query */
  152482. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  152483. sInfo.nPhrase = pCsr->nPhrase;
  152484. /* Determine the number of integers in the buffer returned by this call. */
  152485. for(i=0; zArg[i]; i++){
  152486. char *zErr = 0;
  152487. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  152488. sqlite3_result_error(pCtx, zErr, -1);
  152489. sqlite3_free(zErr);
  152490. return;
  152491. }
  152492. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  152493. }
  152494. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  152495. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  152496. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  152497. pCsr->isMatchinfoNeeded = 1;
  152498. bGlobal = 1;
  152499. }
  152500. if( rc==SQLITE_OK ){
  152501. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  152502. if( xDestroyOut==0 ){
  152503. rc = SQLITE_NOMEM;
  152504. }
  152505. }
  152506. if( rc==SQLITE_OK ){
  152507. sInfo.aMatchinfo = aOut;
  152508. sInfo.nPhrase = pCsr->nPhrase;
  152509. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  152510. if( bGlobal ){
  152511. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  152512. }
  152513. }
  152514. if( rc!=SQLITE_OK ){
  152515. sqlite3_result_error_code(pCtx, rc);
  152516. if( xDestroyOut ) xDestroyOut(aOut);
  152517. }else{
  152518. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  152519. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  152520. }
  152521. }
  152522. /*
  152523. ** Implementation of snippet() function.
  152524. */
  152525. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  152526. sqlite3_context *pCtx, /* SQLite function call context */
  152527. Fts3Cursor *pCsr, /* Cursor object */
  152528. const char *zStart, /* Snippet start text - "<b>" */
  152529. const char *zEnd, /* Snippet end text - "</b>" */
  152530. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  152531. int iCol, /* Extract snippet from this column */
  152532. int nToken /* Approximate number of tokens in snippet */
  152533. ){
  152534. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152535. int rc = SQLITE_OK;
  152536. int i;
  152537. StrBuffer res = {0, 0, 0};
  152538. /* The returned text includes up to four fragments of text extracted from
  152539. ** the data in the current row. The first iteration of the for(...) loop
  152540. ** below attempts to locate a single fragment of text nToken tokens in
  152541. ** size that contains at least one instance of all phrases in the query
  152542. ** expression that appear in the current row. If such a fragment of text
  152543. ** cannot be found, the second iteration of the loop attempts to locate
  152544. ** a pair of fragments, and so on.
  152545. */
  152546. int nSnippet = 0; /* Number of fragments in this snippet */
  152547. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  152548. int nFToken = -1; /* Number of tokens in each fragment */
  152549. if( !pCsr->pExpr ){
  152550. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  152551. return;
  152552. }
  152553. for(nSnippet=1; 1; nSnippet++){
  152554. int iSnip; /* Loop counter 0..nSnippet-1 */
  152555. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  152556. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  152557. if( nToken>=0 ){
  152558. nFToken = (nToken+nSnippet-1) / nSnippet;
  152559. }else{
  152560. nFToken = -1 * nToken;
  152561. }
  152562. for(iSnip=0; iSnip<nSnippet; iSnip++){
  152563. int iBestScore = -1; /* Best score of columns checked so far */
  152564. int iRead; /* Used to iterate through columns */
  152565. SnippetFragment *pFragment = &aSnippet[iSnip];
  152566. memset(pFragment, 0, sizeof(*pFragment));
  152567. /* Loop through all columns of the table being considered for snippets.
  152568. ** If the iCol argument to this function was negative, this means all
  152569. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  152570. */
  152571. for(iRead=0; iRead<pTab->nColumn; iRead++){
  152572. SnippetFragment sF = {0, 0, 0, 0};
  152573. int iS = 0;
  152574. if( iCol>=0 && iRead!=iCol ) continue;
  152575. /* Find the best snippet of nFToken tokens in column iRead. */
  152576. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  152577. if( rc!=SQLITE_OK ){
  152578. goto snippet_out;
  152579. }
  152580. if( iS>iBestScore ){
  152581. *pFragment = sF;
  152582. iBestScore = iS;
  152583. }
  152584. }
  152585. mCovered |= pFragment->covered;
  152586. }
  152587. /* If all query phrases seen by fts3BestSnippet() are present in at least
  152588. ** one of the nSnippet snippet fragments, break out of the loop.
  152589. */
  152590. assert( (mCovered&mSeen)==mCovered );
  152591. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  152592. }
  152593. assert( nFToken>0 );
  152594. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  152595. rc = fts3SnippetText(pCsr, &aSnippet[i],
  152596. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  152597. );
  152598. }
  152599. snippet_out:
  152600. sqlite3Fts3SegmentsClose(pTab);
  152601. if( rc!=SQLITE_OK ){
  152602. sqlite3_result_error_code(pCtx, rc);
  152603. sqlite3_free(res.z);
  152604. }else{
  152605. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  152606. }
  152607. }
  152608. typedef struct TermOffset TermOffset;
  152609. typedef struct TermOffsetCtx TermOffsetCtx;
  152610. struct TermOffset {
  152611. char *pList; /* Position-list */
  152612. int iPos; /* Position just read from pList */
  152613. int iOff; /* Offset of this term from read positions */
  152614. };
  152615. struct TermOffsetCtx {
  152616. Fts3Cursor *pCsr;
  152617. int iCol; /* Column of table to populate aTerm for */
  152618. int iTerm;
  152619. sqlite3_int64 iDocid;
  152620. TermOffset *aTerm;
  152621. };
  152622. /*
  152623. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  152624. */
  152625. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  152626. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  152627. int nTerm; /* Number of tokens in phrase */
  152628. int iTerm; /* For looping through nTerm phrase terms */
  152629. char *pList; /* Pointer to position list for phrase */
  152630. int iPos = 0; /* First position in position-list */
  152631. int rc;
  152632. UNUSED_PARAMETER(iPhrase);
  152633. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  152634. nTerm = pExpr->pPhrase->nToken;
  152635. if( pList ){
  152636. fts3GetDeltaPosition(&pList, &iPos);
  152637. assert( iPos>=0 );
  152638. }
  152639. for(iTerm=0; iTerm<nTerm; iTerm++){
  152640. TermOffset *pT = &p->aTerm[p->iTerm++];
  152641. pT->iOff = nTerm-iTerm-1;
  152642. pT->pList = pList;
  152643. pT->iPos = iPos;
  152644. }
  152645. return rc;
  152646. }
  152647. /*
  152648. ** Implementation of offsets() function.
  152649. */
  152650. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  152651. sqlite3_context *pCtx, /* SQLite function call context */
  152652. Fts3Cursor *pCsr /* Cursor object */
  152653. ){
  152654. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152655. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  152656. int rc; /* Return Code */
  152657. int nToken; /* Number of tokens in query */
  152658. int iCol; /* Column currently being processed */
  152659. StrBuffer res = {0, 0, 0}; /* Result string */
  152660. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  152661. if( !pCsr->pExpr ){
  152662. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  152663. return;
  152664. }
  152665. memset(&sCtx, 0, sizeof(sCtx));
  152666. assert( pCsr->isRequireSeek==0 );
  152667. /* Count the number of terms in the query */
  152668. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  152669. if( rc!=SQLITE_OK ) goto offsets_out;
  152670. /* Allocate the array of TermOffset iterators. */
  152671. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  152672. if( 0==sCtx.aTerm ){
  152673. rc = SQLITE_NOMEM;
  152674. goto offsets_out;
  152675. }
  152676. sCtx.iDocid = pCsr->iPrevId;
  152677. sCtx.pCsr = pCsr;
  152678. /* Loop through the table columns, appending offset information to
  152679. ** string-buffer res for each column.
  152680. */
  152681. for(iCol=0; iCol<pTab->nColumn; iCol++){
  152682. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  152683. const char *ZDUMMY; /* Dummy argument used with xNext() */
  152684. int NDUMMY = 0; /* Dummy argument used with xNext() */
  152685. int iStart = 0;
  152686. int iEnd = 0;
  152687. int iCurrent = 0;
  152688. const char *zDoc;
  152689. int nDoc;
  152690. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  152691. ** no way that this operation can fail, so the return code from
  152692. ** fts3ExprIterate() can be discarded.
  152693. */
  152694. sCtx.iCol = iCol;
  152695. sCtx.iTerm = 0;
  152696. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  152697. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  152698. ** in column iCol, jump immediately to the next iteration of the loop.
  152699. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  152700. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  152701. ** to the caller.
  152702. */
  152703. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  152704. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  152705. if( zDoc==0 ){
  152706. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  152707. continue;
  152708. }
  152709. rc = SQLITE_NOMEM;
  152710. goto offsets_out;
  152711. }
  152712. /* Initialize a tokenizer iterator to iterate through column iCol. */
  152713. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  152714. zDoc, nDoc, &pC
  152715. );
  152716. if( rc!=SQLITE_OK ) goto offsets_out;
  152717. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  152718. while( rc==SQLITE_OK ){
  152719. int i; /* Used to loop through terms */
  152720. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  152721. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  152722. for(i=0; i<nToken; i++){
  152723. TermOffset *pT = &sCtx.aTerm[i];
  152724. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  152725. iMinPos = pT->iPos-pT->iOff;
  152726. pTerm = pT;
  152727. }
  152728. }
  152729. if( !pTerm ){
  152730. /* All offsets for this column have been gathered. */
  152731. rc = SQLITE_DONE;
  152732. }else{
  152733. assert( iCurrent<=iMinPos );
  152734. if( 0==(0xFE&*pTerm->pList) ){
  152735. pTerm->pList = 0;
  152736. }else{
  152737. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  152738. }
  152739. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  152740. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  152741. }
  152742. if( rc==SQLITE_OK ){
  152743. char aBuffer[64];
  152744. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  152745. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  152746. );
  152747. rc = fts3StringAppend(&res, aBuffer, -1);
  152748. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  152749. rc = FTS_CORRUPT_VTAB;
  152750. }
  152751. }
  152752. }
  152753. if( rc==SQLITE_DONE ){
  152754. rc = SQLITE_OK;
  152755. }
  152756. pMod->xClose(pC);
  152757. if( rc!=SQLITE_OK ) goto offsets_out;
  152758. }
  152759. offsets_out:
  152760. sqlite3_free(sCtx.aTerm);
  152761. assert( rc!=SQLITE_DONE );
  152762. sqlite3Fts3SegmentsClose(pTab);
  152763. if( rc!=SQLITE_OK ){
  152764. sqlite3_result_error_code(pCtx, rc);
  152765. sqlite3_free(res.z);
  152766. }else{
  152767. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  152768. }
  152769. return;
  152770. }
  152771. /*
  152772. ** Implementation of matchinfo() function.
  152773. */
  152774. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  152775. sqlite3_context *pContext, /* Function call context */
  152776. Fts3Cursor *pCsr, /* FTS3 table cursor */
  152777. const char *zArg /* Second arg to matchinfo() function */
  152778. ){
  152779. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152780. const char *zFormat;
  152781. if( zArg ){
  152782. zFormat = zArg;
  152783. }else{
  152784. zFormat = FTS3_MATCHINFO_DEFAULT;
  152785. }
  152786. if( !pCsr->pExpr ){
  152787. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  152788. return;
  152789. }else{
  152790. /* Retrieve matchinfo() data. */
  152791. fts3GetMatchinfo(pContext, pCsr, zFormat);
  152792. sqlite3Fts3SegmentsClose(pTab);
  152793. }
  152794. }
  152795. #endif
  152796. /************** End of fts3_snippet.c ****************************************/
  152797. /************** Begin file fts3_unicode.c ************************************/
  152798. /*
  152799. ** 2012 May 24
  152800. **
  152801. ** The author disclaims copyright to this source code. In place of
  152802. ** a legal notice, here is a blessing:
  152803. **
  152804. ** May you do good and not evil.
  152805. ** May you find forgiveness for yourself and forgive others.
  152806. ** May you share freely, never taking more than you give.
  152807. **
  152808. ******************************************************************************
  152809. **
  152810. ** Implementation of the "unicode" full-text-search tokenizer.
  152811. */
  152812. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  152813. /* #include "fts3Int.h" */
  152814. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  152815. /* #include <assert.h> */
  152816. /* #include <stdlib.h> */
  152817. /* #include <stdio.h> */
  152818. /* #include <string.h> */
  152819. /* #include "fts3_tokenizer.h" */
  152820. /*
  152821. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  152822. ** from the sqlite3 source file utf.c. If this file is compiled as part
  152823. ** of the amalgamation, they are not required.
  152824. */
  152825. #ifndef SQLITE_AMALGAMATION
  152826. static const unsigned char sqlite3Utf8Trans1[] = {
  152827. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  152828. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  152829. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  152830. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  152831. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  152832. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  152833. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  152834. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  152835. };
  152836. #define READ_UTF8(zIn, zTerm, c) \
  152837. c = *(zIn++); \
  152838. if( c>=0xc0 ){ \
  152839. c = sqlite3Utf8Trans1[c-0xc0]; \
  152840. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  152841. c = (c<<6) + (0x3f & *(zIn++)); \
  152842. } \
  152843. if( c<0x80 \
  152844. || (c&0xFFFFF800)==0xD800 \
  152845. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  152846. }
  152847. #define WRITE_UTF8(zOut, c) { \
  152848. if( c<0x00080 ){ \
  152849. *zOut++ = (u8)(c&0xFF); \
  152850. } \
  152851. else if( c<0x00800 ){ \
  152852. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  152853. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  152854. } \
  152855. else if( c<0x10000 ){ \
  152856. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  152857. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  152858. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  152859. }else{ \
  152860. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  152861. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  152862. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  152863. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  152864. } \
  152865. }
  152866. #endif /* ifndef SQLITE_AMALGAMATION */
  152867. typedef struct unicode_tokenizer unicode_tokenizer;
  152868. typedef struct unicode_cursor unicode_cursor;
  152869. struct unicode_tokenizer {
  152870. sqlite3_tokenizer base;
  152871. int bRemoveDiacritic;
  152872. int nException;
  152873. int *aiException;
  152874. };
  152875. struct unicode_cursor {
  152876. sqlite3_tokenizer_cursor base;
  152877. const unsigned char *aInput; /* Input text being tokenized */
  152878. int nInput; /* Size of aInput[] in bytes */
  152879. int iOff; /* Current offset within aInput[] */
  152880. int iToken; /* Index of next token to be returned */
  152881. char *zToken; /* storage for current token */
  152882. int nAlloc; /* space allocated at zToken */
  152883. };
  152884. /*
  152885. ** Destroy a tokenizer allocated by unicodeCreate().
  152886. */
  152887. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  152888. if( pTokenizer ){
  152889. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  152890. sqlite3_free(p->aiException);
  152891. sqlite3_free(p);
  152892. }
  152893. return SQLITE_OK;
  152894. }
  152895. /*
  152896. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  152897. ** statement has specified that the tokenizer for this table shall consider
  152898. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  152899. ** token characters (if bAlnum==1).
  152900. **
  152901. ** For each codepoint in the zIn/nIn string, this function checks if the
  152902. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  152903. ** If so, no action is taken. Otherwise, the codepoint is added to the
  152904. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  152905. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  152906. ** codepoints in the aiException[] array.
  152907. **
  152908. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  152909. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  152910. ** It is not possible to change the behavior of the tokenizer with respect
  152911. ** to these codepoints.
  152912. */
  152913. static int unicodeAddExceptions(
  152914. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  152915. int bAlnum, /* Replace Isalnum() return value with this */
  152916. const char *zIn, /* Array of characters to make exceptions */
  152917. int nIn /* Length of z in bytes */
  152918. ){
  152919. const unsigned char *z = (const unsigned char *)zIn;
  152920. const unsigned char *zTerm = &z[nIn];
  152921. unsigned int iCode;
  152922. int nEntry = 0;
  152923. assert( bAlnum==0 || bAlnum==1 );
  152924. while( z<zTerm ){
  152925. READ_UTF8(z, zTerm, iCode);
  152926. assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
  152927. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  152928. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  152929. ){
  152930. nEntry++;
  152931. }
  152932. }
  152933. if( nEntry ){
  152934. int *aNew; /* New aiException[] array */
  152935. int nNew; /* Number of valid entries in array aNew[] */
  152936. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  152937. if( aNew==0 ) return SQLITE_NOMEM;
  152938. nNew = p->nException;
  152939. z = (const unsigned char *)zIn;
  152940. while( z<zTerm ){
  152941. READ_UTF8(z, zTerm, iCode);
  152942. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  152943. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  152944. ){
  152945. int i, j;
  152946. for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
  152947. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  152948. aNew[i] = (int)iCode;
  152949. nNew++;
  152950. }
  152951. }
  152952. p->aiException = aNew;
  152953. p->nException = nNew;
  152954. }
  152955. return SQLITE_OK;
  152956. }
  152957. /*
  152958. ** Return true if the p->aiException[] array contains the value iCode.
  152959. */
  152960. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  152961. if( p->nException>0 ){
  152962. int *a = p->aiException;
  152963. int iLo = 0;
  152964. int iHi = p->nException-1;
  152965. while( iHi>=iLo ){
  152966. int iTest = (iHi + iLo) / 2;
  152967. if( iCode==a[iTest] ){
  152968. return 1;
  152969. }else if( iCode>a[iTest] ){
  152970. iLo = iTest+1;
  152971. }else{
  152972. iHi = iTest-1;
  152973. }
  152974. }
  152975. }
  152976. return 0;
  152977. }
  152978. /*
  152979. ** Return true if, for the purposes of tokenization, codepoint iCode is
  152980. ** considered a token character (not a separator).
  152981. */
  152982. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  152983. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  152984. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  152985. }
  152986. /*
  152987. ** Create a new tokenizer instance.
  152988. */
  152989. static int unicodeCreate(
  152990. int nArg, /* Size of array argv[] */
  152991. const char * const *azArg, /* Tokenizer creation arguments */
  152992. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  152993. ){
  152994. unicode_tokenizer *pNew; /* New tokenizer object */
  152995. int i;
  152996. int rc = SQLITE_OK;
  152997. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  152998. if( pNew==NULL ) return SQLITE_NOMEM;
  152999. memset(pNew, 0, sizeof(unicode_tokenizer));
  153000. pNew->bRemoveDiacritic = 1;
  153001. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  153002. const char *z = azArg[i];
  153003. int n = (int)strlen(z);
  153004. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  153005. pNew->bRemoveDiacritic = 1;
  153006. }
  153007. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  153008. pNew->bRemoveDiacritic = 0;
  153009. }
  153010. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  153011. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  153012. }
  153013. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  153014. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  153015. }
  153016. else{
  153017. /* Unrecognized argument */
  153018. rc = SQLITE_ERROR;
  153019. }
  153020. }
  153021. if( rc!=SQLITE_OK ){
  153022. unicodeDestroy((sqlite3_tokenizer *)pNew);
  153023. pNew = 0;
  153024. }
  153025. *pp = (sqlite3_tokenizer *)pNew;
  153026. return rc;
  153027. }
  153028. /*
  153029. ** Prepare to begin tokenizing a particular string. The input
  153030. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  153031. ** used to incrementally tokenize this string is returned in
  153032. ** *ppCursor.
  153033. */
  153034. static int unicodeOpen(
  153035. sqlite3_tokenizer *p, /* The tokenizer */
  153036. const char *aInput, /* Input string */
  153037. int nInput, /* Size of string aInput in bytes */
  153038. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  153039. ){
  153040. unicode_cursor *pCsr;
  153041. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  153042. if( pCsr==0 ){
  153043. return SQLITE_NOMEM;
  153044. }
  153045. memset(pCsr, 0, sizeof(unicode_cursor));
  153046. pCsr->aInput = (const unsigned char *)aInput;
  153047. if( aInput==0 ){
  153048. pCsr->nInput = 0;
  153049. }else if( nInput<0 ){
  153050. pCsr->nInput = (int)strlen(aInput);
  153051. }else{
  153052. pCsr->nInput = nInput;
  153053. }
  153054. *pp = &pCsr->base;
  153055. UNUSED_PARAMETER(p);
  153056. return SQLITE_OK;
  153057. }
  153058. /*
  153059. ** Close a tokenization cursor previously opened by a call to
  153060. ** simpleOpen() above.
  153061. */
  153062. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  153063. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  153064. sqlite3_free(pCsr->zToken);
  153065. sqlite3_free(pCsr);
  153066. return SQLITE_OK;
  153067. }
  153068. /*
  153069. ** Extract the next token from a tokenization cursor. The cursor must
  153070. ** have been opened by a prior call to simpleOpen().
  153071. */
  153072. static int unicodeNext(
  153073. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  153074. const char **paToken, /* OUT: Token text */
  153075. int *pnToken, /* OUT: Number of bytes at *paToken */
  153076. int *piStart, /* OUT: Starting offset of token */
  153077. int *piEnd, /* OUT: Ending offset of token */
  153078. int *piPos /* OUT: Position integer of token */
  153079. ){
  153080. unicode_cursor *pCsr = (unicode_cursor *)pC;
  153081. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  153082. unsigned int iCode = 0;
  153083. char *zOut;
  153084. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  153085. const unsigned char *zStart = z;
  153086. const unsigned char *zEnd;
  153087. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  153088. /* Scan past any delimiter characters before the start of the next token.
  153089. ** Return SQLITE_DONE early if this takes us all the way to the end of
  153090. ** the input. */
  153091. while( z<zTerm ){
  153092. READ_UTF8(z, zTerm, iCode);
  153093. if( unicodeIsAlnum(p, (int)iCode) ) break;
  153094. zStart = z;
  153095. }
  153096. if( zStart>=zTerm ) return SQLITE_DONE;
  153097. zOut = pCsr->zToken;
  153098. do {
  153099. int iOut;
  153100. /* Grow the output buffer if required. */
  153101. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  153102. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  153103. if( !zNew ) return SQLITE_NOMEM;
  153104. zOut = &zNew[zOut - pCsr->zToken];
  153105. pCsr->zToken = zNew;
  153106. pCsr->nAlloc += 64;
  153107. }
  153108. /* Write the folded case of the last character read to the output */
  153109. zEnd = z;
  153110. iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
  153111. if( iOut ){
  153112. WRITE_UTF8(zOut, iOut);
  153113. }
  153114. /* If the cursor is not at EOF, read the next character */
  153115. if( z>=zTerm ) break;
  153116. READ_UTF8(z, zTerm, iCode);
  153117. }while( unicodeIsAlnum(p, (int)iCode)
  153118. || sqlite3FtsUnicodeIsdiacritic((int)iCode)
  153119. );
  153120. /* Set the output variables and return. */
  153121. pCsr->iOff = (int)(z - pCsr->aInput);
  153122. *paToken = pCsr->zToken;
  153123. *pnToken = (int)(zOut - pCsr->zToken);
  153124. *piStart = (int)(zStart - pCsr->aInput);
  153125. *piEnd = (int)(zEnd - pCsr->aInput);
  153126. *piPos = pCsr->iToken++;
  153127. return SQLITE_OK;
  153128. }
  153129. /*
  153130. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  153131. ** structure for the unicode tokenizer.
  153132. */
  153133. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  153134. static const sqlite3_tokenizer_module module = {
  153135. 0,
  153136. unicodeCreate,
  153137. unicodeDestroy,
  153138. unicodeOpen,
  153139. unicodeClose,
  153140. unicodeNext,
  153141. 0,
  153142. };
  153143. *ppModule = &module;
  153144. }
  153145. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  153146. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  153147. /************** End of fts3_unicode.c ****************************************/
  153148. /************** Begin file fts3_unicode2.c ***********************************/
  153149. /*
  153150. ** 2012 May 25
  153151. **
  153152. ** The author disclaims copyright to this source code. In place of
  153153. ** a legal notice, here is a blessing:
  153154. **
  153155. ** May you do good and not evil.
  153156. ** May you find forgiveness for yourself and forgive others.
  153157. ** May you share freely, never taking more than you give.
  153158. **
  153159. ******************************************************************************
  153160. */
  153161. /*
  153162. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  153163. */
  153164. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  153165. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  153166. /* #include <assert.h> */
  153167. /*
  153168. ** Return true if the argument corresponds to a unicode codepoint
  153169. ** classified as either a letter or a number. Otherwise false.
  153170. **
  153171. ** The results are undefined if the value passed to this function
  153172. ** is less than zero.
  153173. */
  153174. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  153175. /* Each unsigned integer in the following array corresponds to a contiguous
  153176. ** range of unicode codepoints that are not either letters or numbers (i.e.
  153177. ** codepoints for which this function should return 0).
  153178. **
  153179. ** The most significant 22 bits in each 32-bit value contain the first
  153180. ** codepoint in the range. The least significant 10 bits are used to store
  153181. ** the size of the range (always at least 1). In other words, the value
  153182. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  153183. ** C. It is not possible to represent a range larger than 1023 codepoints
  153184. ** using this format.
  153185. */
  153186. static const unsigned int aEntry[] = {
  153187. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  153188. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  153189. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  153190. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  153191. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  153192. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  153193. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  153194. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  153195. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  153196. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  153197. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  153198. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  153199. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  153200. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  153201. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  153202. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  153203. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  153204. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  153205. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  153206. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  153207. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  153208. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  153209. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  153210. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  153211. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  153212. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  153213. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  153214. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  153215. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  153216. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  153217. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  153218. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  153219. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  153220. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  153221. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  153222. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  153223. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  153224. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  153225. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  153226. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  153227. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  153228. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  153229. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  153230. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  153231. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  153232. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  153233. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  153234. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  153235. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  153236. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  153237. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  153238. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  153239. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  153240. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  153241. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  153242. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  153243. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  153244. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  153245. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  153246. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  153247. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  153248. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  153249. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  153250. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  153251. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  153252. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  153253. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  153254. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  153255. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  153256. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  153257. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  153258. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  153259. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  153260. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  153261. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  153262. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  153263. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  153264. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  153265. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  153266. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  153267. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  153268. 0x380400F0,
  153269. };
  153270. static const unsigned int aAscii[4] = {
  153271. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  153272. };
  153273. if( (unsigned int)c<128 ){
  153274. return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
  153275. }else if( (unsigned int)c<(1<<22) ){
  153276. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  153277. int iRes = 0;
  153278. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  153279. int iLo = 0;
  153280. while( iHi>=iLo ){
  153281. int iTest = (iHi + iLo) / 2;
  153282. if( key >= aEntry[iTest] ){
  153283. iRes = iTest;
  153284. iLo = iTest+1;
  153285. }else{
  153286. iHi = iTest-1;
  153287. }
  153288. }
  153289. assert( aEntry[0]<key );
  153290. assert( key>=aEntry[iRes] );
  153291. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  153292. }
  153293. return 1;
  153294. }
  153295. /*
  153296. ** If the argument is a codepoint corresponding to a lowercase letter
  153297. ** in the ASCII range with a diacritic added, return the codepoint
  153298. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  153299. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  153300. ** E"). The resuls of passing a codepoint that corresponds to an
  153301. ** uppercase letter are undefined.
  153302. */
  153303. static int remove_diacritic(int c){
  153304. unsigned short aDia[] = {
  153305. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  153306. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  153307. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  153308. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  153309. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  153310. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  153311. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  153312. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  153313. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  153314. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  153315. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  153316. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  153317. 62924, 63050, 63082, 63274, 63390,
  153318. };
  153319. char aChar[] = {
  153320. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  153321. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  153322. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  153323. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  153324. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  153325. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  153326. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  153327. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  153328. 'e', 'i', 'o', 'u', 'y',
  153329. };
  153330. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  153331. int iRes = 0;
  153332. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  153333. int iLo = 0;
  153334. while( iHi>=iLo ){
  153335. int iTest = (iHi + iLo) / 2;
  153336. if( key >= aDia[iTest] ){
  153337. iRes = iTest;
  153338. iLo = iTest+1;
  153339. }else{
  153340. iHi = iTest-1;
  153341. }
  153342. }
  153343. assert( key>=aDia[iRes] );
  153344. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  153345. }
  153346. /*
  153347. ** Return true if the argument interpreted as a unicode codepoint
  153348. ** is a diacritical modifier character.
  153349. */
  153350. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  153351. unsigned int mask0 = 0x08029FDF;
  153352. unsigned int mask1 = 0x000361F8;
  153353. if( c<768 || c>817 ) return 0;
  153354. return (c < 768+32) ?
  153355. (mask0 & (1 << (c-768))) :
  153356. (mask1 & (1 << (c-768-32)));
  153357. }
  153358. /*
  153359. ** Interpret the argument as a unicode codepoint. If the codepoint
  153360. ** is an upper case character that has a lower case equivalent,
  153361. ** return the codepoint corresponding to the lower case version.
  153362. ** Otherwise, return a copy of the argument.
  153363. **
  153364. ** The results are undefined if the value passed to this function
  153365. ** is less than zero.
  153366. */
  153367. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  153368. /* Each entry in the following array defines a rule for folding a range
  153369. ** of codepoints to lower case. The rule applies to a range of nRange
  153370. ** codepoints starting at codepoint iCode.
  153371. **
  153372. ** If the least significant bit in flags is clear, then the rule applies
  153373. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  153374. ** need to be folded). Or, if it is set, then the rule only applies to
  153375. ** every second codepoint in the range, starting with codepoint C.
  153376. **
  153377. ** The 7 most significant bits in flags are an index into the aiOff[]
  153378. ** array. If a specific codepoint C does require folding, then its lower
  153379. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  153380. **
  153381. ** The contents of this array are generated by parsing the CaseFolding.txt
  153382. ** file distributed as part of the "Unicode Character Database". See
  153383. ** http://www.unicode.org for details.
  153384. */
  153385. static const struct TableEntry {
  153386. unsigned short iCode;
  153387. unsigned char flags;
  153388. unsigned char nRange;
  153389. } aEntry[] = {
  153390. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  153391. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  153392. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  153393. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  153394. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  153395. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  153396. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  153397. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  153398. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  153399. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  153400. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  153401. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  153402. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  153403. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  153404. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  153405. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  153406. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  153407. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  153408. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  153409. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  153410. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  153411. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  153412. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  153413. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  153414. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  153415. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  153416. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  153417. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  153418. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  153419. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  153420. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  153421. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  153422. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  153423. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  153424. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  153425. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  153426. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  153427. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  153428. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  153429. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  153430. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  153431. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  153432. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  153433. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  153434. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  153435. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  153436. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  153437. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  153438. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  153439. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  153440. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  153441. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  153442. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  153443. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  153444. {65313, 14, 26},
  153445. };
  153446. static const unsigned short aiOff[] = {
  153447. 1, 2, 8, 15, 16, 26, 28, 32,
  153448. 37, 38, 40, 48, 63, 64, 69, 71,
  153449. 79, 80, 116, 202, 203, 205, 206, 207,
  153450. 209, 210, 211, 213, 214, 217, 218, 219,
  153451. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  153452. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  153453. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  153454. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  153455. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  153456. 65514, 65521, 65527, 65528, 65529,
  153457. };
  153458. int ret = c;
  153459. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  153460. if( c<128 ){
  153461. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  153462. }else if( c<65536 ){
  153463. const struct TableEntry *p;
  153464. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  153465. int iLo = 0;
  153466. int iRes = -1;
  153467. assert( c>aEntry[0].iCode );
  153468. while( iHi>=iLo ){
  153469. int iTest = (iHi + iLo) / 2;
  153470. int cmp = (c - aEntry[iTest].iCode);
  153471. if( cmp>=0 ){
  153472. iRes = iTest;
  153473. iLo = iTest+1;
  153474. }else{
  153475. iHi = iTest-1;
  153476. }
  153477. }
  153478. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  153479. p = &aEntry[iRes];
  153480. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  153481. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  153482. assert( ret>0 );
  153483. }
  153484. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  153485. }
  153486. else if( c>=66560 && c<66600 ){
  153487. ret = c + 40;
  153488. }
  153489. return ret;
  153490. }
  153491. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  153492. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  153493. /************** End of fts3_unicode2.c ***************************************/
  153494. /************** Begin file rtree.c *******************************************/
  153495. /*
  153496. ** 2001 September 15
  153497. **
  153498. ** The author disclaims copyright to this source code. In place of
  153499. ** a legal notice, here is a blessing:
  153500. **
  153501. ** May you do good and not evil.
  153502. ** May you find forgiveness for yourself and forgive others.
  153503. ** May you share freely, never taking more than you give.
  153504. **
  153505. *************************************************************************
  153506. ** This file contains code for implementations of the r-tree and r*-tree
  153507. ** algorithms packaged as an SQLite virtual table module.
  153508. */
  153509. /*
  153510. ** Database Format of R-Tree Tables
  153511. ** --------------------------------
  153512. **
  153513. ** The data structure for a single virtual r-tree table is stored in three
  153514. ** native SQLite tables declared as follows. In each case, the '%' character
  153515. ** in the table name is replaced with the user-supplied name of the r-tree
  153516. ** table.
  153517. **
  153518. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  153519. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  153520. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  153521. **
  153522. ** The data for each node of the r-tree structure is stored in the %_node
  153523. ** table. For each node that is not the root node of the r-tree, there is
  153524. ** an entry in the %_parent table associating the node with its parent.
  153525. ** And for each row of data in the table, there is an entry in the %_rowid
  153526. ** table that maps from the entries rowid to the id of the node that it
  153527. ** is stored on.
  153528. **
  153529. ** The root node of an r-tree always exists, even if the r-tree table is
  153530. ** empty. The nodeno of the root node is always 1. All other nodes in the
  153531. ** table must be the same size as the root node. The content of each node
  153532. ** is formatted as follows:
  153533. **
  153534. ** 1. If the node is the root node (node 1), then the first 2 bytes
  153535. ** of the node contain the tree depth as a big-endian integer.
  153536. ** For non-root nodes, the first 2 bytes are left unused.
  153537. **
  153538. ** 2. The next 2 bytes contain the number of entries currently
  153539. ** stored in the node.
  153540. **
  153541. ** 3. The remainder of the node contains the node entries. Each entry
  153542. ** consists of a single 8-byte integer followed by an even number
  153543. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  153544. ** of a record. For internal nodes it is the node number of a
  153545. ** child page.
  153546. */
  153547. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  153548. #ifndef SQLITE_CORE
  153549. /* #include "sqlite3ext.h" */
  153550. SQLITE_EXTENSION_INIT1
  153551. #else
  153552. /* #include "sqlite3.h" */
  153553. #endif
  153554. /* #include <string.h> */
  153555. /* #include <assert.h> */
  153556. /* #include <stdio.h> */
  153557. #ifndef SQLITE_AMALGAMATION
  153558. #include "sqlite3rtree.h"
  153559. typedef sqlite3_int64 i64;
  153560. typedef sqlite3_uint64 u64;
  153561. typedef unsigned char u8;
  153562. typedef unsigned short u16;
  153563. typedef unsigned int u32;
  153564. #endif
  153565. /* The following macro is used to suppress compiler warnings.
  153566. */
  153567. #ifndef UNUSED_PARAMETER
  153568. # define UNUSED_PARAMETER(x) (void)(x)
  153569. #endif
  153570. typedef struct Rtree Rtree;
  153571. typedef struct RtreeCursor RtreeCursor;
  153572. typedef struct RtreeNode RtreeNode;
  153573. typedef struct RtreeCell RtreeCell;
  153574. typedef struct RtreeConstraint RtreeConstraint;
  153575. typedef struct RtreeMatchArg RtreeMatchArg;
  153576. typedef struct RtreeGeomCallback RtreeGeomCallback;
  153577. typedef union RtreeCoord RtreeCoord;
  153578. typedef struct RtreeSearchPoint RtreeSearchPoint;
  153579. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  153580. #define RTREE_MAX_DIMENSIONS 5
  153581. /* Size of hash table Rtree.aHash. This hash table is not expected to
  153582. ** ever contain very many entries, so a fixed number of buckets is
  153583. ** used.
  153584. */
  153585. #define HASHSIZE 97
  153586. /* The xBestIndex method of this virtual table requires an estimate of
  153587. ** the number of rows in the virtual table to calculate the costs of
  153588. ** various strategies. If possible, this estimate is loaded from the
  153589. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  153590. ** Otherwise, if no sqlite_stat1 entry is available, use
  153591. ** RTREE_DEFAULT_ROWEST.
  153592. */
  153593. #define RTREE_DEFAULT_ROWEST 1048576
  153594. #define RTREE_MIN_ROWEST 100
  153595. /*
  153596. ** An rtree virtual-table object.
  153597. */
  153598. struct Rtree {
  153599. sqlite3_vtab base; /* Base class. Must be first */
  153600. sqlite3 *db; /* Host database connection */
  153601. int iNodeSize; /* Size in bytes of each node in the node table */
  153602. u8 nDim; /* Number of dimensions */
  153603. u8 nDim2; /* Twice the number of dimensions */
  153604. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  153605. u8 nBytesPerCell; /* Bytes consumed per cell */
  153606. u8 inWrTrans; /* True if inside write transaction */
  153607. int iDepth; /* Current depth of the r-tree structure */
  153608. char *zDb; /* Name of database containing r-tree table */
  153609. char *zName; /* Name of r-tree table */
  153610. u32 nBusy; /* Current number of users of this structure */
  153611. i64 nRowEst; /* Estimated number of rows in this table */
  153612. u32 nCursor; /* Number of open cursors */
  153613. /* List of nodes removed during a CondenseTree operation. List is
  153614. ** linked together via the pointer normally used for hash chains -
  153615. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  153616. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  153617. */
  153618. RtreeNode *pDeleted;
  153619. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  153620. /* Blob I/O on xxx_node */
  153621. sqlite3_blob *pNodeBlob;
  153622. /* Statements to read/write/delete a record from xxx_node */
  153623. sqlite3_stmt *pWriteNode;
  153624. sqlite3_stmt *pDeleteNode;
  153625. /* Statements to read/write/delete a record from xxx_rowid */
  153626. sqlite3_stmt *pReadRowid;
  153627. sqlite3_stmt *pWriteRowid;
  153628. sqlite3_stmt *pDeleteRowid;
  153629. /* Statements to read/write/delete a record from xxx_parent */
  153630. sqlite3_stmt *pReadParent;
  153631. sqlite3_stmt *pWriteParent;
  153632. sqlite3_stmt *pDeleteParent;
  153633. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  153634. };
  153635. /* Possible values for Rtree.eCoordType: */
  153636. #define RTREE_COORD_REAL32 0
  153637. #define RTREE_COORD_INT32 1
  153638. /*
  153639. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  153640. ** only deal with integer coordinates. No floating point operations
  153641. ** will be done.
  153642. */
  153643. #ifdef SQLITE_RTREE_INT_ONLY
  153644. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  153645. typedef int RtreeValue; /* Low accuracy coordinate */
  153646. # define RTREE_ZERO 0
  153647. #else
  153648. typedef double RtreeDValue; /* High accuracy coordinate */
  153649. typedef float RtreeValue; /* Low accuracy coordinate */
  153650. # define RTREE_ZERO 0.0
  153651. #endif
  153652. /*
  153653. ** When doing a search of an r-tree, instances of the following structure
  153654. ** record intermediate results from the tree walk.
  153655. **
  153656. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  153657. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  153658. ** the id is of the parent node and the cell that RtreeSearchPoint
  153659. ** represents is the iCell-th entry in the parent node.
  153660. */
  153661. struct RtreeSearchPoint {
  153662. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  153663. sqlite3_int64 id; /* Node ID */
  153664. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  153665. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  153666. u8 iCell; /* Cell index within the node */
  153667. };
  153668. /*
  153669. ** The minimum number of cells allowed for a node is a third of the
  153670. ** maximum. In Gutman's notation:
  153671. **
  153672. ** m = M/3
  153673. **
  153674. ** If an R*-tree "Reinsert" operation is required, the same number of
  153675. ** cells are removed from the overfull node and reinserted into the tree.
  153676. */
  153677. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  153678. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  153679. #define RTREE_MAXCELLS 51
  153680. /*
  153681. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  153682. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  153683. ** Therefore all non-root nodes must contain at least 3 entries. Since
  153684. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  153685. ** 40 or less.
  153686. */
  153687. #define RTREE_MAX_DEPTH 40
  153688. /*
  153689. ** Number of entries in the cursor RtreeNode cache. The first entry is
  153690. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  153691. ** entries cache the RtreeNode for the first elements of the priority queue.
  153692. */
  153693. #define RTREE_CACHE_SZ 5
  153694. /*
  153695. ** An rtree cursor object.
  153696. */
  153697. struct RtreeCursor {
  153698. sqlite3_vtab_cursor base; /* Base class. Must be first */
  153699. u8 atEOF; /* True if at end of search */
  153700. u8 bPoint; /* True if sPoint is valid */
  153701. int iStrategy; /* Copy of idxNum search parameter */
  153702. int nConstraint; /* Number of entries in aConstraint */
  153703. RtreeConstraint *aConstraint; /* Search constraints. */
  153704. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  153705. int nPoint; /* Number of slots used in aPoint[] */
  153706. int mxLevel; /* iLevel value for root of the tree */
  153707. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  153708. RtreeSearchPoint sPoint; /* Cached next search point */
  153709. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  153710. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  153711. };
  153712. /* Return the Rtree of a RtreeCursor */
  153713. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  153714. /*
  153715. ** A coordinate can be either a floating point number or a integer. All
  153716. ** coordinates within a single R-Tree are always of the same time.
  153717. */
  153718. union RtreeCoord {
  153719. RtreeValue f; /* Floating point value */
  153720. int i; /* Integer value */
  153721. u32 u; /* Unsigned for byte-order conversions */
  153722. };
  153723. /*
  153724. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  153725. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  153726. ** variable pRtree points to the Rtree structure associated with the
  153727. ** RtreeCoord.
  153728. */
  153729. #ifdef SQLITE_RTREE_INT_ONLY
  153730. # define DCOORD(coord) ((RtreeDValue)coord.i)
  153731. #else
  153732. # define DCOORD(coord) ( \
  153733. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  153734. ((double)coord.f) : \
  153735. ((double)coord.i) \
  153736. )
  153737. #endif
  153738. /*
  153739. ** A search constraint.
  153740. */
  153741. struct RtreeConstraint {
  153742. int iCoord; /* Index of constrained coordinate */
  153743. int op; /* Constraining operation */
  153744. union {
  153745. RtreeDValue rValue; /* Constraint value. */
  153746. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  153747. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  153748. } u;
  153749. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  153750. };
  153751. /* Possible values for RtreeConstraint.op */
  153752. #define RTREE_EQ 0x41 /* A */
  153753. #define RTREE_LE 0x42 /* B */
  153754. #define RTREE_LT 0x43 /* C */
  153755. #define RTREE_GE 0x44 /* D */
  153756. #define RTREE_GT 0x45 /* E */
  153757. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  153758. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  153759. /*
  153760. ** An rtree structure node.
  153761. */
  153762. struct RtreeNode {
  153763. RtreeNode *pParent; /* Parent node */
  153764. i64 iNode; /* The node number */
  153765. int nRef; /* Number of references to this node */
  153766. int isDirty; /* True if the node needs to be written to disk */
  153767. u8 *zData; /* Content of the node, as should be on disk */
  153768. RtreeNode *pNext; /* Next node in this hash collision chain */
  153769. };
  153770. /* Return the number of cells in a node */
  153771. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  153772. /*
  153773. ** A single cell from a node, deserialized
  153774. */
  153775. struct RtreeCell {
  153776. i64 iRowid; /* Node or entry ID */
  153777. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  153778. };
  153779. /*
  153780. ** This object becomes the sqlite3_user_data() for the SQL functions
  153781. ** that are created by sqlite3_rtree_geometry_callback() and
  153782. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  153783. ** operators in order to constrain a search.
  153784. **
  153785. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  153786. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  153787. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  153788. ** sqlite3_rtree_query_callback().
  153789. **
  153790. ** This object is deleted automatically by the destructor mechanism in
  153791. ** sqlite3_create_function_v2().
  153792. */
  153793. struct RtreeGeomCallback {
  153794. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  153795. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  153796. void (*xDestructor)(void*);
  153797. void *pContext;
  153798. };
  153799. /*
  153800. ** Value for the first field of every RtreeMatchArg object. The MATCH
  153801. ** operator tests that the first field of a blob operand matches this
  153802. ** value to avoid operating on invalid blobs (which could cause a segfault).
  153803. */
  153804. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  153805. /*
  153806. ** An instance of this structure (in the form of a BLOB) is returned by
  153807. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  153808. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  153809. ** operand to the MATCH operator of an R-Tree.
  153810. */
  153811. struct RtreeMatchArg {
  153812. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  153813. RtreeGeomCallback cb; /* Info about the callback functions */
  153814. int nParam; /* Number of parameters to the SQL function */
  153815. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  153816. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  153817. };
  153818. #ifndef MAX
  153819. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  153820. #endif
  153821. #ifndef MIN
  153822. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  153823. #endif
  153824. /* What version of GCC is being used. 0 means GCC is not being used .
  153825. ** Note that the GCC_VERSION macro will also be set correctly when using
  153826. ** clang, since clang works hard to be gcc compatible. So the gcc
  153827. ** optimizations will also work when compiling with clang.
  153828. */
  153829. #ifndef GCC_VERSION
  153830. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  153831. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  153832. #else
  153833. # define GCC_VERSION 0
  153834. #endif
  153835. #endif
  153836. /* The testcase() macro should already be defined in the amalgamation. If
  153837. ** it is not, make it a no-op.
  153838. */
  153839. #ifndef SQLITE_AMALGAMATION
  153840. # define testcase(X)
  153841. #endif
  153842. /*
  153843. ** Macros to determine whether the machine is big or little endian,
  153844. ** and whether or not that determination is run-time or compile-time.
  153845. **
  153846. ** For best performance, an attempt is made to guess at the byte-order
  153847. ** using C-preprocessor macros. If that is unsuccessful, or if
  153848. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  153849. ** at run-time.
  153850. */
  153851. #ifndef SQLITE_BYTEORDER
  153852. #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  153853. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  153854. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  153855. defined(__arm__)
  153856. # define SQLITE_BYTEORDER 1234
  153857. #elif defined(sparc) || defined(__ppc__)
  153858. # define SQLITE_BYTEORDER 4321
  153859. #else
  153860. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  153861. #endif
  153862. #endif
  153863. /* What version of MSVC is being used. 0 means MSVC is not being used */
  153864. #ifndef MSVC_VERSION
  153865. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  153866. # define MSVC_VERSION _MSC_VER
  153867. #else
  153868. # define MSVC_VERSION 0
  153869. #endif
  153870. #endif
  153871. /*
  153872. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  153873. ** 64 bit integer. The deserialized value is returned.
  153874. */
  153875. static int readInt16(u8 *p){
  153876. return (p[0]<<8) + p[1];
  153877. }
  153878. static void readCoord(u8 *p, RtreeCoord *pCoord){
  153879. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  153880. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  153881. pCoord->u = _byteswap_ulong(*(u32*)p);
  153882. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  153883. pCoord->u = __builtin_bswap32(*(u32*)p);
  153884. #elif SQLITE_BYTEORDER==4321
  153885. pCoord->u = *(u32*)p;
  153886. #else
  153887. pCoord->u = (
  153888. (((u32)p[0]) << 24) +
  153889. (((u32)p[1]) << 16) +
  153890. (((u32)p[2]) << 8) +
  153891. (((u32)p[3]) << 0)
  153892. );
  153893. #endif
  153894. }
  153895. static i64 readInt64(u8 *p){
  153896. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  153897. u64 x;
  153898. memcpy(&x, p, 8);
  153899. return (i64)_byteswap_uint64(x);
  153900. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  153901. u64 x;
  153902. memcpy(&x, p, 8);
  153903. return (i64)__builtin_bswap64(x);
  153904. #elif SQLITE_BYTEORDER==4321
  153905. i64 x;
  153906. memcpy(&x, p, 8);
  153907. return x;
  153908. #else
  153909. return (i64)(
  153910. (((u64)p[0]) << 56) +
  153911. (((u64)p[1]) << 48) +
  153912. (((u64)p[2]) << 40) +
  153913. (((u64)p[3]) << 32) +
  153914. (((u64)p[4]) << 24) +
  153915. (((u64)p[5]) << 16) +
  153916. (((u64)p[6]) << 8) +
  153917. (((u64)p[7]) << 0)
  153918. );
  153919. #endif
  153920. }
  153921. /*
  153922. ** Functions to serialize a 16 bit integer, 32 bit real number and
  153923. ** 64 bit integer. The value returned is the number of bytes written
  153924. ** to the argument buffer (always 2, 4 and 8 respectively).
  153925. */
  153926. static void writeInt16(u8 *p, int i){
  153927. p[0] = (i>> 8)&0xFF;
  153928. p[1] = (i>> 0)&0xFF;
  153929. }
  153930. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  153931. u32 i;
  153932. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  153933. assert( sizeof(RtreeCoord)==4 );
  153934. assert( sizeof(u32)==4 );
  153935. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  153936. i = __builtin_bswap32(pCoord->u);
  153937. memcpy(p, &i, 4);
  153938. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  153939. i = _byteswap_ulong(pCoord->u);
  153940. memcpy(p, &i, 4);
  153941. #elif SQLITE_BYTEORDER==4321
  153942. i = pCoord->u;
  153943. memcpy(p, &i, 4);
  153944. #else
  153945. i = pCoord->u;
  153946. p[0] = (i>>24)&0xFF;
  153947. p[1] = (i>>16)&0xFF;
  153948. p[2] = (i>> 8)&0xFF;
  153949. p[3] = (i>> 0)&0xFF;
  153950. #endif
  153951. return 4;
  153952. }
  153953. static int writeInt64(u8 *p, i64 i){
  153954. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  153955. i = (i64)__builtin_bswap64((u64)i);
  153956. memcpy(p, &i, 8);
  153957. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  153958. i = (i64)_byteswap_uint64((u64)i);
  153959. memcpy(p, &i, 8);
  153960. #elif SQLITE_BYTEORDER==4321
  153961. memcpy(p, &i, 8);
  153962. #else
  153963. p[0] = (i>>56)&0xFF;
  153964. p[1] = (i>>48)&0xFF;
  153965. p[2] = (i>>40)&0xFF;
  153966. p[3] = (i>>32)&0xFF;
  153967. p[4] = (i>>24)&0xFF;
  153968. p[5] = (i>>16)&0xFF;
  153969. p[6] = (i>> 8)&0xFF;
  153970. p[7] = (i>> 0)&0xFF;
  153971. #endif
  153972. return 8;
  153973. }
  153974. /*
  153975. ** Increment the reference count of node p.
  153976. */
  153977. static void nodeReference(RtreeNode *p){
  153978. if( p ){
  153979. p->nRef++;
  153980. }
  153981. }
  153982. /*
  153983. ** Clear the content of node p (set all bytes to 0x00).
  153984. */
  153985. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  153986. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  153987. p->isDirty = 1;
  153988. }
  153989. /*
  153990. ** Given a node number iNode, return the corresponding key to use
  153991. ** in the Rtree.aHash table.
  153992. */
  153993. static int nodeHash(i64 iNode){
  153994. return iNode % HASHSIZE;
  153995. }
  153996. /*
  153997. ** Search the node hash table for node iNode. If found, return a pointer
  153998. ** to it. Otherwise, return 0.
  153999. */
  154000. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  154001. RtreeNode *p;
  154002. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  154003. return p;
  154004. }
  154005. /*
  154006. ** Add node pNode to the node hash table.
  154007. */
  154008. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  154009. int iHash;
  154010. assert( pNode->pNext==0 );
  154011. iHash = nodeHash(pNode->iNode);
  154012. pNode->pNext = pRtree->aHash[iHash];
  154013. pRtree->aHash[iHash] = pNode;
  154014. }
  154015. /*
  154016. ** Remove node pNode from the node hash table.
  154017. */
  154018. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  154019. RtreeNode **pp;
  154020. if( pNode->iNode!=0 ){
  154021. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  154022. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  154023. *pp = pNode->pNext;
  154024. pNode->pNext = 0;
  154025. }
  154026. }
  154027. /*
  154028. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  154029. ** indicating that node has not yet been assigned a node number. It is
  154030. ** assigned a node number when nodeWrite() is called to write the
  154031. ** node contents out to the database.
  154032. */
  154033. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  154034. RtreeNode *pNode;
  154035. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  154036. if( pNode ){
  154037. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  154038. pNode->zData = (u8 *)&pNode[1];
  154039. pNode->nRef = 1;
  154040. pNode->pParent = pParent;
  154041. pNode->isDirty = 1;
  154042. nodeReference(pParent);
  154043. }
  154044. return pNode;
  154045. }
  154046. /*
  154047. ** Clear the Rtree.pNodeBlob object
  154048. */
  154049. static void nodeBlobReset(Rtree *pRtree){
  154050. if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
  154051. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  154052. pRtree->pNodeBlob = 0;
  154053. sqlite3_blob_close(pBlob);
  154054. }
  154055. }
  154056. /*
  154057. ** Obtain a reference to an r-tree node.
  154058. */
  154059. static int nodeAcquire(
  154060. Rtree *pRtree, /* R-tree structure */
  154061. i64 iNode, /* Node number to load */
  154062. RtreeNode *pParent, /* Either the parent node or NULL */
  154063. RtreeNode **ppNode /* OUT: Acquired node */
  154064. ){
  154065. int rc = SQLITE_OK;
  154066. RtreeNode *pNode = 0;
  154067. /* Check if the requested node is already in the hash table. If so,
  154068. ** increase its reference count and return it.
  154069. */
  154070. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  154071. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  154072. if( pParent && !pNode->pParent ){
  154073. nodeReference(pParent);
  154074. pNode->pParent = pParent;
  154075. }
  154076. pNode->nRef++;
  154077. *ppNode = pNode;
  154078. return SQLITE_OK;
  154079. }
  154080. if( pRtree->pNodeBlob ){
  154081. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  154082. pRtree->pNodeBlob = 0;
  154083. rc = sqlite3_blob_reopen(pBlob, iNode);
  154084. pRtree->pNodeBlob = pBlob;
  154085. if( rc ){
  154086. nodeBlobReset(pRtree);
  154087. if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
  154088. }
  154089. }
  154090. if( pRtree->pNodeBlob==0 ){
  154091. char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
  154092. if( zTab==0 ) return SQLITE_NOMEM;
  154093. rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
  154094. &pRtree->pNodeBlob);
  154095. sqlite3_free(zTab);
  154096. }
  154097. if( rc ){
  154098. nodeBlobReset(pRtree);
  154099. *ppNode = 0;
  154100. /* If unable to open an sqlite3_blob on the desired row, that can only
  154101. ** be because the shadow tables hold erroneous data. */
  154102. if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
  154103. }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
  154104. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  154105. if( !pNode ){
  154106. rc = SQLITE_NOMEM;
  154107. }else{
  154108. pNode->pParent = pParent;
  154109. pNode->zData = (u8 *)&pNode[1];
  154110. pNode->nRef = 1;
  154111. pNode->iNode = iNode;
  154112. pNode->isDirty = 0;
  154113. pNode->pNext = 0;
  154114. rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
  154115. pRtree->iNodeSize, 0);
  154116. nodeReference(pParent);
  154117. }
  154118. }
  154119. /* If the root node was just loaded, set pRtree->iDepth to the height
  154120. ** of the r-tree structure. A height of zero means all data is stored on
  154121. ** the root node. A height of one means the children of the root node
  154122. ** are the leaves, and so on. If the depth as specified on the root node
  154123. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  154124. */
  154125. if( pNode && iNode==1 ){
  154126. pRtree->iDepth = readInt16(pNode->zData);
  154127. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  154128. rc = SQLITE_CORRUPT_VTAB;
  154129. }
  154130. }
  154131. /* If no error has occurred so far, check if the "number of entries"
  154132. ** field on the node is too large. If so, set the return code to
  154133. ** SQLITE_CORRUPT_VTAB.
  154134. */
  154135. if( pNode && rc==SQLITE_OK ){
  154136. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  154137. rc = SQLITE_CORRUPT_VTAB;
  154138. }
  154139. }
  154140. if( rc==SQLITE_OK ){
  154141. if( pNode!=0 ){
  154142. nodeHashInsert(pRtree, pNode);
  154143. }else{
  154144. rc = SQLITE_CORRUPT_VTAB;
  154145. }
  154146. *ppNode = pNode;
  154147. }else{
  154148. sqlite3_free(pNode);
  154149. *ppNode = 0;
  154150. }
  154151. return rc;
  154152. }
  154153. /*
  154154. ** Overwrite cell iCell of node pNode with the contents of pCell.
  154155. */
  154156. static void nodeOverwriteCell(
  154157. Rtree *pRtree, /* The overall R-Tree */
  154158. RtreeNode *pNode, /* The node into which the cell is to be written */
  154159. RtreeCell *pCell, /* The cell to write */
  154160. int iCell /* Index into pNode into which pCell is written */
  154161. ){
  154162. int ii;
  154163. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  154164. p += writeInt64(p, pCell->iRowid);
  154165. for(ii=0; ii<pRtree->nDim2; ii++){
  154166. p += writeCoord(p, &pCell->aCoord[ii]);
  154167. }
  154168. pNode->isDirty = 1;
  154169. }
  154170. /*
  154171. ** Remove the cell with index iCell from node pNode.
  154172. */
  154173. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  154174. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  154175. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  154176. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  154177. memmove(pDst, pSrc, nByte);
  154178. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  154179. pNode->isDirty = 1;
  154180. }
  154181. /*
  154182. ** Insert the contents of cell pCell into node pNode. If the insert
  154183. ** is successful, return SQLITE_OK.
  154184. **
  154185. ** If there is not enough free space in pNode, return SQLITE_FULL.
  154186. */
  154187. static int nodeInsertCell(
  154188. Rtree *pRtree, /* The overall R-Tree */
  154189. RtreeNode *pNode, /* Write new cell into this node */
  154190. RtreeCell *pCell /* The cell to be inserted */
  154191. ){
  154192. int nCell; /* Current number of cells in pNode */
  154193. int nMaxCell; /* Maximum number of cells for pNode */
  154194. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  154195. nCell = NCELL(pNode);
  154196. assert( nCell<=nMaxCell );
  154197. if( nCell<nMaxCell ){
  154198. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  154199. writeInt16(&pNode->zData[2], nCell+1);
  154200. pNode->isDirty = 1;
  154201. }
  154202. return (nCell==nMaxCell);
  154203. }
  154204. /*
  154205. ** If the node is dirty, write it out to the database.
  154206. */
  154207. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  154208. int rc = SQLITE_OK;
  154209. if( pNode->isDirty ){
  154210. sqlite3_stmt *p = pRtree->pWriteNode;
  154211. if( pNode->iNode ){
  154212. sqlite3_bind_int64(p, 1, pNode->iNode);
  154213. }else{
  154214. sqlite3_bind_null(p, 1);
  154215. }
  154216. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  154217. sqlite3_step(p);
  154218. pNode->isDirty = 0;
  154219. rc = sqlite3_reset(p);
  154220. if( pNode->iNode==0 && rc==SQLITE_OK ){
  154221. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  154222. nodeHashInsert(pRtree, pNode);
  154223. }
  154224. }
  154225. return rc;
  154226. }
  154227. /*
  154228. ** Release a reference to a node. If the node is dirty and the reference
  154229. ** count drops to zero, the node data is written to the database.
  154230. */
  154231. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  154232. int rc = SQLITE_OK;
  154233. if( pNode ){
  154234. assert( pNode->nRef>0 );
  154235. pNode->nRef--;
  154236. if( pNode->nRef==0 ){
  154237. if( pNode->iNode==1 ){
  154238. pRtree->iDepth = -1;
  154239. }
  154240. if( pNode->pParent ){
  154241. rc = nodeRelease(pRtree, pNode->pParent);
  154242. }
  154243. if( rc==SQLITE_OK ){
  154244. rc = nodeWrite(pRtree, pNode);
  154245. }
  154246. nodeHashDelete(pRtree, pNode);
  154247. sqlite3_free(pNode);
  154248. }
  154249. }
  154250. return rc;
  154251. }
  154252. /*
  154253. ** Return the 64-bit integer value associated with cell iCell of
  154254. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  154255. ** an internal node, then the 64-bit integer is a child page number.
  154256. */
  154257. static i64 nodeGetRowid(
  154258. Rtree *pRtree, /* The overall R-Tree */
  154259. RtreeNode *pNode, /* The node from which to extract the ID */
  154260. int iCell /* The cell index from which to extract the ID */
  154261. ){
  154262. assert( iCell<NCELL(pNode) );
  154263. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  154264. }
  154265. /*
  154266. ** Return coordinate iCoord from cell iCell in node pNode.
  154267. */
  154268. static void nodeGetCoord(
  154269. Rtree *pRtree, /* The overall R-Tree */
  154270. RtreeNode *pNode, /* The node from which to extract a coordinate */
  154271. int iCell, /* The index of the cell within the node */
  154272. int iCoord, /* Which coordinate to extract */
  154273. RtreeCoord *pCoord /* OUT: Space to write result to */
  154274. ){
  154275. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  154276. }
  154277. /*
  154278. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  154279. ** to by pCell with the results.
  154280. */
  154281. static void nodeGetCell(
  154282. Rtree *pRtree, /* The overall R-Tree */
  154283. RtreeNode *pNode, /* The node containing the cell to be read */
  154284. int iCell, /* Index of the cell within the node */
  154285. RtreeCell *pCell /* OUT: Write the cell contents here */
  154286. ){
  154287. u8 *pData;
  154288. RtreeCoord *pCoord;
  154289. int ii = 0;
  154290. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  154291. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  154292. pCoord = pCell->aCoord;
  154293. do{
  154294. readCoord(pData, &pCoord[ii]);
  154295. readCoord(pData+4, &pCoord[ii+1]);
  154296. pData += 8;
  154297. ii += 2;
  154298. }while( ii<pRtree->nDim2 );
  154299. }
  154300. /* Forward declaration for the function that does the work of
  154301. ** the virtual table module xCreate() and xConnect() methods.
  154302. */
  154303. static int rtreeInit(
  154304. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  154305. );
  154306. /*
  154307. ** Rtree virtual table module xCreate method.
  154308. */
  154309. static int rtreeCreate(
  154310. sqlite3 *db,
  154311. void *pAux,
  154312. int argc, const char *const*argv,
  154313. sqlite3_vtab **ppVtab,
  154314. char **pzErr
  154315. ){
  154316. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  154317. }
  154318. /*
  154319. ** Rtree virtual table module xConnect method.
  154320. */
  154321. static int rtreeConnect(
  154322. sqlite3 *db,
  154323. void *pAux,
  154324. int argc, const char *const*argv,
  154325. sqlite3_vtab **ppVtab,
  154326. char **pzErr
  154327. ){
  154328. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  154329. }
  154330. /*
  154331. ** Increment the r-tree reference count.
  154332. */
  154333. static void rtreeReference(Rtree *pRtree){
  154334. pRtree->nBusy++;
  154335. }
  154336. /*
  154337. ** Decrement the r-tree reference count. When the reference count reaches
  154338. ** zero the structure is deleted.
  154339. */
  154340. static void rtreeRelease(Rtree *pRtree){
  154341. pRtree->nBusy--;
  154342. if( pRtree->nBusy==0 ){
  154343. pRtree->inWrTrans = 0;
  154344. pRtree->nCursor = 0;
  154345. nodeBlobReset(pRtree);
  154346. sqlite3_finalize(pRtree->pWriteNode);
  154347. sqlite3_finalize(pRtree->pDeleteNode);
  154348. sqlite3_finalize(pRtree->pReadRowid);
  154349. sqlite3_finalize(pRtree->pWriteRowid);
  154350. sqlite3_finalize(pRtree->pDeleteRowid);
  154351. sqlite3_finalize(pRtree->pReadParent);
  154352. sqlite3_finalize(pRtree->pWriteParent);
  154353. sqlite3_finalize(pRtree->pDeleteParent);
  154354. sqlite3_free(pRtree);
  154355. }
  154356. }
  154357. /*
  154358. ** Rtree virtual table module xDisconnect method.
  154359. */
  154360. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  154361. rtreeRelease((Rtree *)pVtab);
  154362. return SQLITE_OK;
  154363. }
  154364. /*
  154365. ** Rtree virtual table module xDestroy method.
  154366. */
  154367. static int rtreeDestroy(sqlite3_vtab *pVtab){
  154368. Rtree *pRtree = (Rtree *)pVtab;
  154369. int rc;
  154370. char *zCreate = sqlite3_mprintf(
  154371. "DROP TABLE '%q'.'%q_node';"
  154372. "DROP TABLE '%q'.'%q_rowid';"
  154373. "DROP TABLE '%q'.'%q_parent';",
  154374. pRtree->zDb, pRtree->zName,
  154375. pRtree->zDb, pRtree->zName,
  154376. pRtree->zDb, pRtree->zName
  154377. );
  154378. if( !zCreate ){
  154379. rc = SQLITE_NOMEM;
  154380. }else{
  154381. nodeBlobReset(pRtree);
  154382. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  154383. sqlite3_free(zCreate);
  154384. }
  154385. if( rc==SQLITE_OK ){
  154386. rtreeRelease(pRtree);
  154387. }
  154388. return rc;
  154389. }
  154390. /*
  154391. ** Rtree virtual table module xOpen method.
  154392. */
  154393. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  154394. int rc = SQLITE_NOMEM;
  154395. Rtree *pRtree = (Rtree *)pVTab;
  154396. RtreeCursor *pCsr;
  154397. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  154398. if( pCsr ){
  154399. memset(pCsr, 0, sizeof(RtreeCursor));
  154400. pCsr->base.pVtab = pVTab;
  154401. rc = SQLITE_OK;
  154402. pRtree->nCursor++;
  154403. }
  154404. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  154405. return rc;
  154406. }
  154407. /*
  154408. ** Free the RtreeCursor.aConstraint[] array and its contents.
  154409. */
  154410. static void freeCursorConstraints(RtreeCursor *pCsr){
  154411. if( pCsr->aConstraint ){
  154412. int i; /* Used to iterate through constraint array */
  154413. for(i=0; i<pCsr->nConstraint; i++){
  154414. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  154415. if( pInfo ){
  154416. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  154417. sqlite3_free(pInfo);
  154418. }
  154419. }
  154420. sqlite3_free(pCsr->aConstraint);
  154421. pCsr->aConstraint = 0;
  154422. }
  154423. }
  154424. /*
  154425. ** Rtree virtual table module xClose method.
  154426. */
  154427. static int rtreeClose(sqlite3_vtab_cursor *cur){
  154428. Rtree *pRtree = (Rtree *)(cur->pVtab);
  154429. int ii;
  154430. RtreeCursor *pCsr = (RtreeCursor *)cur;
  154431. assert( pRtree->nCursor>0 );
  154432. freeCursorConstraints(pCsr);
  154433. sqlite3_free(pCsr->aPoint);
  154434. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  154435. sqlite3_free(pCsr);
  154436. pRtree->nCursor--;
  154437. nodeBlobReset(pRtree);
  154438. return SQLITE_OK;
  154439. }
  154440. /*
  154441. ** Rtree virtual table module xEof method.
  154442. **
  154443. ** Return non-zero if the cursor does not currently point to a valid
  154444. ** record (i.e if the scan has finished), or zero otherwise.
  154445. */
  154446. static int rtreeEof(sqlite3_vtab_cursor *cur){
  154447. RtreeCursor *pCsr = (RtreeCursor *)cur;
  154448. return pCsr->atEOF;
  154449. }
  154450. /*
  154451. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  154452. ** The on-disk format is big-endian and needs to be converted for little-
  154453. ** endian platforms. The on-disk record stores integer coordinates if
  154454. ** eInt is true and it stores 32-bit floating point records if eInt is
  154455. ** false. a[] is the four bytes of the on-disk record to be decoded.
  154456. ** Store the results in "r".
  154457. **
  154458. ** There are five versions of this macro. The last one is generic. The
  154459. ** other four are various architectures-specific optimizations.
  154460. */
  154461. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  154462. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154463. RtreeCoord c; /* Coordinate decoded */ \
  154464. c.u = _byteswap_ulong(*(u32*)a); \
  154465. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154466. }
  154467. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  154468. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154469. RtreeCoord c; /* Coordinate decoded */ \
  154470. c.u = __builtin_bswap32(*(u32*)a); \
  154471. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154472. }
  154473. #elif SQLITE_BYTEORDER==1234
  154474. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154475. RtreeCoord c; /* Coordinate decoded */ \
  154476. memcpy(&c.u,a,4); \
  154477. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  154478. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  154479. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154480. }
  154481. #elif SQLITE_BYTEORDER==4321
  154482. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154483. RtreeCoord c; /* Coordinate decoded */ \
  154484. memcpy(&c.u,a,4); \
  154485. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154486. }
  154487. #else
  154488. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154489. RtreeCoord c; /* Coordinate decoded */ \
  154490. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  154491. +((u32)a[2]<<8) + a[3]; \
  154492. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154493. }
  154494. #endif
  154495. /*
  154496. ** Check the RTree node or entry given by pCellData and p against the MATCH
  154497. ** constraint pConstraint.
  154498. */
  154499. static int rtreeCallbackConstraint(
  154500. RtreeConstraint *pConstraint, /* The constraint to test */
  154501. int eInt, /* True if RTree holding integer coordinates */
  154502. u8 *pCellData, /* Raw cell content */
  154503. RtreeSearchPoint *pSearch, /* Container of this cell */
  154504. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  154505. int *peWithin /* OUT: visibility of the cell */
  154506. ){
  154507. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  154508. int nCoord = pInfo->nCoord; /* No. of coordinates */
  154509. int rc; /* Callback return code */
  154510. RtreeCoord c; /* Translator union */
  154511. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  154512. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  154513. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  154514. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  154515. pInfo->iRowid = readInt64(pCellData);
  154516. }
  154517. pCellData += 8;
  154518. #ifndef SQLITE_RTREE_INT_ONLY
  154519. if( eInt==0 ){
  154520. switch( nCoord ){
  154521. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
  154522. readCoord(pCellData+32, &c); aCoord[8] = c.f;
  154523. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
  154524. readCoord(pCellData+24, &c); aCoord[6] = c.f;
  154525. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
  154526. readCoord(pCellData+16, &c); aCoord[4] = c.f;
  154527. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
  154528. readCoord(pCellData+8, &c); aCoord[2] = c.f;
  154529. default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
  154530. readCoord(pCellData, &c); aCoord[0] = c.f;
  154531. }
  154532. }else
  154533. #endif
  154534. {
  154535. switch( nCoord ){
  154536. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
  154537. readCoord(pCellData+32, &c); aCoord[8] = c.i;
  154538. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
  154539. readCoord(pCellData+24, &c); aCoord[6] = c.i;
  154540. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
  154541. readCoord(pCellData+16, &c); aCoord[4] = c.i;
  154542. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
  154543. readCoord(pCellData+8, &c); aCoord[2] = c.i;
  154544. default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
  154545. readCoord(pCellData, &c); aCoord[0] = c.i;
  154546. }
  154547. }
  154548. if( pConstraint->op==RTREE_MATCH ){
  154549. int eWithin = 0;
  154550. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  154551. nCoord, aCoord, &eWithin);
  154552. if( eWithin==0 ) *peWithin = NOT_WITHIN;
  154553. *prScore = RTREE_ZERO;
  154554. }else{
  154555. pInfo->aCoord = aCoord;
  154556. pInfo->iLevel = pSearch->iLevel - 1;
  154557. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  154558. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  154559. rc = pConstraint->u.xQueryFunc(pInfo);
  154560. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  154561. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  154562. *prScore = pInfo->rScore;
  154563. }
  154564. }
  154565. return rc;
  154566. }
  154567. /*
  154568. ** Check the internal RTree node given by pCellData against constraint p.
  154569. ** If this constraint cannot be satisfied by any child within the node,
  154570. ** set *peWithin to NOT_WITHIN.
  154571. */
  154572. static void rtreeNonleafConstraint(
  154573. RtreeConstraint *p, /* The constraint to test */
  154574. int eInt, /* True if RTree holds integer coordinates */
  154575. u8 *pCellData, /* Raw cell content as appears on disk */
  154576. int *peWithin /* Adjust downward, as appropriate */
  154577. ){
  154578. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  154579. /* p->iCoord might point to either a lower or upper bound coordinate
  154580. ** in a coordinate pair. But make pCellData point to the lower bound.
  154581. */
  154582. pCellData += 8 + 4*(p->iCoord&0xfe);
  154583. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  154584. || p->op==RTREE_GT || p->op==RTREE_EQ );
  154585. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  154586. switch( p->op ){
  154587. case RTREE_LE:
  154588. case RTREE_LT:
  154589. case RTREE_EQ:
  154590. RTREE_DECODE_COORD(eInt, pCellData, val);
  154591. /* val now holds the lower bound of the coordinate pair */
  154592. if( p->u.rValue>=val ) return;
  154593. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  154594. /* Fall through for the RTREE_EQ case */
  154595. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  154596. pCellData += 4;
  154597. RTREE_DECODE_COORD(eInt, pCellData, val);
  154598. /* val now holds the upper bound of the coordinate pair */
  154599. if( p->u.rValue<=val ) return;
  154600. }
  154601. *peWithin = NOT_WITHIN;
  154602. }
  154603. /*
  154604. ** Check the leaf RTree cell given by pCellData against constraint p.
  154605. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  154606. ** If the constraint is satisfied, leave *peWithin unchanged.
  154607. **
  154608. ** The constraint is of the form: xN op $val
  154609. **
  154610. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  154611. ** pCellData. $val is given by p->u.rValue.
  154612. */
  154613. static void rtreeLeafConstraint(
  154614. RtreeConstraint *p, /* The constraint to test */
  154615. int eInt, /* True if RTree holds integer coordinates */
  154616. u8 *pCellData, /* Raw cell content as appears on disk */
  154617. int *peWithin /* Adjust downward, as appropriate */
  154618. ){
  154619. RtreeDValue xN; /* Coordinate value converted to a double */
  154620. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  154621. || p->op==RTREE_GT || p->op==RTREE_EQ );
  154622. pCellData += 8 + p->iCoord*4;
  154623. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  154624. RTREE_DECODE_COORD(eInt, pCellData, xN);
  154625. switch( p->op ){
  154626. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  154627. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  154628. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  154629. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  154630. default: if( xN == p->u.rValue ) return; break;
  154631. }
  154632. *peWithin = NOT_WITHIN;
  154633. }
  154634. /*
  154635. ** One of the cells in node pNode is guaranteed to have a 64-bit
  154636. ** integer value equal to iRowid. Return the index of this cell.
  154637. */
  154638. static int nodeRowidIndex(
  154639. Rtree *pRtree,
  154640. RtreeNode *pNode,
  154641. i64 iRowid,
  154642. int *piIndex
  154643. ){
  154644. int ii;
  154645. int nCell = NCELL(pNode);
  154646. assert( nCell<200 );
  154647. for(ii=0; ii<nCell; ii++){
  154648. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  154649. *piIndex = ii;
  154650. return SQLITE_OK;
  154651. }
  154652. }
  154653. return SQLITE_CORRUPT_VTAB;
  154654. }
  154655. /*
  154656. ** Return the index of the cell containing a pointer to node pNode
  154657. ** in its parent. If pNode is the root node, return -1.
  154658. */
  154659. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  154660. RtreeNode *pParent = pNode->pParent;
  154661. if( pParent ){
  154662. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  154663. }
  154664. *piIndex = -1;
  154665. return SQLITE_OK;
  154666. }
  154667. /*
  154668. ** Compare two search points. Return negative, zero, or positive if the first
  154669. ** is less than, equal to, or greater than the second.
  154670. **
  154671. ** The rScore is the primary key. Smaller rScore values come first.
  154672. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  154673. ** iLevel values coming first. In this way, if rScore is the same for all
  154674. ** SearchPoints, then iLevel becomes the deciding factor and the result
  154675. ** is a depth-first search, which is the desired default behavior.
  154676. */
  154677. static int rtreeSearchPointCompare(
  154678. const RtreeSearchPoint *pA,
  154679. const RtreeSearchPoint *pB
  154680. ){
  154681. if( pA->rScore<pB->rScore ) return -1;
  154682. if( pA->rScore>pB->rScore ) return +1;
  154683. if( pA->iLevel<pB->iLevel ) return -1;
  154684. if( pA->iLevel>pB->iLevel ) return +1;
  154685. return 0;
  154686. }
  154687. /*
  154688. ** Interchange two search points in a cursor.
  154689. */
  154690. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  154691. RtreeSearchPoint t = p->aPoint[i];
  154692. assert( i<j );
  154693. p->aPoint[i] = p->aPoint[j];
  154694. p->aPoint[j] = t;
  154695. i++; j++;
  154696. if( i<RTREE_CACHE_SZ ){
  154697. if( j>=RTREE_CACHE_SZ ){
  154698. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  154699. p->aNode[i] = 0;
  154700. }else{
  154701. RtreeNode *pTemp = p->aNode[i];
  154702. p->aNode[i] = p->aNode[j];
  154703. p->aNode[j] = pTemp;
  154704. }
  154705. }
  154706. }
  154707. /*
  154708. ** Return the search point with the lowest current score.
  154709. */
  154710. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  154711. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  154712. }
  154713. /*
  154714. ** Get the RtreeNode for the search point with the lowest score.
  154715. */
  154716. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  154717. sqlite3_int64 id;
  154718. int ii = 1 - pCur->bPoint;
  154719. assert( ii==0 || ii==1 );
  154720. assert( pCur->bPoint || pCur->nPoint );
  154721. if( pCur->aNode[ii]==0 ){
  154722. assert( pRC!=0 );
  154723. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  154724. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  154725. }
  154726. return pCur->aNode[ii];
  154727. }
  154728. /*
  154729. ** Push a new element onto the priority queue
  154730. */
  154731. static RtreeSearchPoint *rtreeEnqueue(
  154732. RtreeCursor *pCur, /* The cursor */
  154733. RtreeDValue rScore, /* Score for the new search point */
  154734. u8 iLevel /* Level for the new search point */
  154735. ){
  154736. int i, j;
  154737. RtreeSearchPoint *pNew;
  154738. if( pCur->nPoint>=pCur->nPointAlloc ){
  154739. int nNew = pCur->nPointAlloc*2 + 8;
  154740. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  154741. if( pNew==0 ) return 0;
  154742. pCur->aPoint = pNew;
  154743. pCur->nPointAlloc = nNew;
  154744. }
  154745. i = pCur->nPoint++;
  154746. pNew = pCur->aPoint + i;
  154747. pNew->rScore = rScore;
  154748. pNew->iLevel = iLevel;
  154749. assert( iLevel<=RTREE_MAX_DEPTH );
  154750. while( i>0 ){
  154751. RtreeSearchPoint *pParent;
  154752. j = (i-1)/2;
  154753. pParent = pCur->aPoint + j;
  154754. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  154755. rtreeSearchPointSwap(pCur, j, i);
  154756. i = j;
  154757. pNew = pParent;
  154758. }
  154759. return pNew;
  154760. }
  154761. /*
  154762. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  154763. ** NULL if malloc fails.
  154764. */
  154765. static RtreeSearchPoint *rtreeSearchPointNew(
  154766. RtreeCursor *pCur, /* The cursor */
  154767. RtreeDValue rScore, /* Score for the new search point */
  154768. u8 iLevel /* Level for the new search point */
  154769. ){
  154770. RtreeSearchPoint *pNew, *pFirst;
  154771. pFirst = rtreeSearchPointFirst(pCur);
  154772. pCur->anQueue[iLevel]++;
  154773. if( pFirst==0
  154774. || pFirst->rScore>rScore
  154775. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  154776. ){
  154777. if( pCur->bPoint ){
  154778. int ii;
  154779. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  154780. if( pNew==0 ) return 0;
  154781. ii = (int)(pNew - pCur->aPoint) + 1;
  154782. if( ii<RTREE_CACHE_SZ ){
  154783. assert( pCur->aNode[ii]==0 );
  154784. pCur->aNode[ii] = pCur->aNode[0];
  154785. }else{
  154786. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  154787. }
  154788. pCur->aNode[0] = 0;
  154789. *pNew = pCur->sPoint;
  154790. }
  154791. pCur->sPoint.rScore = rScore;
  154792. pCur->sPoint.iLevel = iLevel;
  154793. pCur->bPoint = 1;
  154794. return &pCur->sPoint;
  154795. }else{
  154796. return rtreeEnqueue(pCur, rScore, iLevel);
  154797. }
  154798. }
  154799. #if 0
  154800. /* Tracing routines for the RtreeSearchPoint queue */
  154801. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  154802. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  154803. printf(" %d.%05lld.%02d %g %d",
  154804. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  154805. );
  154806. idx++;
  154807. if( idx<RTREE_CACHE_SZ ){
  154808. printf(" %p\n", pCur->aNode[idx]);
  154809. }else{
  154810. printf("\n");
  154811. }
  154812. }
  154813. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  154814. int ii;
  154815. printf("=== %9s ", zPrefix);
  154816. if( pCur->bPoint ){
  154817. tracePoint(&pCur->sPoint, -1, pCur);
  154818. }
  154819. for(ii=0; ii<pCur->nPoint; ii++){
  154820. if( ii>0 || pCur->bPoint ) printf(" ");
  154821. tracePoint(&pCur->aPoint[ii], ii, pCur);
  154822. }
  154823. }
  154824. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  154825. #else
  154826. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  154827. #endif
  154828. /* Remove the search point with the lowest current score.
  154829. */
  154830. static void rtreeSearchPointPop(RtreeCursor *p){
  154831. int i, j, k, n;
  154832. i = 1 - p->bPoint;
  154833. assert( i==0 || i==1 );
  154834. if( p->aNode[i] ){
  154835. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  154836. p->aNode[i] = 0;
  154837. }
  154838. if( p->bPoint ){
  154839. p->anQueue[p->sPoint.iLevel]--;
  154840. p->bPoint = 0;
  154841. }else if( p->nPoint ){
  154842. p->anQueue[p->aPoint[0].iLevel]--;
  154843. n = --p->nPoint;
  154844. p->aPoint[0] = p->aPoint[n];
  154845. if( n<RTREE_CACHE_SZ-1 ){
  154846. p->aNode[1] = p->aNode[n+1];
  154847. p->aNode[n+1] = 0;
  154848. }
  154849. i = 0;
  154850. while( (j = i*2+1)<n ){
  154851. k = j+1;
  154852. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  154853. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  154854. rtreeSearchPointSwap(p, i, k);
  154855. i = k;
  154856. }else{
  154857. break;
  154858. }
  154859. }else{
  154860. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  154861. rtreeSearchPointSwap(p, i, j);
  154862. i = j;
  154863. }else{
  154864. break;
  154865. }
  154866. }
  154867. }
  154868. }
  154869. }
  154870. /*
  154871. ** Continue the search on cursor pCur until the front of the queue
  154872. ** contains an entry suitable for returning as a result-set row,
  154873. ** or until the RtreeSearchPoint queue is empty, indicating that the
  154874. ** query has completed.
  154875. */
  154876. static int rtreeStepToLeaf(RtreeCursor *pCur){
  154877. RtreeSearchPoint *p;
  154878. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  154879. RtreeNode *pNode;
  154880. int eWithin;
  154881. int rc = SQLITE_OK;
  154882. int nCell;
  154883. int nConstraint = pCur->nConstraint;
  154884. int ii;
  154885. int eInt;
  154886. RtreeSearchPoint x;
  154887. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  154888. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  154889. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  154890. if( rc ) return rc;
  154891. nCell = NCELL(pNode);
  154892. assert( nCell<200 );
  154893. while( p->iCell<nCell ){
  154894. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  154895. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  154896. eWithin = FULLY_WITHIN;
  154897. for(ii=0; ii<nConstraint; ii++){
  154898. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  154899. if( pConstraint->op>=RTREE_MATCH ){
  154900. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  154901. &rScore, &eWithin);
  154902. if( rc ) return rc;
  154903. }else if( p->iLevel==1 ){
  154904. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  154905. }else{
  154906. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  154907. }
  154908. if( eWithin==NOT_WITHIN ) break;
  154909. }
  154910. p->iCell++;
  154911. if( eWithin==NOT_WITHIN ) continue;
  154912. x.iLevel = p->iLevel - 1;
  154913. if( x.iLevel ){
  154914. x.id = readInt64(pCellData);
  154915. x.iCell = 0;
  154916. }else{
  154917. x.id = p->id;
  154918. x.iCell = p->iCell - 1;
  154919. }
  154920. if( p->iCell>=nCell ){
  154921. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  154922. rtreeSearchPointPop(pCur);
  154923. }
  154924. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  154925. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  154926. if( p==0 ) return SQLITE_NOMEM;
  154927. p->eWithin = (u8)eWithin;
  154928. p->id = x.id;
  154929. p->iCell = x.iCell;
  154930. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  154931. break;
  154932. }
  154933. if( p->iCell>=nCell ){
  154934. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  154935. rtreeSearchPointPop(pCur);
  154936. }
  154937. }
  154938. pCur->atEOF = p==0;
  154939. return SQLITE_OK;
  154940. }
  154941. /*
  154942. ** Rtree virtual table module xNext method.
  154943. */
  154944. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  154945. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  154946. int rc = SQLITE_OK;
  154947. /* Move to the next entry that matches the configured constraints. */
  154948. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  154949. rtreeSearchPointPop(pCsr);
  154950. rc = rtreeStepToLeaf(pCsr);
  154951. return rc;
  154952. }
  154953. /*
  154954. ** Rtree virtual table module xRowid method.
  154955. */
  154956. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  154957. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  154958. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  154959. int rc = SQLITE_OK;
  154960. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  154961. if( rc==SQLITE_OK && p ){
  154962. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  154963. }
  154964. return rc;
  154965. }
  154966. /*
  154967. ** Rtree virtual table module xColumn method.
  154968. */
  154969. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  154970. Rtree *pRtree = (Rtree *)cur->pVtab;
  154971. RtreeCursor *pCsr = (RtreeCursor *)cur;
  154972. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  154973. RtreeCoord c;
  154974. int rc = SQLITE_OK;
  154975. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  154976. if( rc ) return rc;
  154977. if( p==0 ) return SQLITE_OK;
  154978. if( i==0 ){
  154979. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  154980. }else{
  154981. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  154982. #ifndef SQLITE_RTREE_INT_ONLY
  154983. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  154984. sqlite3_result_double(ctx, c.f);
  154985. }else
  154986. #endif
  154987. {
  154988. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  154989. sqlite3_result_int(ctx, c.i);
  154990. }
  154991. }
  154992. return SQLITE_OK;
  154993. }
  154994. /*
  154995. ** Use nodeAcquire() to obtain the leaf node containing the record with
  154996. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  154997. ** return SQLITE_OK. If there is no such record in the table, set
  154998. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  154999. ** to zero and return an SQLite error code.
  155000. */
  155001. static int findLeafNode(
  155002. Rtree *pRtree, /* RTree to search */
  155003. i64 iRowid, /* The rowid searching for */
  155004. RtreeNode **ppLeaf, /* Write the node here */
  155005. sqlite3_int64 *piNode /* Write the node-id here */
  155006. ){
  155007. int rc;
  155008. *ppLeaf = 0;
  155009. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  155010. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  155011. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  155012. if( piNode ) *piNode = iNode;
  155013. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  155014. sqlite3_reset(pRtree->pReadRowid);
  155015. }else{
  155016. rc = sqlite3_reset(pRtree->pReadRowid);
  155017. }
  155018. return rc;
  155019. }
  155020. /*
  155021. ** This function is called to configure the RtreeConstraint object passed
  155022. ** as the second argument for a MATCH constraint. The value passed as the
  155023. ** first argument to this function is the right-hand operand to the MATCH
  155024. ** operator.
  155025. */
  155026. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  155027. RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
  155028. sqlite3_rtree_query_info *pInfo; /* Callback information */
  155029. int nBlob; /* Size of the geometry function blob */
  155030. int nExpected; /* Expected size of the BLOB */
  155031. /* Check that value is actually a blob. */
  155032. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  155033. /* Check that the blob is roughly the right size. */
  155034. nBlob = sqlite3_value_bytes(pValue);
  155035. if( nBlob<(int)sizeof(RtreeMatchArg) ){
  155036. return SQLITE_ERROR;
  155037. }
  155038. pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
  155039. if( !pInfo ) return SQLITE_NOMEM;
  155040. memset(pInfo, 0, sizeof(*pInfo));
  155041. pBlob = (RtreeMatchArg*)&pInfo[1];
  155042. memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
  155043. nExpected = (int)(sizeof(RtreeMatchArg) +
  155044. pBlob->nParam*sizeof(sqlite3_value*) +
  155045. (pBlob->nParam-1)*sizeof(RtreeDValue));
  155046. if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
  155047. sqlite3_free(pInfo);
  155048. return SQLITE_ERROR;
  155049. }
  155050. pInfo->pContext = pBlob->cb.pContext;
  155051. pInfo->nParam = pBlob->nParam;
  155052. pInfo->aParam = pBlob->aParam;
  155053. pInfo->apSqlParam = pBlob->apSqlParam;
  155054. if( pBlob->cb.xGeom ){
  155055. pCons->u.xGeom = pBlob->cb.xGeom;
  155056. }else{
  155057. pCons->op = RTREE_QUERY;
  155058. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  155059. }
  155060. pCons->pInfo = pInfo;
  155061. return SQLITE_OK;
  155062. }
  155063. /*
  155064. ** Rtree virtual table module xFilter method.
  155065. */
  155066. static int rtreeFilter(
  155067. sqlite3_vtab_cursor *pVtabCursor,
  155068. int idxNum, const char *idxStr,
  155069. int argc, sqlite3_value **argv
  155070. ){
  155071. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  155072. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  155073. RtreeNode *pRoot = 0;
  155074. int ii;
  155075. int rc = SQLITE_OK;
  155076. int iCell = 0;
  155077. rtreeReference(pRtree);
  155078. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  155079. freeCursorConstraints(pCsr);
  155080. sqlite3_free(pCsr->aPoint);
  155081. memset(pCsr, 0, sizeof(RtreeCursor));
  155082. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  155083. pCsr->iStrategy = idxNum;
  155084. if( idxNum==1 ){
  155085. /* Special case - lookup by rowid. */
  155086. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  155087. RtreeSearchPoint *p; /* Search point for the leaf */
  155088. i64 iRowid = sqlite3_value_int64(argv[0]);
  155089. i64 iNode = 0;
  155090. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  155091. if( rc==SQLITE_OK && pLeaf!=0 ){
  155092. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  155093. assert( p!=0 ); /* Always returns pCsr->sPoint */
  155094. pCsr->aNode[0] = pLeaf;
  155095. p->id = iNode;
  155096. p->eWithin = PARTLY_WITHIN;
  155097. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  155098. p->iCell = (u8)iCell;
  155099. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  155100. }else{
  155101. pCsr->atEOF = 1;
  155102. }
  155103. }else{
  155104. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  155105. ** with the configured constraints.
  155106. */
  155107. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  155108. if( rc==SQLITE_OK && argc>0 ){
  155109. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  155110. pCsr->nConstraint = argc;
  155111. if( !pCsr->aConstraint ){
  155112. rc = SQLITE_NOMEM;
  155113. }else{
  155114. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  155115. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  155116. assert( (idxStr==0 && argc==0)
  155117. || (idxStr && (int)strlen(idxStr)==argc*2) );
  155118. for(ii=0; ii<argc; ii++){
  155119. RtreeConstraint *p = &pCsr->aConstraint[ii];
  155120. p->op = idxStr[ii*2];
  155121. p->iCoord = idxStr[ii*2+1]-'0';
  155122. if( p->op>=RTREE_MATCH ){
  155123. /* A MATCH operator. The right-hand-side must be a blob that
  155124. ** can be cast into an RtreeMatchArg object. One created using
  155125. ** an sqlite3_rtree_geometry_callback() SQL user function.
  155126. */
  155127. rc = deserializeGeometry(argv[ii], p);
  155128. if( rc!=SQLITE_OK ){
  155129. break;
  155130. }
  155131. p->pInfo->nCoord = pRtree->nDim2;
  155132. p->pInfo->anQueue = pCsr->anQueue;
  155133. p->pInfo->mxLevel = pRtree->iDepth + 1;
  155134. }else{
  155135. #ifdef SQLITE_RTREE_INT_ONLY
  155136. p->u.rValue = sqlite3_value_int64(argv[ii]);
  155137. #else
  155138. p->u.rValue = sqlite3_value_double(argv[ii]);
  155139. #endif
  155140. }
  155141. }
  155142. }
  155143. }
  155144. if( rc==SQLITE_OK ){
  155145. RtreeSearchPoint *pNew;
  155146. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  155147. if( pNew==0 ) return SQLITE_NOMEM;
  155148. pNew->id = 1;
  155149. pNew->iCell = 0;
  155150. pNew->eWithin = PARTLY_WITHIN;
  155151. assert( pCsr->bPoint==1 );
  155152. pCsr->aNode[0] = pRoot;
  155153. pRoot = 0;
  155154. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  155155. rc = rtreeStepToLeaf(pCsr);
  155156. }
  155157. }
  155158. nodeRelease(pRtree, pRoot);
  155159. rtreeRelease(pRtree);
  155160. return rc;
  155161. }
  155162. /*
  155163. ** Rtree virtual table module xBestIndex method. There are three
  155164. ** table scan strategies to choose from (in order from most to
  155165. ** least desirable):
  155166. **
  155167. ** idxNum idxStr Strategy
  155168. ** ------------------------------------------------
  155169. ** 1 Unused Direct lookup by rowid.
  155170. ** 2 See below R-tree query or full-table scan.
  155171. ** ------------------------------------------------
  155172. **
  155173. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  155174. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  155175. ** constraint used. The first two bytes of idxStr correspond to
  155176. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  155177. ** (argvIndex==1) etc.
  155178. **
  155179. ** The first of each pair of bytes in idxStr identifies the constraint
  155180. ** operator as follows:
  155181. **
  155182. ** Operator Byte Value
  155183. ** ----------------------
  155184. ** = 0x41 ('A')
  155185. ** <= 0x42 ('B')
  155186. ** < 0x43 ('C')
  155187. ** >= 0x44 ('D')
  155188. ** > 0x45 ('E')
  155189. ** MATCH 0x46 ('F')
  155190. ** ----------------------
  155191. **
  155192. ** The second of each pair of bytes identifies the coordinate column
  155193. ** to which the constraint applies. The leftmost coordinate column
  155194. ** is 'a', the second from the left 'b' etc.
  155195. */
  155196. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  155197. Rtree *pRtree = (Rtree*)tab;
  155198. int rc = SQLITE_OK;
  155199. int ii;
  155200. int bMatch = 0; /* True if there exists a MATCH constraint */
  155201. i64 nRow; /* Estimated rows returned by this scan */
  155202. int iIdx = 0;
  155203. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  155204. memset(zIdxStr, 0, sizeof(zIdxStr));
  155205. /* Check if there exists a MATCH constraint - even an unusable one. If there
  155206. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  155207. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  155208. ** possible. */
  155209. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  155210. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  155211. bMatch = 1;
  155212. }
  155213. }
  155214. assert( pIdxInfo->idxStr==0 );
  155215. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  155216. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  155217. if( bMatch==0 && p->usable
  155218. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  155219. ){
  155220. /* We have an equality constraint on the rowid. Use strategy 1. */
  155221. int jj;
  155222. for(jj=0; jj<ii; jj++){
  155223. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  155224. pIdxInfo->aConstraintUsage[jj].omit = 0;
  155225. }
  155226. pIdxInfo->idxNum = 1;
  155227. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  155228. pIdxInfo->aConstraintUsage[jj].omit = 1;
  155229. /* This strategy involves a two rowid lookups on an B-Tree structures
  155230. ** and then a linear search of an R-Tree node. This should be
  155231. ** considered almost as quick as a direct rowid lookup (for which
  155232. ** sqlite uses an internal cost of 0.0). It is expected to return
  155233. ** a single row.
  155234. */
  155235. pIdxInfo->estimatedCost = 30.0;
  155236. pIdxInfo->estimatedRows = 1;
  155237. return SQLITE_OK;
  155238. }
  155239. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  155240. u8 op;
  155241. switch( p->op ){
  155242. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  155243. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  155244. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  155245. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  155246. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  155247. default:
  155248. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  155249. op = RTREE_MATCH;
  155250. break;
  155251. }
  155252. zIdxStr[iIdx++] = op;
  155253. zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
  155254. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  155255. pIdxInfo->aConstraintUsage[ii].omit = 1;
  155256. }
  155257. }
  155258. pIdxInfo->idxNum = 2;
  155259. pIdxInfo->needToFreeIdxStr = 1;
  155260. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  155261. return SQLITE_NOMEM;
  155262. }
  155263. nRow = pRtree->nRowEst >> (iIdx/2);
  155264. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  155265. pIdxInfo->estimatedRows = nRow;
  155266. return rc;
  155267. }
  155268. /*
  155269. ** Return the N-dimensional volumn of the cell stored in *p.
  155270. */
  155271. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  155272. RtreeDValue area = (RtreeDValue)1;
  155273. assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
  155274. #ifndef SQLITE_RTREE_INT_ONLY
  155275. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  155276. switch( pRtree->nDim ){
  155277. case 5: area = p->aCoord[9].f - p->aCoord[8].f;
  155278. case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
  155279. case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
  155280. case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
  155281. default: area *= p->aCoord[1].f - p->aCoord[0].f;
  155282. }
  155283. }else
  155284. #endif
  155285. {
  155286. switch( pRtree->nDim ){
  155287. case 5: area = p->aCoord[9].i - p->aCoord[8].i;
  155288. case 4: area *= p->aCoord[7].i - p->aCoord[6].i;
  155289. case 3: area *= p->aCoord[5].i - p->aCoord[4].i;
  155290. case 2: area *= p->aCoord[3].i - p->aCoord[2].i;
  155291. default: area *= p->aCoord[1].i - p->aCoord[0].i;
  155292. }
  155293. }
  155294. return area;
  155295. }
  155296. /*
  155297. ** Return the margin length of cell p. The margin length is the sum
  155298. ** of the objects size in each dimension.
  155299. */
  155300. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  155301. RtreeDValue margin = 0;
  155302. int ii = pRtree->nDim2 - 2;
  155303. do{
  155304. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  155305. ii -= 2;
  155306. }while( ii>=0 );
  155307. return margin;
  155308. }
  155309. /*
  155310. ** Store the union of cells p1 and p2 in p1.
  155311. */
  155312. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  155313. int ii = 0;
  155314. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  155315. do{
  155316. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  155317. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  155318. ii += 2;
  155319. }while( ii<pRtree->nDim2 );
  155320. }else{
  155321. do{
  155322. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  155323. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  155324. ii += 2;
  155325. }while( ii<pRtree->nDim2 );
  155326. }
  155327. }
  155328. /*
  155329. ** Return true if the area covered by p2 is a subset of the area covered
  155330. ** by p1. False otherwise.
  155331. */
  155332. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  155333. int ii;
  155334. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  155335. for(ii=0; ii<pRtree->nDim2; ii+=2){
  155336. RtreeCoord *a1 = &p1->aCoord[ii];
  155337. RtreeCoord *a2 = &p2->aCoord[ii];
  155338. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  155339. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  155340. ){
  155341. return 0;
  155342. }
  155343. }
  155344. return 1;
  155345. }
  155346. /*
  155347. ** Return the amount cell p would grow by if it were unioned with pCell.
  155348. */
  155349. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  155350. RtreeDValue area;
  155351. RtreeCell cell;
  155352. memcpy(&cell, p, sizeof(RtreeCell));
  155353. area = cellArea(pRtree, &cell);
  155354. cellUnion(pRtree, &cell, pCell);
  155355. return (cellArea(pRtree, &cell)-area);
  155356. }
  155357. static RtreeDValue cellOverlap(
  155358. Rtree *pRtree,
  155359. RtreeCell *p,
  155360. RtreeCell *aCell,
  155361. int nCell
  155362. ){
  155363. int ii;
  155364. RtreeDValue overlap = RTREE_ZERO;
  155365. for(ii=0; ii<nCell; ii++){
  155366. int jj;
  155367. RtreeDValue o = (RtreeDValue)1;
  155368. for(jj=0; jj<pRtree->nDim2; jj+=2){
  155369. RtreeDValue x1, x2;
  155370. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  155371. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  155372. if( x2<x1 ){
  155373. o = (RtreeDValue)0;
  155374. break;
  155375. }else{
  155376. o = o * (x2-x1);
  155377. }
  155378. }
  155379. overlap += o;
  155380. }
  155381. return overlap;
  155382. }
  155383. /*
  155384. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  155385. ** ChooseSubTree in r*tree terminology.
  155386. */
  155387. static int ChooseLeaf(
  155388. Rtree *pRtree, /* Rtree table */
  155389. RtreeCell *pCell, /* Cell to insert into rtree */
  155390. int iHeight, /* Height of sub-tree rooted at pCell */
  155391. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  155392. ){
  155393. int rc;
  155394. int ii;
  155395. RtreeNode *pNode;
  155396. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  155397. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  155398. int iCell;
  155399. sqlite3_int64 iBest = 0;
  155400. RtreeDValue fMinGrowth = RTREE_ZERO;
  155401. RtreeDValue fMinArea = RTREE_ZERO;
  155402. int nCell = NCELL(pNode);
  155403. RtreeCell cell;
  155404. RtreeNode *pChild;
  155405. RtreeCell *aCell = 0;
  155406. /* Select the child node which will be enlarged the least if pCell
  155407. ** is inserted into it. Resolve ties by choosing the entry with
  155408. ** the smallest area.
  155409. */
  155410. for(iCell=0; iCell<nCell; iCell++){
  155411. int bBest = 0;
  155412. RtreeDValue growth;
  155413. RtreeDValue area;
  155414. nodeGetCell(pRtree, pNode, iCell, &cell);
  155415. growth = cellGrowth(pRtree, &cell, pCell);
  155416. area = cellArea(pRtree, &cell);
  155417. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  155418. bBest = 1;
  155419. }
  155420. if( bBest ){
  155421. fMinGrowth = growth;
  155422. fMinArea = area;
  155423. iBest = cell.iRowid;
  155424. }
  155425. }
  155426. sqlite3_free(aCell);
  155427. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  155428. nodeRelease(pRtree, pNode);
  155429. pNode = pChild;
  155430. }
  155431. *ppLeaf = pNode;
  155432. return rc;
  155433. }
  155434. /*
  155435. ** A cell with the same content as pCell has just been inserted into
  155436. ** the node pNode. This function updates the bounding box cells in
  155437. ** all ancestor elements.
  155438. */
  155439. static int AdjustTree(
  155440. Rtree *pRtree, /* Rtree table */
  155441. RtreeNode *pNode, /* Adjust ancestry of this node. */
  155442. RtreeCell *pCell /* This cell was just inserted */
  155443. ){
  155444. RtreeNode *p = pNode;
  155445. while( p->pParent ){
  155446. RtreeNode *pParent = p->pParent;
  155447. RtreeCell cell;
  155448. int iCell;
  155449. if( nodeParentIndex(pRtree, p, &iCell) ){
  155450. return SQLITE_CORRUPT_VTAB;
  155451. }
  155452. nodeGetCell(pRtree, pParent, iCell, &cell);
  155453. if( !cellContains(pRtree, &cell, pCell) ){
  155454. cellUnion(pRtree, &cell, pCell);
  155455. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  155456. }
  155457. p = pParent;
  155458. }
  155459. return SQLITE_OK;
  155460. }
  155461. /*
  155462. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  155463. */
  155464. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  155465. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  155466. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  155467. sqlite3_step(pRtree->pWriteRowid);
  155468. return sqlite3_reset(pRtree->pWriteRowid);
  155469. }
  155470. /*
  155471. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  155472. */
  155473. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  155474. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  155475. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  155476. sqlite3_step(pRtree->pWriteParent);
  155477. return sqlite3_reset(pRtree->pWriteParent);
  155478. }
  155479. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  155480. /*
  155481. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  155482. ** nIdx. The aIdx array contains the set of integers from 0 to
  155483. ** (nIdx-1) in no particular order. This function sorts the values
  155484. ** in aIdx according to the indexed values in aDistance. For
  155485. ** example, assuming the inputs:
  155486. **
  155487. ** aIdx = { 0, 1, 2, 3 }
  155488. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  155489. **
  155490. ** this function sets the aIdx array to contain:
  155491. **
  155492. ** aIdx = { 0, 1, 2, 3 }
  155493. **
  155494. ** The aSpare array is used as temporary working space by the
  155495. ** sorting algorithm.
  155496. */
  155497. static void SortByDistance(
  155498. int *aIdx,
  155499. int nIdx,
  155500. RtreeDValue *aDistance,
  155501. int *aSpare
  155502. ){
  155503. if( nIdx>1 ){
  155504. int iLeft = 0;
  155505. int iRight = 0;
  155506. int nLeft = nIdx/2;
  155507. int nRight = nIdx-nLeft;
  155508. int *aLeft = aIdx;
  155509. int *aRight = &aIdx[nLeft];
  155510. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  155511. SortByDistance(aRight, nRight, aDistance, aSpare);
  155512. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  155513. aLeft = aSpare;
  155514. while( iLeft<nLeft || iRight<nRight ){
  155515. if( iLeft==nLeft ){
  155516. aIdx[iLeft+iRight] = aRight[iRight];
  155517. iRight++;
  155518. }else if( iRight==nRight ){
  155519. aIdx[iLeft+iRight] = aLeft[iLeft];
  155520. iLeft++;
  155521. }else{
  155522. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  155523. RtreeDValue fRight = aDistance[aRight[iRight]];
  155524. if( fLeft<fRight ){
  155525. aIdx[iLeft+iRight] = aLeft[iLeft];
  155526. iLeft++;
  155527. }else{
  155528. aIdx[iLeft+iRight] = aRight[iRight];
  155529. iRight++;
  155530. }
  155531. }
  155532. }
  155533. #if 0
  155534. /* Check that the sort worked */
  155535. {
  155536. int jj;
  155537. for(jj=1; jj<nIdx; jj++){
  155538. RtreeDValue left = aDistance[aIdx[jj-1]];
  155539. RtreeDValue right = aDistance[aIdx[jj]];
  155540. assert( left<=right );
  155541. }
  155542. }
  155543. #endif
  155544. }
  155545. }
  155546. /*
  155547. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  155548. ** nIdx. The aIdx array contains the set of integers from 0 to
  155549. ** (nIdx-1) in no particular order. This function sorts the values
  155550. ** in aIdx according to dimension iDim of the cells in aCell. The
  155551. ** minimum value of dimension iDim is considered first, the
  155552. ** maximum used to break ties.
  155553. **
  155554. ** The aSpare array is used as temporary working space by the
  155555. ** sorting algorithm.
  155556. */
  155557. static void SortByDimension(
  155558. Rtree *pRtree,
  155559. int *aIdx,
  155560. int nIdx,
  155561. int iDim,
  155562. RtreeCell *aCell,
  155563. int *aSpare
  155564. ){
  155565. if( nIdx>1 ){
  155566. int iLeft = 0;
  155567. int iRight = 0;
  155568. int nLeft = nIdx/2;
  155569. int nRight = nIdx-nLeft;
  155570. int *aLeft = aIdx;
  155571. int *aRight = &aIdx[nLeft];
  155572. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  155573. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  155574. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  155575. aLeft = aSpare;
  155576. while( iLeft<nLeft || iRight<nRight ){
  155577. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  155578. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  155579. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  155580. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  155581. if( (iLeft!=nLeft) && ((iRight==nRight)
  155582. || (xleft1<xright1)
  155583. || (xleft1==xright1 && xleft2<xright2)
  155584. )){
  155585. aIdx[iLeft+iRight] = aLeft[iLeft];
  155586. iLeft++;
  155587. }else{
  155588. aIdx[iLeft+iRight] = aRight[iRight];
  155589. iRight++;
  155590. }
  155591. }
  155592. #if 0
  155593. /* Check that the sort worked */
  155594. {
  155595. int jj;
  155596. for(jj=1; jj<nIdx; jj++){
  155597. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  155598. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  155599. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  155600. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  155601. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  155602. }
  155603. }
  155604. #endif
  155605. }
  155606. }
  155607. /*
  155608. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  155609. */
  155610. static int splitNodeStartree(
  155611. Rtree *pRtree,
  155612. RtreeCell *aCell,
  155613. int nCell,
  155614. RtreeNode *pLeft,
  155615. RtreeNode *pRight,
  155616. RtreeCell *pBboxLeft,
  155617. RtreeCell *pBboxRight
  155618. ){
  155619. int **aaSorted;
  155620. int *aSpare;
  155621. int ii;
  155622. int iBestDim = 0;
  155623. int iBestSplit = 0;
  155624. RtreeDValue fBestMargin = RTREE_ZERO;
  155625. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  155626. aaSorted = (int **)sqlite3_malloc(nByte);
  155627. if( !aaSorted ){
  155628. return SQLITE_NOMEM;
  155629. }
  155630. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  155631. memset(aaSorted, 0, nByte);
  155632. for(ii=0; ii<pRtree->nDim; ii++){
  155633. int jj;
  155634. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  155635. for(jj=0; jj<nCell; jj++){
  155636. aaSorted[ii][jj] = jj;
  155637. }
  155638. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  155639. }
  155640. for(ii=0; ii<pRtree->nDim; ii++){
  155641. RtreeDValue margin = RTREE_ZERO;
  155642. RtreeDValue fBestOverlap = RTREE_ZERO;
  155643. RtreeDValue fBestArea = RTREE_ZERO;
  155644. int iBestLeft = 0;
  155645. int nLeft;
  155646. for(
  155647. nLeft=RTREE_MINCELLS(pRtree);
  155648. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  155649. nLeft++
  155650. ){
  155651. RtreeCell left;
  155652. RtreeCell right;
  155653. int kk;
  155654. RtreeDValue overlap;
  155655. RtreeDValue area;
  155656. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  155657. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  155658. for(kk=1; kk<(nCell-1); kk++){
  155659. if( kk<nLeft ){
  155660. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  155661. }else{
  155662. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  155663. }
  155664. }
  155665. margin += cellMargin(pRtree, &left);
  155666. margin += cellMargin(pRtree, &right);
  155667. overlap = cellOverlap(pRtree, &left, &right, 1);
  155668. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  155669. if( (nLeft==RTREE_MINCELLS(pRtree))
  155670. || (overlap<fBestOverlap)
  155671. || (overlap==fBestOverlap && area<fBestArea)
  155672. ){
  155673. iBestLeft = nLeft;
  155674. fBestOverlap = overlap;
  155675. fBestArea = area;
  155676. }
  155677. }
  155678. if( ii==0 || margin<fBestMargin ){
  155679. iBestDim = ii;
  155680. fBestMargin = margin;
  155681. iBestSplit = iBestLeft;
  155682. }
  155683. }
  155684. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  155685. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  155686. for(ii=0; ii<nCell; ii++){
  155687. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  155688. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  155689. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  155690. nodeInsertCell(pRtree, pTarget, pCell);
  155691. cellUnion(pRtree, pBbox, pCell);
  155692. }
  155693. sqlite3_free(aaSorted);
  155694. return SQLITE_OK;
  155695. }
  155696. static int updateMapping(
  155697. Rtree *pRtree,
  155698. i64 iRowid,
  155699. RtreeNode *pNode,
  155700. int iHeight
  155701. ){
  155702. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  155703. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  155704. if( iHeight>0 ){
  155705. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  155706. if( pChild ){
  155707. nodeRelease(pRtree, pChild->pParent);
  155708. nodeReference(pNode);
  155709. pChild->pParent = pNode;
  155710. }
  155711. }
  155712. return xSetMapping(pRtree, iRowid, pNode->iNode);
  155713. }
  155714. static int SplitNode(
  155715. Rtree *pRtree,
  155716. RtreeNode *pNode,
  155717. RtreeCell *pCell,
  155718. int iHeight
  155719. ){
  155720. int i;
  155721. int newCellIsRight = 0;
  155722. int rc = SQLITE_OK;
  155723. int nCell = NCELL(pNode);
  155724. RtreeCell *aCell;
  155725. int *aiUsed;
  155726. RtreeNode *pLeft = 0;
  155727. RtreeNode *pRight = 0;
  155728. RtreeCell leftbbox;
  155729. RtreeCell rightbbox;
  155730. /* Allocate an array and populate it with a copy of pCell and
  155731. ** all cells from node pLeft. Then zero the original node.
  155732. */
  155733. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  155734. if( !aCell ){
  155735. rc = SQLITE_NOMEM;
  155736. goto splitnode_out;
  155737. }
  155738. aiUsed = (int *)&aCell[nCell+1];
  155739. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  155740. for(i=0; i<nCell; i++){
  155741. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  155742. }
  155743. nodeZero(pRtree, pNode);
  155744. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  155745. nCell++;
  155746. if( pNode->iNode==1 ){
  155747. pRight = nodeNew(pRtree, pNode);
  155748. pLeft = nodeNew(pRtree, pNode);
  155749. pRtree->iDepth++;
  155750. pNode->isDirty = 1;
  155751. writeInt16(pNode->zData, pRtree->iDepth);
  155752. }else{
  155753. pLeft = pNode;
  155754. pRight = nodeNew(pRtree, pLeft->pParent);
  155755. nodeReference(pLeft);
  155756. }
  155757. if( !pLeft || !pRight ){
  155758. rc = SQLITE_NOMEM;
  155759. goto splitnode_out;
  155760. }
  155761. memset(pLeft->zData, 0, pRtree->iNodeSize);
  155762. memset(pRight->zData, 0, pRtree->iNodeSize);
  155763. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  155764. &leftbbox, &rightbbox);
  155765. if( rc!=SQLITE_OK ){
  155766. goto splitnode_out;
  155767. }
  155768. /* Ensure both child nodes have node numbers assigned to them by calling
  155769. ** nodeWrite(). Node pRight always needs a node number, as it was created
  155770. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  155771. ** In this case avoid the all to nodeWrite().
  155772. */
  155773. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  155774. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  155775. ){
  155776. goto splitnode_out;
  155777. }
  155778. rightbbox.iRowid = pRight->iNode;
  155779. leftbbox.iRowid = pLeft->iNode;
  155780. if( pNode->iNode==1 ){
  155781. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  155782. if( rc!=SQLITE_OK ){
  155783. goto splitnode_out;
  155784. }
  155785. }else{
  155786. RtreeNode *pParent = pLeft->pParent;
  155787. int iCell;
  155788. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  155789. if( rc==SQLITE_OK ){
  155790. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  155791. rc = AdjustTree(pRtree, pParent, &leftbbox);
  155792. }
  155793. if( rc!=SQLITE_OK ){
  155794. goto splitnode_out;
  155795. }
  155796. }
  155797. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  155798. goto splitnode_out;
  155799. }
  155800. for(i=0; i<NCELL(pRight); i++){
  155801. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  155802. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  155803. if( iRowid==pCell->iRowid ){
  155804. newCellIsRight = 1;
  155805. }
  155806. if( rc!=SQLITE_OK ){
  155807. goto splitnode_out;
  155808. }
  155809. }
  155810. if( pNode->iNode==1 ){
  155811. for(i=0; i<NCELL(pLeft); i++){
  155812. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  155813. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  155814. if( rc!=SQLITE_OK ){
  155815. goto splitnode_out;
  155816. }
  155817. }
  155818. }else if( newCellIsRight==0 ){
  155819. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  155820. }
  155821. if( rc==SQLITE_OK ){
  155822. rc = nodeRelease(pRtree, pRight);
  155823. pRight = 0;
  155824. }
  155825. if( rc==SQLITE_OK ){
  155826. rc = nodeRelease(pRtree, pLeft);
  155827. pLeft = 0;
  155828. }
  155829. splitnode_out:
  155830. nodeRelease(pRtree, pRight);
  155831. nodeRelease(pRtree, pLeft);
  155832. sqlite3_free(aCell);
  155833. return rc;
  155834. }
  155835. /*
  155836. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  155837. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  155838. ** the pLeaf->pParent chain all the way up to the root node.
  155839. **
  155840. ** This operation is required when a row is deleted (or updated - an update
  155841. ** is implemented as a delete followed by an insert). SQLite provides the
  155842. ** rowid of the row to delete, which can be used to find the leaf on which
  155843. ** the entry resides (argument pLeaf). Once the leaf is located, this
  155844. ** function is called to determine its ancestry.
  155845. */
  155846. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  155847. int rc = SQLITE_OK;
  155848. RtreeNode *pChild = pLeaf;
  155849. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  155850. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  155851. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  155852. rc = sqlite3_step(pRtree->pReadParent);
  155853. if( rc==SQLITE_ROW ){
  155854. RtreeNode *pTest; /* Used to test for reference loops */
  155855. i64 iNode; /* Node number of parent node */
  155856. /* Before setting pChild->pParent, test that we are not creating a
  155857. ** loop of references (as we would if, say, pChild==pParent). We don't
  155858. ** want to do this as it leads to a memory leak when trying to delete
  155859. ** the referenced counted node structures.
  155860. */
  155861. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  155862. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  155863. if( !pTest ){
  155864. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  155865. }
  155866. }
  155867. rc = sqlite3_reset(pRtree->pReadParent);
  155868. if( rc==SQLITE_OK ) rc = rc2;
  155869. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  155870. pChild = pChild->pParent;
  155871. }
  155872. return rc;
  155873. }
  155874. static int deleteCell(Rtree *, RtreeNode *, int, int);
  155875. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  155876. int rc;
  155877. int rc2;
  155878. RtreeNode *pParent = 0;
  155879. int iCell;
  155880. assert( pNode->nRef==1 );
  155881. /* Remove the entry in the parent cell. */
  155882. rc = nodeParentIndex(pRtree, pNode, &iCell);
  155883. if( rc==SQLITE_OK ){
  155884. pParent = pNode->pParent;
  155885. pNode->pParent = 0;
  155886. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  155887. }
  155888. rc2 = nodeRelease(pRtree, pParent);
  155889. if( rc==SQLITE_OK ){
  155890. rc = rc2;
  155891. }
  155892. if( rc!=SQLITE_OK ){
  155893. return rc;
  155894. }
  155895. /* Remove the xxx_node entry. */
  155896. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  155897. sqlite3_step(pRtree->pDeleteNode);
  155898. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  155899. return rc;
  155900. }
  155901. /* Remove the xxx_parent entry. */
  155902. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  155903. sqlite3_step(pRtree->pDeleteParent);
  155904. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  155905. return rc;
  155906. }
  155907. /* Remove the node from the in-memory hash table and link it into
  155908. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  155909. */
  155910. nodeHashDelete(pRtree, pNode);
  155911. pNode->iNode = iHeight;
  155912. pNode->pNext = pRtree->pDeleted;
  155913. pNode->nRef++;
  155914. pRtree->pDeleted = pNode;
  155915. return SQLITE_OK;
  155916. }
  155917. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  155918. RtreeNode *pParent = pNode->pParent;
  155919. int rc = SQLITE_OK;
  155920. if( pParent ){
  155921. int ii;
  155922. int nCell = NCELL(pNode);
  155923. RtreeCell box; /* Bounding box for pNode */
  155924. nodeGetCell(pRtree, pNode, 0, &box);
  155925. for(ii=1; ii<nCell; ii++){
  155926. RtreeCell cell;
  155927. nodeGetCell(pRtree, pNode, ii, &cell);
  155928. cellUnion(pRtree, &box, &cell);
  155929. }
  155930. box.iRowid = pNode->iNode;
  155931. rc = nodeParentIndex(pRtree, pNode, &ii);
  155932. if( rc==SQLITE_OK ){
  155933. nodeOverwriteCell(pRtree, pParent, &box, ii);
  155934. rc = fixBoundingBox(pRtree, pParent);
  155935. }
  155936. }
  155937. return rc;
  155938. }
  155939. /*
  155940. ** Delete the cell at index iCell of node pNode. After removing the
  155941. ** cell, adjust the r-tree data structure if required.
  155942. */
  155943. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  155944. RtreeNode *pParent;
  155945. int rc;
  155946. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  155947. return rc;
  155948. }
  155949. /* Remove the cell from the node. This call just moves bytes around
  155950. ** the in-memory node image, so it cannot fail.
  155951. */
  155952. nodeDeleteCell(pRtree, pNode, iCell);
  155953. /* If the node is not the tree root and now has less than the minimum
  155954. ** number of cells, remove it from the tree. Otherwise, update the
  155955. ** cell in the parent node so that it tightly contains the updated
  155956. ** node.
  155957. */
  155958. pParent = pNode->pParent;
  155959. assert( pParent || pNode->iNode==1 );
  155960. if( pParent ){
  155961. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  155962. rc = removeNode(pRtree, pNode, iHeight);
  155963. }else{
  155964. rc = fixBoundingBox(pRtree, pNode);
  155965. }
  155966. }
  155967. return rc;
  155968. }
  155969. static int Reinsert(
  155970. Rtree *pRtree,
  155971. RtreeNode *pNode,
  155972. RtreeCell *pCell,
  155973. int iHeight
  155974. ){
  155975. int *aOrder;
  155976. int *aSpare;
  155977. RtreeCell *aCell;
  155978. RtreeDValue *aDistance;
  155979. int nCell;
  155980. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  155981. int iDim;
  155982. int ii;
  155983. int rc = SQLITE_OK;
  155984. int n;
  155985. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  155986. nCell = NCELL(pNode)+1;
  155987. n = (nCell+1)&(~1);
  155988. /* Allocate the buffers used by this operation. The allocation is
  155989. ** relinquished before this function returns.
  155990. */
  155991. aCell = (RtreeCell *)sqlite3_malloc(n * (
  155992. sizeof(RtreeCell) + /* aCell array */
  155993. sizeof(int) + /* aOrder array */
  155994. sizeof(int) + /* aSpare array */
  155995. sizeof(RtreeDValue) /* aDistance array */
  155996. ));
  155997. if( !aCell ){
  155998. return SQLITE_NOMEM;
  155999. }
  156000. aOrder = (int *)&aCell[n];
  156001. aSpare = (int *)&aOrder[n];
  156002. aDistance = (RtreeDValue *)&aSpare[n];
  156003. for(ii=0; ii<nCell; ii++){
  156004. if( ii==(nCell-1) ){
  156005. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  156006. }else{
  156007. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  156008. }
  156009. aOrder[ii] = ii;
  156010. for(iDim=0; iDim<pRtree->nDim; iDim++){
  156011. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  156012. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  156013. }
  156014. }
  156015. for(iDim=0; iDim<pRtree->nDim; iDim++){
  156016. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  156017. }
  156018. for(ii=0; ii<nCell; ii++){
  156019. aDistance[ii] = RTREE_ZERO;
  156020. for(iDim=0; iDim<pRtree->nDim; iDim++){
  156021. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  156022. DCOORD(aCell[ii].aCoord[iDim*2]));
  156023. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  156024. }
  156025. }
  156026. SortByDistance(aOrder, nCell, aDistance, aSpare);
  156027. nodeZero(pRtree, pNode);
  156028. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  156029. RtreeCell *p = &aCell[aOrder[ii]];
  156030. nodeInsertCell(pRtree, pNode, p);
  156031. if( p->iRowid==pCell->iRowid ){
  156032. if( iHeight==0 ){
  156033. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  156034. }else{
  156035. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  156036. }
  156037. }
  156038. }
  156039. if( rc==SQLITE_OK ){
  156040. rc = fixBoundingBox(pRtree, pNode);
  156041. }
  156042. for(; rc==SQLITE_OK && ii<nCell; ii++){
  156043. /* Find a node to store this cell in. pNode->iNode currently contains
  156044. ** the height of the sub-tree headed by the cell.
  156045. */
  156046. RtreeNode *pInsert;
  156047. RtreeCell *p = &aCell[aOrder[ii]];
  156048. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  156049. if( rc==SQLITE_OK ){
  156050. int rc2;
  156051. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  156052. rc2 = nodeRelease(pRtree, pInsert);
  156053. if( rc==SQLITE_OK ){
  156054. rc = rc2;
  156055. }
  156056. }
  156057. }
  156058. sqlite3_free(aCell);
  156059. return rc;
  156060. }
  156061. /*
  156062. ** Insert cell pCell into node pNode. Node pNode is the head of a
  156063. ** subtree iHeight high (leaf nodes have iHeight==0).
  156064. */
  156065. static int rtreeInsertCell(
  156066. Rtree *pRtree,
  156067. RtreeNode *pNode,
  156068. RtreeCell *pCell,
  156069. int iHeight
  156070. ){
  156071. int rc = SQLITE_OK;
  156072. if( iHeight>0 ){
  156073. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  156074. if( pChild ){
  156075. nodeRelease(pRtree, pChild->pParent);
  156076. nodeReference(pNode);
  156077. pChild->pParent = pNode;
  156078. }
  156079. }
  156080. if( nodeInsertCell(pRtree, pNode, pCell) ){
  156081. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  156082. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  156083. }else{
  156084. pRtree->iReinsertHeight = iHeight;
  156085. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  156086. }
  156087. }else{
  156088. rc = AdjustTree(pRtree, pNode, pCell);
  156089. if( rc==SQLITE_OK ){
  156090. if( iHeight==0 ){
  156091. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  156092. }else{
  156093. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  156094. }
  156095. }
  156096. }
  156097. return rc;
  156098. }
  156099. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  156100. int ii;
  156101. int rc = SQLITE_OK;
  156102. int nCell = NCELL(pNode);
  156103. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  156104. RtreeNode *pInsert;
  156105. RtreeCell cell;
  156106. nodeGetCell(pRtree, pNode, ii, &cell);
  156107. /* Find a node to store this cell in. pNode->iNode currently contains
  156108. ** the height of the sub-tree headed by the cell.
  156109. */
  156110. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  156111. if( rc==SQLITE_OK ){
  156112. int rc2;
  156113. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  156114. rc2 = nodeRelease(pRtree, pInsert);
  156115. if( rc==SQLITE_OK ){
  156116. rc = rc2;
  156117. }
  156118. }
  156119. }
  156120. return rc;
  156121. }
  156122. /*
  156123. ** Select a currently unused rowid for a new r-tree record.
  156124. */
  156125. static int newRowid(Rtree *pRtree, i64 *piRowid){
  156126. int rc;
  156127. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  156128. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  156129. sqlite3_step(pRtree->pWriteRowid);
  156130. rc = sqlite3_reset(pRtree->pWriteRowid);
  156131. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  156132. return rc;
  156133. }
  156134. /*
  156135. ** Remove the entry with rowid=iDelete from the r-tree structure.
  156136. */
  156137. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  156138. int rc; /* Return code */
  156139. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  156140. int iCell; /* Index of iDelete cell in pLeaf */
  156141. RtreeNode *pRoot; /* Root node of rtree structure */
  156142. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  156143. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  156144. /* Obtain a reference to the leaf node that contains the entry
  156145. ** about to be deleted.
  156146. */
  156147. if( rc==SQLITE_OK ){
  156148. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  156149. }
  156150. /* Delete the cell in question from the leaf node. */
  156151. if( rc==SQLITE_OK ){
  156152. int rc2;
  156153. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  156154. if( rc==SQLITE_OK ){
  156155. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  156156. }
  156157. rc2 = nodeRelease(pRtree, pLeaf);
  156158. if( rc==SQLITE_OK ){
  156159. rc = rc2;
  156160. }
  156161. }
  156162. /* Delete the corresponding entry in the <rtree>_rowid table. */
  156163. if( rc==SQLITE_OK ){
  156164. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  156165. sqlite3_step(pRtree->pDeleteRowid);
  156166. rc = sqlite3_reset(pRtree->pDeleteRowid);
  156167. }
  156168. /* Check if the root node now has exactly one child. If so, remove
  156169. ** it, schedule the contents of the child for reinsertion and
  156170. ** reduce the tree height by one.
  156171. **
  156172. ** This is equivalent to copying the contents of the child into
  156173. ** the root node (the operation that Gutman's paper says to perform
  156174. ** in this scenario).
  156175. */
  156176. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  156177. int rc2;
  156178. RtreeNode *pChild;
  156179. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  156180. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  156181. if( rc==SQLITE_OK ){
  156182. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  156183. }
  156184. rc2 = nodeRelease(pRtree, pChild);
  156185. if( rc==SQLITE_OK ) rc = rc2;
  156186. if( rc==SQLITE_OK ){
  156187. pRtree->iDepth--;
  156188. writeInt16(pRoot->zData, pRtree->iDepth);
  156189. pRoot->isDirty = 1;
  156190. }
  156191. }
  156192. /* Re-insert the contents of any underfull nodes removed from the tree. */
  156193. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  156194. if( rc==SQLITE_OK ){
  156195. rc = reinsertNodeContent(pRtree, pLeaf);
  156196. }
  156197. pRtree->pDeleted = pLeaf->pNext;
  156198. sqlite3_free(pLeaf);
  156199. }
  156200. /* Release the reference to the root node. */
  156201. if( rc==SQLITE_OK ){
  156202. rc = nodeRelease(pRtree, pRoot);
  156203. }else{
  156204. nodeRelease(pRtree, pRoot);
  156205. }
  156206. return rc;
  156207. }
  156208. /*
  156209. ** Rounding constants for float->double conversion.
  156210. */
  156211. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  156212. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  156213. #if !defined(SQLITE_RTREE_INT_ONLY)
  156214. /*
  156215. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  156216. ** while taking care to round toward negative or positive, respectively.
  156217. */
  156218. static RtreeValue rtreeValueDown(sqlite3_value *v){
  156219. double d = sqlite3_value_double(v);
  156220. float f = (float)d;
  156221. if( f>d ){
  156222. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  156223. }
  156224. return f;
  156225. }
  156226. static RtreeValue rtreeValueUp(sqlite3_value *v){
  156227. double d = sqlite3_value_double(v);
  156228. float f = (float)d;
  156229. if( f<d ){
  156230. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  156231. }
  156232. return f;
  156233. }
  156234. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  156235. /*
  156236. ** A constraint has failed while inserting a row into an rtree table.
  156237. ** Assuming no OOM error occurs, this function sets the error message
  156238. ** (at pRtree->base.zErrMsg) to an appropriate value and returns
  156239. ** SQLITE_CONSTRAINT.
  156240. **
  156241. ** Parameter iCol is the index of the leftmost column involved in the
  156242. ** constraint failure. If it is 0, then the constraint that failed is
  156243. ** the unique constraint on the id column. Otherwise, it is the rtree
  156244. ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
  156245. **
  156246. ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
  156247. */
  156248. static int rtreeConstraintError(Rtree *pRtree, int iCol){
  156249. sqlite3_stmt *pStmt = 0;
  156250. char *zSql;
  156251. int rc;
  156252. assert( iCol==0 || iCol%2 );
  156253. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
  156254. if( zSql ){
  156255. rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
  156256. }else{
  156257. rc = SQLITE_NOMEM;
  156258. }
  156259. sqlite3_free(zSql);
  156260. if( rc==SQLITE_OK ){
  156261. if( iCol==0 ){
  156262. const char *zCol = sqlite3_column_name(pStmt, 0);
  156263. pRtree->base.zErrMsg = sqlite3_mprintf(
  156264. "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
  156265. );
  156266. }else{
  156267. const char *zCol1 = sqlite3_column_name(pStmt, iCol);
  156268. const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
  156269. pRtree->base.zErrMsg = sqlite3_mprintf(
  156270. "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
  156271. );
  156272. }
  156273. }
  156274. sqlite3_finalize(pStmt);
  156275. return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
  156276. }
  156277. /*
  156278. ** The xUpdate method for rtree module virtual tables.
  156279. */
  156280. static int rtreeUpdate(
  156281. sqlite3_vtab *pVtab,
  156282. int nData,
  156283. sqlite3_value **azData,
  156284. sqlite_int64 *pRowid
  156285. ){
  156286. Rtree *pRtree = (Rtree *)pVtab;
  156287. int rc = SQLITE_OK;
  156288. RtreeCell cell; /* New cell to insert if nData>1 */
  156289. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  156290. rtreeReference(pRtree);
  156291. assert(nData>=1);
  156292. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  156293. /* Constraint handling. A write operation on an r-tree table may return
  156294. ** SQLITE_CONSTRAINT for two reasons:
  156295. **
  156296. ** 1. A duplicate rowid value, or
  156297. ** 2. The supplied data violates the "x2>=x1" constraint.
  156298. **
  156299. ** In the first case, if the conflict-handling mode is REPLACE, then
  156300. ** the conflicting row can be removed before proceeding. In the second
  156301. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  156302. ** conflict-handling mode specified by the user.
  156303. */
  156304. if( nData>1 ){
  156305. int ii;
  156306. /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
  156307. **
  156308. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  156309. ** with "column" that are interpreted as table constraints.
  156310. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  156311. ** This problem was discovered after years of use, so we silently ignore
  156312. ** these kinds of misdeclared tables to avoid breaking any legacy.
  156313. */
  156314. assert( nData<=(pRtree->nDim2 + 3) );
  156315. #ifndef SQLITE_RTREE_INT_ONLY
  156316. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  156317. for(ii=0; ii<nData-4; ii+=2){
  156318. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  156319. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  156320. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  156321. rc = rtreeConstraintError(pRtree, ii+1);
  156322. goto constraint;
  156323. }
  156324. }
  156325. }else
  156326. #endif
  156327. {
  156328. for(ii=0; ii<nData-4; ii+=2){
  156329. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  156330. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  156331. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  156332. rc = rtreeConstraintError(pRtree, ii+1);
  156333. goto constraint;
  156334. }
  156335. }
  156336. }
  156337. /* If a rowid value was supplied, check if it is already present in
  156338. ** the table. If so, the constraint has failed. */
  156339. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  156340. cell.iRowid = sqlite3_value_int64(azData[2]);
  156341. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  156342. || sqlite3_value_int64(azData[0])!=cell.iRowid
  156343. ){
  156344. int steprc;
  156345. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  156346. steprc = sqlite3_step(pRtree->pReadRowid);
  156347. rc = sqlite3_reset(pRtree->pReadRowid);
  156348. if( SQLITE_ROW==steprc ){
  156349. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  156350. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  156351. }else{
  156352. rc = rtreeConstraintError(pRtree, 0);
  156353. goto constraint;
  156354. }
  156355. }
  156356. }
  156357. bHaveRowid = 1;
  156358. }
  156359. }
  156360. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  156361. ** record to delete from the r-tree table. The following block does
  156362. ** just that.
  156363. */
  156364. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  156365. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  156366. }
  156367. /* If the azData[] array contains more than one element, elements
  156368. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  156369. ** the r-tree structure.
  156370. */
  156371. if( rc==SQLITE_OK && nData>1 ){
  156372. /* Insert the new record into the r-tree */
  156373. RtreeNode *pLeaf = 0;
  156374. /* Figure out the rowid of the new row. */
  156375. if( bHaveRowid==0 ){
  156376. rc = newRowid(pRtree, &cell.iRowid);
  156377. }
  156378. *pRowid = cell.iRowid;
  156379. if( rc==SQLITE_OK ){
  156380. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  156381. }
  156382. if( rc==SQLITE_OK ){
  156383. int rc2;
  156384. pRtree->iReinsertHeight = -1;
  156385. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  156386. rc2 = nodeRelease(pRtree, pLeaf);
  156387. if( rc==SQLITE_OK ){
  156388. rc = rc2;
  156389. }
  156390. }
  156391. }
  156392. constraint:
  156393. rtreeRelease(pRtree);
  156394. return rc;
  156395. }
  156396. /*
  156397. ** Called when a transaction starts.
  156398. */
  156399. static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
  156400. Rtree *pRtree = (Rtree *)pVtab;
  156401. assert( pRtree->inWrTrans==0 );
  156402. pRtree->inWrTrans++;
  156403. return SQLITE_OK;
  156404. }
  156405. /*
  156406. ** Called when a transaction completes (either by COMMIT or ROLLBACK).
  156407. ** The sqlite3_blob object should be released at this point.
  156408. */
  156409. static int rtreeEndTransaction(sqlite3_vtab *pVtab){
  156410. Rtree *pRtree = (Rtree *)pVtab;
  156411. pRtree->inWrTrans = 0;
  156412. nodeBlobReset(pRtree);
  156413. return SQLITE_OK;
  156414. }
  156415. /*
  156416. ** The xRename method for rtree module virtual tables.
  156417. */
  156418. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  156419. Rtree *pRtree = (Rtree *)pVtab;
  156420. int rc = SQLITE_NOMEM;
  156421. char *zSql = sqlite3_mprintf(
  156422. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  156423. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  156424. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  156425. , pRtree->zDb, pRtree->zName, zNewName
  156426. , pRtree->zDb, pRtree->zName, zNewName
  156427. , pRtree->zDb, pRtree->zName, zNewName
  156428. );
  156429. if( zSql ){
  156430. nodeBlobReset(pRtree);
  156431. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  156432. sqlite3_free(zSql);
  156433. }
  156434. return rc;
  156435. }
  156436. /*
  156437. ** The xSavepoint method.
  156438. **
  156439. ** This module does not need to do anything to support savepoints. However,
  156440. ** it uses this hook to close any open blob handle. This is done because a
  156441. ** DROP TABLE command - which fortunately always opens a savepoint - cannot
  156442. ** succeed if there are any open blob handles. i.e. if the blob handle were
  156443. ** not closed here, the following would fail:
  156444. **
  156445. ** BEGIN;
  156446. ** INSERT INTO rtree...
  156447. ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
  156448. ** COMMIT;
  156449. */
  156450. static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
  156451. Rtree *pRtree = (Rtree *)pVtab;
  156452. int iwt = pRtree->inWrTrans;
  156453. UNUSED_PARAMETER(iSavepoint);
  156454. pRtree->inWrTrans = 0;
  156455. nodeBlobReset(pRtree);
  156456. pRtree->inWrTrans = iwt;
  156457. return SQLITE_OK;
  156458. }
  156459. /*
  156460. ** This function populates the pRtree->nRowEst variable with an estimate
  156461. ** of the number of rows in the virtual table. If possible, this is based
  156462. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  156463. */
  156464. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  156465. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  156466. char *zSql;
  156467. sqlite3_stmt *p;
  156468. int rc;
  156469. i64 nRow = 0;
  156470. rc = sqlite3_table_column_metadata(
  156471. db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
  156472. );
  156473. if( rc!=SQLITE_OK ){
  156474. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  156475. return rc==SQLITE_ERROR ? SQLITE_OK : rc;
  156476. }
  156477. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  156478. if( zSql==0 ){
  156479. rc = SQLITE_NOMEM;
  156480. }else{
  156481. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  156482. if( rc==SQLITE_OK ){
  156483. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  156484. rc = sqlite3_finalize(p);
  156485. }else if( rc!=SQLITE_NOMEM ){
  156486. rc = SQLITE_OK;
  156487. }
  156488. if( rc==SQLITE_OK ){
  156489. if( nRow==0 ){
  156490. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  156491. }else{
  156492. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  156493. }
  156494. }
  156495. sqlite3_free(zSql);
  156496. }
  156497. return rc;
  156498. }
  156499. static sqlite3_module rtreeModule = {
  156500. 2, /* iVersion */
  156501. rtreeCreate, /* xCreate - create a table */
  156502. rtreeConnect, /* xConnect - connect to an existing table */
  156503. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  156504. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  156505. rtreeDestroy, /* xDestroy - Drop a table */
  156506. rtreeOpen, /* xOpen - open a cursor */
  156507. rtreeClose, /* xClose - close a cursor */
  156508. rtreeFilter, /* xFilter - configure scan constraints */
  156509. rtreeNext, /* xNext - advance a cursor */
  156510. rtreeEof, /* xEof */
  156511. rtreeColumn, /* xColumn - read data */
  156512. rtreeRowid, /* xRowid - read data */
  156513. rtreeUpdate, /* xUpdate - write data */
  156514. rtreeBeginTransaction, /* xBegin - begin transaction */
  156515. rtreeEndTransaction, /* xSync - sync transaction */
  156516. rtreeEndTransaction, /* xCommit - commit transaction */
  156517. rtreeEndTransaction, /* xRollback - rollback transaction */
  156518. 0, /* xFindFunction - function overloading */
  156519. rtreeRename, /* xRename - rename the table */
  156520. rtreeSavepoint, /* xSavepoint */
  156521. 0, /* xRelease */
  156522. 0, /* xRollbackTo */
  156523. };
  156524. static int rtreeSqlInit(
  156525. Rtree *pRtree,
  156526. sqlite3 *db,
  156527. const char *zDb,
  156528. const char *zPrefix,
  156529. int isCreate
  156530. ){
  156531. int rc = SQLITE_OK;
  156532. #define N_STATEMENT 8
  156533. static const char *azSql[N_STATEMENT] = {
  156534. /* Write the xxx_node table */
  156535. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  156536. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  156537. /* Read and write the xxx_rowid table */
  156538. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  156539. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  156540. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  156541. /* Read and write the xxx_parent table */
  156542. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  156543. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  156544. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  156545. };
  156546. sqlite3_stmt **appStmt[N_STATEMENT];
  156547. int i;
  156548. pRtree->db = db;
  156549. if( isCreate ){
  156550. char *zCreate = sqlite3_mprintf(
  156551. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  156552. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  156553. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  156554. " parentnode INTEGER);"
  156555. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  156556. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  156557. );
  156558. if( !zCreate ){
  156559. return SQLITE_NOMEM;
  156560. }
  156561. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  156562. sqlite3_free(zCreate);
  156563. if( rc!=SQLITE_OK ){
  156564. return rc;
  156565. }
  156566. }
  156567. appStmt[0] = &pRtree->pWriteNode;
  156568. appStmt[1] = &pRtree->pDeleteNode;
  156569. appStmt[2] = &pRtree->pReadRowid;
  156570. appStmt[3] = &pRtree->pWriteRowid;
  156571. appStmt[4] = &pRtree->pDeleteRowid;
  156572. appStmt[5] = &pRtree->pReadParent;
  156573. appStmt[6] = &pRtree->pWriteParent;
  156574. appStmt[7] = &pRtree->pDeleteParent;
  156575. rc = rtreeQueryStat1(db, pRtree);
  156576. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  156577. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  156578. if( zSql ){
  156579. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  156580. }else{
  156581. rc = SQLITE_NOMEM;
  156582. }
  156583. sqlite3_free(zSql);
  156584. }
  156585. return rc;
  156586. }
  156587. /*
  156588. ** The second argument to this function contains the text of an SQL statement
  156589. ** that returns a single integer value. The statement is compiled and executed
  156590. ** using database connection db. If successful, the integer value returned
  156591. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  156592. ** code is returned and the value of *piVal after returning is not defined.
  156593. */
  156594. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  156595. int rc = SQLITE_NOMEM;
  156596. if( zSql ){
  156597. sqlite3_stmt *pStmt = 0;
  156598. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  156599. if( rc==SQLITE_OK ){
  156600. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  156601. *piVal = sqlite3_column_int(pStmt, 0);
  156602. }
  156603. rc = sqlite3_finalize(pStmt);
  156604. }
  156605. }
  156606. return rc;
  156607. }
  156608. /*
  156609. ** This function is called from within the xConnect() or xCreate() method to
  156610. ** determine the node-size used by the rtree table being created or connected
  156611. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  156612. ** Otherwise, an SQLite error code is returned.
  156613. **
  156614. ** If this function is being called as part of an xConnect(), then the rtree
  156615. ** table already exists. In this case the node-size is determined by inspecting
  156616. ** the root node of the tree.
  156617. **
  156618. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  156619. ** This ensures that each node is stored on a single database page. If the
  156620. ** database page-size is so large that more than RTREE_MAXCELLS entries
  156621. ** would fit in a single node, use a smaller node-size.
  156622. */
  156623. static int getNodeSize(
  156624. sqlite3 *db, /* Database handle */
  156625. Rtree *pRtree, /* Rtree handle */
  156626. int isCreate, /* True for xCreate, false for xConnect */
  156627. char **pzErr /* OUT: Error message, if any */
  156628. ){
  156629. int rc;
  156630. char *zSql;
  156631. if( isCreate ){
  156632. int iPageSize = 0;
  156633. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  156634. rc = getIntFromStmt(db, zSql, &iPageSize);
  156635. if( rc==SQLITE_OK ){
  156636. pRtree->iNodeSize = iPageSize-64;
  156637. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  156638. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  156639. }
  156640. }else{
  156641. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  156642. }
  156643. }else{
  156644. zSql = sqlite3_mprintf(
  156645. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  156646. pRtree->zDb, pRtree->zName
  156647. );
  156648. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  156649. if( rc!=SQLITE_OK ){
  156650. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  156651. }
  156652. }
  156653. sqlite3_free(zSql);
  156654. return rc;
  156655. }
  156656. /*
  156657. ** This function is the implementation of both the xConnect and xCreate
  156658. ** methods of the r-tree virtual table.
  156659. **
  156660. ** argv[0] -> module name
  156661. ** argv[1] -> database name
  156662. ** argv[2] -> table name
  156663. ** argv[...] -> column names...
  156664. */
  156665. static int rtreeInit(
  156666. sqlite3 *db, /* Database connection */
  156667. void *pAux, /* One of the RTREE_COORD_* constants */
  156668. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  156669. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  156670. char **pzErr, /* OUT: Error message, if any */
  156671. int isCreate /* True for xCreate, false for xConnect */
  156672. ){
  156673. int rc = SQLITE_OK;
  156674. Rtree *pRtree;
  156675. int nDb; /* Length of string argv[1] */
  156676. int nName; /* Length of string argv[2] */
  156677. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  156678. const char *aErrMsg[] = {
  156679. 0, /* 0 */
  156680. "Wrong number of columns for an rtree table", /* 1 */
  156681. "Too few columns for an rtree table", /* 2 */
  156682. "Too many columns for an rtree table" /* 3 */
  156683. };
  156684. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  156685. if( aErrMsg[iErr] ){
  156686. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  156687. return SQLITE_ERROR;
  156688. }
  156689. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  156690. /* Allocate the sqlite3_vtab structure */
  156691. nDb = (int)strlen(argv[1]);
  156692. nName = (int)strlen(argv[2]);
  156693. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  156694. if( !pRtree ){
  156695. return SQLITE_NOMEM;
  156696. }
  156697. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  156698. pRtree->nBusy = 1;
  156699. pRtree->base.pModule = &rtreeModule;
  156700. pRtree->zDb = (char *)&pRtree[1];
  156701. pRtree->zName = &pRtree->zDb[nDb+1];
  156702. pRtree->nDim = (u8)((argc-4)/2);
  156703. pRtree->nDim2 = pRtree->nDim*2;
  156704. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  156705. pRtree->eCoordType = (u8)eCoordType;
  156706. memcpy(pRtree->zDb, argv[1], nDb);
  156707. memcpy(pRtree->zName, argv[2], nName);
  156708. /* Figure out the node size to use. */
  156709. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  156710. /* Create/Connect to the underlying relational database schema. If
  156711. ** that is successful, call sqlite3_declare_vtab() to configure
  156712. ** the r-tree table schema.
  156713. */
  156714. if( rc==SQLITE_OK ){
  156715. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  156716. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  156717. }else{
  156718. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  156719. char *zTmp;
  156720. int ii;
  156721. for(ii=4; zSql && ii<argc; ii++){
  156722. zTmp = zSql;
  156723. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  156724. sqlite3_free(zTmp);
  156725. }
  156726. if( zSql ){
  156727. zTmp = zSql;
  156728. zSql = sqlite3_mprintf("%s);", zTmp);
  156729. sqlite3_free(zTmp);
  156730. }
  156731. if( !zSql ){
  156732. rc = SQLITE_NOMEM;
  156733. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  156734. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  156735. }
  156736. sqlite3_free(zSql);
  156737. }
  156738. }
  156739. if( rc==SQLITE_OK ){
  156740. *ppVtab = (sqlite3_vtab *)pRtree;
  156741. }else{
  156742. assert( *ppVtab==0 );
  156743. assert( pRtree->nBusy==1 );
  156744. rtreeRelease(pRtree);
  156745. }
  156746. return rc;
  156747. }
  156748. /*
  156749. ** Implementation of a scalar function that decodes r-tree nodes to
  156750. ** human readable strings. This can be used for debugging and analysis.
  156751. **
  156752. ** The scalar function takes two arguments: (1) the number of dimensions
  156753. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  156754. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  156755. ** deserialize all nodes, a statement like:
  156756. **
  156757. ** SELECT rtreenode(2, data) FROM rt_node;
  156758. **
  156759. ** The human readable string takes the form of a Tcl list with one
  156760. ** entry for each cell in the r-tree node. Each entry is itself a
  156761. ** list, containing the 8-byte rowid/pageno followed by the
  156762. ** <num-dimension>*2 coordinates.
  156763. */
  156764. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  156765. char *zText = 0;
  156766. RtreeNode node;
  156767. Rtree tree;
  156768. int ii;
  156769. UNUSED_PARAMETER(nArg);
  156770. memset(&node, 0, sizeof(RtreeNode));
  156771. memset(&tree, 0, sizeof(Rtree));
  156772. tree.nDim = (u8)sqlite3_value_int(apArg[0]);
  156773. tree.nDim2 = tree.nDim*2;
  156774. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  156775. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  156776. for(ii=0; ii<NCELL(&node); ii++){
  156777. char zCell[512];
  156778. int nCell = 0;
  156779. RtreeCell cell;
  156780. int jj;
  156781. nodeGetCell(&tree, &node, ii, &cell);
  156782. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  156783. nCell = (int)strlen(zCell);
  156784. for(jj=0; jj<tree.nDim2; jj++){
  156785. #ifndef SQLITE_RTREE_INT_ONLY
  156786. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  156787. (double)cell.aCoord[jj].f);
  156788. #else
  156789. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  156790. cell.aCoord[jj].i);
  156791. #endif
  156792. nCell = (int)strlen(zCell);
  156793. }
  156794. if( zText ){
  156795. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  156796. sqlite3_free(zText);
  156797. zText = zTextNew;
  156798. }else{
  156799. zText = sqlite3_mprintf("{%s}", zCell);
  156800. }
  156801. }
  156802. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  156803. }
  156804. /* This routine implements an SQL function that returns the "depth" parameter
  156805. ** from the front of a blob that is an r-tree node. For example:
  156806. **
  156807. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  156808. **
  156809. ** The depth value is 0 for all nodes other than the root node, and the root
  156810. ** node always has nodeno=1, so the example above is the primary use for this
  156811. ** routine. This routine is intended for testing and analysis only.
  156812. */
  156813. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  156814. UNUSED_PARAMETER(nArg);
  156815. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  156816. || sqlite3_value_bytes(apArg[0])<2
  156817. ){
  156818. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  156819. }else{
  156820. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  156821. sqlite3_result_int(ctx, readInt16(zBlob));
  156822. }
  156823. }
  156824. /*
  156825. ** Register the r-tree module with database handle db. This creates the
  156826. ** virtual table module "rtree" and the debugging/analysis scalar
  156827. ** function "rtreenode".
  156828. */
  156829. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  156830. const int utf8 = SQLITE_UTF8;
  156831. int rc;
  156832. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  156833. if( rc==SQLITE_OK ){
  156834. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  156835. }
  156836. if( rc==SQLITE_OK ){
  156837. #ifdef SQLITE_RTREE_INT_ONLY
  156838. void *c = (void *)RTREE_COORD_INT32;
  156839. #else
  156840. void *c = (void *)RTREE_COORD_REAL32;
  156841. #endif
  156842. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  156843. }
  156844. if( rc==SQLITE_OK ){
  156845. void *c = (void *)RTREE_COORD_INT32;
  156846. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  156847. }
  156848. return rc;
  156849. }
  156850. /*
  156851. ** This routine deletes the RtreeGeomCallback object that was attached
  156852. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  156853. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  156854. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  156855. ** the corresponding SQL function is deleted.
  156856. */
  156857. static void rtreeFreeCallback(void *p){
  156858. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  156859. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  156860. sqlite3_free(p);
  156861. }
  156862. /*
  156863. ** This routine frees the BLOB that is returned by geomCallback().
  156864. */
  156865. static void rtreeMatchArgFree(void *pArg){
  156866. int i;
  156867. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  156868. for(i=0; i<p->nParam; i++){
  156869. sqlite3_value_free(p->apSqlParam[i]);
  156870. }
  156871. sqlite3_free(p);
  156872. }
  156873. /*
  156874. ** Each call to sqlite3_rtree_geometry_callback() or
  156875. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  156876. ** scalar function that is implemented by this routine.
  156877. **
  156878. ** All this function does is construct an RtreeMatchArg object that
  156879. ** contains the geometry-checking callback routines and a list of
  156880. ** parameters to this function, then return that RtreeMatchArg object
  156881. ** as a BLOB.
  156882. **
  156883. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  156884. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  156885. ** out which elements of the R-Tree should be returned by the query.
  156886. */
  156887. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  156888. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  156889. RtreeMatchArg *pBlob;
  156890. int nBlob;
  156891. int memErr = 0;
  156892. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  156893. + nArg*sizeof(sqlite3_value*);
  156894. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  156895. if( !pBlob ){
  156896. sqlite3_result_error_nomem(ctx);
  156897. }else{
  156898. int i;
  156899. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  156900. pBlob->cb = pGeomCtx[0];
  156901. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  156902. pBlob->nParam = nArg;
  156903. for(i=0; i<nArg; i++){
  156904. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  156905. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  156906. #ifdef SQLITE_RTREE_INT_ONLY
  156907. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  156908. #else
  156909. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  156910. #endif
  156911. }
  156912. if( memErr ){
  156913. sqlite3_result_error_nomem(ctx);
  156914. rtreeMatchArgFree(pBlob);
  156915. }else{
  156916. sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
  156917. }
  156918. }
  156919. }
  156920. /*
  156921. ** Register a new geometry function for use with the r-tree MATCH operator.
  156922. */
  156923. SQLITE_API int sqlite3_rtree_geometry_callback(
  156924. sqlite3 *db, /* Register SQL function on this connection */
  156925. const char *zGeom, /* Name of the new SQL function */
  156926. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  156927. void *pContext /* Extra data associated with the callback */
  156928. ){
  156929. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  156930. /* Allocate and populate the context object. */
  156931. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  156932. if( !pGeomCtx ) return SQLITE_NOMEM;
  156933. pGeomCtx->xGeom = xGeom;
  156934. pGeomCtx->xQueryFunc = 0;
  156935. pGeomCtx->xDestructor = 0;
  156936. pGeomCtx->pContext = pContext;
  156937. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  156938. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  156939. );
  156940. }
  156941. /*
  156942. ** Register a new 2nd-generation geometry function for use with the
  156943. ** r-tree MATCH operator.
  156944. */
  156945. SQLITE_API int sqlite3_rtree_query_callback(
  156946. sqlite3 *db, /* Register SQL function on this connection */
  156947. const char *zQueryFunc, /* Name of new SQL function */
  156948. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  156949. void *pContext, /* Extra data passed into the callback */
  156950. void (*xDestructor)(void*) /* Destructor for the extra data */
  156951. ){
  156952. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  156953. /* Allocate and populate the context object. */
  156954. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  156955. if( !pGeomCtx ) return SQLITE_NOMEM;
  156956. pGeomCtx->xGeom = 0;
  156957. pGeomCtx->xQueryFunc = xQueryFunc;
  156958. pGeomCtx->xDestructor = xDestructor;
  156959. pGeomCtx->pContext = pContext;
  156960. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  156961. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  156962. );
  156963. }
  156964. #if !SQLITE_CORE
  156965. #ifdef _WIN32
  156966. __declspec(dllexport)
  156967. #endif
  156968. SQLITE_API int sqlite3_rtree_init(
  156969. sqlite3 *db,
  156970. char **pzErrMsg,
  156971. const sqlite3_api_routines *pApi
  156972. ){
  156973. SQLITE_EXTENSION_INIT2(pApi)
  156974. return sqlite3RtreeInit(db);
  156975. }
  156976. #endif
  156977. #endif
  156978. /************** End of rtree.c ***********************************************/
  156979. /************** Begin file icu.c *********************************************/
  156980. /*
  156981. ** 2007 May 6
  156982. **
  156983. ** The author disclaims copyright to this source code. In place of
  156984. ** a legal notice, here is a blessing:
  156985. **
  156986. ** May you do good and not evil.
  156987. ** May you find forgiveness for yourself and forgive others.
  156988. ** May you share freely, never taking more than you give.
  156989. **
  156990. *************************************************************************
  156991. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  156992. **
  156993. ** This file implements an integration between the ICU library
  156994. ** ("International Components for Unicode", an open-source library
  156995. ** for handling unicode data) and SQLite. The integration uses
  156996. ** ICU to provide the following to SQLite:
  156997. **
  156998. ** * An implementation of the SQL regexp() function (and hence REGEXP
  156999. ** operator) using the ICU uregex_XX() APIs.
  157000. **
  157001. ** * Implementations of the SQL scalar upper() and lower() functions
  157002. ** for case mapping.
  157003. **
  157004. ** * Integration of ICU and SQLite collation sequences.
  157005. **
  157006. ** * An implementation of the LIKE operator that uses ICU to
  157007. ** provide case-independent matching.
  157008. */
  157009. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  157010. /* Include ICU headers */
  157011. #include <unicode/utypes.h>
  157012. #include <unicode/uregex.h>
  157013. #include <unicode/ustring.h>
  157014. #include <unicode/ucol.h>
  157015. /* #include <assert.h> */
  157016. #ifndef SQLITE_CORE
  157017. /* #include "sqlite3ext.h" */
  157018. SQLITE_EXTENSION_INIT1
  157019. #else
  157020. /* #include "sqlite3.h" */
  157021. #endif
  157022. /*
  157023. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  157024. ** operator.
  157025. */
  157026. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  157027. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  157028. #endif
  157029. /*
  157030. ** Version of sqlite3_free() that is always a function, never a macro.
  157031. */
  157032. static void xFree(void *p){
  157033. sqlite3_free(p);
  157034. }
  157035. /*
  157036. ** This lookup table is used to help decode the first byte of
  157037. ** a multi-byte UTF8 character. It is copied here from SQLite source
  157038. ** code file utf8.c.
  157039. */
  157040. static const unsigned char icuUtf8Trans1[] = {
  157041. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  157042. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  157043. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  157044. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  157045. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  157046. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  157047. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  157048. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  157049. };
  157050. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  157051. c = *(zIn++); \
  157052. if( c>=0xc0 ){ \
  157053. c = icuUtf8Trans1[c-0xc0]; \
  157054. while( (*zIn & 0xc0)==0x80 ){ \
  157055. c = (c<<6) + (0x3f & *(zIn++)); \
  157056. } \
  157057. }
  157058. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  157059. assert( *zIn ); \
  157060. if( *(zIn++)>=0xc0 ){ \
  157061. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  157062. }
  157063. /*
  157064. ** Compare two UTF-8 strings for equality where the first string is
  157065. ** a "LIKE" expression. Return true (1) if they are the same and
  157066. ** false (0) if they are different.
  157067. */
  157068. static int icuLikeCompare(
  157069. const uint8_t *zPattern, /* LIKE pattern */
  157070. const uint8_t *zString, /* The UTF-8 string to compare against */
  157071. const UChar32 uEsc /* The escape character */
  157072. ){
  157073. static const int MATCH_ONE = (UChar32)'_';
  157074. static const int MATCH_ALL = (UChar32)'%';
  157075. int prevEscape = 0; /* True if the previous character was uEsc */
  157076. while( 1 ){
  157077. /* Read (and consume) the next character from the input pattern. */
  157078. UChar32 uPattern;
  157079. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  157080. if( uPattern==0 ) break;
  157081. /* There are now 4 possibilities:
  157082. **
  157083. ** 1. uPattern is an unescaped match-all character "%",
  157084. ** 2. uPattern is an unescaped match-one character "_",
  157085. ** 3. uPattern is an unescaped escape character, or
  157086. ** 4. uPattern is to be handled as an ordinary character
  157087. */
  157088. if( !prevEscape && uPattern==MATCH_ALL ){
  157089. /* Case 1. */
  157090. uint8_t c;
  157091. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  157092. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  157093. ** test string.
  157094. */
  157095. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  157096. if( c==MATCH_ONE ){
  157097. if( *zString==0 ) return 0;
  157098. SQLITE_ICU_SKIP_UTF8(zString);
  157099. }
  157100. zPattern++;
  157101. }
  157102. if( *zPattern==0 ) return 1;
  157103. while( *zString ){
  157104. if( icuLikeCompare(zPattern, zString, uEsc) ){
  157105. return 1;
  157106. }
  157107. SQLITE_ICU_SKIP_UTF8(zString);
  157108. }
  157109. return 0;
  157110. }else if( !prevEscape && uPattern==MATCH_ONE ){
  157111. /* Case 2. */
  157112. if( *zString==0 ) return 0;
  157113. SQLITE_ICU_SKIP_UTF8(zString);
  157114. }else if( !prevEscape && uPattern==uEsc){
  157115. /* Case 3. */
  157116. prevEscape = 1;
  157117. }else{
  157118. /* Case 4. */
  157119. UChar32 uString;
  157120. SQLITE_ICU_READ_UTF8(zString, uString);
  157121. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  157122. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  157123. if( uString!=uPattern ){
  157124. return 0;
  157125. }
  157126. prevEscape = 0;
  157127. }
  157128. }
  157129. return *zString==0;
  157130. }
  157131. /*
  157132. ** Implementation of the like() SQL function. This function implements
  157133. ** the build-in LIKE operator. The first argument to the function is the
  157134. ** pattern and the second argument is the string. So, the SQL statements:
  157135. **
  157136. ** A LIKE B
  157137. **
  157138. ** is implemented as like(B, A). If there is an escape character E,
  157139. **
  157140. ** A LIKE B ESCAPE E
  157141. **
  157142. ** is mapped to like(B, A, E).
  157143. */
  157144. static void icuLikeFunc(
  157145. sqlite3_context *context,
  157146. int argc,
  157147. sqlite3_value **argv
  157148. ){
  157149. const unsigned char *zA = sqlite3_value_text(argv[0]);
  157150. const unsigned char *zB = sqlite3_value_text(argv[1]);
  157151. UChar32 uEsc = 0;
  157152. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  157153. ** of deep recursion and N*N behavior in patternCompare().
  157154. */
  157155. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  157156. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  157157. return;
  157158. }
  157159. if( argc==3 ){
  157160. /* The escape character string must consist of a single UTF-8 character.
  157161. ** Otherwise, return an error.
  157162. */
  157163. int nE= sqlite3_value_bytes(argv[2]);
  157164. const unsigned char *zE = sqlite3_value_text(argv[2]);
  157165. int i = 0;
  157166. if( zE==0 ) return;
  157167. U8_NEXT(zE, i, nE, uEsc);
  157168. if( i!=nE){
  157169. sqlite3_result_error(context,
  157170. "ESCAPE expression must be a single character", -1);
  157171. return;
  157172. }
  157173. }
  157174. if( zA && zB ){
  157175. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  157176. }
  157177. }
  157178. /*
  157179. ** This function is called when an ICU function called from within
  157180. ** the implementation of an SQL scalar function returns an error.
  157181. **
  157182. ** The scalar function context passed as the first argument is
  157183. ** loaded with an error message based on the following two args.
  157184. */
  157185. static void icuFunctionError(
  157186. sqlite3_context *pCtx, /* SQLite scalar function context */
  157187. const char *zName, /* Name of ICU function that failed */
  157188. UErrorCode e /* Error code returned by ICU function */
  157189. ){
  157190. char zBuf[128];
  157191. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  157192. zBuf[127] = '\0';
  157193. sqlite3_result_error(pCtx, zBuf, -1);
  157194. }
  157195. /*
  157196. ** Function to delete compiled regexp objects. Registered as
  157197. ** a destructor function with sqlite3_set_auxdata().
  157198. */
  157199. static void icuRegexpDelete(void *p){
  157200. URegularExpression *pExpr = (URegularExpression *)p;
  157201. uregex_close(pExpr);
  157202. }
  157203. /*
  157204. ** Implementation of SQLite REGEXP operator. This scalar function takes
  157205. ** two arguments. The first is a regular expression pattern to compile
  157206. ** the second is a string to match against that pattern. If either
  157207. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  157208. ** is 1 if the string matches the pattern, or 0 otherwise.
  157209. **
  157210. ** SQLite maps the regexp() function to the regexp() operator such
  157211. ** that the following two are equivalent:
  157212. **
  157213. ** zString REGEXP zPattern
  157214. ** regexp(zPattern, zString)
  157215. **
  157216. ** Uses the following ICU regexp APIs:
  157217. **
  157218. ** uregex_open()
  157219. ** uregex_matches()
  157220. ** uregex_close()
  157221. */
  157222. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  157223. UErrorCode status = U_ZERO_ERROR;
  157224. URegularExpression *pExpr;
  157225. UBool res;
  157226. const UChar *zString = sqlite3_value_text16(apArg[1]);
  157227. (void)nArg; /* Unused parameter */
  157228. /* If the left hand side of the regexp operator is NULL,
  157229. ** then the result is also NULL.
  157230. */
  157231. if( !zString ){
  157232. return;
  157233. }
  157234. pExpr = sqlite3_get_auxdata(p, 0);
  157235. if( !pExpr ){
  157236. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  157237. if( !zPattern ){
  157238. return;
  157239. }
  157240. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  157241. if( U_SUCCESS(status) ){
  157242. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  157243. }else{
  157244. assert(!pExpr);
  157245. icuFunctionError(p, "uregex_open", status);
  157246. return;
  157247. }
  157248. }
  157249. /* Configure the text that the regular expression operates on. */
  157250. uregex_setText(pExpr, zString, -1, &status);
  157251. if( !U_SUCCESS(status) ){
  157252. icuFunctionError(p, "uregex_setText", status);
  157253. return;
  157254. }
  157255. /* Attempt the match */
  157256. res = uregex_matches(pExpr, 0, &status);
  157257. if( !U_SUCCESS(status) ){
  157258. icuFunctionError(p, "uregex_matches", status);
  157259. return;
  157260. }
  157261. /* Set the text that the regular expression operates on to a NULL
  157262. ** pointer. This is not really necessary, but it is tidier than
  157263. ** leaving the regular expression object configured with an invalid
  157264. ** pointer after this function returns.
  157265. */
  157266. uregex_setText(pExpr, 0, 0, &status);
  157267. /* Return 1 or 0. */
  157268. sqlite3_result_int(p, res ? 1 : 0);
  157269. }
  157270. /*
  157271. ** Implementations of scalar functions for case mapping - upper() and
  157272. ** lower(). Function upper() converts its input to upper-case (ABC).
  157273. ** Function lower() converts to lower-case (abc).
  157274. **
  157275. ** ICU provides two types of case mapping, "general" case mapping and
  157276. ** "language specific". Refer to ICU documentation for the differences
  157277. ** between the two.
  157278. **
  157279. ** To utilise "general" case mapping, the upper() or lower() scalar
  157280. ** functions are invoked with one argument:
  157281. **
  157282. ** upper('ABC') -> 'abc'
  157283. ** lower('abc') -> 'ABC'
  157284. **
  157285. ** To access ICU "language specific" case mapping, upper() or lower()
  157286. ** should be invoked with two arguments. The second argument is the name
  157287. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  157288. ** as the second argument is the same as invoking the 1 argument version
  157289. ** of upper() or lower().
  157290. **
  157291. ** lower('I', 'en_us') -> 'i'
  157292. ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
  157293. **
  157294. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  157295. */
  157296. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  157297. const UChar *zInput; /* Pointer to input string */
  157298. UChar *zOutput = 0; /* Pointer to output buffer */
  157299. int nInput; /* Size of utf-16 input string in bytes */
  157300. int nOut; /* Size of output buffer in bytes */
  157301. int cnt;
  157302. int bToUpper; /* True for toupper(), false for tolower() */
  157303. UErrorCode status;
  157304. const char *zLocale = 0;
  157305. assert(nArg==1 || nArg==2);
  157306. bToUpper = (sqlite3_user_data(p)!=0);
  157307. if( nArg==2 ){
  157308. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  157309. }
  157310. zInput = sqlite3_value_text16(apArg[0]);
  157311. if( !zInput ){
  157312. return;
  157313. }
  157314. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  157315. if( nOut==0 ){
  157316. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  157317. return;
  157318. }
  157319. for(cnt=0; cnt<2; cnt++){
  157320. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  157321. if( zNew==0 ){
  157322. sqlite3_free(zOutput);
  157323. sqlite3_result_error_nomem(p);
  157324. return;
  157325. }
  157326. zOutput = zNew;
  157327. status = U_ZERO_ERROR;
  157328. if( bToUpper ){
  157329. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  157330. }else{
  157331. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  157332. }
  157333. if( U_SUCCESS(status) ){
  157334. sqlite3_result_text16(p, zOutput, nOut, xFree);
  157335. }else if( status==U_BUFFER_OVERFLOW_ERROR ){
  157336. assert( cnt==0 );
  157337. continue;
  157338. }else{
  157339. icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
  157340. }
  157341. return;
  157342. }
  157343. assert( 0 ); /* Unreachable */
  157344. }
  157345. /*
  157346. ** Collation sequence destructor function. The pCtx argument points to
  157347. ** a UCollator structure previously allocated using ucol_open().
  157348. */
  157349. static void icuCollationDel(void *pCtx){
  157350. UCollator *p = (UCollator *)pCtx;
  157351. ucol_close(p);
  157352. }
  157353. /*
  157354. ** Collation sequence comparison function. The pCtx argument points to
  157355. ** a UCollator structure previously allocated using ucol_open().
  157356. */
  157357. static int icuCollationColl(
  157358. void *pCtx,
  157359. int nLeft,
  157360. const void *zLeft,
  157361. int nRight,
  157362. const void *zRight
  157363. ){
  157364. UCollationResult res;
  157365. UCollator *p = (UCollator *)pCtx;
  157366. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  157367. switch( res ){
  157368. case UCOL_LESS: return -1;
  157369. case UCOL_GREATER: return +1;
  157370. case UCOL_EQUAL: return 0;
  157371. }
  157372. assert(!"Unexpected return value from ucol_strcoll()");
  157373. return 0;
  157374. }
  157375. /*
  157376. ** Implementation of the scalar function icu_load_collation().
  157377. **
  157378. ** This scalar function is used to add ICU collation based collation
  157379. ** types to an SQLite database connection. It is intended to be called
  157380. ** as follows:
  157381. **
  157382. ** SELECT icu_load_collation(<locale>, <collation-name>);
  157383. **
  157384. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  157385. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  157386. ** collation sequence to create.
  157387. */
  157388. static void icuLoadCollation(
  157389. sqlite3_context *p,
  157390. int nArg,
  157391. sqlite3_value **apArg
  157392. ){
  157393. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  157394. UErrorCode status = U_ZERO_ERROR;
  157395. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  157396. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  157397. UCollator *pUCollator; /* ICU library collation object */
  157398. int rc; /* Return code from sqlite3_create_collation_x() */
  157399. assert(nArg==2);
  157400. (void)nArg; /* Unused parameter */
  157401. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  157402. zName = (const char *)sqlite3_value_text(apArg[1]);
  157403. if( !zLocale || !zName ){
  157404. return;
  157405. }
  157406. pUCollator = ucol_open(zLocale, &status);
  157407. if( !U_SUCCESS(status) ){
  157408. icuFunctionError(p, "ucol_open", status);
  157409. return;
  157410. }
  157411. assert(p);
  157412. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  157413. icuCollationColl, icuCollationDel
  157414. );
  157415. if( rc!=SQLITE_OK ){
  157416. ucol_close(pUCollator);
  157417. sqlite3_result_error(p, "Error registering collation function", -1);
  157418. }
  157419. }
  157420. /*
  157421. ** Register the ICU extension functions with database db.
  157422. */
  157423. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  157424. static const struct IcuScalar {
  157425. const char *zName; /* Function name */
  157426. unsigned char nArg; /* Number of arguments */
  157427. unsigned short enc; /* Optimal text encoding */
  157428. unsigned char iContext; /* sqlite3_user_data() context */
  157429. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  157430. } scalars[] = {
  157431. {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation},
  157432. {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
  157433. {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  157434. {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  157435. {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  157436. {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  157437. {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  157438. {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  157439. {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  157440. {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  157441. {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  157442. {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  157443. };
  157444. int rc = SQLITE_OK;
  157445. int i;
  157446. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  157447. const struct IcuScalar *p = &scalars[i];
  157448. rc = sqlite3_create_function(
  157449. db, p->zName, p->nArg, p->enc,
  157450. p->iContext ? (void*)db : (void*)0,
  157451. p->xFunc, 0, 0
  157452. );
  157453. }
  157454. return rc;
  157455. }
  157456. #if !SQLITE_CORE
  157457. #ifdef _WIN32
  157458. __declspec(dllexport)
  157459. #endif
  157460. SQLITE_API int sqlite3_icu_init(
  157461. sqlite3 *db,
  157462. char **pzErrMsg,
  157463. const sqlite3_api_routines *pApi
  157464. ){
  157465. SQLITE_EXTENSION_INIT2(pApi)
  157466. return sqlite3IcuInit(db);
  157467. }
  157468. #endif
  157469. #endif
  157470. /************** End of icu.c *************************************************/
  157471. /************** Begin file fts3_icu.c ****************************************/
  157472. /*
  157473. ** 2007 June 22
  157474. **
  157475. ** The author disclaims copyright to this source code. In place of
  157476. ** a legal notice, here is a blessing:
  157477. **
  157478. ** May you do good and not evil.
  157479. ** May you find forgiveness for yourself and forgive others.
  157480. ** May you share freely, never taking more than you give.
  157481. **
  157482. *************************************************************************
  157483. ** This file implements a tokenizer for fts3 based on the ICU library.
  157484. */
  157485. /* #include "fts3Int.h" */
  157486. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  157487. #ifdef SQLITE_ENABLE_ICU
  157488. /* #include <assert.h> */
  157489. /* #include <string.h> */
  157490. /* #include "fts3_tokenizer.h" */
  157491. #include <unicode/ubrk.h>
  157492. /* #include <unicode/ucol.h> */
  157493. /* #include <unicode/ustring.h> */
  157494. #include <unicode/utf16.h>
  157495. typedef struct IcuTokenizer IcuTokenizer;
  157496. typedef struct IcuCursor IcuCursor;
  157497. struct IcuTokenizer {
  157498. sqlite3_tokenizer base;
  157499. char *zLocale;
  157500. };
  157501. struct IcuCursor {
  157502. sqlite3_tokenizer_cursor base;
  157503. UBreakIterator *pIter; /* ICU break-iterator object */
  157504. int nChar; /* Number of UChar elements in pInput */
  157505. UChar *aChar; /* Copy of input using utf-16 encoding */
  157506. int *aOffset; /* Offsets of each character in utf-8 input */
  157507. int nBuffer;
  157508. char *zBuffer;
  157509. int iToken;
  157510. };
  157511. /*
  157512. ** Create a new tokenizer instance.
  157513. */
  157514. static int icuCreate(
  157515. int argc, /* Number of entries in argv[] */
  157516. const char * const *argv, /* Tokenizer creation arguments */
  157517. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  157518. ){
  157519. IcuTokenizer *p;
  157520. int n = 0;
  157521. if( argc>0 ){
  157522. n = strlen(argv[0])+1;
  157523. }
  157524. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  157525. if( !p ){
  157526. return SQLITE_NOMEM;
  157527. }
  157528. memset(p, 0, sizeof(IcuTokenizer));
  157529. if( n ){
  157530. p->zLocale = (char *)&p[1];
  157531. memcpy(p->zLocale, argv[0], n);
  157532. }
  157533. *ppTokenizer = (sqlite3_tokenizer *)p;
  157534. return SQLITE_OK;
  157535. }
  157536. /*
  157537. ** Destroy a tokenizer
  157538. */
  157539. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  157540. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  157541. sqlite3_free(p);
  157542. return SQLITE_OK;
  157543. }
  157544. /*
  157545. ** Prepare to begin tokenizing a particular string. The input
  157546. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  157547. ** used to incrementally tokenize this string is returned in
  157548. ** *ppCursor.
  157549. */
  157550. static int icuOpen(
  157551. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  157552. const char *zInput, /* Input string */
  157553. int nInput, /* Length of zInput in bytes */
  157554. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  157555. ){
  157556. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  157557. IcuCursor *pCsr;
  157558. const int32_t opt = U_FOLD_CASE_DEFAULT;
  157559. UErrorCode status = U_ZERO_ERROR;
  157560. int nChar;
  157561. UChar32 c;
  157562. int iInput = 0;
  157563. int iOut = 0;
  157564. *ppCursor = 0;
  157565. if( zInput==0 ){
  157566. nInput = 0;
  157567. zInput = "";
  157568. }else if( nInput<0 ){
  157569. nInput = strlen(zInput);
  157570. }
  157571. nChar = nInput+1;
  157572. pCsr = (IcuCursor *)sqlite3_malloc(
  157573. sizeof(IcuCursor) + /* IcuCursor */
  157574. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  157575. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  157576. );
  157577. if( !pCsr ){
  157578. return SQLITE_NOMEM;
  157579. }
  157580. memset(pCsr, 0, sizeof(IcuCursor));
  157581. pCsr->aChar = (UChar *)&pCsr[1];
  157582. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  157583. pCsr->aOffset[iOut] = iInput;
  157584. U8_NEXT(zInput, iInput, nInput, c);
  157585. while( c>0 ){
  157586. int isError = 0;
  157587. c = u_foldCase(c, opt);
  157588. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  157589. if( isError ){
  157590. sqlite3_free(pCsr);
  157591. return SQLITE_ERROR;
  157592. }
  157593. pCsr->aOffset[iOut] = iInput;
  157594. if( iInput<nInput ){
  157595. U8_NEXT(zInput, iInput, nInput, c);
  157596. }else{
  157597. c = 0;
  157598. }
  157599. }
  157600. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  157601. if( !U_SUCCESS(status) ){
  157602. sqlite3_free(pCsr);
  157603. return SQLITE_ERROR;
  157604. }
  157605. pCsr->nChar = iOut;
  157606. ubrk_first(pCsr->pIter);
  157607. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  157608. return SQLITE_OK;
  157609. }
  157610. /*
  157611. ** Close a tokenization cursor previously opened by a call to icuOpen().
  157612. */
  157613. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  157614. IcuCursor *pCsr = (IcuCursor *)pCursor;
  157615. ubrk_close(pCsr->pIter);
  157616. sqlite3_free(pCsr->zBuffer);
  157617. sqlite3_free(pCsr);
  157618. return SQLITE_OK;
  157619. }
  157620. /*
  157621. ** Extract the next token from a tokenization cursor.
  157622. */
  157623. static int icuNext(
  157624. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  157625. const char **ppToken, /* OUT: *ppToken is the token text */
  157626. int *pnBytes, /* OUT: Number of bytes in token */
  157627. int *piStartOffset, /* OUT: Starting offset of token */
  157628. int *piEndOffset, /* OUT: Ending offset of token */
  157629. int *piPosition /* OUT: Position integer of token */
  157630. ){
  157631. IcuCursor *pCsr = (IcuCursor *)pCursor;
  157632. int iStart = 0;
  157633. int iEnd = 0;
  157634. int nByte = 0;
  157635. while( iStart==iEnd ){
  157636. UChar32 c;
  157637. iStart = ubrk_current(pCsr->pIter);
  157638. iEnd = ubrk_next(pCsr->pIter);
  157639. if( iEnd==UBRK_DONE ){
  157640. return SQLITE_DONE;
  157641. }
  157642. while( iStart<iEnd ){
  157643. int iWhite = iStart;
  157644. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  157645. if( u_isspace(c) ){
  157646. iStart = iWhite;
  157647. }else{
  157648. break;
  157649. }
  157650. }
  157651. assert(iStart<=iEnd);
  157652. }
  157653. do {
  157654. UErrorCode status = U_ZERO_ERROR;
  157655. if( nByte ){
  157656. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  157657. if( !zNew ){
  157658. return SQLITE_NOMEM;
  157659. }
  157660. pCsr->zBuffer = zNew;
  157661. pCsr->nBuffer = nByte;
  157662. }
  157663. u_strToUTF8(
  157664. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  157665. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  157666. &status /* Output success/failure */
  157667. );
  157668. } while( nByte>pCsr->nBuffer );
  157669. *ppToken = pCsr->zBuffer;
  157670. *pnBytes = nByte;
  157671. *piStartOffset = pCsr->aOffset[iStart];
  157672. *piEndOffset = pCsr->aOffset[iEnd];
  157673. *piPosition = pCsr->iToken++;
  157674. return SQLITE_OK;
  157675. }
  157676. /*
  157677. ** The set of routines that implement the simple tokenizer
  157678. */
  157679. static const sqlite3_tokenizer_module icuTokenizerModule = {
  157680. 0, /* iVersion */
  157681. icuCreate, /* xCreate */
  157682. icuDestroy, /* xCreate */
  157683. icuOpen, /* xOpen */
  157684. icuClose, /* xClose */
  157685. icuNext, /* xNext */
  157686. 0, /* xLanguageid */
  157687. };
  157688. /*
  157689. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  157690. */
  157691. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  157692. sqlite3_tokenizer_module const**ppModule
  157693. ){
  157694. *ppModule = &icuTokenizerModule;
  157695. }
  157696. #endif /* defined(SQLITE_ENABLE_ICU) */
  157697. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  157698. /************** End of fts3_icu.c ********************************************/
  157699. /************** Begin file sqlite3rbu.c **************************************/
  157700. /*
  157701. ** 2014 August 30
  157702. **
  157703. ** The author disclaims copyright to this source code. In place of
  157704. ** a legal notice, here is a blessing:
  157705. **
  157706. ** May you do good and not evil.
  157707. ** May you find forgiveness for yourself and forgive others.
  157708. ** May you share freely, never taking more than you give.
  157709. **
  157710. *************************************************************************
  157711. **
  157712. **
  157713. ** OVERVIEW
  157714. **
  157715. ** The RBU extension requires that the RBU update be packaged as an
  157716. ** SQLite database. The tables it expects to find are described in
  157717. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  157718. ** that the user wishes to write to, a corresponding data_xyz table is
  157719. ** created in the RBU database and populated with one row for each row to
  157720. ** update, insert or delete from the target table.
  157721. **
  157722. ** The update proceeds in three stages:
  157723. **
  157724. ** 1) The database is updated. The modified database pages are written
  157725. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  157726. ** that it is named "<database>-oal" instead of "<database>-wal".
  157727. ** Because regular SQLite clients do not look for file named
  157728. ** "<database>-oal", they go on using the original database in
  157729. ** rollback mode while the *-oal file is being generated.
  157730. **
  157731. ** During this stage RBU does not update the database by writing
  157732. ** directly to the target tables. Instead it creates "imposter"
  157733. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  157734. ** to update each b-tree individually. All updates required by each
  157735. ** b-tree are completed before moving on to the next, and all
  157736. ** updates are done in sorted key order.
  157737. **
  157738. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  157739. ** location using a call to rename(2). Before doing this the RBU
  157740. ** module takes an EXCLUSIVE lock on the database file, ensuring
  157741. ** that there are no other active readers.
  157742. **
  157743. ** Once the EXCLUSIVE lock is released, any other database readers
  157744. ** detect the new *-wal file and read the database in wal mode. At
  157745. ** this point they see the new version of the database - including
  157746. ** the updates made as part of the RBU update.
  157747. **
  157748. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  157749. ** as a regular database checkpoint, except that a single frame is
  157750. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  157751. ** handle is closed before the entire *-wal file is checkpointed,
  157752. ** the checkpoint progress is saved in the RBU database and the
  157753. ** checkpoint can be resumed by another RBU client at some point in
  157754. ** the future.
  157755. **
  157756. ** POTENTIAL PROBLEMS
  157757. **
  157758. ** The rename() call might not be portable. And RBU is not currently
  157759. ** syncing the directory after renaming the file.
  157760. **
  157761. ** When state is saved, any commit to the *-oal file and the commit to
  157762. ** the RBU update database are not atomic. So if the power fails at the
  157763. ** wrong moment they might get out of sync. As the main database will be
  157764. ** committed before the RBU update database this will likely either just
  157765. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  157766. ** constraint violations).
  157767. **
  157768. ** If some client does modify the target database mid RBU update, or some
  157769. ** other error occurs, the RBU extension will keep throwing errors. It's
  157770. ** not really clear how to get out of this state. The system could just
  157771. ** by delete the RBU update database and *-oal file and have the device
  157772. ** download the update again and start over.
  157773. **
  157774. ** At present, for an UPDATE, both the new.* and old.* records are
  157775. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  157776. ** fields are collected. This means we're probably writing a lot more
  157777. ** data to disk when saving the state of an ongoing update to the RBU
  157778. ** update database than is strictly necessary.
  157779. **
  157780. */
  157781. /* #include <assert.h> */
  157782. /* #include <string.h> */
  157783. /* #include <stdio.h> */
  157784. /* #include "sqlite3.h" */
  157785. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  157786. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  157787. /************** Begin file sqlite3rbu.h **************************************/
  157788. /*
  157789. ** 2014 August 30
  157790. **
  157791. ** The author disclaims copyright to this source code. In place of
  157792. ** a legal notice, here is a blessing:
  157793. **
  157794. ** May you do good and not evil.
  157795. ** May you find forgiveness for yourself and forgive others.
  157796. ** May you share freely, never taking more than you give.
  157797. **
  157798. *************************************************************************
  157799. **
  157800. ** This file contains the public interface for the RBU extension.
  157801. */
  157802. /*
  157803. ** SUMMARY
  157804. **
  157805. ** Writing a transaction containing a large number of operations on
  157806. ** b-tree indexes that are collectively larger than the available cache
  157807. ** memory can be very inefficient.
  157808. **
  157809. ** The problem is that in order to update a b-tree, the leaf page (at least)
  157810. ** containing the entry being inserted or deleted must be modified. If the
  157811. ** working set of leaves is larger than the available cache memory, then a
  157812. ** single leaf that is modified more than once as part of the transaction
  157813. ** may be loaded from or written to the persistent media multiple times.
  157814. ** Additionally, because the index updates are likely to be applied in
  157815. ** random order, access to pages within the database is also likely to be in
  157816. ** random order, which is itself quite inefficient.
  157817. **
  157818. ** One way to improve the situation is to sort the operations on each index
  157819. ** by index key before applying them to the b-tree. This leads to an IO
  157820. ** pattern that resembles a single linear scan through the index b-tree,
  157821. ** and all but guarantees each modified leaf page is loaded and stored
  157822. ** exactly once. SQLite uses this trick to improve the performance of
  157823. ** CREATE INDEX commands. This extension allows it to be used to improve
  157824. ** the performance of large transactions on existing databases.
  157825. **
  157826. ** Additionally, this extension allows the work involved in writing the
  157827. ** large transaction to be broken down into sub-transactions performed
  157828. ** sequentially by separate processes. This is useful if the system cannot
  157829. ** guarantee that a single update process will run for long enough to apply
  157830. ** the entire update, for example because the update is being applied on a
  157831. ** mobile device that is frequently rebooted. Even after the writer process
  157832. ** has committed one or more sub-transactions, other database clients continue
  157833. ** to read from the original database snapshot. In other words, partially
  157834. ** applied transactions are not visible to other clients.
  157835. **
  157836. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  157837. ** transmitted via a wireless network to a mobile device. A transaction
  157838. ** applied using this extension is hence refered to as an "RBU update".
  157839. **
  157840. **
  157841. ** LIMITATIONS
  157842. **
  157843. ** An "RBU update" transaction is subject to the following limitations:
  157844. **
  157845. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  157846. ** only.
  157847. **
  157848. ** * INSERT statements may not use any default values.
  157849. **
  157850. ** * UPDATE and DELETE statements must identify their target rows by
  157851. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  157852. ** KEY fields may not be updated or deleted. If the table being written
  157853. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  157854. **
  157855. ** * UPDATE statements may not modify PRIMARY KEY columns.
  157856. **
  157857. ** * No triggers will be fired.
  157858. **
  157859. ** * No foreign key violations are detected or reported.
  157860. **
  157861. ** * CHECK constraints are not enforced.
  157862. **
  157863. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  157864. **
  157865. **
  157866. ** PREPARATION
  157867. **
  157868. ** An "RBU update" is stored as a separate SQLite database. A database
  157869. ** containing an RBU update is an "RBU database". For each table in the
  157870. ** target database to be updated, the RBU database should contain a table
  157871. ** named "data_<target name>" containing the same set of columns as the
  157872. ** target table, and one more - "rbu_control". The data_% table should
  157873. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  157874. ** the same type as the corresponding column in the target database.
  157875. ** The "rbu_control" column should have no type at all. For example, if
  157876. ** the target database contains:
  157877. **
  157878. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  157879. **
  157880. ** Then the RBU database should contain:
  157881. **
  157882. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  157883. **
  157884. ** The order of the columns in the data_% table does not matter.
  157885. **
  157886. ** Instead of a regular table, the RBU database may also contain virtual
  157887. ** tables or view named using the data_<target> naming scheme.
  157888. **
  157889. ** Instead of the plain data_<target> naming scheme, RBU database tables
  157890. ** may also be named data<integer>_<target>, where <integer> is any sequence
  157891. ** of zero or more numeric characters (0-9). This can be significant because
  157892. ** tables within the RBU database are always processed in order sorted by
  157893. ** name. By judicious selection of the <integer> portion of the names
  157894. ** of the RBU tables the user can therefore control the order in which they
  157895. ** are processed. This can be useful, for example, to ensure that "external
  157896. ** content" FTS4 tables are updated before their underlying content tables.
  157897. **
  157898. ** If the target database table is a virtual table or a table that has no
  157899. ** PRIMARY KEY declaration, the data_% table must also contain a column
  157900. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  157901. ** key column - "rowid". Virtual tables for which the "rowid" column does
  157902. ** not function like a primary key value cannot be updated using RBU. For
  157903. ** example, if the target db contains either of the following:
  157904. **
  157905. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  157906. ** CREATE TABLE x1(a, b)
  157907. **
  157908. ** then the RBU database should contain:
  157909. **
  157910. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  157911. **
  157912. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  157913. ** target table must be present in the input table. For virtual tables,
  157914. ** hidden columns are optional - they are updated by RBU if present in
  157915. ** the input table, or not otherwise. For example, to write to an fts4
  157916. ** table with a hidden languageid column such as:
  157917. **
  157918. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  157919. **
  157920. ** Either of the following input table schemas may be used:
  157921. **
  157922. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  157923. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  157924. **
  157925. ** For each row to INSERT into the target database as part of the RBU
  157926. ** update, the corresponding data_% table should contain a single record
  157927. ** with the "rbu_control" column set to contain integer value 0. The
  157928. ** other columns should be set to the values that make up the new record
  157929. ** to insert.
  157930. **
  157931. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  157932. ** possible to insert a NULL value into the IPK column. Attempting to
  157933. ** do so results in an SQLITE_MISMATCH error.
  157934. **
  157935. ** For each row to DELETE from the target database as part of the RBU
  157936. ** update, the corresponding data_% table should contain a single record
  157937. ** with the "rbu_control" column set to contain integer value 1. The
  157938. ** real primary key values of the row to delete should be stored in the
  157939. ** corresponding columns of the data_% table. The values stored in the
  157940. ** other columns are not used.
  157941. **
  157942. ** For each row to UPDATE from the target database as part of the RBU
  157943. ** update, the corresponding data_% table should contain a single record
  157944. ** with the "rbu_control" column set to contain a value of type text.
  157945. ** The real primary key values identifying the row to update should be
  157946. ** stored in the corresponding columns of the data_% table row, as should
  157947. ** the new values of all columns being update. The text value in the
  157948. ** "rbu_control" column must contain the same number of characters as
  157949. ** there are columns in the target database table, and must consist entirely
  157950. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  157951. ** each column that is being updated, the corresponding character is set to
  157952. ** 'x'. For those that remain as they are, the corresponding character of the
  157953. ** rbu_control value should be set to '.'. For example, given the tables
  157954. ** above, the update statement:
  157955. **
  157956. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  157957. **
  157958. ** is represented by the data_t1 row created by:
  157959. **
  157960. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  157961. **
  157962. ** Instead of an 'x' character, characters of the rbu_control value specified
  157963. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  157964. ** target table with the value stored in the corresponding data_% column, the
  157965. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  157966. ** the target table column. rbu_delta() is invoked with two arguments - the
  157967. ** original value currently stored in the target table column and the
  157968. ** value specified in the data_xxx table.
  157969. **
  157970. ** For example, this row:
  157971. **
  157972. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  157973. **
  157974. ** is similar to an UPDATE statement such as:
  157975. **
  157976. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  157977. **
  157978. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  157979. ** ota_control string, the contents of the data_xxx table column is assumed
  157980. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  157981. ** format used by the fossil source-code management system. In this case
  157982. ** the existing value within the target database table must be of type BLOB.
  157983. ** It is replaced by the result of applying the specified fossil delta to
  157984. ** itself.
  157985. **
  157986. ** If the target database table is a virtual table or a table with no PRIMARY
  157987. ** KEY, the rbu_control value should not include a character corresponding
  157988. ** to the rbu_rowid value. For example, this:
  157989. **
  157990. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  157991. ** VALUES(NULL, 'usa', 12, '.x');
  157992. **
  157993. ** causes a result similar to:
  157994. **
  157995. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  157996. **
  157997. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  157998. ** However, RBU is more efficient if reading the rows in from each data_xxx
  157999. ** table in "rowid" order is roughly the same as reading them sorted by
  158000. ** the PRIMARY KEY of the corresponding target database table. In other
  158001. ** words, rows should be sorted using the destination table PRIMARY KEY
  158002. ** fields before they are inserted into the data_xxx tables.
  158003. **
  158004. ** USAGE
  158005. **
  158006. ** The API declared below allows an application to apply an RBU update
  158007. ** stored on disk to an existing target database. Essentially, the
  158008. ** application:
  158009. **
  158010. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  158011. **
  158012. ** 2) Registers any required virtual table modules with the database
  158013. ** handle returned by sqlite3rbu_db(). Also, if required, register
  158014. ** the rbu_delta() implementation.
  158015. **
  158016. ** 3) Calls the sqlite3rbu_step() function one or more times on
  158017. ** the new handle. Each call to sqlite3rbu_step() performs a single
  158018. ** b-tree operation, so thousands of calls may be required to apply
  158019. ** a complete update.
  158020. **
  158021. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  158022. ** sqlite3rbu_step() has been called enough times to completely
  158023. ** apply the update to the target database, then the RBU database
  158024. ** is marked as fully applied. Otherwise, the state of the RBU
  158025. ** update application is saved in the RBU database for later
  158026. ** resumption.
  158027. **
  158028. ** See comments below for more detail on APIs.
  158029. **
  158030. ** If an update is only partially applied to the target database by the
  158031. ** time sqlite3rbu_close() is called, various state information is saved
  158032. ** within the RBU database. This allows subsequent processes to automatically
  158033. ** resume the RBU update from where it left off.
  158034. **
  158035. ** To remove all RBU extension state information, returning an RBU database
  158036. ** to its original contents, it is sufficient to drop all tables that begin
  158037. ** with the prefix "rbu_"
  158038. **
  158039. ** DATABASE LOCKING
  158040. **
  158041. ** An RBU update may not be applied to a database in WAL mode. Attempting
  158042. ** to do so is an error (SQLITE_ERROR).
  158043. **
  158044. ** While an RBU handle is open, a SHARED lock may be held on the target
  158045. ** database file. This means it is possible for other clients to read the
  158046. ** database, but not to write it.
  158047. **
  158048. ** If an RBU update is started and then suspended before it is completed,
  158049. ** then an external client writes to the database, then attempting to resume
  158050. ** the suspended RBU update is also an error (SQLITE_BUSY).
  158051. */
  158052. #ifndef _SQLITE3RBU_H
  158053. #define _SQLITE3RBU_H
  158054. /* #include "sqlite3.h" ** Required for error code definitions ** */
  158055. #if 0
  158056. extern "C" {
  158057. #endif
  158058. typedef struct sqlite3rbu sqlite3rbu;
  158059. /*
  158060. ** Open an RBU handle.
  158061. **
  158062. ** Argument zTarget is the path to the target database. Argument zRbu is
  158063. ** the path to the RBU database. Each call to this function must be matched
  158064. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  158065. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  158066. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  158067. ** database URI, not a regular file name.
  158068. **
  158069. ** If the zState argument is passed a NULL value, the RBU extension stores
  158070. ** the current state of the update (how many rows have been updated, which
  158071. ** indexes are yet to be updated etc.) within the RBU database itself. This
  158072. ** can be convenient, as it means that the RBU application does not need to
  158073. ** organize removing a separate state file after the update is concluded.
  158074. ** Or, if zState is non-NULL, it must be a path to a database file in which
  158075. ** the RBU extension can store the state of the update.
  158076. **
  158077. ** When resuming an RBU update, the zState argument must be passed the same
  158078. ** value as when the RBU update was started.
  158079. **
  158080. ** Once the RBU update is finished, the RBU extension does not
  158081. ** automatically remove any zState database file, even if it created it.
  158082. **
  158083. ** By default, RBU uses the default VFS to access the files on disk. To
  158084. ** use a VFS other than the default, an SQLite "file:" URI containing a
  158085. ** "vfs=..." option may be passed as the zTarget option.
  158086. **
  158087. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  158088. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  158089. ** not work out of the box with zipvfs. Refer to the comment describing
  158090. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  158091. */
  158092. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  158093. const char *zTarget,
  158094. const char *zRbu,
  158095. const char *zState
  158096. );
  158097. /*
  158098. ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
  158099. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
  158100. ** that it can be suspended and resumed like an RBU update.
  158101. **
  158102. ** The second argument to this function identifies a database in which
  158103. ** to store the state of the RBU vacuum operation if it is suspended. The
  158104. ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
  158105. ** operation, the state database should either not exist or be empty
  158106. ** (contain no tables). If an RBU vacuum is suspended by calling
  158107. ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
  158108. ** returned SQLITE_DONE, the vacuum state is stored in the state database.
  158109. ** The vacuum can be resumed by calling this function to open a new RBU
  158110. ** handle specifying the same target and state databases.
  158111. **
  158112. ** If the second argument passed to this function is NULL, then the
  158113. ** name of the state database is "<database>-vacuum", where <database>
  158114. ** is the name of the target database file. In this case, on UNIX, if the
  158115. ** state database is not already present in the file-system, it is created
  158116. ** with the same permissions as the target db is made.
  158117. **
  158118. ** This function does not delete the state database after an RBU vacuum
  158119. ** is completed, even if it created it. However, if the call to
  158120. ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
  158121. ** of the state tables within the state database are zeroed. This way,
  158122. ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
  158123. ** new RBU vacuum operation.
  158124. **
  158125. ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
  158126. ** describing the sqlite3rbu_create_vfs() API function below for
  158127. ** a description of the complications associated with using RBU with
  158128. ** zipvfs databases.
  158129. */
  158130. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  158131. const char *zTarget,
  158132. const char *zState
  158133. );
  158134. /*
  158135. ** Internally, each RBU connection uses a separate SQLite database
  158136. ** connection to access the target and rbu update databases. This
  158137. ** API allows the application direct access to these database handles.
  158138. **
  158139. ** The first argument passed to this function must be a valid, open, RBU
  158140. ** handle. The second argument should be passed zero to access the target
  158141. ** database handle, or non-zero to access the rbu update database handle.
  158142. ** Accessing the underlying database handles may be useful in the
  158143. ** following scenarios:
  158144. **
  158145. ** * If any target tables are virtual tables, it may be necessary to
  158146. ** call sqlite3_create_module() on the target database handle to
  158147. ** register the required virtual table implementations.
  158148. **
  158149. ** * If the data_xxx tables in the RBU source database are virtual
  158150. ** tables, the application may need to call sqlite3_create_module() on
  158151. ** the rbu update db handle to any required virtual table
  158152. ** implementations.
  158153. **
  158154. ** * If the application uses the "rbu_delta()" feature described above,
  158155. ** it must use sqlite3_create_function() or similar to register the
  158156. ** rbu_delta() implementation with the target database handle.
  158157. **
  158158. ** If an error has occurred, either while opening or stepping the RBU object,
  158159. ** this function may return NULL. The error code and message may be collected
  158160. ** when sqlite3rbu_close() is called.
  158161. **
  158162. ** Database handles returned by this function remain valid until the next
  158163. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  158164. */
  158165. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
  158166. /*
  158167. ** Do some work towards applying the RBU update to the target db.
  158168. **
  158169. ** Return SQLITE_DONE if the update has been completely applied, or
  158170. ** SQLITE_OK if no error occurs but there remains work to do to apply
  158171. ** the RBU update. If an error does occur, some other error code is
  158172. ** returned.
  158173. **
  158174. ** Once a call to sqlite3rbu_step() has returned a value other than
  158175. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  158176. ** that immediately return the same value.
  158177. */
  158178. SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
  158179. /*
  158180. ** Force RBU to save its state to disk.
  158181. **
  158182. ** If a power failure or application crash occurs during an update, following
  158183. ** system recovery RBU may resume the update from the point at which the state
  158184. ** was last saved. In other words, from the most recent successful call to
  158185. ** sqlite3rbu_close() or this function.
  158186. **
  158187. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  158188. */
  158189. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
  158190. /*
  158191. ** Close an RBU handle.
  158192. **
  158193. ** If the RBU update has been completely applied, mark the RBU database
  158194. ** as fully applied. Otherwise, assuming no error has occurred, save the
  158195. ** current state of the RBU update appliation to the RBU database.
  158196. **
  158197. ** If an error has already occurred as part of an sqlite3rbu_step()
  158198. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  158199. ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
  158200. ** point to a buffer containing a utf-8 formatted English language error
  158201. ** message. It is the responsibility of the caller to eventually free any
  158202. ** such buffer using sqlite3_free().
  158203. **
  158204. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  158205. ** update has been partially applied, or SQLITE_DONE if it has been
  158206. ** completely applied.
  158207. */
  158208. SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  158209. /*
  158210. ** Return the total number of key-value operations (inserts, deletes or
  158211. ** updates) that have been performed on the target database since the
  158212. ** current RBU update was started.
  158213. */
  158214. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
  158215. /*
  158216. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  158217. ** progress indications for the two stages of an RBU update. This API may
  158218. ** be useful for driving GUI progress indicators and similar.
  158219. **
  158220. ** An RBU update is divided into two stages:
  158221. **
  158222. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  158223. ** * Stage 2, in which the contents of the wal file are copied into the
  158224. ** main database.
  158225. **
  158226. ** The update is visible to non-RBU clients during stage 2. During stage 1
  158227. ** non-RBU reader clients may see the original database.
  158228. **
  158229. ** If this API is called during stage 2 of the update, output variable
  158230. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  158231. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  158232. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  158233. ** 9000 indicates that it is 90% finished, and so on.
  158234. **
  158235. ** If this API is called during stage 1 of the update, output variable
  158236. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  158237. ** value to which (*pnOne) is set depends on whether or not the RBU
  158238. ** database contains an "rbu_count" table. The rbu_count table, if it
  158239. ** exists, must contain the same columns as the following:
  158240. **
  158241. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  158242. **
  158243. ** There must be one row in the table for each source (data_xxx) table within
  158244. ** the RBU database. The 'tbl' column should contain the name of the source
  158245. ** table. The 'cnt' column should contain the number of rows within the
  158246. ** source table.
  158247. **
  158248. ** If the rbu_count table is present and populated correctly and this
  158249. ** API is called during stage 1, the *pnOne output variable is set to the
  158250. ** permyriadage progress of the same stage. If the rbu_count table does
  158251. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  158252. ** table exists but is not correctly populated, the value of the *pnOne
  158253. ** output variable during stage 1 is undefined.
  158254. */
  158255. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
  158256. /*
  158257. ** Obtain an indication as to the current stage of an RBU update or vacuum.
  158258. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
  158259. ** defined in this file. Return values should be interpreted as follows:
  158260. **
  158261. ** SQLITE_RBU_STATE_OAL:
  158262. ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
  158263. ** may either add further data to the *-oal file, or compute data that will
  158264. ** be added by a subsequent call.
  158265. **
  158266. ** SQLITE_RBU_STATE_MOVE:
  158267. ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
  158268. ** will move the *-oal file to the equivalent *-wal path. If the current
  158269. ** operation is an RBU update, then the updated version of the database
  158270. ** file will become visible to ordinary SQLite clients following the next
  158271. ** call to sqlite3rbu_step().
  158272. **
  158273. ** SQLITE_RBU_STATE_CHECKPOINT:
  158274. ** RBU is currently performing an incremental checkpoint. The next call to
  158275. ** sqlite3rbu_step() will copy a page of data from the *-wal file into
  158276. ** the target database file.
  158277. **
  158278. ** SQLITE_RBU_STATE_DONE:
  158279. ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
  158280. ** will immediately return SQLITE_DONE.
  158281. **
  158282. ** SQLITE_RBU_STATE_ERROR:
  158283. ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
  158284. ** immediately return the SQLite error code associated with the error.
  158285. */
  158286. #define SQLITE_RBU_STATE_OAL 1
  158287. #define SQLITE_RBU_STATE_MOVE 2
  158288. #define SQLITE_RBU_STATE_CHECKPOINT 3
  158289. #define SQLITE_RBU_STATE_DONE 4
  158290. #define SQLITE_RBU_STATE_ERROR 5
  158291. SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
  158292. /*
  158293. ** Create an RBU VFS named zName that accesses the underlying file-system
  158294. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  158295. ** then the new RBU VFS uses the default system VFS to access the file-system.
  158296. ** The new object is registered as a non-default VFS with SQLite before
  158297. ** returning.
  158298. **
  158299. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  158300. ** object is created and deleted automatically by RBU.
  158301. **
  158302. ** The exception is for applications that also use zipvfs. In this case,
  158303. ** the custom VFS must be explicitly created by the user before the RBU
  158304. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  158305. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  158306. ** (for example multiplexor) to access the file-system. For example,
  158307. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  158308. ** multiplexor (error checking omitted):
  158309. **
  158310. ** // Create a VFS named "multiplex" (not the default).
  158311. ** sqlite3_multiplex_initialize(0, 0);
  158312. **
  158313. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  158314. ** // second argument were replaced with NULL, the "rbu" VFS would
  158315. ** // access the file-system via the system default VFS, bypassing the
  158316. ** // multiplexor.
  158317. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  158318. **
  158319. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  158320. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  158321. **
  158322. ** // Make zipvfs the default VFS.
  158323. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  158324. **
  158325. ** Because the default VFS created above includes a RBU functionality, it
  158326. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  158327. ** that does not include the RBU layer results in an error.
  158328. **
  158329. ** The overhead of adding the "rbu" VFS to the system is negligible for
  158330. ** non-RBU users. There is no harm in an application accessing the
  158331. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  158332. ** occasionally.
  158333. */
  158334. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  158335. /*
  158336. ** Deregister and destroy an RBU vfs created by an earlier call to
  158337. ** sqlite3rbu_create_vfs().
  158338. **
  158339. ** VFS objects are not reference counted. If a VFS object is destroyed
  158340. ** before all database handles that use it have been closed, the results
  158341. ** are undefined.
  158342. */
  158343. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
  158344. #if 0
  158345. } /* end of the 'extern "C"' block */
  158346. #endif
  158347. #endif /* _SQLITE3RBU_H */
  158348. /************** End of sqlite3rbu.h ******************************************/
  158349. /************** Continuing where we left off in sqlite3rbu.c *****************/
  158350. #if defined(_WIN32_WCE)
  158351. /* #include "windows.h" */
  158352. #endif
  158353. /* Maximum number of prepared UPDATE statements held by this module */
  158354. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  158355. /*
  158356. ** Swap two objects of type TYPE.
  158357. */
  158358. #if !defined(SQLITE_AMALGAMATION)
  158359. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  158360. #endif
  158361. /*
  158362. ** The rbu_state table is used to save the state of a partially applied
  158363. ** update so that it can be resumed later. The table consists of integer
  158364. ** keys mapped to values as follows:
  158365. **
  158366. ** RBU_STATE_STAGE:
  158367. ** May be set to integer values 1, 2, 4 or 5. As follows:
  158368. ** 1: the *-rbu file is currently under construction.
  158369. ** 2: the *-rbu file has been constructed, but not yet moved
  158370. ** to the *-wal path.
  158371. ** 4: the checkpoint is underway.
  158372. ** 5: the rbu update has been checkpointed.
  158373. **
  158374. ** RBU_STATE_TBL:
  158375. ** Only valid if STAGE==1. The target database name of the table
  158376. ** currently being written.
  158377. **
  158378. ** RBU_STATE_IDX:
  158379. ** Only valid if STAGE==1. The target database name of the index
  158380. ** currently being written, or NULL if the main table is currently being
  158381. ** updated.
  158382. **
  158383. ** RBU_STATE_ROW:
  158384. ** Only valid if STAGE==1. Number of rows already processed for the current
  158385. ** table/index.
  158386. **
  158387. ** RBU_STATE_PROGRESS:
  158388. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  158389. ** rbu update.
  158390. **
  158391. ** RBU_STATE_CKPT:
  158392. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  158393. ** header created by recovering the *-wal file. This is used to detect
  158394. ** cases when another client appends frames to the *-wal file in the
  158395. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  158396. ** be continued if this happens).
  158397. **
  158398. ** RBU_STATE_COOKIE:
  158399. ** Valid if STAGE==1. The current change-counter cookie value in the
  158400. ** target db file.
  158401. **
  158402. ** RBU_STATE_OALSZ:
  158403. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  158404. */
  158405. #define RBU_STATE_STAGE 1
  158406. #define RBU_STATE_TBL 2
  158407. #define RBU_STATE_IDX 3
  158408. #define RBU_STATE_ROW 4
  158409. #define RBU_STATE_PROGRESS 5
  158410. #define RBU_STATE_CKPT 6
  158411. #define RBU_STATE_COOKIE 7
  158412. #define RBU_STATE_OALSZ 8
  158413. #define RBU_STATE_PHASEONESTEP 9
  158414. #define RBU_STAGE_OAL 1
  158415. #define RBU_STAGE_MOVE 2
  158416. #define RBU_STAGE_CAPTURE 3
  158417. #define RBU_STAGE_CKPT 4
  158418. #define RBU_STAGE_DONE 5
  158419. #define RBU_CREATE_STATE \
  158420. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  158421. typedef struct RbuFrame RbuFrame;
  158422. typedef struct RbuObjIter RbuObjIter;
  158423. typedef struct RbuState RbuState;
  158424. typedef struct rbu_vfs rbu_vfs;
  158425. typedef struct rbu_file rbu_file;
  158426. typedef struct RbuUpdateStmt RbuUpdateStmt;
  158427. #if !defined(SQLITE_AMALGAMATION)
  158428. typedef unsigned int u32;
  158429. typedef unsigned short u16;
  158430. typedef unsigned char u8;
  158431. typedef sqlite3_int64 i64;
  158432. #endif
  158433. /*
  158434. ** These values must match the values defined in wal.c for the equivalent
  158435. ** locks. These are not magic numbers as they are part of the SQLite file
  158436. ** format.
  158437. */
  158438. #define WAL_LOCK_WRITE 0
  158439. #define WAL_LOCK_CKPT 1
  158440. #define WAL_LOCK_READ0 3
  158441. #define SQLITE_FCNTL_RBUCNT 5149216
  158442. /*
  158443. ** A structure to store values read from the rbu_state table in memory.
  158444. */
  158445. struct RbuState {
  158446. int eStage;
  158447. char *zTbl;
  158448. char *zIdx;
  158449. i64 iWalCksum;
  158450. int nRow;
  158451. i64 nProgress;
  158452. u32 iCookie;
  158453. i64 iOalSz;
  158454. i64 nPhaseOneStep;
  158455. };
  158456. struct RbuUpdateStmt {
  158457. char *zMask; /* Copy of update mask used with pUpdate */
  158458. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  158459. RbuUpdateStmt *pNext;
  158460. };
  158461. /*
  158462. ** An iterator of this type is used to iterate through all objects in
  158463. ** the target database that require updating. For each such table, the
  158464. ** iterator visits, in order:
  158465. **
  158466. ** * the table itself,
  158467. ** * each index of the table (zero or more points to visit), and
  158468. ** * a special "cleanup table" state.
  158469. **
  158470. ** abIndexed:
  158471. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  158472. ** it points to an array of flags nTblCol elements in size. The flag is
  158473. ** set for each column that is either a part of the PK or a part of an
  158474. ** index. Or clear otherwise.
  158475. **
  158476. */
  158477. struct RbuObjIter {
  158478. sqlite3_stmt *pTblIter; /* Iterate through tables */
  158479. sqlite3_stmt *pIdxIter; /* Index iterator */
  158480. int nTblCol; /* Size of azTblCol[] array */
  158481. char **azTblCol; /* Array of unquoted target column names */
  158482. char **azTblType; /* Array of target column types */
  158483. int *aiSrcOrder; /* src table col -> target table col */
  158484. u8 *abTblPk; /* Array of flags, set on target PK columns */
  158485. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  158486. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  158487. int eType; /* Table type - an RBU_PK_XXX value */
  158488. /* Output variables. zTbl==0 implies EOF. */
  158489. int bCleanup; /* True in "cleanup" state */
  158490. const char *zTbl; /* Name of target db table */
  158491. const char *zDataTbl; /* Name of rbu db table (or null) */
  158492. const char *zIdx; /* Name of target db index (or null) */
  158493. int iTnum; /* Root page of current object */
  158494. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  158495. int bUnique; /* Current index is unique */
  158496. int nIndex; /* Number of aux. indexes on table zTbl */
  158497. /* Statements created by rbuObjIterPrepareAll() */
  158498. int nCol; /* Number of columns in current object */
  158499. sqlite3_stmt *pSelect; /* Source data */
  158500. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  158501. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  158502. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  158503. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  158504. RbuUpdateStmt *pRbuUpdate;
  158505. };
  158506. /*
  158507. ** Values for RbuObjIter.eType
  158508. **
  158509. ** 0: Table does not exist (error)
  158510. ** 1: Table has an implicit rowid.
  158511. ** 2: Table has an explicit IPK column.
  158512. ** 3: Table has an external PK index.
  158513. ** 4: Table is WITHOUT ROWID.
  158514. ** 5: Table is a virtual table.
  158515. */
  158516. #define RBU_PK_NOTABLE 0
  158517. #define RBU_PK_NONE 1
  158518. #define RBU_PK_IPK 2
  158519. #define RBU_PK_EXTERNAL 3
  158520. #define RBU_PK_WITHOUT_ROWID 4
  158521. #define RBU_PK_VTAB 5
  158522. /*
  158523. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  158524. ** one of the following operations.
  158525. */
  158526. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  158527. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  158528. #define RBU_REPLACE 3 /* Delete and then insert a row */
  158529. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  158530. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  158531. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  158532. /*
  158533. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  158534. ** file should be copied to page iDbPage of the database file.
  158535. */
  158536. struct RbuFrame {
  158537. u32 iDbPage;
  158538. u32 iWalFrame;
  158539. };
  158540. /*
  158541. ** RBU handle.
  158542. **
  158543. ** nPhaseOneStep:
  158544. ** If the RBU database contains an rbu_count table, this value is set to
  158545. ** a running estimate of the number of b-tree operations required to
  158546. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  158547. ** API to calculate the permyriadage progress of populating the *-oal file
  158548. ** using the formula:
  158549. **
  158550. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  158551. **
  158552. ** nPhaseOneStep is initialized to the sum of:
  158553. **
  158554. ** nRow * (nIndex + 1)
  158555. **
  158556. ** for all source tables in the RBU database, where nRow is the number
  158557. ** of rows in the source table and nIndex the number of indexes on the
  158558. ** corresponding target database table.
  158559. **
  158560. ** This estimate is accurate if the RBU update consists entirely of
  158561. ** INSERT operations. However, it is inaccurate if:
  158562. **
  158563. ** * the RBU update contains any UPDATE operations. If the PK specified
  158564. ** for an UPDATE operation does not exist in the target table, then
  158565. ** no b-tree operations are required on index b-trees. Or if the
  158566. ** specified PK does exist, then (nIndex*2) such operations are
  158567. ** required (one delete and one insert on each index b-tree).
  158568. **
  158569. ** * the RBU update contains any DELETE operations for which the specified
  158570. ** PK does not exist. In this case no operations are required on index
  158571. ** b-trees.
  158572. **
  158573. ** * the RBU update contains REPLACE operations. These are similar to
  158574. ** UPDATE operations.
  158575. **
  158576. ** nPhaseOneStep is updated to account for the conditions above during the
  158577. ** first pass of each source table. The updated nPhaseOneStep value is
  158578. ** stored in the rbu_state table if the RBU update is suspended.
  158579. */
  158580. struct sqlite3rbu {
  158581. int eStage; /* Value of RBU_STATE_STAGE field */
  158582. sqlite3 *dbMain; /* target database handle */
  158583. sqlite3 *dbRbu; /* rbu database handle */
  158584. char *zTarget; /* Path to target db */
  158585. char *zRbu; /* Path to rbu db */
  158586. char *zState; /* Path to state db (or NULL if zRbu) */
  158587. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  158588. int rc; /* Value returned by last rbu_step() call */
  158589. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  158590. int nStep; /* Rows processed for current object */
  158591. int nProgress; /* Rows processed for all objects */
  158592. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  158593. const char *zVfsName; /* Name of automatically created rbu vfs */
  158594. rbu_file *pTargetFd; /* File handle open on target db */
  158595. int nPagePerSector; /* Pages per sector for pTargetFd */
  158596. i64 iOalSz;
  158597. i64 nPhaseOneStep;
  158598. /* The following state variables are used as part of the incremental
  158599. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  158600. ** function rbuSetupCheckpoint() for details. */
  158601. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  158602. u32 mLock;
  158603. int nFrame; /* Entries in aFrame[] array */
  158604. int nFrameAlloc; /* Allocated size of aFrame[] array */
  158605. RbuFrame *aFrame;
  158606. int pgsz;
  158607. u8 *aBuf;
  158608. i64 iWalCksum;
  158609. /* Used in RBU vacuum mode only */
  158610. int nRbu; /* Number of RBU VFS in the stack */
  158611. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  158612. };
  158613. /*
  158614. ** An rbu VFS is implemented using an instance of this structure.
  158615. */
  158616. struct rbu_vfs {
  158617. sqlite3_vfs base; /* rbu VFS shim methods */
  158618. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  158619. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  158620. rbu_file *pMain; /* Linked list of main db files */
  158621. };
  158622. /*
  158623. ** Each file opened by an rbu VFS is represented by an instance of
  158624. ** the following structure.
  158625. */
  158626. struct rbu_file {
  158627. sqlite3_file base; /* sqlite3_file methods */
  158628. sqlite3_file *pReal; /* Underlying file handle */
  158629. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  158630. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  158631. int openFlags; /* Flags this file was opened with */
  158632. u32 iCookie; /* Cookie value for main db files */
  158633. u8 iWriteVer; /* "write-version" value for main db files */
  158634. u8 bNolock; /* True to fail EXCLUSIVE locks */
  158635. int nShm; /* Number of entries in apShm[] array */
  158636. char **apShm; /* Array of mmap'd *-shm regions */
  158637. char *zDel; /* Delete this when closing file */
  158638. const char *zWal; /* Wal filename for this main db file */
  158639. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  158640. rbu_file *pMainNext; /* Next MAIN_DB file */
  158641. };
  158642. /*
  158643. ** True for an RBU vacuum handle, or false otherwise.
  158644. */
  158645. #define rbuIsVacuum(p) ((p)->zTarget==0)
  158646. /*************************************************************************
  158647. ** The following three functions, found below:
  158648. **
  158649. ** rbuDeltaGetInt()
  158650. ** rbuDeltaChecksum()
  158651. ** rbuDeltaApply()
  158652. **
  158653. ** are lifted from the fossil source code (http://fossil-scm.org). They
  158654. ** are used to implement the scalar SQL function rbu_fossil_delta().
  158655. */
  158656. /*
  158657. ** Read bytes from *pz and convert them into a positive integer. When
  158658. ** finished, leave *pz pointing to the first character past the end of
  158659. ** the integer. The *pLen parameter holds the length of the string
  158660. ** in *pz and is decremented once for each character in the integer.
  158661. */
  158662. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  158663. static const signed char zValue[] = {
  158664. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  158665. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  158666. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  158667. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  158668. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  158669. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  158670. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  158671. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  158672. };
  158673. unsigned int v = 0;
  158674. int c;
  158675. unsigned char *z = (unsigned char*)*pz;
  158676. unsigned char *zStart = z;
  158677. while( (c = zValue[0x7f&*(z++)])>=0 ){
  158678. v = (v<<6) + c;
  158679. }
  158680. z--;
  158681. *pLen -= z - zStart;
  158682. *pz = (char*)z;
  158683. return v;
  158684. }
  158685. /*
  158686. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  158687. */
  158688. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  158689. const unsigned char *z = (const unsigned char *)zIn;
  158690. unsigned sum0 = 0;
  158691. unsigned sum1 = 0;
  158692. unsigned sum2 = 0;
  158693. unsigned sum3 = 0;
  158694. while(N >= 16){
  158695. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  158696. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  158697. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  158698. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  158699. z += 16;
  158700. N -= 16;
  158701. }
  158702. while(N >= 4){
  158703. sum0 += z[0];
  158704. sum1 += z[1];
  158705. sum2 += z[2];
  158706. sum3 += z[3];
  158707. z += 4;
  158708. N -= 4;
  158709. }
  158710. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  158711. switch(N){
  158712. case 3: sum3 += (z[2] << 8);
  158713. case 2: sum3 += (z[1] << 16);
  158714. case 1: sum3 += (z[0] << 24);
  158715. default: ;
  158716. }
  158717. return sum3;
  158718. }
  158719. /*
  158720. ** Apply a delta.
  158721. **
  158722. ** The output buffer should be big enough to hold the whole output
  158723. ** file and a NUL terminator at the end. The delta_output_size()
  158724. ** routine will determine this size for you.
  158725. **
  158726. ** The delta string should be null-terminated. But the delta string
  158727. ** may contain embedded NUL characters (if the input and output are
  158728. ** binary files) so we also have to pass in the length of the delta in
  158729. ** the lenDelta parameter.
  158730. **
  158731. ** This function returns the size of the output file in bytes (excluding
  158732. ** the final NUL terminator character). Except, if the delta string is
  158733. ** malformed or intended for use with a source file other than zSrc,
  158734. ** then this routine returns -1.
  158735. **
  158736. ** Refer to the delta_create() documentation above for a description
  158737. ** of the delta file format.
  158738. */
  158739. static int rbuDeltaApply(
  158740. const char *zSrc, /* The source or pattern file */
  158741. int lenSrc, /* Length of the source file */
  158742. const char *zDelta, /* Delta to apply to the pattern */
  158743. int lenDelta, /* Length of the delta */
  158744. char *zOut /* Write the output into this preallocated buffer */
  158745. ){
  158746. unsigned int limit;
  158747. unsigned int total = 0;
  158748. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  158749. char *zOrigOut = zOut;
  158750. #endif
  158751. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  158752. if( *zDelta!='\n' ){
  158753. /* ERROR: size integer not terminated by "\n" */
  158754. return -1;
  158755. }
  158756. zDelta++; lenDelta--;
  158757. while( *zDelta && lenDelta>0 ){
  158758. unsigned int cnt, ofst;
  158759. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  158760. switch( zDelta[0] ){
  158761. case '@': {
  158762. zDelta++; lenDelta--;
  158763. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  158764. if( lenDelta>0 && zDelta[0]!=',' ){
  158765. /* ERROR: copy command not terminated by ',' */
  158766. return -1;
  158767. }
  158768. zDelta++; lenDelta--;
  158769. total += cnt;
  158770. if( total>limit ){
  158771. /* ERROR: copy exceeds output file size */
  158772. return -1;
  158773. }
  158774. if( (int)(ofst+cnt) > lenSrc ){
  158775. /* ERROR: copy extends past end of input */
  158776. return -1;
  158777. }
  158778. memcpy(zOut, &zSrc[ofst], cnt);
  158779. zOut += cnt;
  158780. break;
  158781. }
  158782. case ':': {
  158783. zDelta++; lenDelta--;
  158784. total += cnt;
  158785. if( total>limit ){
  158786. /* ERROR: insert command gives an output larger than predicted */
  158787. return -1;
  158788. }
  158789. if( (int)cnt>lenDelta ){
  158790. /* ERROR: insert count exceeds size of delta */
  158791. return -1;
  158792. }
  158793. memcpy(zOut, zDelta, cnt);
  158794. zOut += cnt;
  158795. zDelta += cnt;
  158796. lenDelta -= cnt;
  158797. break;
  158798. }
  158799. case ';': {
  158800. zDelta++; lenDelta--;
  158801. zOut[0] = 0;
  158802. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  158803. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  158804. /* ERROR: bad checksum */
  158805. return -1;
  158806. }
  158807. #endif
  158808. if( total!=limit ){
  158809. /* ERROR: generated size does not match predicted size */
  158810. return -1;
  158811. }
  158812. return total;
  158813. }
  158814. default: {
  158815. /* ERROR: unknown delta operator */
  158816. return -1;
  158817. }
  158818. }
  158819. }
  158820. /* ERROR: unterminated delta */
  158821. return -1;
  158822. }
  158823. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  158824. int size;
  158825. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  158826. if( *zDelta!='\n' ){
  158827. /* ERROR: size integer not terminated by "\n" */
  158828. return -1;
  158829. }
  158830. return size;
  158831. }
  158832. /*
  158833. ** End of code taken from fossil.
  158834. *************************************************************************/
  158835. /*
  158836. ** Implementation of SQL scalar function rbu_fossil_delta().
  158837. **
  158838. ** This function applies a fossil delta patch to a blob. Exactly two
  158839. ** arguments must be passed to this function. The first is the blob to
  158840. ** patch and the second the patch to apply. If no error occurs, this
  158841. ** function returns the patched blob.
  158842. */
  158843. static void rbuFossilDeltaFunc(
  158844. sqlite3_context *context,
  158845. int argc,
  158846. sqlite3_value **argv
  158847. ){
  158848. const char *aDelta;
  158849. int nDelta;
  158850. const char *aOrig;
  158851. int nOrig;
  158852. int nOut;
  158853. int nOut2;
  158854. char *aOut;
  158855. assert( argc==2 );
  158856. nOrig = sqlite3_value_bytes(argv[0]);
  158857. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  158858. nDelta = sqlite3_value_bytes(argv[1]);
  158859. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  158860. /* Figure out the size of the output */
  158861. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  158862. if( nOut<0 ){
  158863. sqlite3_result_error(context, "corrupt fossil delta", -1);
  158864. return;
  158865. }
  158866. aOut = sqlite3_malloc(nOut+1);
  158867. if( aOut==0 ){
  158868. sqlite3_result_error_nomem(context);
  158869. }else{
  158870. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  158871. if( nOut2!=nOut ){
  158872. sqlite3_result_error(context, "corrupt fossil delta", -1);
  158873. }else{
  158874. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  158875. }
  158876. }
  158877. }
  158878. /*
  158879. ** Prepare the SQL statement in buffer zSql against database handle db.
  158880. ** If successful, set *ppStmt to point to the new statement and return
  158881. ** SQLITE_OK.
  158882. **
  158883. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  158884. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  158885. ** point to a buffer containing an error message. It is the responsibility
  158886. ** of the caller to (eventually) free this buffer using sqlite3_free().
  158887. */
  158888. static int prepareAndCollectError(
  158889. sqlite3 *db,
  158890. sqlite3_stmt **ppStmt,
  158891. char **pzErrmsg,
  158892. const char *zSql
  158893. ){
  158894. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  158895. if( rc!=SQLITE_OK ){
  158896. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  158897. *ppStmt = 0;
  158898. }
  158899. return rc;
  158900. }
  158901. /*
  158902. ** Reset the SQL statement passed as the first argument. Return a copy
  158903. ** of the value returned by sqlite3_reset().
  158904. **
  158905. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  158906. ** containing an error message. It is the responsibility of the caller
  158907. ** to eventually free this buffer using sqlite3_free().
  158908. */
  158909. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  158910. int rc = sqlite3_reset(pStmt);
  158911. if( rc!=SQLITE_OK ){
  158912. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  158913. }
  158914. return rc;
  158915. }
  158916. /*
  158917. ** Unless it is NULL, argument zSql points to a buffer allocated using
  158918. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  158919. ** statement against database db and frees the buffer. If statement
  158920. ** compilation is successful, *ppStmt is set to point to the new statement
  158921. ** handle and SQLITE_OK is returned.
  158922. **
  158923. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  158924. ** returned. In this case, *pzErrmsg may also be set to point to an error
  158925. ** message. It is the responsibility of the caller to free this error message
  158926. ** buffer using sqlite3_free().
  158927. **
  158928. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  158929. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  158930. */
  158931. static int prepareFreeAndCollectError(
  158932. sqlite3 *db,
  158933. sqlite3_stmt **ppStmt,
  158934. char **pzErrmsg,
  158935. char *zSql
  158936. ){
  158937. int rc;
  158938. assert( *pzErrmsg==0 );
  158939. if( zSql==0 ){
  158940. rc = SQLITE_NOMEM;
  158941. *ppStmt = 0;
  158942. }else{
  158943. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  158944. sqlite3_free(zSql);
  158945. }
  158946. return rc;
  158947. }
  158948. /*
  158949. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  158950. ** by an earlier call to rbuObjIterCacheTableInfo().
  158951. */
  158952. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  158953. int i;
  158954. for(i=0; i<pIter->nTblCol; i++){
  158955. sqlite3_free(pIter->azTblCol[i]);
  158956. sqlite3_free(pIter->azTblType[i]);
  158957. }
  158958. sqlite3_free(pIter->azTblCol);
  158959. pIter->azTblCol = 0;
  158960. pIter->azTblType = 0;
  158961. pIter->aiSrcOrder = 0;
  158962. pIter->abTblPk = 0;
  158963. pIter->abNotNull = 0;
  158964. pIter->nTblCol = 0;
  158965. pIter->eType = 0; /* Invalid value */
  158966. }
  158967. /*
  158968. ** Finalize all statements and free all allocations that are specific to
  158969. ** the current object (table/index pair).
  158970. */
  158971. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  158972. RbuUpdateStmt *pUp;
  158973. sqlite3_finalize(pIter->pSelect);
  158974. sqlite3_finalize(pIter->pInsert);
  158975. sqlite3_finalize(pIter->pDelete);
  158976. sqlite3_finalize(pIter->pTmpInsert);
  158977. pUp = pIter->pRbuUpdate;
  158978. while( pUp ){
  158979. RbuUpdateStmt *pTmp = pUp->pNext;
  158980. sqlite3_finalize(pUp->pUpdate);
  158981. sqlite3_free(pUp);
  158982. pUp = pTmp;
  158983. }
  158984. pIter->pSelect = 0;
  158985. pIter->pInsert = 0;
  158986. pIter->pDelete = 0;
  158987. pIter->pRbuUpdate = 0;
  158988. pIter->pTmpInsert = 0;
  158989. pIter->nCol = 0;
  158990. }
  158991. /*
  158992. ** Clean up any resources allocated as part of the iterator object passed
  158993. ** as the only argument.
  158994. */
  158995. static void rbuObjIterFinalize(RbuObjIter *pIter){
  158996. rbuObjIterClearStatements(pIter);
  158997. sqlite3_finalize(pIter->pTblIter);
  158998. sqlite3_finalize(pIter->pIdxIter);
  158999. rbuObjIterFreeCols(pIter);
  159000. memset(pIter, 0, sizeof(RbuObjIter));
  159001. }
  159002. /*
  159003. ** Advance the iterator to the next position.
  159004. **
  159005. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  159006. ** pointing to the next entry. Otherwise, an error code and message is
  159007. ** left in the RBU handle passed as the first argument. A copy of the
  159008. ** error code is returned.
  159009. */
  159010. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  159011. int rc = p->rc;
  159012. if( rc==SQLITE_OK ){
  159013. /* Free any SQLite statements used while processing the previous object */
  159014. rbuObjIterClearStatements(pIter);
  159015. if( pIter->zIdx==0 ){
  159016. rc = sqlite3_exec(p->dbMain,
  159017. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  159018. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  159019. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  159020. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  159021. , 0, 0, &p->zErrmsg
  159022. );
  159023. }
  159024. if( rc==SQLITE_OK ){
  159025. if( pIter->bCleanup ){
  159026. rbuObjIterFreeCols(pIter);
  159027. pIter->bCleanup = 0;
  159028. rc = sqlite3_step(pIter->pTblIter);
  159029. if( rc!=SQLITE_ROW ){
  159030. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  159031. pIter->zTbl = 0;
  159032. }else{
  159033. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  159034. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  159035. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  159036. }
  159037. }else{
  159038. if( pIter->zIdx==0 ){
  159039. sqlite3_stmt *pIdx = pIter->pIdxIter;
  159040. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  159041. }
  159042. if( rc==SQLITE_OK ){
  159043. rc = sqlite3_step(pIter->pIdxIter);
  159044. if( rc!=SQLITE_ROW ){
  159045. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  159046. pIter->bCleanup = 1;
  159047. pIter->zIdx = 0;
  159048. }else{
  159049. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  159050. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  159051. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  159052. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  159053. }
  159054. }
  159055. }
  159056. }
  159057. }
  159058. if( rc!=SQLITE_OK ){
  159059. rbuObjIterFinalize(pIter);
  159060. p->rc = rc;
  159061. }
  159062. return rc;
  159063. }
  159064. /*
  159065. ** The implementation of the rbu_target_name() SQL function. This function
  159066. ** accepts one or two arguments. The first argument is the name of a table -
  159067. ** the name of a table in the RBU database. The second, if it is present, is 1
  159068. ** for a view or 0 for a table.
  159069. **
  159070. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  159071. **
  159072. ** data[0-9]_<name>
  159073. **
  159074. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  159075. ** Otherwise, if the only argument does not match the above pattern, an SQL
  159076. ** NULL is returned.
  159077. **
  159078. ** "data_t1" -> "t1"
  159079. ** "data0123_t2" -> "t2"
  159080. ** "dataAB_t3" -> NULL
  159081. **
  159082. ** For an rbu vacuum handle, a copy of the first argument is returned if
  159083. ** the second argument is either missing or 0 (not a view).
  159084. */
  159085. static void rbuTargetNameFunc(
  159086. sqlite3_context *pCtx,
  159087. int argc,
  159088. sqlite3_value **argv
  159089. ){
  159090. sqlite3rbu *p = sqlite3_user_data(pCtx);
  159091. const char *zIn;
  159092. assert( argc==1 || argc==2 );
  159093. zIn = (const char*)sqlite3_value_text(argv[0]);
  159094. if( zIn ){
  159095. if( rbuIsVacuum(p) ){
  159096. if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
  159097. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  159098. }
  159099. }else{
  159100. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  159101. int i;
  159102. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  159103. if( zIn[i]=='_' && zIn[i+1] ){
  159104. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  159105. }
  159106. }
  159107. }
  159108. }
  159109. }
  159110. /*
  159111. ** Initialize the iterator structure passed as the second argument.
  159112. **
  159113. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  159114. ** pointing to the first entry. Otherwise, an error code and message is
  159115. ** left in the RBU handle passed as the first argument. A copy of the
  159116. ** error code is returned.
  159117. */
  159118. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  159119. int rc;
  159120. memset(pIter, 0, sizeof(RbuObjIter));
  159121. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  159122. sqlite3_mprintf(
  159123. "SELECT rbu_target_name(name, type='view') AS target, name "
  159124. "FROM sqlite_master "
  159125. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  159126. " %s "
  159127. "ORDER BY name"
  159128. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  159129. if( rc==SQLITE_OK ){
  159130. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  159131. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  159132. " FROM main.sqlite_master "
  159133. " WHERE type='index' AND tbl_name = ?"
  159134. );
  159135. }
  159136. pIter->bCleanup = 1;
  159137. p->rc = rc;
  159138. return rbuObjIterNext(p, pIter);
  159139. }
  159140. /*
  159141. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  159142. ** an error code is stored in the RBU handle passed as the first argument.
  159143. **
  159144. ** If an error has already occurred (p->rc is already set to something other
  159145. ** than SQLITE_OK), then this function returns NULL without modifying the
  159146. ** stored error code. In this case it still calls sqlite3_free() on any
  159147. ** printf() parameters associated with %z conversions.
  159148. */
  159149. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  159150. char *zSql = 0;
  159151. va_list ap;
  159152. va_start(ap, zFmt);
  159153. zSql = sqlite3_vmprintf(zFmt, ap);
  159154. if( p->rc==SQLITE_OK ){
  159155. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  159156. }else{
  159157. sqlite3_free(zSql);
  159158. zSql = 0;
  159159. }
  159160. va_end(ap);
  159161. return zSql;
  159162. }
  159163. /*
  159164. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  159165. ** arguments are the usual subsitution values. This function performs
  159166. ** the printf() style substitutions and executes the result as an SQL
  159167. ** statement on the RBU handles database.
  159168. **
  159169. ** If an error occurs, an error code and error message is stored in the
  159170. ** RBU handle. If an error has already occurred when this function is
  159171. ** called, it is a no-op.
  159172. */
  159173. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  159174. va_list ap;
  159175. char *zSql;
  159176. va_start(ap, zFmt);
  159177. zSql = sqlite3_vmprintf(zFmt, ap);
  159178. if( p->rc==SQLITE_OK ){
  159179. if( zSql==0 ){
  159180. p->rc = SQLITE_NOMEM;
  159181. }else{
  159182. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  159183. }
  159184. }
  159185. sqlite3_free(zSql);
  159186. va_end(ap);
  159187. return p->rc;
  159188. }
  159189. /*
  159190. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  159191. ** bytes.
  159192. **
  159193. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  159194. ** error code in the rbu handle passed as the first argument. Or, if an
  159195. ** error has already occurred when this function is called, return NULL
  159196. ** immediately without attempting the allocation or modifying the stored
  159197. ** error code.
  159198. */
  159199. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  159200. void *pRet = 0;
  159201. if( p->rc==SQLITE_OK ){
  159202. assert( nByte>0 );
  159203. pRet = sqlite3_malloc64(nByte);
  159204. if( pRet==0 ){
  159205. p->rc = SQLITE_NOMEM;
  159206. }else{
  159207. memset(pRet, 0, nByte);
  159208. }
  159209. }
  159210. return pRet;
  159211. }
  159212. /*
  159213. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  159214. ** there is room for at least nCol elements. If an OOM occurs, store an
  159215. ** error code in the RBU handle passed as the first argument.
  159216. */
  159217. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  159218. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  159219. char **azNew;
  159220. azNew = (char**)rbuMalloc(p, nByte);
  159221. if( azNew ){
  159222. pIter->azTblCol = azNew;
  159223. pIter->azTblType = &azNew[nCol];
  159224. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  159225. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  159226. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  159227. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  159228. }
  159229. }
  159230. /*
  159231. ** The first argument must be a nul-terminated string. This function
  159232. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  159233. ** It is the responsibility of the caller to eventually free this memory
  159234. ** using sqlite3_free().
  159235. **
  159236. ** If an OOM condition is encountered when attempting to allocate memory,
  159237. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  159238. ** if the allocation succeeds, (*pRc) is left unchanged.
  159239. */
  159240. static char *rbuStrndup(const char *zStr, int *pRc){
  159241. char *zRet = 0;
  159242. assert( *pRc==SQLITE_OK );
  159243. if( zStr ){
  159244. size_t nCopy = strlen(zStr) + 1;
  159245. zRet = (char*)sqlite3_malloc64(nCopy);
  159246. if( zRet ){
  159247. memcpy(zRet, zStr, nCopy);
  159248. }else{
  159249. *pRc = SQLITE_NOMEM;
  159250. }
  159251. }
  159252. return zRet;
  159253. }
  159254. /*
  159255. ** Finalize the statement passed as the second argument.
  159256. **
  159257. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  159258. ** rbu handle error code is not already set, set the error code and error
  159259. ** message accordingly.
  159260. */
  159261. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  159262. sqlite3 *db = sqlite3_db_handle(pStmt);
  159263. int rc = sqlite3_finalize(pStmt);
  159264. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  159265. p->rc = rc;
  159266. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  159267. }
  159268. }
  159269. /* Determine the type of a table.
  159270. **
  159271. ** peType is of type (int*), a pointer to an output parameter of type
  159272. ** (int). This call sets the output parameter as follows, depending
  159273. ** on the type of the table specified by parameters dbName and zTbl.
  159274. **
  159275. ** RBU_PK_NOTABLE: No such table.
  159276. ** RBU_PK_NONE: Table has an implicit rowid.
  159277. ** RBU_PK_IPK: Table has an explicit IPK column.
  159278. ** RBU_PK_EXTERNAL: Table has an external PK index.
  159279. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  159280. ** RBU_PK_VTAB: Table is a virtual table.
  159281. **
  159282. ** Argument *piPk is also of type (int*), and also points to an output
  159283. ** parameter. Unless the table has an external primary key index
  159284. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  159285. ** if the table does have an external primary key index, then *piPk
  159286. ** is set to the root page number of the primary key index before
  159287. ** returning.
  159288. **
  159289. ** ALGORITHM:
  159290. **
  159291. ** if( no entry exists in sqlite_master ){
  159292. ** return RBU_PK_NOTABLE
  159293. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  159294. ** return RBU_PK_VTAB
  159295. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  159296. ** if( the index that is the pk exists in sqlite_master ){
  159297. ** *piPK = rootpage of that index.
  159298. ** return RBU_PK_EXTERNAL
  159299. ** }else{
  159300. ** return RBU_PK_WITHOUT_ROWID
  159301. ** }
  159302. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  159303. ** return RBU_PK_IPK
  159304. ** }else{
  159305. ** return RBU_PK_NONE
  159306. ** }
  159307. */
  159308. static void rbuTableType(
  159309. sqlite3rbu *p,
  159310. const char *zTab,
  159311. int *peType,
  159312. int *piTnum,
  159313. int *piPk
  159314. ){
  159315. /*
  159316. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  159317. ** 1) PRAGMA index_list = ?
  159318. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  159319. ** 3) PRAGMA table_info = ?
  159320. */
  159321. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  159322. *peType = RBU_PK_NOTABLE;
  159323. *piPk = 0;
  159324. assert( p->rc==SQLITE_OK );
  159325. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  159326. sqlite3_mprintf(
  159327. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  159328. " FROM sqlite_master"
  159329. " WHERE name=%Q", zTab
  159330. ));
  159331. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  159332. /* Either an error, or no such table. */
  159333. goto rbuTableType_end;
  159334. }
  159335. if( sqlite3_column_int(aStmt[0], 0) ){
  159336. *peType = RBU_PK_VTAB; /* virtual table */
  159337. goto rbuTableType_end;
  159338. }
  159339. *piTnum = sqlite3_column_int(aStmt[0], 1);
  159340. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  159341. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  159342. );
  159343. if( p->rc ) goto rbuTableType_end;
  159344. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  159345. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  159346. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  159347. if( zOrig && zIdx && zOrig[0]=='p' ){
  159348. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  159349. sqlite3_mprintf(
  159350. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  159351. ));
  159352. if( p->rc==SQLITE_OK ){
  159353. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  159354. *piPk = sqlite3_column_int(aStmt[2], 0);
  159355. *peType = RBU_PK_EXTERNAL;
  159356. }else{
  159357. *peType = RBU_PK_WITHOUT_ROWID;
  159358. }
  159359. }
  159360. goto rbuTableType_end;
  159361. }
  159362. }
  159363. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  159364. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  159365. );
  159366. if( p->rc==SQLITE_OK ){
  159367. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  159368. if( sqlite3_column_int(aStmt[3],5)>0 ){
  159369. *peType = RBU_PK_IPK; /* explicit IPK column */
  159370. goto rbuTableType_end;
  159371. }
  159372. }
  159373. *peType = RBU_PK_NONE;
  159374. }
  159375. rbuTableType_end: {
  159376. unsigned int i;
  159377. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  159378. rbuFinalize(p, aStmt[i]);
  159379. }
  159380. }
  159381. }
  159382. /*
  159383. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  159384. ** the pIter->abIndexed[] array.
  159385. */
  159386. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  159387. sqlite3_stmt *pList = 0;
  159388. int bIndex = 0;
  159389. if( p->rc==SQLITE_OK ){
  159390. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  159391. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  159392. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  159393. );
  159394. }
  159395. pIter->nIndex = 0;
  159396. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  159397. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  159398. sqlite3_stmt *pXInfo = 0;
  159399. if( zIdx==0 ) break;
  159400. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  159401. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  159402. );
  159403. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  159404. int iCid = sqlite3_column_int(pXInfo, 1);
  159405. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  159406. }
  159407. rbuFinalize(p, pXInfo);
  159408. bIndex = 1;
  159409. pIter->nIndex++;
  159410. }
  159411. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  159412. /* "PRAGMA index_list" includes the main PK b-tree */
  159413. pIter->nIndex--;
  159414. }
  159415. rbuFinalize(p, pList);
  159416. if( bIndex==0 ) pIter->abIndexed = 0;
  159417. }
  159418. /*
  159419. ** If they are not already populated, populate the pIter->azTblCol[],
  159420. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  159421. ** the table (not index) that the iterator currently points to.
  159422. **
  159423. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  159424. ** an error does occur, an error code and error message are also left in
  159425. ** the RBU handle.
  159426. */
  159427. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  159428. if( pIter->azTblCol==0 ){
  159429. sqlite3_stmt *pStmt = 0;
  159430. int nCol = 0;
  159431. int i; /* for() loop iterator variable */
  159432. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  159433. int iOrder = 0;
  159434. int iTnum = 0;
  159435. /* Figure out the type of table this step will deal with. */
  159436. assert( pIter->eType==0 );
  159437. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  159438. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  159439. p->rc = SQLITE_ERROR;
  159440. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  159441. }
  159442. if( p->rc ) return p->rc;
  159443. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  159444. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  159445. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  159446. || pIter->eType==RBU_PK_VTAB
  159447. );
  159448. /* Populate the azTblCol[] and nTblCol variables based on the columns
  159449. ** of the input table. Ignore any input table columns that begin with
  159450. ** "rbu_". */
  159451. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  159452. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  159453. );
  159454. if( p->rc==SQLITE_OK ){
  159455. nCol = sqlite3_column_count(pStmt);
  159456. rbuAllocateIterArrays(p, pIter, nCol);
  159457. }
  159458. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  159459. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  159460. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  159461. char *zCopy = rbuStrndup(zName, &p->rc);
  159462. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  159463. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  159464. }
  159465. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  159466. bRbuRowid = 1;
  159467. }
  159468. }
  159469. sqlite3_finalize(pStmt);
  159470. pStmt = 0;
  159471. if( p->rc==SQLITE_OK
  159472. && rbuIsVacuum(p)==0
  159473. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  159474. ){
  159475. p->rc = SQLITE_ERROR;
  159476. p->zErrmsg = sqlite3_mprintf(
  159477. "table %q %s rbu_rowid column", pIter->zDataTbl,
  159478. (bRbuRowid ? "may not have" : "requires")
  159479. );
  159480. }
  159481. /* Check that all non-HIDDEN columns in the destination table are also
  159482. ** present in the input table. Populate the abTblPk[], azTblType[] and
  159483. ** aiTblOrder[] arrays at the same time. */
  159484. if( p->rc==SQLITE_OK ){
  159485. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  159486. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  159487. );
  159488. }
  159489. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  159490. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  159491. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  159492. for(i=iOrder; i<pIter->nTblCol; i++){
  159493. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  159494. }
  159495. if( i==pIter->nTblCol ){
  159496. p->rc = SQLITE_ERROR;
  159497. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  159498. pIter->zDataTbl, zName
  159499. );
  159500. }else{
  159501. int iPk = sqlite3_column_int(pStmt, 5);
  159502. int bNotNull = sqlite3_column_int(pStmt, 3);
  159503. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  159504. if( i!=iOrder ){
  159505. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  159506. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  159507. }
  159508. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  159509. pIter->abTblPk[iOrder] = (iPk!=0);
  159510. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  159511. iOrder++;
  159512. }
  159513. }
  159514. rbuFinalize(p, pStmt);
  159515. rbuObjIterCacheIndexedCols(p, pIter);
  159516. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  159517. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  159518. }
  159519. return p->rc;
  159520. }
  159521. /*
  159522. ** This function constructs and returns a pointer to a nul-terminated
  159523. ** string containing some SQL clause or list based on one or more of the
  159524. ** column names currently stored in the pIter->azTblCol[] array.
  159525. */
  159526. static char *rbuObjIterGetCollist(
  159527. sqlite3rbu *p, /* RBU object */
  159528. RbuObjIter *pIter /* Object iterator for column names */
  159529. ){
  159530. char *zList = 0;
  159531. const char *zSep = "";
  159532. int i;
  159533. for(i=0; i<pIter->nTblCol; i++){
  159534. const char *z = pIter->azTblCol[i];
  159535. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  159536. zSep = ", ";
  159537. }
  159538. return zList;
  159539. }
  159540. /*
  159541. ** This function is used to create a SELECT list (the list of SQL
  159542. ** expressions that follows a SELECT keyword) for a SELECT statement
  159543. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  159544. ** index object currently indicated by the iterator object passed as the
  159545. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  159546. ** to obtain the required information.
  159547. **
  159548. ** If the index is of the following form:
  159549. **
  159550. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  159551. **
  159552. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  159553. ** "ipk", the returned string is:
  159554. **
  159555. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  159556. **
  159557. ** As well as the returned string, three other malloc'd strings are
  159558. ** returned via output parameters. As follows:
  159559. **
  159560. ** pzImposterCols: ...
  159561. ** pzImposterPk: ...
  159562. ** pzWhere: ...
  159563. */
  159564. static char *rbuObjIterGetIndexCols(
  159565. sqlite3rbu *p, /* RBU object */
  159566. RbuObjIter *pIter, /* Object iterator for column names */
  159567. char **pzImposterCols, /* OUT: Columns for imposter table */
  159568. char **pzImposterPk, /* OUT: Imposter PK clause */
  159569. char **pzWhere, /* OUT: WHERE clause */
  159570. int *pnBind /* OUT: Trbul number of columns */
  159571. ){
  159572. int rc = p->rc; /* Error code */
  159573. int rc2; /* sqlite3_finalize() return code */
  159574. char *zRet = 0; /* String to return */
  159575. char *zImpCols = 0; /* String to return via *pzImposterCols */
  159576. char *zImpPK = 0; /* String to return via *pzImposterPK */
  159577. char *zWhere = 0; /* String to return via *pzWhere */
  159578. int nBind = 0; /* Value to return via *pnBind */
  159579. const char *zCom = ""; /* Set to ", " later on */
  159580. const char *zAnd = ""; /* Set to " AND " later on */
  159581. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  159582. if( rc==SQLITE_OK ){
  159583. assert( p->zErrmsg==0 );
  159584. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  159585. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  159586. );
  159587. }
  159588. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  159589. int iCid = sqlite3_column_int(pXInfo, 1);
  159590. int bDesc = sqlite3_column_int(pXInfo, 3);
  159591. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  159592. const char *zCol;
  159593. const char *zType;
  159594. if( iCid<0 ){
  159595. /* An integer primary key. If the table has an explicit IPK, use
  159596. ** its name. Otherwise, use "rbu_rowid". */
  159597. if( pIter->eType==RBU_PK_IPK ){
  159598. int i;
  159599. for(i=0; pIter->abTblPk[i]==0; i++);
  159600. assert( i<pIter->nTblCol );
  159601. zCol = pIter->azTblCol[i];
  159602. }else if( rbuIsVacuum(p) ){
  159603. zCol = "_rowid_";
  159604. }else{
  159605. zCol = "rbu_rowid";
  159606. }
  159607. zType = "INTEGER";
  159608. }else{
  159609. zCol = pIter->azTblCol[iCid];
  159610. zType = pIter->azTblType[iCid];
  159611. }
  159612. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  159613. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  159614. const char *zOrder = (bDesc ? " DESC" : "");
  159615. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  159616. zImpPK, zCom, nBind, zCol, zOrder
  159617. );
  159618. }
  159619. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  159620. zImpCols, zCom, nBind, zCol, zType, zCollate
  159621. );
  159622. zWhere = sqlite3_mprintf(
  159623. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  159624. );
  159625. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  159626. zCom = ", ";
  159627. zAnd = " AND ";
  159628. nBind++;
  159629. }
  159630. rc2 = sqlite3_finalize(pXInfo);
  159631. if( rc==SQLITE_OK ) rc = rc2;
  159632. if( rc!=SQLITE_OK ){
  159633. sqlite3_free(zRet);
  159634. sqlite3_free(zImpCols);
  159635. sqlite3_free(zImpPK);
  159636. sqlite3_free(zWhere);
  159637. zRet = 0;
  159638. zImpCols = 0;
  159639. zImpPK = 0;
  159640. zWhere = 0;
  159641. p->rc = rc;
  159642. }
  159643. *pzImposterCols = zImpCols;
  159644. *pzImposterPk = zImpPK;
  159645. *pzWhere = zWhere;
  159646. *pnBind = nBind;
  159647. return zRet;
  159648. }
  159649. /*
  159650. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  159651. ** paramter is passed "old", return a string of the form:
  159652. **
  159653. ** "old.a, old.b, old.b"
  159654. **
  159655. ** With the column names escaped.
  159656. **
  159657. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  159658. ** the text ", old._rowid_" to the returned value.
  159659. */
  159660. static char *rbuObjIterGetOldlist(
  159661. sqlite3rbu *p,
  159662. RbuObjIter *pIter,
  159663. const char *zObj
  159664. ){
  159665. char *zList = 0;
  159666. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  159667. const char *zS = "";
  159668. int i;
  159669. for(i=0; i<pIter->nTblCol; i++){
  159670. if( pIter->abIndexed[i] ){
  159671. const char *zCol = pIter->azTblCol[i];
  159672. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  159673. }else{
  159674. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  159675. }
  159676. zS = ", ";
  159677. if( zList==0 ){
  159678. p->rc = SQLITE_NOMEM;
  159679. break;
  159680. }
  159681. }
  159682. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  159683. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  159684. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  159685. }
  159686. }
  159687. return zList;
  159688. }
  159689. /*
  159690. ** Return an expression that can be used in a WHERE clause to match the
  159691. ** primary key of the current table. For example, if the table is:
  159692. **
  159693. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  159694. **
  159695. ** Return the string:
  159696. **
  159697. ** "b = ?1 AND c = ?2"
  159698. */
  159699. static char *rbuObjIterGetWhere(
  159700. sqlite3rbu *p,
  159701. RbuObjIter *pIter
  159702. ){
  159703. char *zList = 0;
  159704. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  159705. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  159706. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  159707. const char *zSep = "";
  159708. int i;
  159709. for(i=0; i<pIter->nTblCol; i++){
  159710. if( pIter->abTblPk[i] ){
  159711. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  159712. zSep = " AND ";
  159713. }
  159714. }
  159715. zList = rbuMPrintf(p,
  159716. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  159717. );
  159718. }else{
  159719. const char *zSep = "";
  159720. int i;
  159721. for(i=0; i<pIter->nTblCol; i++){
  159722. if( pIter->abTblPk[i] ){
  159723. const char *zCol = pIter->azTblCol[i];
  159724. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  159725. zSep = " AND ";
  159726. }
  159727. }
  159728. }
  159729. return zList;
  159730. }
  159731. /*
  159732. ** The SELECT statement iterating through the keys for the current object
  159733. ** (p->objiter.pSelect) currently points to a valid row. However, there
  159734. ** is something wrong with the rbu_control value in the rbu_control value
  159735. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  159736. ** of the RBU handle to something reflecting this.
  159737. */
  159738. static void rbuBadControlError(sqlite3rbu *p){
  159739. p->rc = SQLITE_ERROR;
  159740. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  159741. }
  159742. /*
  159743. ** Return a nul-terminated string containing the comma separated list of
  159744. ** assignments that should be included following the "SET" keyword of
  159745. ** an UPDATE statement used to update the table object that the iterator
  159746. ** passed as the second argument currently points to if the rbu_control
  159747. ** column of the data_xxx table entry is set to zMask.
  159748. **
  159749. ** The memory for the returned string is obtained from sqlite3_malloc().
  159750. ** It is the responsibility of the caller to eventually free it using
  159751. ** sqlite3_free().
  159752. **
  159753. ** If an OOM error is encountered when allocating space for the new
  159754. ** string, an error code is left in the rbu handle passed as the first
  159755. ** argument and NULL is returned. Or, if an error has already occurred
  159756. ** when this function is called, NULL is returned immediately, without
  159757. ** attempting the allocation or modifying the stored error code.
  159758. */
  159759. static char *rbuObjIterGetSetlist(
  159760. sqlite3rbu *p,
  159761. RbuObjIter *pIter,
  159762. const char *zMask
  159763. ){
  159764. char *zList = 0;
  159765. if( p->rc==SQLITE_OK ){
  159766. int i;
  159767. if( (int)strlen(zMask)!=pIter->nTblCol ){
  159768. rbuBadControlError(p);
  159769. }else{
  159770. const char *zSep = "";
  159771. for(i=0; i<pIter->nTblCol; i++){
  159772. char c = zMask[pIter->aiSrcOrder[i]];
  159773. if( c=='x' ){
  159774. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  159775. zList, zSep, pIter->azTblCol[i], i+1
  159776. );
  159777. zSep = ", ";
  159778. }
  159779. else if( c=='d' ){
  159780. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  159781. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  159782. );
  159783. zSep = ", ";
  159784. }
  159785. else if( c=='f' ){
  159786. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  159787. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  159788. );
  159789. zSep = ", ";
  159790. }
  159791. }
  159792. }
  159793. }
  159794. return zList;
  159795. }
  159796. /*
  159797. ** Return a nul-terminated string consisting of nByte comma separated
  159798. ** "?" expressions. For example, if nByte is 3, return a pointer to
  159799. ** a buffer containing the string "?,?,?".
  159800. **
  159801. ** The memory for the returned string is obtained from sqlite3_malloc().
  159802. ** It is the responsibility of the caller to eventually free it using
  159803. ** sqlite3_free().
  159804. **
  159805. ** If an OOM error is encountered when allocating space for the new
  159806. ** string, an error code is left in the rbu handle passed as the first
  159807. ** argument and NULL is returned. Or, if an error has already occurred
  159808. ** when this function is called, NULL is returned immediately, without
  159809. ** attempting the allocation or modifying the stored error code.
  159810. */
  159811. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  159812. char *zRet = 0;
  159813. int nByte = nBind*2 + 1;
  159814. zRet = (char*)rbuMalloc(p, nByte);
  159815. if( zRet ){
  159816. int i;
  159817. for(i=0; i<nBind; i++){
  159818. zRet[i*2] = '?';
  159819. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  159820. }
  159821. }
  159822. return zRet;
  159823. }
  159824. /*
  159825. ** The iterator currently points to a table (not index) of type
  159826. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  159827. ** declaration for the corresponding imposter table. For example,
  159828. ** if the iterator points to a table created as:
  159829. **
  159830. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  159831. **
  159832. ** this function returns:
  159833. **
  159834. ** PRIMARY KEY("b", "a" DESC)
  159835. */
  159836. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  159837. char *z = 0;
  159838. assert( pIter->zIdx==0 );
  159839. if( p->rc==SQLITE_OK ){
  159840. const char *zSep = "PRIMARY KEY(";
  159841. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  159842. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  159843. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  159844. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  159845. );
  159846. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  159847. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  159848. if( zOrig && strcmp(zOrig, "pk")==0 ){
  159849. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  159850. if( zIdx ){
  159851. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  159852. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  159853. );
  159854. }
  159855. break;
  159856. }
  159857. }
  159858. rbuFinalize(p, pXList);
  159859. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  159860. if( sqlite3_column_int(pXInfo, 5) ){
  159861. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  159862. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  159863. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  159864. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  159865. zSep = ", ";
  159866. }
  159867. }
  159868. z = rbuMPrintf(p, "%z)", z);
  159869. rbuFinalize(p, pXInfo);
  159870. }
  159871. return z;
  159872. }
  159873. /*
  159874. ** This function creates the second imposter table used when writing to
  159875. ** a table b-tree where the table has an external primary key. If the
  159876. ** iterator passed as the second argument does not currently point to
  159877. ** a table (not index) with an external primary key, this function is a
  159878. ** no-op.
  159879. **
  159880. ** Assuming the iterator does point to a table with an external PK, this
  159881. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  159882. ** used to access that PK index. For example, if the target table is
  159883. ** declared as follows:
  159884. **
  159885. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  159886. **
  159887. ** then the imposter table schema is:
  159888. **
  159889. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  159890. **
  159891. */
  159892. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  159893. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  159894. int tnum = pIter->iPkTnum; /* Root page of PK index */
  159895. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  159896. const char *zIdx = 0; /* Name of PK index */
  159897. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  159898. const char *zComma = "";
  159899. char *zCols = 0; /* Used to build up list of table cols */
  159900. char *zPk = 0; /* Used to build up table PK declaration */
  159901. /* Figure out the name of the primary key index for the current table.
  159902. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  159903. ** zIdx to point to a nul-terminated string containing this name. */
  159904. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  159905. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  159906. );
  159907. if( p->rc==SQLITE_OK ){
  159908. sqlite3_bind_int(pQuery, 1, tnum);
  159909. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  159910. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  159911. }
  159912. }
  159913. if( zIdx ){
  159914. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  159915. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  159916. );
  159917. }
  159918. rbuFinalize(p, pQuery);
  159919. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  159920. int bKey = sqlite3_column_int(pXInfo, 5);
  159921. if( bKey ){
  159922. int iCid = sqlite3_column_int(pXInfo, 1);
  159923. int bDesc = sqlite3_column_int(pXInfo, 3);
  159924. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  159925. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
  159926. iCid, pIter->azTblType[iCid], zCollate
  159927. );
  159928. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  159929. zComma = ", ";
  159930. }
  159931. }
  159932. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  159933. rbuFinalize(p, pXInfo);
  159934. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  159935. rbuMPrintfExec(p, p->dbMain,
  159936. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  159937. zCols, zPk
  159938. );
  159939. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  159940. }
  159941. }
  159942. /*
  159943. ** If an error has already occurred when this function is called, it
  159944. ** immediately returns zero (without doing any work). Or, if an error
  159945. ** occurs during the execution of this function, it sets the error code
  159946. ** in the sqlite3rbu object indicated by the first argument and returns
  159947. ** zero.
  159948. **
  159949. ** The iterator passed as the second argument is guaranteed to point to
  159950. ** a table (not an index) when this function is called. This function
  159951. ** attempts to create any imposter table required to write to the main
  159952. ** table b-tree of the table before returning. Non-zero is returned if
  159953. ** an imposter table are created, or zero otherwise.
  159954. **
  159955. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  159956. ** virtual tables are written to directly. The imposter table has the
  159957. ** same schema as the actual target table (less any UNIQUE constraints).
  159958. ** More precisely, the "same schema" means the same columns, types,
  159959. ** collation sequences. For tables that do not have an external PRIMARY
  159960. ** KEY, it also means the same PRIMARY KEY declaration.
  159961. */
  159962. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  159963. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  159964. int tnum = pIter->iTnum;
  159965. const char *zComma = "";
  159966. char *zSql = 0;
  159967. int iCol;
  159968. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  159969. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  159970. const char *zPk = "";
  159971. const char *zCol = pIter->azTblCol[iCol];
  159972. const char *zColl = 0;
  159973. p->rc = sqlite3_table_column_metadata(
  159974. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  159975. );
  159976. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  159977. /* If the target table column is an "INTEGER PRIMARY KEY", add
  159978. ** "PRIMARY KEY" to the imposter table column declaration. */
  159979. zPk = "PRIMARY KEY ";
  159980. }
  159981. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
  159982. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  159983. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  159984. );
  159985. zComma = ", ";
  159986. }
  159987. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  159988. char *zPk = rbuWithoutRowidPK(p, pIter);
  159989. if( zPk ){
  159990. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  159991. }
  159992. }
  159993. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  159994. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  159995. pIter->zTbl, zSql,
  159996. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  159997. );
  159998. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  159999. }
  160000. }
  160001. /*
  160002. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  160003. ** Specifically a statement of the form:
  160004. **
  160005. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  160006. **
  160007. ** The number of bound variables is equal to the number of columns in
  160008. ** the target table, plus one (for the rbu_control column), plus one more
  160009. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  160010. ** virtual table.
  160011. */
  160012. static void rbuObjIterPrepareTmpInsert(
  160013. sqlite3rbu *p,
  160014. RbuObjIter *pIter,
  160015. const char *zCollist,
  160016. const char *zRbuRowid
  160017. ){
  160018. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  160019. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  160020. if( zBind ){
  160021. assert( pIter->pTmpInsert==0 );
  160022. p->rc = prepareFreeAndCollectError(
  160023. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  160024. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  160025. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  160026. ));
  160027. }
  160028. }
  160029. static void rbuTmpInsertFunc(
  160030. sqlite3_context *pCtx,
  160031. int nVal,
  160032. sqlite3_value **apVal
  160033. ){
  160034. sqlite3rbu *p = sqlite3_user_data(pCtx);
  160035. int rc = SQLITE_OK;
  160036. int i;
  160037. assert( sqlite3_value_int(apVal[0])!=0
  160038. || p->objiter.eType==RBU_PK_EXTERNAL
  160039. || p->objiter.eType==RBU_PK_NONE
  160040. );
  160041. if( sqlite3_value_int(apVal[0])!=0 ){
  160042. p->nPhaseOneStep += p->objiter.nIndex;
  160043. }
  160044. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  160045. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  160046. }
  160047. if( rc==SQLITE_OK ){
  160048. sqlite3_step(p->objiter.pTmpInsert);
  160049. rc = sqlite3_reset(p->objiter.pTmpInsert);
  160050. }
  160051. if( rc!=SQLITE_OK ){
  160052. sqlite3_result_error_code(pCtx, rc);
  160053. }
  160054. }
  160055. /*
  160056. ** Ensure that the SQLite statement handles required to update the
  160057. ** target database object currently indicated by the iterator passed
  160058. ** as the second argument are available.
  160059. */
  160060. static int rbuObjIterPrepareAll(
  160061. sqlite3rbu *p,
  160062. RbuObjIter *pIter,
  160063. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  160064. ){
  160065. assert( pIter->bCleanup==0 );
  160066. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  160067. const int tnum = pIter->iTnum;
  160068. char *zCollist = 0; /* List of indexed columns */
  160069. char **pz = &p->zErrmsg;
  160070. const char *zIdx = pIter->zIdx;
  160071. char *zLimit = 0;
  160072. if( nOffset ){
  160073. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  160074. if( !zLimit ) p->rc = SQLITE_NOMEM;
  160075. }
  160076. if( zIdx ){
  160077. const char *zTbl = pIter->zTbl;
  160078. char *zImposterCols = 0; /* Columns for imposter table */
  160079. char *zImposterPK = 0; /* Primary key declaration for imposter */
  160080. char *zWhere = 0; /* WHERE clause on PK columns */
  160081. char *zBind = 0;
  160082. int nBind = 0;
  160083. assert( pIter->eType!=RBU_PK_VTAB );
  160084. zCollist = rbuObjIterGetIndexCols(
  160085. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  160086. );
  160087. zBind = rbuObjIterGetBindlist(p, nBind);
  160088. /* Create the imposter table used to write to this index. */
  160089. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  160090. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  160091. rbuMPrintfExec(p, p->dbMain,
  160092. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  160093. zTbl, zImposterCols, zImposterPK
  160094. );
  160095. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  160096. /* Create the statement to insert index entries */
  160097. pIter->nCol = nBind;
  160098. if( p->rc==SQLITE_OK ){
  160099. p->rc = prepareFreeAndCollectError(
  160100. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  160101. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  160102. );
  160103. }
  160104. /* And to delete index entries */
  160105. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  160106. p->rc = prepareFreeAndCollectError(
  160107. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  160108. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  160109. );
  160110. }
  160111. /* Create the SELECT statement to read keys in sorted order */
  160112. if( p->rc==SQLITE_OK ){
  160113. char *zSql;
  160114. if( rbuIsVacuum(p) ){
  160115. zSql = sqlite3_mprintf(
  160116. "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
  160117. zCollist,
  160118. pIter->zDataTbl,
  160119. zCollist, zLimit
  160120. );
  160121. }else
  160122. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  160123. zSql = sqlite3_mprintf(
  160124. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  160125. zCollist, p->zStateDb, pIter->zDataTbl,
  160126. zCollist, zLimit
  160127. );
  160128. }else{
  160129. zSql = sqlite3_mprintf(
  160130. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  160131. "UNION ALL "
  160132. "SELECT %s, rbu_control FROM '%q' "
  160133. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  160134. "ORDER BY %s%s",
  160135. zCollist, p->zStateDb, pIter->zDataTbl,
  160136. zCollist, pIter->zDataTbl,
  160137. zCollist, zLimit
  160138. );
  160139. }
  160140. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  160141. }
  160142. sqlite3_free(zImposterCols);
  160143. sqlite3_free(zImposterPK);
  160144. sqlite3_free(zWhere);
  160145. sqlite3_free(zBind);
  160146. }else{
  160147. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  160148. ||(pIter->eType==RBU_PK_NONE)
  160149. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  160150. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  160151. const char *zWrite; /* Imposter table name */
  160152. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  160153. char *zWhere = rbuObjIterGetWhere(p, pIter);
  160154. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  160155. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  160156. zCollist = rbuObjIterGetCollist(p, pIter);
  160157. pIter->nCol = pIter->nTblCol;
  160158. /* Create the imposter table or tables (if required). */
  160159. rbuCreateImposterTable(p, pIter);
  160160. rbuCreateImposterTable2(p, pIter);
  160161. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  160162. /* Create the INSERT statement to write to the target PK b-tree */
  160163. if( p->rc==SQLITE_OK ){
  160164. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  160165. sqlite3_mprintf(
  160166. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  160167. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  160168. )
  160169. );
  160170. }
  160171. /* Create the DELETE statement to write to the target PK b-tree.
  160172. ** Because it only performs INSERT operations, this is not required for
  160173. ** an rbu vacuum handle. */
  160174. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  160175. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  160176. sqlite3_mprintf(
  160177. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  160178. )
  160179. );
  160180. }
  160181. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  160182. const char *zRbuRowid = "";
  160183. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  160184. zRbuRowid = ", rbu_rowid";
  160185. }
  160186. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  160187. rbuMPrintfExec(p, p->dbRbu,
  160188. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  160189. "SELECT *%s FROM '%q' WHERE 0;"
  160190. , p->zStateDb, pIter->zDataTbl
  160191. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  160192. , pIter->zDataTbl
  160193. );
  160194. rbuMPrintfExec(p, p->dbMain,
  160195. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  160196. "BEGIN "
  160197. " SELECT rbu_tmp_insert(3, %s);"
  160198. "END;"
  160199. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  160200. "BEGIN "
  160201. " SELECT rbu_tmp_insert(3, %s);"
  160202. "END;"
  160203. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  160204. "BEGIN "
  160205. " SELECT rbu_tmp_insert(4, %s);"
  160206. "END;",
  160207. zWrite, zTbl, zOldlist,
  160208. zWrite, zTbl, zOldlist,
  160209. zWrite, zTbl, zNewlist
  160210. );
  160211. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  160212. rbuMPrintfExec(p, p->dbMain,
  160213. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  160214. "BEGIN "
  160215. " SELECT rbu_tmp_insert(0, %s);"
  160216. "END;",
  160217. zWrite, zTbl, zNewlist
  160218. );
  160219. }
  160220. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  160221. }
  160222. /* Create the SELECT statement to read keys from data_xxx */
  160223. if( p->rc==SQLITE_OK ){
  160224. const char *zRbuRowid = "";
  160225. if( bRbuRowid ){
  160226. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  160227. }
  160228. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  160229. sqlite3_mprintf(
  160230. "SELECT %s,%s rbu_control%s FROM '%q'%s",
  160231. zCollist,
  160232. (rbuIsVacuum(p) ? "0 AS " : ""),
  160233. zRbuRowid,
  160234. pIter->zDataTbl, zLimit
  160235. )
  160236. );
  160237. }
  160238. sqlite3_free(zWhere);
  160239. sqlite3_free(zOldlist);
  160240. sqlite3_free(zNewlist);
  160241. sqlite3_free(zBindings);
  160242. }
  160243. sqlite3_free(zCollist);
  160244. sqlite3_free(zLimit);
  160245. }
  160246. return p->rc;
  160247. }
  160248. /*
  160249. ** Set output variable *ppStmt to point to an UPDATE statement that may
  160250. ** be used to update the imposter table for the main table b-tree of the
  160251. ** table object that pIter currently points to, assuming that the
  160252. ** rbu_control column of the data_xyz table contains zMask.
  160253. **
  160254. ** If the zMask string does not specify any columns to update, then this
  160255. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  160256. */
  160257. static int rbuGetUpdateStmt(
  160258. sqlite3rbu *p, /* RBU handle */
  160259. RbuObjIter *pIter, /* Object iterator */
  160260. const char *zMask, /* rbu_control value ('x.x.') */
  160261. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  160262. ){
  160263. RbuUpdateStmt **pp;
  160264. RbuUpdateStmt *pUp = 0;
  160265. int nUp = 0;
  160266. /* In case an error occurs */
  160267. *ppStmt = 0;
  160268. /* Search for an existing statement. If one is found, shift it to the front
  160269. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  160270. ** to the number of statements currently in the cache and pUp to the
  160271. ** last object in the list. */
  160272. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  160273. pUp = *pp;
  160274. if( strcmp(pUp->zMask, zMask)==0 ){
  160275. *pp = pUp->pNext;
  160276. pUp->pNext = pIter->pRbuUpdate;
  160277. pIter->pRbuUpdate = pUp;
  160278. *ppStmt = pUp->pUpdate;
  160279. return SQLITE_OK;
  160280. }
  160281. nUp++;
  160282. }
  160283. assert( pUp==0 || pUp->pNext==0 );
  160284. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  160285. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  160286. *pp = 0;
  160287. sqlite3_finalize(pUp->pUpdate);
  160288. pUp->pUpdate = 0;
  160289. }else{
  160290. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  160291. }
  160292. if( pUp ){
  160293. char *zWhere = rbuObjIterGetWhere(p, pIter);
  160294. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  160295. char *zUpdate = 0;
  160296. pUp->zMask = (char*)&pUp[1];
  160297. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  160298. pUp->pNext = pIter->pRbuUpdate;
  160299. pIter->pRbuUpdate = pUp;
  160300. if( zSet ){
  160301. const char *zPrefix = "";
  160302. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  160303. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  160304. zPrefix, pIter->zTbl, zSet, zWhere
  160305. );
  160306. p->rc = prepareFreeAndCollectError(
  160307. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  160308. );
  160309. *ppStmt = pUp->pUpdate;
  160310. }
  160311. sqlite3_free(zWhere);
  160312. sqlite3_free(zSet);
  160313. }
  160314. return p->rc;
  160315. }
  160316. static sqlite3 *rbuOpenDbhandle(
  160317. sqlite3rbu *p,
  160318. const char *zName,
  160319. int bUseVfs
  160320. ){
  160321. sqlite3 *db = 0;
  160322. if( p->rc==SQLITE_OK ){
  160323. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  160324. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  160325. if( p->rc ){
  160326. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  160327. sqlite3_close(db);
  160328. db = 0;
  160329. }
  160330. }
  160331. return db;
  160332. }
  160333. /*
  160334. ** Free an RbuState object allocated by rbuLoadState().
  160335. */
  160336. static void rbuFreeState(RbuState *p){
  160337. if( p ){
  160338. sqlite3_free(p->zTbl);
  160339. sqlite3_free(p->zIdx);
  160340. sqlite3_free(p);
  160341. }
  160342. }
  160343. /*
  160344. ** Allocate an RbuState object and load the contents of the rbu_state
  160345. ** table into it. Return a pointer to the new object. It is the
  160346. ** responsibility of the caller to eventually free the object using
  160347. ** sqlite3_free().
  160348. **
  160349. ** If an error occurs, leave an error code and message in the rbu handle
  160350. ** and return NULL.
  160351. */
  160352. static RbuState *rbuLoadState(sqlite3rbu *p){
  160353. RbuState *pRet = 0;
  160354. sqlite3_stmt *pStmt = 0;
  160355. int rc;
  160356. int rc2;
  160357. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  160358. if( pRet==0 ) return 0;
  160359. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  160360. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  160361. );
  160362. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  160363. switch( sqlite3_column_int(pStmt, 0) ){
  160364. case RBU_STATE_STAGE:
  160365. pRet->eStage = sqlite3_column_int(pStmt, 1);
  160366. if( pRet->eStage!=RBU_STAGE_OAL
  160367. && pRet->eStage!=RBU_STAGE_MOVE
  160368. && pRet->eStage!=RBU_STAGE_CKPT
  160369. ){
  160370. p->rc = SQLITE_CORRUPT;
  160371. }
  160372. break;
  160373. case RBU_STATE_TBL:
  160374. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  160375. break;
  160376. case RBU_STATE_IDX:
  160377. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  160378. break;
  160379. case RBU_STATE_ROW:
  160380. pRet->nRow = sqlite3_column_int(pStmt, 1);
  160381. break;
  160382. case RBU_STATE_PROGRESS:
  160383. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  160384. break;
  160385. case RBU_STATE_CKPT:
  160386. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  160387. break;
  160388. case RBU_STATE_COOKIE:
  160389. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  160390. break;
  160391. case RBU_STATE_OALSZ:
  160392. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  160393. break;
  160394. case RBU_STATE_PHASEONESTEP:
  160395. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  160396. break;
  160397. default:
  160398. rc = SQLITE_CORRUPT;
  160399. break;
  160400. }
  160401. }
  160402. rc2 = sqlite3_finalize(pStmt);
  160403. if( rc==SQLITE_OK ) rc = rc2;
  160404. p->rc = rc;
  160405. return pRet;
  160406. }
  160407. /*
  160408. ** Open the database handle and attach the RBU database as "rbu". If an
  160409. ** error occurs, leave an error code and message in the RBU handle.
  160410. */
  160411. static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
  160412. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  160413. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  160414. /* Open the RBU database */
  160415. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  160416. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  160417. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  160418. if( p->zState==0 ){
  160419. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  160420. p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
  160421. }
  160422. }
  160423. /* If using separate RBU and state databases, attach the state database to
  160424. ** the RBU db handle now. */
  160425. if( p->zState ){
  160426. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  160427. memcpy(p->zStateDb, "stat", 4);
  160428. }else{
  160429. memcpy(p->zStateDb, "main", 4);
  160430. }
  160431. #if 0
  160432. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  160433. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  160434. }
  160435. #endif
  160436. /* If it has not already been created, create the rbu_state table */
  160437. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  160438. #if 0
  160439. if( rbuIsVacuum(p) ){
  160440. if( p->rc==SQLITE_OK ){
  160441. int rc2;
  160442. int bOk = 0;
  160443. sqlite3_stmt *pCnt = 0;
  160444. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  160445. "SELECT count(*) FROM stat.sqlite_master"
  160446. );
  160447. if( p->rc==SQLITE_OK
  160448. && sqlite3_step(pCnt)==SQLITE_ROW
  160449. && 1==sqlite3_column_int(pCnt, 0)
  160450. ){
  160451. bOk = 1;
  160452. }
  160453. rc2 = sqlite3_finalize(pCnt);
  160454. if( p->rc==SQLITE_OK ) p->rc = rc2;
  160455. if( p->rc==SQLITE_OK && bOk==0 ){
  160456. p->rc = SQLITE_ERROR;
  160457. p->zErrmsg = sqlite3_mprintf("invalid state database");
  160458. }
  160459. if( p->rc==SQLITE_OK ){
  160460. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  160461. }
  160462. }
  160463. }
  160464. #endif
  160465. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  160466. int bOpen = 0;
  160467. int rc;
  160468. p->nRbu = 0;
  160469. p->pRbuFd = 0;
  160470. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  160471. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  160472. if( p->eStage>=RBU_STAGE_MOVE ){
  160473. bOpen = 1;
  160474. }else{
  160475. RbuState *pState = rbuLoadState(p);
  160476. if( pState ){
  160477. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  160478. rbuFreeState(pState);
  160479. }
  160480. }
  160481. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  160482. }
  160483. p->eStage = 0;
  160484. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  160485. if( !rbuIsVacuum(p) ){
  160486. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  160487. }else if( p->pRbuFd->pWalFd ){
  160488. if( pbRetry ){
  160489. p->pRbuFd->bNolock = 0;
  160490. sqlite3_close(p->dbRbu);
  160491. sqlite3_close(p->dbMain);
  160492. p->dbMain = 0;
  160493. p->dbRbu = 0;
  160494. *pbRetry = 1;
  160495. return;
  160496. }
  160497. p->rc = SQLITE_ERROR;
  160498. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  160499. }else{
  160500. char *zTarget;
  160501. char *zExtra = 0;
  160502. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  160503. zExtra = &p->zRbu[5];
  160504. while( *zExtra ){
  160505. if( *zExtra++=='?' ) break;
  160506. }
  160507. if( *zExtra=='\0' ) zExtra = 0;
  160508. }
  160509. zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
  160510. sqlite3_db_filename(p->dbRbu, "main"),
  160511. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  160512. );
  160513. if( zTarget==0 ){
  160514. p->rc = SQLITE_NOMEM;
  160515. return;
  160516. }
  160517. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  160518. sqlite3_free(zTarget);
  160519. }
  160520. }
  160521. if( p->rc==SQLITE_OK ){
  160522. p->rc = sqlite3_create_function(p->dbMain,
  160523. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  160524. );
  160525. }
  160526. if( p->rc==SQLITE_OK ){
  160527. p->rc = sqlite3_create_function(p->dbMain,
  160528. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  160529. );
  160530. }
  160531. if( p->rc==SQLITE_OK ){
  160532. p->rc = sqlite3_create_function(p->dbRbu,
  160533. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  160534. );
  160535. }
  160536. if( p->rc==SQLITE_OK ){
  160537. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  160538. }
  160539. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  160540. /* Mark the database file just opened as an RBU target database. If
  160541. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  160542. ** This is an error. */
  160543. if( p->rc==SQLITE_OK ){
  160544. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  160545. }
  160546. if( p->rc==SQLITE_NOTFOUND ){
  160547. p->rc = SQLITE_ERROR;
  160548. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  160549. }
  160550. }
  160551. /*
  160552. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  160553. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  160554. **
  160555. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  160556. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  160557. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  160558. ** three characters, then shorten the suffix on z[] to be the last three
  160559. ** characters of the original suffix.
  160560. **
  160561. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  160562. ** do the suffix shortening regardless of URI parameter.
  160563. **
  160564. ** Examples:
  160565. **
  160566. ** test.db-journal => test.nal
  160567. ** test.db-wal => test.wal
  160568. ** test.db-shm => test.shm
  160569. ** test.db-mj7f3319fa => test.9fa
  160570. */
  160571. static void rbuFileSuffix3(const char *zBase, char *z){
  160572. #ifdef SQLITE_ENABLE_8_3_NAMES
  160573. #if SQLITE_ENABLE_8_3_NAMES<2
  160574. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  160575. #endif
  160576. {
  160577. int i, sz;
  160578. sz = (int)strlen(z)&0xffffff;
  160579. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  160580. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  160581. }
  160582. #endif
  160583. }
  160584. /*
  160585. ** Return the current wal-index header checksum for the target database
  160586. ** as a 64-bit integer.
  160587. **
  160588. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  160589. ** blob starting at byte offset 40.
  160590. */
  160591. static i64 rbuShmChecksum(sqlite3rbu *p){
  160592. i64 iRet = 0;
  160593. if( p->rc==SQLITE_OK ){
  160594. sqlite3_file *pDb = p->pTargetFd->pReal;
  160595. u32 volatile *ptr;
  160596. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  160597. if( p->rc==SQLITE_OK ){
  160598. iRet = ((i64)ptr[10] << 32) + ptr[11];
  160599. }
  160600. }
  160601. return iRet;
  160602. }
  160603. /*
  160604. ** This function is called as part of initializing or reinitializing an
  160605. ** incremental checkpoint.
  160606. **
  160607. ** It populates the sqlite3rbu.aFrame[] array with the set of
  160608. ** (wal frame -> db page) copy operations required to checkpoint the
  160609. ** current wal file, and obtains the set of shm locks required to safely
  160610. ** perform the copy operations directly on the file-system.
  160611. **
  160612. ** If argument pState is not NULL, then the incremental checkpoint is
  160613. ** being resumed. In this case, if the checksum of the wal-index-header
  160614. ** following recovery is not the same as the checksum saved in the RbuState
  160615. ** object, then the rbu handle is set to DONE state. This occurs if some
  160616. ** other client appends a transaction to the wal file in the middle of
  160617. ** an incremental checkpoint.
  160618. */
  160619. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  160620. /* If pState is NULL, then the wal file may not have been opened and
  160621. ** recovered. Running a read-statement here to ensure that doing so
  160622. ** does not interfere with the "capture" process below. */
  160623. if( pState==0 ){
  160624. p->eStage = 0;
  160625. if( p->rc==SQLITE_OK ){
  160626. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  160627. }
  160628. }
  160629. /* Assuming no error has occurred, run a "restart" checkpoint with the
  160630. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  160631. ** special behaviour in the rbu VFS:
  160632. **
  160633. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  160634. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  160635. ** proceed with running a passive checkpoint instead of failing).
  160636. **
  160637. ** * Attempts to read from the *-wal file or write to the database file
  160638. ** do not perform any IO. Instead, the frame/page combinations that
  160639. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  160640. ** array.
  160641. **
  160642. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  160643. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  160644. ** no-ops. These locks will not be released until the connection
  160645. ** is closed.
  160646. **
  160647. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  160648. ** error.
  160649. **
  160650. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  160651. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  160652. ** array populated with a set of (frame -> page) mappings. Because the
  160653. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  160654. ** data from the wal file into the database file according to the
  160655. ** contents of aFrame[].
  160656. */
  160657. if( p->rc==SQLITE_OK ){
  160658. int rc2;
  160659. p->eStage = RBU_STAGE_CAPTURE;
  160660. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  160661. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  160662. }
  160663. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  160664. p->eStage = RBU_STAGE_CKPT;
  160665. p->nStep = (pState ? pState->nRow : 0);
  160666. p->aBuf = rbuMalloc(p, p->pgsz);
  160667. p->iWalCksum = rbuShmChecksum(p);
  160668. }
  160669. if( p->rc==SQLITE_OK ){
  160670. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  160671. p->rc = SQLITE_DONE;
  160672. p->eStage = RBU_STAGE_DONE;
  160673. }else{
  160674. int nSectorSize;
  160675. sqlite3_file *pDb = p->pTargetFd->pReal;
  160676. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  160677. assert( p->nPagePerSector==0 );
  160678. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  160679. if( nSectorSize>p->pgsz ){
  160680. p->nPagePerSector = nSectorSize / p->pgsz;
  160681. }else{
  160682. p->nPagePerSector = 1;
  160683. }
  160684. /* Call xSync() on the wal file. This causes SQLite to sync the
  160685. ** directory in which the target database and the wal file reside, in
  160686. ** case it has not been synced since the rename() call in
  160687. ** rbuMoveOalFile(). */
  160688. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  160689. }
  160690. }
  160691. }
  160692. /*
  160693. ** Called when iAmt bytes are read from offset iOff of the wal file while
  160694. ** the rbu object is in capture mode. Record the frame number of the frame
  160695. ** being read in the aFrame[] array.
  160696. */
  160697. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  160698. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  160699. u32 iFrame;
  160700. if( pRbu->mLock!=mReq ){
  160701. pRbu->rc = SQLITE_BUSY;
  160702. return SQLITE_INTERNAL;
  160703. }
  160704. pRbu->pgsz = iAmt;
  160705. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  160706. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  160707. RbuFrame *aNew;
  160708. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  160709. if( aNew==0 ) return SQLITE_NOMEM;
  160710. pRbu->aFrame = aNew;
  160711. pRbu->nFrameAlloc = nNew;
  160712. }
  160713. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  160714. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  160715. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  160716. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  160717. pRbu->nFrame++;
  160718. return SQLITE_OK;
  160719. }
  160720. /*
  160721. ** Called when a page of data is written to offset iOff of the database
  160722. ** file while the rbu handle is in capture mode. Record the page number
  160723. ** of the page being written in the aFrame[] array.
  160724. */
  160725. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  160726. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  160727. return SQLITE_OK;
  160728. }
  160729. /*
  160730. ** This is called as part of an incremental checkpoint operation. Copy
  160731. ** a single frame of data from the wal file into the database file, as
  160732. ** indicated by the RbuFrame object.
  160733. */
  160734. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  160735. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  160736. sqlite3_file *pDb = p->pTargetFd->pReal;
  160737. i64 iOff;
  160738. assert( p->rc==SQLITE_OK );
  160739. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  160740. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  160741. if( p->rc ) return;
  160742. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  160743. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  160744. }
  160745. /*
  160746. ** Take an EXCLUSIVE lock on the database file.
  160747. */
  160748. static void rbuLockDatabase(sqlite3rbu *p){
  160749. sqlite3_file *pReal = p->pTargetFd->pReal;
  160750. assert( p->rc==SQLITE_OK );
  160751. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  160752. if( p->rc==SQLITE_OK ){
  160753. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  160754. }
  160755. }
  160756. #if defined(_WIN32_WCE)
  160757. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  160758. int nChar;
  160759. LPWSTR zWideFilename;
  160760. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  160761. if( nChar==0 ){
  160762. return 0;
  160763. }
  160764. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  160765. if( zWideFilename==0 ){
  160766. return 0;
  160767. }
  160768. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  160769. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  160770. nChar);
  160771. if( nChar==0 ){
  160772. sqlite3_free(zWideFilename);
  160773. zWideFilename = 0;
  160774. }
  160775. return zWideFilename;
  160776. }
  160777. #endif
  160778. /*
  160779. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  160780. ** on the database file. This proc moves the *-oal file to the *-wal path,
  160781. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  160782. ** If an error occurs, leave an error code and error message in the rbu
  160783. ** handle.
  160784. */
  160785. static void rbuMoveOalFile(sqlite3rbu *p){
  160786. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  160787. const char *zMove = zBase;
  160788. char *zOal;
  160789. char *zWal;
  160790. if( rbuIsVacuum(p) ){
  160791. zMove = sqlite3_db_filename(p->dbRbu, "main");
  160792. }
  160793. zOal = sqlite3_mprintf("%s-oal", zMove);
  160794. zWal = sqlite3_mprintf("%s-wal", zMove);
  160795. assert( p->eStage==RBU_STAGE_MOVE );
  160796. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  160797. if( zWal==0 || zOal==0 ){
  160798. p->rc = SQLITE_NOMEM;
  160799. }else{
  160800. /* Move the *-oal file to *-wal. At this point connection p->db is
  160801. ** holding a SHARED lock on the target database file (because it is
  160802. ** in WAL mode). So no other connection may be writing the db.
  160803. **
  160804. ** In order to ensure that there are no database readers, an EXCLUSIVE
  160805. ** lock is obtained here before the *-oal is moved to *-wal.
  160806. */
  160807. rbuLockDatabase(p);
  160808. if( p->rc==SQLITE_OK ){
  160809. rbuFileSuffix3(zBase, zWal);
  160810. rbuFileSuffix3(zBase, zOal);
  160811. /* Re-open the databases. */
  160812. rbuObjIterFinalize(&p->objiter);
  160813. sqlite3_close(p->dbRbu);
  160814. sqlite3_close(p->dbMain);
  160815. p->dbMain = 0;
  160816. p->dbRbu = 0;
  160817. #if defined(_WIN32_WCE)
  160818. {
  160819. LPWSTR zWideOal;
  160820. LPWSTR zWideWal;
  160821. zWideOal = rbuWinUtf8ToUnicode(zOal);
  160822. if( zWideOal ){
  160823. zWideWal = rbuWinUtf8ToUnicode(zWal);
  160824. if( zWideWal ){
  160825. if( MoveFileW(zWideOal, zWideWal) ){
  160826. p->rc = SQLITE_OK;
  160827. }else{
  160828. p->rc = SQLITE_IOERR;
  160829. }
  160830. sqlite3_free(zWideWal);
  160831. }else{
  160832. p->rc = SQLITE_IOERR_NOMEM;
  160833. }
  160834. sqlite3_free(zWideOal);
  160835. }else{
  160836. p->rc = SQLITE_IOERR_NOMEM;
  160837. }
  160838. }
  160839. #else
  160840. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  160841. #endif
  160842. if( p->rc==SQLITE_OK ){
  160843. rbuOpenDatabase(p, 0);
  160844. rbuSetupCheckpoint(p, 0);
  160845. }
  160846. }
  160847. }
  160848. sqlite3_free(zWal);
  160849. sqlite3_free(zOal);
  160850. }
  160851. /*
  160852. ** The SELECT statement iterating through the keys for the current object
  160853. ** (p->objiter.pSelect) currently points to a valid row. This function
  160854. ** determines the type of operation requested by this row and returns
  160855. ** one of the following values to indicate the result:
  160856. **
  160857. ** * RBU_INSERT
  160858. ** * RBU_DELETE
  160859. ** * RBU_IDX_DELETE
  160860. ** * RBU_UPDATE
  160861. **
  160862. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  160863. ** point to the text value indicating the columns to update.
  160864. **
  160865. ** If the rbu_control field contains an invalid value, an error code and
  160866. ** message are left in the RBU handle and zero returned.
  160867. */
  160868. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  160869. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  160870. int res = 0; /* Return value */
  160871. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  160872. case SQLITE_INTEGER: {
  160873. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  160874. switch( iVal ){
  160875. case 0: res = RBU_INSERT; break;
  160876. case 1: res = RBU_DELETE; break;
  160877. case 2: res = RBU_REPLACE; break;
  160878. case 3: res = RBU_IDX_DELETE; break;
  160879. case 4: res = RBU_IDX_INSERT; break;
  160880. }
  160881. break;
  160882. }
  160883. case SQLITE_TEXT: {
  160884. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  160885. if( z==0 ){
  160886. p->rc = SQLITE_NOMEM;
  160887. }else{
  160888. *pzMask = (const char*)z;
  160889. }
  160890. res = RBU_UPDATE;
  160891. break;
  160892. }
  160893. default:
  160894. break;
  160895. }
  160896. if( res==0 ){
  160897. rbuBadControlError(p);
  160898. }
  160899. return res;
  160900. }
  160901. #ifdef SQLITE_DEBUG
  160902. /*
  160903. ** Assert that column iCol of statement pStmt is named zName.
  160904. */
  160905. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  160906. const char *zCol = sqlite3_column_name(pStmt, iCol);
  160907. assert( 0==sqlite3_stricmp(zName, zCol) );
  160908. }
  160909. #else
  160910. # define assertColumnName(x,y,z)
  160911. #endif
  160912. /*
  160913. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  160914. ** RBU_IDX_DELETE. This function performs the work of a single
  160915. ** sqlite3rbu_step() call for the type of operation specified by eType.
  160916. */
  160917. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  160918. RbuObjIter *pIter = &p->objiter;
  160919. sqlite3_value *pVal;
  160920. sqlite3_stmt *pWriter;
  160921. int i;
  160922. assert( p->rc==SQLITE_OK );
  160923. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  160924. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  160925. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  160926. );
  160927. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  160928. ** statement below does actually delete a row, nPhaseOneStep will be
  160929. ** incremented by the same amount when SQL function rbu_tmp_insert()
  160930. ** is invoked by the trigger. */
  160931. if( eType==RBU_DELETE ){
  160932. p->nPhaseOneStep -= p->objiter.nIndex;
  160933. }
  160934. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  160935. pWriter = pIter->pDelete;
  160936. }else{
  160937. pWriter = pIter->pInsert;
  160938. }
  160939. for(i=0; i<pIter->nCol; i++){
  160940. /* If this is an INSERT into a table b-tree and the table has an
  160941. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  160942. ** to write a NULL into the IPK column. That is not permitted. */
  160943. if( eType==RBU_INSERT
  160944. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  160945. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  160946. ){
  160947. p->rc = SQLITE_MISMATCH;
  160948. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  160949. return;
  160950. }
  160951. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  160952. continue;
  160953. }
  160954. pVal = sqlite3_column_value(pIter->pSelect, i);
  160955. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  160956. if( p->rc ) return;
  160957. }
  160958. if( pIter->zIdx==0 ){
  160959. if( pIter->eType==RBU_PK_VTAB
  160960. || pIter->eType==RBU_PK_NONE
  160961. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  160962. ){
  160963. /* For a virtual table, or a table with no primary key, the
  160964. ** SELECT statement is:
  160965. **
  160966. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  160967. **
  160968. ** Hence column_value(pIter->nCol+1).
  160969. */
  160970. assertColumnName(pIter->pSelect, pIter->nCol+1,
  160971. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  160972. );
  160973. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  160974. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  160975. }
  160976. }
  160977. if( p->rc==SQLITE_OK ){
  160978. sqlite3_step(pWriter);
  160979. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  160980. }
  160981. }
  160982. /*
  160983. ** This function does the work for an sqlite3rbu_step() call.
  160984. **
  160985. ** The object-iterator (p->objiter) currently points to a valid object,
  160986. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  160987. ** input row. Perform whatever processing is required and return.
  160988. **
  160989. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  160990. ** and message is left in the RBU handle and a copy of the error code
  160991. ** returned.
  160992. */
  160993. static int rbuStep(sqlite3rbu *p){
  160994. RbuObjIter *pIter = &p->objiter;
  160995. const char *zMask = 0;
  160996. int eType = rbuStepType(p, &zMask);
  160997. if( eType ){
  160998. assert( eType==RBU_INSERT || eType==RBU_DELETE
  160999. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  161000. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  161001. );
  161002. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  161003. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  161004. rbuBadControlError(p);
  161005. }
  161006. else if( eType==RBU_REPLACE ){
  161007. if( pIter->zIdx==0 ){
  161008. p->nPhaseOneStep += p->objiter.nIndex;
  161009. rbuStepOneOp(p, RBU_DELETE);
  161010. }
  161011. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  161012. }
  161013. else if( eType!=RBU_UPDATE ){
  161014. rbuStepOneOp(p, eType);
  161015. }
  161016. else{
  161017. sqlite3_value *pVal;
  161018. sqlite3_stmt *pUpdate = 0;
  161019. assert( eType==RBU_UPDATE );
  161020. p->nPhaseOneStep -= p->objiter.nIndex;
  161021. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  161022. if( pUpdate ){
  161023. int i;
  161024. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  161025. char c = zMask[pIter->aiSrcOrder[i]];
  161026. pVal = sqlite3_column_value(pIter->pSelect, i);
  161027. if( pIter->abTblPk[i] || c!='.' ){
  161028. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  161029. }
  161030. }
  161031. if( p->rc==SQLITE_OK
  161032. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  161033. ){
  161034. /* Bind the rbu_rowid value to column _rowid_ */
  161035. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  161036. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  161037. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  161038. }
  161039. if( p->rc==SQLITE_OK ){
  161040. sqlite3_step(pUpdate);
  161041. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  161042. }
  161043. }
  161044. }
  161045. }
  161046. return p->rc;
  161047. }
  161048. /*
  161049. ** Increment the schema cookie of the main database opened by p->dbMain.
  161050. **
  161051. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  161052. ** opened by p->dbMain to one more than the schema cookie of the main
  161053. ** db opened by p->dbRbu.
  161054. */
  161055. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  161056. if( p->rc==SQLITE_OK ){
  161057. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  161058. int iCookie = 1000000;
  161059. sqlite3_stmt *pStmt;
  161060. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  161061. "PRAGMA schema_version"
  161062. );
  161063. if( p->rc==SQLITE_OK ){
  161064. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  161065. ** is already a transaction open, so the prepared statement cannot
  161066. ** throw an SQLITE_SCHEMA exception. The only database page the
  161067. ** statement reads is page 1, which is guaranteed to be in the cache.
  161068. ** And no memory allocations are required. */
  161069. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161070. iCookie = sqlite3_column_int(pStmt, 0);
  161071. }
  161072. rbuFinalize(p, pStmt);
  161073. }
  161074. if( p->rc==SQLITE_OK ){
  161075. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  161076. }
  161077. }
  161078. }
  161079. /*
  161080. ** Update the contents of the rbu_state table within the rbu database. The
  161081. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  161082. ** are determined by inspecting the rbu handle passed as the first argument.
  161083. */
  161084. static void rbuSaveState(sqlite3rbu *p, int eStage){
  161085. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  161086. sqlite3_stmt *pInsert = 0;
  161087. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  161088. int rc;
  161089. assert( p->zErrmsg==0 );
  161090. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  161091. sqlite3_mprintf(
  161092. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  161093. "(%d, %d), "
  161094. "(%d, %Q), "
  161095. "(%d, %Q), "
  161096. "(%d, %d), "
  161097. "(%d, %d), "
  161098. "(%d, %lld), "
  161099. "(%d, %lld), "
  161100. "(%d, %lld), "
  161101. "(%d, %lld) ",
  161102. p->zStateDb,
  161103. RBU_STATE_STAGE, eStage,
  161104. RBU_STATE_TBL, p->objiter.zTbl,
  161105. RBU_STATE_IDX, p->objiter.zIdx,
  161106. RBU_STATE_ROW, p->nStep,
  161107. RBU_STATE_PROGRESS, p->nProgress,
  161108. RBU_STATE_CKPT, p->iWalCksum,
  161109. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  161110. RBU_STATE_OALSZ, p->iOalSz,
  161111. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
  161112. )
  161113. );
  161114. assert( pInsert==0 || rc==SQLITE_OK );
  161115. if( rc==SQLITE_OK ){
  161116. sqlite3_step(pInsert);
  161117. rc = sqlite3_finalize(pInsert);
  161118. }
  161119. if( rc!=SQLITE_OK ) p->rc = rc;
  161120. }
  161121. }
  161122. /*
  161123. ** The second argument passed to this function is the name of a PRAGMA
  161124. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  161125. ** This function executes the following on sqlite3rbu.dbRbu:
  161126. **
  161127. ** "PRAGMA main.$zPragma"
  161128. **
  161129. ** where $zPragma is the string passed as the second argument, then
  161130. ** on sqlite3rbu.dbMain:
  161131. **
  161132. ** "PRAGMA main.$zPragma = $val"
  161133. **
  161134. ** where $val is the value returned by the first PRAGMA invocation.
  161135. **
  161136. ** In short, it copies the value of the specified PRAGMA setting from
  161137. ** dbRbu to dbMain.
  161138. */
  161139. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  161140. if( p->rc==SQLITE_OK ){
  161141. sqlite3_stmt *pPragma = 0;
  161142. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  161143. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  161144. );
  161145. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  161146. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  161147. zPragma, sqlite3_column_int(pPragma, 0)
  161148. );
  161149. }
  161150. rbuFinalize(p, pPragma);
  161151. }
  161152. }
  161153. /*
  161154. ** The RBU handle passed as the only argument has just been opened and
  161155. ** the state database is empty. If this RBU handle was opened for an
  161156. ** RBU vacuum operation, create the schema in the target db.
  161157. */
  161158. static void rbuCreateTargetSchema(sqlite3rbu *p){
  161159. sqlite3_stmt *pSql = 0;
  161160. sqlite3_stmt *pInsert = 0;
  161161. assert( rbuIsVacuum(p) );
  161162. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  161163. if( p->rc==SQLITE_OK ){
  161164. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  161165. "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
  161166. " AND name!='sqlite_sequence' "
  161167. " ORDER BY type DESC"
  161168. );
  161169. }
  161170. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  161171. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  161172. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  161173. }
  161174. rbuFinalize(p, pSql);
  161175. if( p->rc!=SQLITE_OK ) return;
  161176. if( p->rc==SQLITE_OK ){
  161177. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  161178. "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
  161179. );
  161180. }
  161181. if( p->rc==SQLITE_OK ){
  161182. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  161183. "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
  161184. );
  161185. }
  161186. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  161187. int i;
  161188. for(i=0; i<5; i++){
  161189. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  161190. }
  161191. sqlite3_step(pInsert);
  161192. p->rc = sqlite3_reset(pInsert);
  161193. }
  161194. if( p->rc==SQLITE_OK ){
  161195. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  161196. }
  161197. rbuFinalize(p, pSql);
  161198. rbuFinalize(p, pInsert);
  161199. }
  161200. /*
  161201. ** Step the RBU object.
  161202. */
  161203. SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
  161204. if( p ){
  161205. switch( p->eStage ){
  161206. case RBU_STAGE_OAL: {
  161207. RbuObjIter *pIter = &p->objiter;
  161208. /* If this is an RBU vacuum operation and the state table was empty
  161209. ** when this handle was opened, create the target database schema. */
  161210. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  161211. rbuCreateTargetSchema(p);
  161212. rbuCopyPragma(p, "user_version");
  161213. rbuCopyPragma(p, "application_id");
  161214. }
  161215. while( p->rc==SQLITE_OK && pIter->zTbl ){
  161216. if( pIter->bCleanup ){
  161217. /* Clean up the rbu_tmp_xxx table for the previous table. It
  161218. ** cannot be dropped as there are currently active SQL statements.
  161219. ** But the contents can be deleted. */
  161220. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  161221. rbuMPrintfExec(p, p->dbRbu,
  161222. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  161223. );
  161224. }
  161225. }else{
  161226. rbuObjIterPrepareAll(p, pIter, 0);
  161227. /* Advance to the next row to process. */
  161228. if( p->rc==SQLITE_OK ){
  161229. int rc = sqlite3_step(pIter->pSelect);
  161230. if( rc==SQLITE_ROW ){
  161231. p->nProgress++;
  161232. p->nStep++;
  161233. return rbuStep(p);
  161234. }
  161235. p->rc = sqlite3_reset(pIter->pSelect);
  161236. p->nStep = 0;
  161237. }
  161238. }
  161239. rbuObjIterNext(p, pIter);
  161240. }
  161241. if( p->rc==SQLITE_OK ){
  161242. assert( pIter->zTbl==0 );
  161243. rbuSaveState(p, RBU_STAGE_MOVE);
  161244. rbuIncrSchemaCookie(p);
  161245. if( p->rc==SQLITE_OK ){
  161246. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  161247. }
  161248. if( p->rc==SQLITE_OK ){
  161249. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  161250. }
  161251. p->eStage = RBU_STAGE_MOVE;
  161252. }
  161253. break;
  161254. }
  161255. case RBU_STAGE_MOVE: {
  161256. if( p->rc==SQLITE_OK ){
  161257. rbuMoveOalFile(p);
  161258. p->nProgress++;
  161259. }
  161260. break;
  161261. }
  161262. case RBU_STAGE_CKPT: {
  161263. if( p->rc==SQLITE_OK ){
  161264. if( p->nStep>=p->nFrame ){
  161265. sqlite3_file *pDb = p->pTargetFd->pReal;
  161266. /* Sync the db file */
  161267. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  161268. /* Update nBackfill */
  161269. if( p->rc==SQLITE_OK ){
  161270. void volatile *ptr;
  161271. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  161272. if( p->rc==SQLITE_OK ){
  161273. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  161274. }
  161275. }
  161276. if( p->rc==SQLITE_OK ){
  161277. p->eStage = RBU_STAGE_DONE;
  161278. p->rc = SQLITE_DONE;
  161279. }
  161280. }else{
  161281. /* At one point the following block copied a single frame from the
  161282. ** wal file to the database file. So that one call to sqlite3rbu_step()
  161283. ** checkpointed a single frame.
  161284. **
  161285. ** However, if the sector-size is larger than the page-size, and the
  161286. ** application calls sqlite3rbu_savestate() or close() immediately
  161287. ** after this step, then rbu_step() again, then a power failure occurs,
  161288. ** then the database page written here may be damaged. Work around
  161289. ** this by checkpointing frames until the next page in the aFrame[]
  161290. ** lies on a different disk sector to the current one. */
  161291. u32 iSector;
  161292. do{
  161293. RbuFrame *pFrame = &p->aFrame[p->nStep];
  161294. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  161295. rbuCheckpointFrame(p, pFrame);
  161296. p->nStep++;
  161297. }while( p->nStep<p->nFrame
  161298. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  161299. && p->rc==SQLITE_OK
  161300. );
  161301. }
  161302. p->nProgress++;
  161303. }
  161304. break;
  161305. }
  161306. default:
  161307. break;
  161308. }
  161309. return p->rc;
  161310. }else{
  161311. return SQLITE_NOMEM;
  161312. }
  161313. }
  161314. /*
  161315. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  161316. ** otherwise. Either or both argument may be NULL. Two NULL values are
  161317. ** considered equal, and NULL is considered distinct from all other values.
  161318. */
  161319. static int rbuStrCompare(const char *z1, const char *z2){
  161320. if( z1==0 && z2==0 ) return 0;
  161321. if( z1==0 || z2==0 ) return 1;
  161322. return (sqlite3_stricmp(z1, z2)!=0);
  161323. }
  161324. /*
  161325. ** This function is called as part of sqlite3rbu_open() when initializing
  161326. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  161327. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  161328. ** things so that the next call to sqlite3rbu_step() continues on from
  161329. ** where the previous rbu handle left off.
  161330. **
  161331. ** If an error occurs, an error code and error message are left in the
  161332. ** rbu handle passed as the first argument.
  161333. */
  161334. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  161335. assert( p->rc==SQLITE_OK );
  161336. if( pState->zTbl ){
  161337. RbuObjIter *pIter = &p->objiter;
  161338. int rc = SQLITE_OK;
  161339. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  161340. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  161341. || rbuStrCompare(pIter->zTbl, pState->zTbl)
  161342. )){
  161343. rc = rbuObjIterNext(p, pIter);
  161344. }
  161345. if( rc==SQLITE_OK && !pIter->zTbl ){
  161346. rc = SQLITE_ERROR;
  161347. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  161348. }
  161349. if( rc==SQLITE_OK ){
  161350. p->nStep = pState->nRow;
  161351. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  161352. }
  161353. p->rc = rc;
  161354. }
  161355. }
  161356. /*
  161357. ** If there is a "*-oal" file in the file-system corresponding to the
  161358. ** target database in the file-system, delete it. If an error occurs,
  161359. ** leave an error code and error message in the rbu handle.
  161360. */
  161361. static void rbuDeleteOalFile(sqlite3rbu *p){
  161362. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  161363. if( zOal ){
  161364. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  161365. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  161366. pVfs->xDelete(pVfs, zOal, 0);
  161367. sqlite3_free(zOal);
  161368. }
  161369. }
  161370. /*
  161371. ** Allocate a private rbu VFS for the rbu handle passed as the only
  161372. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  161373. ** specified a URI with a vfs=? option in place of a target database
  161374. ** file name.
  161375. */
  161376. static void rbuCreateVfs(sqlite3rbu *p){
  161377. int rnd;
  161378. char zRnd[64];
  161379. assert( p->rc==SQLITE_OK );
  161380. sqlite3_randomness(sizeof(int), (void*)&rnd);
  161381. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  161382. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  161383. if( p->rc==SQLITE_OK ){
  161384. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  161385. assert( pVfs );
  161386. p->zVfsName = pVfs->zName;
  161387. }
  161388. }
  161389. /*
  161390. ** Destroy the private VFS created for the rbu handle passed as the only
  161391. ** argument by an earlier call to rbuCreateVfs().
  161392. */
  161393. static void rbuDeleteVfs(sqlite3rbu *p){
  161394. if( p->zVfsName ){
  161395. sqlite3rbu_destroy_vfs(p->zVfsName);
  161396. p->zVfsName = 0;
  161397. }
  161398. }
  161399. /*
  161400. ** This user-defined SQL function is invoked with a single argument - the
  161401. ** name of a table expected to appear in the target database. It returns
  161402. ** the number of auxilliary indexes on the table.
  161403. */
  161404. static void rbuIndexCntFunc(
  161405. sqlite3_context *pCtx,
  161406. int nVal,
  161407. sqlite3_value **apVal
  161408. ){
  161409. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  161410. sqlite3_stmt *pStmt = 0;
  161411. char *zErrmsg = 0;
  161412. int rc;
  161413. assert( nVal==1 );
  161414. rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
  161415. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  161416. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  161417. );
  161418. if( rc!=SQLITE_OK ){
  161419. sqlite3_result_error(pCtx, zErrmsg, -1);
  161420. }else{
  161421. int nIndex = 0;
  161422. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161423. nIndex = sqlite3_column_int(pStmt, 0);
  161424. }
  161425. rc = sqlite3_finalize(pStmt);
  161426. if( rc==SQLITE_OK ){
  161427. sqlite3_result_int(pCtx, nIndex);
  161428. }else{
  161429. sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
  161430. }
  161431. }
  161432. sqlite3_free(zErrmsg);
  161433. }
  161434. /*
  161435. ** If the RBU database contains the rbu_count table, use it to initialize
  161436. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  161437. ** is assumed to contain the same columns as:
  161438. **
  161439. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  161440. **
  161441. ** There should be one row in the table for each data_xxx table in the
  161442. ** database. The 'tbl' column should contain the name of a data_xxx table,
  161443. ** and the cnt column the number of rows it contains.
  161444. **
  161445. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  161446. ** for all rows in the rbu_count table, where nIndex is the number of
  161447. ** indexes on the corresponding target database table.
  161448. */
  161449. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  161450. if( p->rc==SQLITE_OK ){
  161451. sqlite3_stmt *pStmt = 0;
  161452. int bExists = 0; /* True if rbu_count exists */
  161453. p->nPhaseOneStep = -1;
  161454. p->rc = sqlite3_create_function(p->dbRbu,
  161455. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  161456. );
  161457. /* Check for the rbu_count table. If it does not exist, or if an error
  161458. ** occurs, nPhaseOneStep will be left set to -1. */
  161459. if( p->rc==SQLITE_OK ){
  161460. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  161461. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  161462. );
  161463. }
  161464. if( p->rc==SQLITE_OK ){
  161465. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161466. bExists = 1;
  161467. }
  161468. p->rc = sqlite3_finalize(pStmt);
  161469. }
  161470. if( p->rc==SQLITE_OK && bExists ){
  161471. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  161472. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  161473. "FROM rbu_count"
  161474. );
  161475. if( p->rc==SQLITE_OK ){
  161476. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161477. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  161478. }
  161479. p->rc = sqlite3_finalize(pStmt);
  161480. }
  161481. }
  161482. }
  161483. }
  161484. static sqlite3rbu *openRbuHandle(
  161485. const char *zTarget,
  161486. const char *zRbu,
  161487. const char *zState
  161488. ){
  161489. sqlite3rbu *p;
  161490. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  161491. size_t nRbu = strlen(zRbu);
  161492. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  161493. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  161494. if( p ){
  161495. RbuState *pState = 0;
  161496. /* Create the custom VFS. */
  161497. memset(p, 0, sizeof(sqlite3rbu));
  161498. rbuCreateVfs(p);
  161499. /* Open the target, RBU and state databases */
  161500. if( p->rc==SQLITE_OK ){
  161501. char *pCsr = (char*)&p[1];
  161502. int bRetry = 0;
  161503. if( zTarget ){
  161504. p->zTarget = pCsr;
  161505. memcpy(p->zTarget, zTarget, nTarget+1);
  161506. pCsr += nTarget+1;
  161507. }
  161508. p->zRbu = pCsr;
  161509. memcpy(p->zRbu, zRbu, nRbu+1);
  161510. pCsr += nRbu+1;
  161511. if( zState ){
  161512. p->zState = rbuMPrintf(p, "%s", zState);
  161513. }
  161514. /* If the first attempt to open the database file fails and the bRetry
  161515. ** flag it set, this means that the db was not opened because it seemed
  161516. ** to be a wal-mode db. But, this may have happened due to an earlier
  161517. ** RBU vacuum operation leaving an old wal file in the directory.
  161518. ** If this is the case, it will have been checkpointed and deleted
  161519. ** when the handle was closed and a second attempt to open the
  161520. ** database may succeed. */
  161521. rbuOpenDatabase(p, &bRetry);
  161522. if( bRetry ){
  161523. rbuOpenDatabase(p, 0);
  161524. }
  161525. }
  161526. if( p->rc==SQLITE_OK ){
  161527. pState = rbuLoadState(p);
  161528. assert( pState || p->rc!=SQLITE_OK );
  161529. if( p->rc==SQLITE_OK ){
  161530. if( pState->eStage==0 ){
  161531. rbuDeleteOalFile(p);
  161532. rbuInitPhaseOneSteps(p);
  161533. p->eStage = RBU_STAGE_OAL;
  161534. }else{
  161535. p->eStage = pState->eStage;
  161536. p->nPhaseOneStep = pState->nPhaseOneStep;
  161537. }
  161538. p->nProgress = pState->nProgress;
  161539. p->iOalSz = pState->iOalSz;
  161540. }
  161541. }
  161542. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  161543. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  161544. if( p->eStage==RBU_STAGE_OAL ){
  161545. p->rc = SQLITE_ERROR;
  161546. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  161547. }else if( p->eStage==RBU_STAGE_MOVE ){
  161548. p->eStage = RBU_STAGE_CKPT;
  161549. p->nStep = 0;
  161550. }
  161551. }
  161552. if( p->rc==SQLITE_OK
  161553. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  161554. && pState->eStage!=0
  161555. ){
  161556. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  161557. if( pFd->iCookie!=pState->iCookie ){
  161558. /* At this point (pTargetFd->iCookie) contains the value of the
  161559. ** change-counter cookie (the thing that gets incremented when a
  161560. ** transaction is committed in rollback mode) currently stored on
  161561. ** page 1 of the database file. */
  161562. p->rc = SQLITE_BUSY;
  161563. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  161564. (rbuIsVacuum(p) ? "vacuum" : "update")
  161565. );
  161566. }
  161567. }
  161568. if( p->rc==SQLITE_OK ){
  161569. if( p->eStage==RBU_STAGE_OAL ){
  161570. sqlite3 *db = p->dbMain;
  161571. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  161572. /* Point the object iterator at the first object */
  161573. if( p->rc==SQLITE_OK ){
  161574. p->rc = rbuObjIterFirst(p, &p->objiter);
  161575. }
  161576. /* If the RBU database contains no data_xxx tables, declare the RBU
  161577. ** update finished. */
  161578. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  161579. p->rc = SQLITE_DONE;
  161580. p->eStage = RBU_STAGE_DONE;
  161581. }else{
  161582. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  161583. rbuCopyPragma(p, "page_size");
  161584. rbuCopyPragma(p, "auto_vacuum");
  161585. }
  161586. /* Open transactions both databases. The *-oal file is opened or
  161587. ** created at this point. */
  161588. if( p->rc==SQLITE_OK ){
  161589. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  161590. }
  161591. /* Check if the main database is a zipvfs db. If it is, set the upper
  161592. ** level pager to use "journal_mode=off". This prevents it from
  161593. ** generating a large journal using a temp file. */
  161594. if( p->rc==SQLITE_OK ){
  161595. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  161596. if( frc==SQLITE_OK ){
  161597. p->rc = sqlite3_exec(
  161598. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  161599. }
  161600. }
  161601. if( p->rc==SQLITE_OK ){
  161602. rbuSetupOal(p, pState);
  161603. }
  161604. }
  161605. }else if( p->eStage==RBU_STAGE_MOVE ){
  161606. /* no-op */
  161607. }else if( p->eStage==RBU_STAGE_CKPT ){
  161608. rbuSetupCheckpoint(p, pState);
  161609. }else if( p->eStage==RBU_STAGE_DONE ){
  161610. p->rc = SQLITE_DONE;
  161611. }else{
  161612. p->rc = SQLITE_CORRUPT;
  161613. }
  161614. }
  161615. rbuFreeState(pState);
  161616. }
  161617. return p;
  161618. }
  161619. /*
  161620. ** Allocate and return an RBU handle with all fields zeroed except for the
  161621. ** error code, which is set to SQLITE_MISUSE.
  161622. */
  161623. static sqlite3rbu *rbuMisuseError(void){
  161624. sqlite3rbu *pRet;
  161625. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  161626. if( pRet ){
  161627. memset(pRet, 0, sizeof(sqlite3rbu));
  161628. pRet->rc = SQLITE_MISUSE;
  161629. }
  161630. return pRet;
  161631. }
  161632. /*
  161633. ** Open and return a new RBU handle.
  161634. */
  161635. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  161636. const char *zTarget,
  161637. const char *zRbu,
  161638. const char *zState
  161639. ){
  161640. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  161641. /* TODO: Check that zTarget and zRbu are non-NULL */
  161642. return openRbuHandle(zTarget, zRbu, zState);
  161643. }
  161644. /*
  161645. ** Open a handle to begin or resume an RBU VACUUM operation.
  161646. */
  161647. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  161648. const char *zTarget,
  161649. const char *zState
  161650. ){
  161651. if( zTarget==0 ){ return rbuMisuseError(); }
  161652. /* TODO: Check that both arguments are non-NULL */
  161653. return openRbuHandle(0, zTarget, zState);
  161654. }
  161655. /*
  161656. ** Return the database handle used by pRbu.
  161657. */
  161658. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  161659. sqlite3 *db = 0;
  161660. if( pRbu ){
  161661. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  161662. }
  161663. return db;
  161664. }
  161665. /*
  161666. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  161667. ** then edit any error message string so as to remove all occurrences of
  161668. ** the pattern "rbu_imp_[0-9]*".
  161669. */
  161670. static void rbuEditErrmsg(sqlite3rbu *p){
  161671. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  161672. unsigned int i;
  161673. size_t nErrmsg = strlen(p->zErrmsg);
  161674. for(i=0; i<(nErrmsg-8); i++){
  161675. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  161676. int nDel = 8;
  161677. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  161678. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  161679. nErrmsg -= nDel;
  161680. }
  161681. }
  161682. }
  161683. }
  161684. /*
  161685. ** Close the RBU handle.
  161686. */
  161687. SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  161688. int rc;
  161689. if( p ){
  161690. /* Commit the transaction to the *-oal file. */
  161691. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  161692. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  161693. }
  161694. /* Sync the db file if currently doing an incremental checkpoint */
  161695. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  161696. sqlite3_file *pDb = p->pTargetFd->pReal;
  161697. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  161698. }
  161699. rbuSaveState(p, p->eStage);
  161700. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  161701. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  161702. }
  161703. /* Close any open statement handles. */
  161704. rbuObjIterFinalize(&p->objiter);
  161705. /* If this is an RBU vacuum handle and the vacuum has either finished
  161706. ** successfully or encountered an error, delete the contents of the
  161707. ** state table. This causes the next call to sqlite3rbu_vacuum()
  161708. ** specifying the current target and state databases to start a new
  161709. ** vacuum from scratch. */
  161710. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  161711. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  161712. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  161713. }
  161714. /* Close the open database handle and VFS object. */
  161715. sqlite3_close(p->dbRbu);
  161716. sqlite3_close(p->dbMain);
  161717. rbuDeleteVfs(p);
  161718. sqlite3_free(p->aBuf);
  161719. sqlite3_free(p->aFrame);
  161720. rbuEditErrmsg(p);
  161721. rc = p->rc;
  161722. *pzErrmsg = p->zErrmsg;
  161723. sqlite3_free(p->zState);
  161724. sqlite3_free(p);
  161725. }else{
  161726. rc = SQLITE_NOMEM;
  161727. *pzErrmsg = 0;
  161728. }
  161729. return rc;
  161730. }
  161731. /*
  161732. ** Return the total number of key-value operations (inserts, deletes or
  161733. ** updates) that have been performed on the target database since the
  161734. ** current RBU update was started.
  161735. */
  161736. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  161737. return pRbu->nProgress;
  161738. }
  161739. /*
  161740. ** Return permyriadage progress indications for the two main stages of
  161741. ** an RBU update.
  161742. */
  161743. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  161744. const int MAX_PROGRESS = 10000;
  161745. switch( p->eStage ){
  161746. case RBU_STAGE_OAL:
  161747. if( p->nPhaseOneStep>0 ){
  161748. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  161749. }else{
  161750. *pnOne = -1;
  161751. }
  161752. *pnTwo = 0;
  161753. break;
  161754. case RBU_STAGE_MOVE:
  161755. *pnOne = MAX_PROGRESS;
  161756. *pnTwo = 0;
  161757. break;
  161758. case RBU_STAGE_CKPT:
  161759. *pnOne = MAX_PROGRESS;
  161760. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  161761. break;
  161762. case RBU_STAGE_DONE:
  161763. *pnOne = MAX_PROGRESS;
  161764. *pnTwo = MAX_PROGRESS;
  161765. break;
  161766. default:
  161767. assert( 0 );
  161768. }
  161769. }
  161770. /*
  161771. ** Return the current state of the RBU vacuum or update operation.
  161772. */
  161773. SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
  161774. int aRes[] = {
  161775. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  161776. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  161777. };
  161778. assert( RBU_STAGE_OAL==1 );
  161779. assert( RBU_STAGE_MOVE==2 );
  161780. assert( RBU_STAGE_CKPT==4 );
  161781. assert( RBU_STAGE_DONE==5 );
  161782. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  161783. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  161784. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  161785. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  161786. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  161787. return SQLITE_RBU_STATE_ERROR;
  161788. }else{
  161789. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  161790. assert( p->eStage==RBU_STAGE_OAL
  161791. || p->eStage==RBU_STAGE_MOVE
  161792. || p->eStage==RBU_STAGE_CKPT
  161793. || p->eStage==RBU_STAGE_DONE
  161794. );
  161795. return aRes[p->eStage];
  161796. }
  161797. }
  161798. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
  161799. int rc = p->rc;
  161800. if( rc==SQLITE_DONE ) return SQLITE_OK;
  161801. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  161802. if( p->eStage==RBU_STAGE_OAL ){
  161803. assert( rc!=SQLITE_DONE );
  161804. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  161805. }
  161806. /* Sync the db file */
  161807. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  161808. sqlite3_file *pDb = p->pTargetFd->pReal;
  161809. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  161810. }
  161811. p->rc = rc;
  161812. rbuSaveState(p, p->eStage);
  161813. rc = p->rc;
  161814. if( p->eStage==RBU_STAGE_OAL ){
  161815. assert( rc!=SQLITE_DONE );
  161816. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  161817. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
  161818. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  161819. }
  161820. p->rc = rc;
  161821. return rc;
  161822. }
  161823. /**************************************************************************
  161824. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  161825. ** of a standard VFS in the following ways:
  161826. **
  161827. ** 1. Whenever the first page of a main database file is read or
  161828. ** written, the value of the change-counter cookie is stored in
  161829. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  161830. ** database header field is stored in rbu_file.iWriteVer. This ensures
  161831. ** that the values are always trustworthy within an open transaction.
  161832. **
  161833. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  161834. ** member variable of the associated database file descriptor is set
  161835. ** to point to the new file. A mutex protected linked list of all main
  161836. ** db fds opened using a particular RBU VFS is maintained at
  161837. ** rbu_vfs.pMain to facilitate this.
  161838. **
  161839. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  161840. ** object can be marked as the target database of an RBU update. This
  161841. ** turns on the following extra special behaviour:
  161842. **
  161843. ** 3a. If xAccess() is called to check if there exists a *-wal file
  161844. ** associated with an RBU target database currently in RBU_STAGE_OAL
  161845. ** stage (preparing the *-oal file), the following special handling
  161846. ** applies:
  161847. **
  161848. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  161849. ** target database may not be in wal mode already.
  161850. **
  161851. ** * if the *-wal file does not exist, set the output parameter to
  161852. ** non-zero (to tell SQLite that it does exist) anyway.
  161853. **
  161854. ** Then, when xOpen() is called to open the *-wal file associated with
  161855. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  161856. ** file, the rbu vfs opens the corresponding *-oal file instead.
  161857. **
  161858. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  161859. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  161860. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  161861. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  161862. ** because assert() statements in some VFS implementations fail if
  161863. ** xShmLock() is called before xShmMap().
  161864. **
  161865. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  161866. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  161867. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  161868. ** from automatically checkpointing a *-wal (or *-oal) file from within
  161869. ** sqlite3_close().
  161870. **
  161871. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  161872. ** all xWrite() calls on the target database file perform no IO.
  161873. ** Instead the frame and page numbers that would be read and written
  161874. ** are recorded. Additionally, successful attempts to obtain exclusive
  161875. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  161876. ** database file are recorded. xShmLock() calls to unlock the same
  161877. ** locks are no-ops (so that once obtained, these locks are never
  161878. ** relinquished). Finally, calls to xSync() on the target database
  161879. ** file fail with SQLITE_INTERNAL errors.
  161880. */
  161881. static void rbuUnlockShm(rbu_file *p){
  161882. if( p->pRbu ){
  161883. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  161884. int i;
  161885. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  161886. if( (1<<i) & p->pRbu->mLock ){
  161887. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  161888. }
  161889. }
  161890. p->pRbu->mLock = 0;
  161891. }
  161892. }
  161893. /*
  161894. ** Close an rbu file.
  161895. */
  161896. static int rbuVfsClose(sqlite3_file *pFile){
  161897. rbu_file *p = (rbu_file*)pFile;
  161898. int rc;
  161899. int i;
  161900. /* Free the contents of the apShm[] array. And the array itself. */
  161901. for(i=0; i<p->nShm; i++){
  161902. sqlite3_free(p->apShm[i]);
  161903. }
  161904. sqlite3_free(p->apShm);
  161905. p->apShm = 0;
  161906. sqlite3_free(p->zDel);
  161907. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  161908. rbu_file **pp;
  161909. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  161910. for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
  161911. *pp = p->pMainNext;
  161912. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  161913. rbuUnlockShm(p);
  161914. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  161915. }
  161916. /* Close the underlying file handle */
  161917. rc = p->pReal->pMethods->xClose(p->pReal);
  161918. return rc;
  161919. }
  161920. /*
  161921. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  161922. ** passed as the only argument.
  161923. */
  161924. static u32 rbuGetU32(u8 *aBuf){
  161925. return ((u32)aBuf[0] << 24)
  161926. + ((u32)aBuf[1] << 16)
  161927. + ((u32)aBuf[2] << 8)
  161928. + ((u32)aBuf[3]);
  161929. }
  161930. /*
  161931. ** Write an unsigned 32-bit value in big-endian format to the supplied
  161932. ** buffer.
  161933. */
  161934. static void rbuPutU32(u8 *aBuf, u32 iVal){
  161935. aBuf[0] = (iVal >> 24) & 0xFF;
  161936. aBuf[1] = (iVal >> 16) & 0xFF;
  161937. aBuf[2] = (iVal >> 8) & 0xFF;
  161938. aBuf[3] = (iVal >> 0) & 0xFF;
  161939. }
  161940. static void rbuPutU16(u8 *aBuf, u16 iVal){
  161941. aBuf[0] = (iVal >> 8) & 0xFF;
  161942. aBuf[1] = (iVal >> 0) & 0xFF;
  161943. }
  161944. /*
  161945. ** Read data from an rbuVfs-file.
  161946. */
  161947. static int rbuVfsRead(
  161948. sqlite3_file *pFile,
  161949. void *zBuf,
  161950. int iAmt,
  161951. sqlite_int64 iOfst
  161952. ){
  161953. rbu_file *p = (rbu_file*)pFile;
  161954. sqlite3rbu *pRbu = p->pRbu;
  161955. int rc;
  161956. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  161957. assert( p->openFlags & SQLITE_OPEN_WAL );
  161958. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  161959. }else{
  161960. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  161961. && (p->openFlags & SQLITE_OPEN_WAL)
  161962. && iOfst>=pRbu->iOalSz
  161963. ){
  161964. rc = SQLITE_OK;
  161965. memset(zBuf, 0, iAmt);
  161966. }else{
  161967. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  161968. #if 1
  161969. /* If this is being called to read the first page of the target
  161970. ** database as part of an rbu vacuum operation, synthesize the
  161971. ** contents of the first page if it does not yet exist. Otherwise,
  161972. ** SQLite will not check for a *-wal file. */
  161973. if( pRbu && rbuIsVacuum(pRbu)
  161974. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  161975. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  161976. && pRbu->rc==SQLITE_OK
  161977. ){
  161978. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  161979. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  161980. if( rc==SQLITE_OK ){
  161981. u8 *aBuf = (u8*)zBuf;
  161982. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  161983. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  161984. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  161985. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  161986. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  161987. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  161988. if( iAmt>100 ){
  161989. memset(&aBuf[100], 0, iAmt-100);
  161990. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  161991. aBuf[100] = 0x0D;
  161992. }
  161993. }
  161994. }
  161995. #endif
  161996. }
  161997. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  161998. /* These look like magic numbers. But they are stable, as they are part
  161999. ** of the definition of the SQLite file format, which may not change. */
  162000. u8 *pBuf = (u8*)zBuf;
  162001. p->iCookie = rbuGetU32(&pBuf[24]);
  162002. p->iWriteVer = pBuf[19];
  162003. }
  162004. }
  162005. return rc;
  162006. }
  162007. /*
  162008. ** Write data to an rbuVfs-file.
  162009. */
  162010. static int rbuVfsWrite(
  162011. sqlite3_file *pFile,
  162012. const void *zBuf,
  162013. int iAmt,
  162014. sqlite_int64 iOfst
  162015. ){
  162016. rbu_file *p = (rbu_file*)pFile;
  162017. sqlite3rbu *pRbu = p->pRbu;
  162018. int rc;
  162019. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  162020. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  162021. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  162022. }else{
  162023. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  162024. && (p->openFlags & SQLITE_OPEN_WAL)
  162025. && iOfst>=pRbu->iOalSz
  162026. ){
  162027. pRbu->iOalSz = iAmt + iOfst;
  162028. }
  162029. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  162030. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  162031. /* These look like magic numbers. But they are stable, as they are part
  162032. ** of the definition of the SQLite file format, which may not change. */
  162033. u8 *pBuf = (u8*)zBuf;
  162034. p->iCookie = rbuGetU32(&pBuf[24]);
  162035. p->iWriteVer = pBuf[19];
  162036. }
  162037. }
  162038. return rc;
  162039. }
  162040. /*
  162041. ** Truncate an rbuVfs-file.
  162042. */
  162043. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  162044. rbu_file *p = (rbu_file*)pFile;
  162045. return p->pReal->pMethods->xTruncate(p->pReal, size);
  162046. }
  162047. /*
  162048. ** Sync an rbuVfs-file.
  162049. */
  162050. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  162051. rbu_file *p = (rbu_file *)pFile;
  162052. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  162053. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  162054. return SQLITE_INTERNAL;
  162055. }
  162056. return SQLITE_OK;
  162057. }
  162058. return p->pReal->pMethods->xSync(p->pReal, flags);
  162059. }
  162060. /*
  162061. ** Return the current file-size of an rbuVfs-file.
  162062. */
  162063. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  162064. rbu_file *p = (rbu_file *)pFile;
  162065. int rc;
  162066. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  162067. /* If this is an RBU vacuum operation and this is the target database,
  162068. ** pretend that it has at least one page. Otherwise, SQLite will not
  162069. ** check for the existance of a *-wal file. rbuVfsRead() contains
  162070. ** similar logic. */
  162071. if( rc==SQLITE_OK && *pSize==0
  162072. && p->pRbu && rbuIsVacuum(p->pRbu)
  162073. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  162074. ){
  162075. *pSize = 1024;
  162076. }
  162077. return rc;
  162078. }
  162079. /*
  162080. ** Lock an rbuVfs-file.
  162081. */
  162082. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  162083. rbu_file *p = (rbu_file*)pFile;
  162084. sqlite3rbu *pRbu = p->pRbu;
  162085. int rc = SQLITE_OK;
  162086. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  162087. if( eLock==SQLITE_LOCK_EXCLUSIVE
  162088. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  162089. ){
  162090. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  162091. ** prevents it from checkpointing the database from sqlite3_close(). */
  162092. rc = SQLITE_BUSY;
  162093. }else{
  162094. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  162095. }
  162096. return rc;
  162097. }
  162098. /*
  162099. ** Unlock an rbuVfs-file.
  162100. */
  162101. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  162102. rbu_file *p = (rbu_file *)pFile;
  162103. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  162104. }
  162105. /*
  162106. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  162107. */
  162108. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  162109. rbu_file *p = (rbu_file *)pFile;
  162110. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  162111. }
  162112. /*
  162113. ** File control method. For custom operations on an rbuVfs-file.
  162114. */
  162115. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  162116. rbu_file *p = (rbu_file *)pFile;
  162117. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  162118. int rc;
  162119. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  162120. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  162121. );
  162122. if( op==SQLITE_FCNTL_RBU ){
  162123. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  162124. /* First try to find another RBU vfs lower down in the vfs stack. If
  162125. ** one is found, this vfs will operate in pass-through mode. The lower
  162126. ** level vfs will do the special RBU handling. */
  162127. rc = xControl(p->pReal, op, pArg);
  162128. if( rc==SQLITE_NOTFOUND ){
  162129. /* Now search for a zipvfs instance lower down in the VFS stack. If
  162130. ** one is found, this is an error. */
  162131. void *dummy = 0;
  162132. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  162133. if( rc==SQLITE_OK ){
  162134. rc = SQLITE_ERROR;
  162135. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  162136. }else if( rc==SQLITE_NOTFOUND ){
  162137. pRbu->pTargetFd = p;
  162138. p->pRbu = pRbu;
  162139. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  162140. rc = SQLITE_OK;
  162141. }
  162142. }
  162143. return rc;
  162144. }
  162145. else if( op==SQLITE_FCNTL_RBUCNT ){
  162146. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  162147. pRbu->nRbu++;
  162148. pRbu->pRbuFd = p;
  162149. p->bNolock = 1;
  162150. }
  162151. rc = xControl(p->pReal, op, pArg);
  162152. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  162153. rbu_vfs *pRbuVfs = p->pRbuVfs;
  162154. char *zIn = *(char**)pArg;
  162155. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  162156. *(char**)pArg = zOut;
  162157. if( zOut==0 ) rc = SQLITE_NOMEM;
  162158. }
  162159. return rc;
  162160. }
  162161. /*
  162162. ** Return the sector-size in bytes for an rbuVfs-file.
  162163. */
  162164. static int rbuVfsSectorSize(sqlite3_file *pFile){
  162165. rbu_file *p = (rbu_file *)pFile;
  162166. return p->pReal->pMethods->xSectorSize(p->pReal);
  162167. }
  162168. /*
  162169. ** Return the device characteristic flags supported by an rbuVfs-file.
  162170. */
  162171. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  162172. rbu_file *p = (rbu_file *)pFile;
  162173. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  162174. }
  162175. /*
  162176. ** Take or release a shared-memory lock.
  162177. */
  162178. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  162179. rbu_file *p = (rbu_file*)pFile;
  162180. sqlite3rbu *pRbu = p->pRbu;
  162181. int rc = SQLITE_OK;
  162182. #ifdef SQLITE_AMALGAMATION
  162183. assert( WAL_CKPT_LOCK==1 );
  162184. #endif
  162185. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  162186. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  162187. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  162188. ** taking this lock also prevents any checkpoints from occurring.
  162189. ** todo: really, it's not clear why this might occur, as
  162190. ** wal_autocheckpoint ought to be turned off. */
  162191. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  162192. }else{
  162193. int bCapture = 0;
  162194. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  162195. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  162196. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  162197. ){
  162198. bCapture = 1;
  162199. }
  162200. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  162201. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  162202. if( bCapture && rc==SQLITE_OK ){
  162203. pRbu->mLock |= (1 << ofst);
  162204. }
  162205. }
  162206. }
  162207. return rc;
  162208. }
  162209. /*
  162210. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  162211. */
  162212. static int rbuVfsShmMap(
  162213. sqlite3_file *pFile,
  162214. int iRegion,
  162215. int szRegion,
  162216. int isWrite,
  162217. void volatile **pp
  162218. ){
  162219. rbu_file *p = (rbu_file*)pFile;
  162220. int rc = SQLITE_OK;
  162221. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  162222. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  162223. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  162224. ** instead of a file on disk. */
  162225. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  162226. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  162227. if( iRegion<=p->nShm ){
  162228. int nByte = (iRegion+1) * sizeof(char*);
  162229. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  162230. if( apNew==0 ){
  162231. rc = SQLITE_NOMEM;
  162232. }else{
  162233. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  162234. p->apShm = apNew;
  162235. p->nShm = iRegion+1;
  162236. }
  162237. }
  162238. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  162239. char *pNew = (char*)sqlite3_malloc64(szRegion);
  162240. if( pNew==0 ){
  162241. rc = SQLITE_NOMEM;
  162242. }else{
  162243. memset(pNew, 0, szRegion);
  162244. p->apShm[iRegion] = pNew;
  162245. }
  162246. }
  162247. if( rc==SQLITE_OK ){
  162248. *pp = p->apShm[iRegion];
  162249. }else{
  162250. *pp = 0;
  162251. }
  162252. }else{
  162253. assert( p->apShm==0 );
  162254. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  162255. }
  162256. return rc;
  162257. }
  162258. /*
  162259. ** Memory barrier.
  162260. */
  162261. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  162262. rbu_file *p = (rbu_file *)pFile;
  162263. p->pReal->pMethods->xShmBarrier(p->pReal);
  162264. }
  162265. /*
  162266. ** The xShmUnmap method.
  162267. */
  162268. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  162269. rbu_file *p = (rbu_file*)pFile;
  162270. int rc = SQLITE_OK;
  162271. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  162272. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  162273. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  162274. /* no-op */
  162275. }else{
  162276. /* Release the checkpointer and writer locks */
  162277. rbuUnlockShm(p);
  162278. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  162279. }
  162280. return rc;
  162281. }
  162282. /*
  162283. ** Given that zWal points to a buffer containing a wal file name passed to
  162284. ** either the xOpen() or xAccess() VFS method, return a pointer to the
  162285. ** file-handle opened by the same database connection on the corresponding
  162286. ** database file.
  162287. */
  162288. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
  162289. rbu_file *pDb;
  162290. sqlite3_mutex_enter(pRbuVfs->mutex);
  162291. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  162292. sqlite3_mutex_leave(pRbuVfs->mutex);
  162293. return pDb;
  162294. }
  162295. /*
  162296. ** A main database named zName has just been opened. The following
  162297. ** function returns a pointer to a buffer owned by SQLite that contains
  162298. ** the name of the *-wal file this db connection will use. SQLite
  162299. ** happens to pass a pointer to this buffer when using xAccess()
  162300. ** or xOpen() to operate on the *-wal file.
  162301. */
  162302. static const char *rbuMainToWal(const char *zName, int flags){
  162303. int n = (int)strlen(zName);
  162304. const char *z = &zName[n];
  162305. if( flags & SQLITE_OPEN_URI ){
  162306. int odd = 0;
  162307. while( 1 ){
  162308. if( z[0]==0 ){
  162309. odd = 1 - odd;
  162310. if( odd && z[1]==0 ) break;
  162311. }
  162312. z++;
  162313. }
  162314. z += 2;
  162315. }else{
  162316. while( *z==0 ) z++;
  162317. }
  162318. z += (n + 8 + 1);
  162319. return z;
  162320. }
  162321. /*
  162322. ** Open an rbu file handle.
  162323. */
  162324. static int rbuVfsOpen(
  162325. sqlite3_vfs *pVfs,
  162326. const char *zName,
  162327. sqlite3_file *pFile,
  162328. int flags,
  162329. int *pOutFlags
  162330. ){
  162331. static sqlite3_io_methods rbuvfs_io_methods = {
  162332. 2, /* iVersion */
  162333. rbuVfsClose, /* xClose */
  162334. rbuVfsRead, /* xRead */
  162335. rbuVfsWrite, /* xWrite */
  162336. rbuVfsTruncate, /* xTruncate */
  162337. rbuVfsSync, /* xSync */
  162338. rbuVfsFileSize, /* xFileSize */
  162339. rbuVfsLock, /* xLock */
  162340. rbuVfsUnlock, /* xUnlock */
  162341. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  162342. rbuVfsFileControl, /* xFileControl */
  162343. rbuVfsSectorSize, /* xSectorSize */
  162344. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  162345. rbuVfsShmMap, /* xShmMap */
  162346. rbuVfsShmLock, /* xShmLock */
  162347. rbuVfsShmBarrier, /* xShmBarrier */
  162348. rbuVfsShmUnmap, /* xShmUnmap */
  162349. 0, 0 /* xFetch, xUnfetch */
  162350. };
  162351. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  162352. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  162353. rbu_file *pFd = (rbu_file *)pFile;
  162354. int rc = SQLITE_OK;
  162355. const char *zOpen = zName;
  162356. int oflags = flags;
  162357. memset(pFd, 0, sizeof(rbu_file));
  162358. pFd->pReal = (sqlite3_file*)&pFd[1];
  162359. pFd->pRbuVfs = pRbuVfs;
  162360. pFd->openFlags = flags;
  162361. if( zName ){
  162362. if( flags & SQLITE_OPEN_MAIN_DB ){
  162363. /* A main database has just been opened. The following block sets
  162364. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  162365. ** the name of the *-wal file this db connection will use. SQLite
  162366. ** happens to pass a pointer to this buffer when using xAccess()
  162367. ** or xOpen() to operate on the *-wal file. */
  162368. pFd->zWal = rbuMainToWal(zName, flags);
  162369. }
  162370. else if( flags & SQLITE_OPEN_WAL ){
  162371. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
  162372. if( pDb ){
  162373. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  162374. /* This call is to open a *-wal file. Intead, open the *-oal. This
  162375. ** code ensures that the string passed to xOpen() is terminated by a
  162376. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  162377. ** parameter from it. */
  162378. const char *zBase = zName;
  162379. size_t nCopy;
  162380. char *zCopy;
  162381. if( rbuIsVacuum(pDb->pRbu) ){
  162382. zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  162383. zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
  162384. }
  162385. nCopy = strlen(zBase);
  162386. zCopy = sqlite3_malloc64(nCopy+2);
  162387. if( zCopy ){
  162388. memcpy(zCopy, zBase, nCopy);
  162389. zCopy[nCopy-3] = 'o';
  162390. zCopy[nCopy] = '\0';
  162391. zCopy[nCopy+1] = '\0';
  162392. zOpen = (const char*)(pFd->zDel = zCopy);
  162393. }else{
  162394. rc = SQLITE_NOMEM;
  162395. }
  162396. pFd->pRbu = pDb->pRbu;
  162397. }
  162398. pDb->pWalFd = pFd;
  162399. }
  162400. }
  162401. }
  162402. if( oflags & SQLITE_OPEN_MAIN_DB
  162403. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  162404. ){
  162405. assert( oflags & SQLITE_OPEN_MAIN_DB );
  162406. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  162407. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  162408. zOpen = 0;
  162409. }
  162410. if( rc==SQLITE_OK ){
  162411. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  162412. }
  162413. if( pFd->pReal->pMethods ){
  162414. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  162415. ** pointer and, if the file is a main database file, link it into the
  162416. ** mutex protected linked list of all such files. */
  162417. pFile->pMethods = &rbuvfs_io_methods;
  162418. if( flags & SQLITE_OPEN_MAIN_DB ){
  162419. sqlite3_mutex_enter(pRbuVfs->mutex);
  162420. pFd->pMainNext = pRbuVfs->pMain;
  162421. pRbuVfs->pMain = pFd;
  162422. sqlite3_mutex_leave(pRbuVfs->mutex);
  162423. }
  162424. }else{
  162425. sqlite3_free(pFd->zDel);
  162426. }
  162427. return rc;
  162428. }
  162429. /*
  162430. ** Delete the file located at zPath.
  162431. */
  162432. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  162433. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162434. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  162435. }
  162436. /*
  162437. ** Test for access permissions. Return true if the requested permission
  162438. ** is available, or false otherwise.
  162439. */
  162440. static int rbuVfsAccess(
  162441. sqlite3_vfs *pVfs,
  162442. const char *zPath,
  162443. int flags,
  162444. int *pResOut
  162445. ){
  162446. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  162447. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  162448. int rc;
  162449. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  162450. /* If this call is to check if a *-wal file associated with an RBU target
  162451. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  162452. ** the following special handling is activated:
  162453. **
  162454. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  162455. ** ensures that the RBU extension never tries to update a database
  162456. ** in wal mode, even if the first page of the database file has
  162457. ** been damaged.
  162458. **
  162459. ** b) if the *-wal file does not exist, claim that it does anyway,
  162460. ** causing SQLite to call xOpen() to open it. This call will also
  162461. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  162462. ** file opened instead.
  162463. */
  162464. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  162465. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
  162466. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  162467. if( *pResOut ){
  162468. rc = SQLITE_CANTOPEN;
  162469. }else{
  162470. *pResOut = 1;
  162471. }
  162472. }
  162473. }
  162474. return rc;
  162475. }
  162476. /*
  162477. ** Populate buffer zOut with the full canonical pathname corresponding
  162478. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  162479. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  162480. */
  162481. static int rbuVfsFullPathname(
  162482. sqlite3_vfs *pVfs,
  162483. const char *zPath,
  162484. int nOut,
  162485. char *zOut
  162486. ){
  162487. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162488. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  162489. }
  162490. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  162491. /*
  162492. ** Open the dynamic library located at zPath and return a handle.
  162493. */
  162494. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  162495. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162496. return pRealVfs->xDlOpen(pRealVfs, zPath);
  162497. }
  162498. /*
  162499. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  162500. ** utf-8 string describing the most recent error encountered associated
  162501. ** with dynamic libraries.
  162502. */
  162503. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  162504. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162505. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  162506. }
  162507. /*
  162508. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  162509. */
  162510. static void (*rbuVfsDlSym(
  162511. sqlite3_vfs *pVfs,
  162512. void *pArg,
  162513. const char *zSym
  162514. ))(void){
  162515. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162516. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  162517. }
  162518. /*
  162519. ** Close the dynamic library handle pHandle.
  162520. */
  162521. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  162522. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162523. pRealVfs->xDlClose(pRealVfs, pHandle);
  162524. }
  162525. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  162526. /*
  162527. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  162528. ** random data.
  162529. */
  162530. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  162531. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162532. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  162533. }
  162534. /*
  162535. ** Sleep for nMicro microseconds. Return the number of microseconds
  162536. ** actually slept.
  162537. */
  162538. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  162539. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162540. return pRealVfs->xSleep(pRealVfs, nMicro);
  162541. }
  162542. /*
  162543. ** Return the current time as a Julian Day number in *pTimeOut.
  162544. */
  162545. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  162546. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162547. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  162548. }
  162549. /*
  162550. ** No-op.
  162551. */
  162552. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  162553. return 0;
  162554. }
  162555. /*
  162556. ** Deregister and destroy an RBU vfs created by an earlier call to
  162557. ** sqlite3rbu_create_vfs().
  162558. */
  162559. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
  162560. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  162561. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  162562. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  162563. sqlite3_vfs_unregister(pVfs);
  162564. sqlite3_free(pVfs);
  162565. }
  162566. }
  162567. /*
  162568. ** Create an RBU VFS named zName that accesses the underlying file-system
  162569. ** via existing VFS zParent. The new object is registered as a non-default
  162570. ** VFS with SQLite before returning.
  162571. */
  162572. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  162573. /* Template for VFS */
  162574. static sqlite3_vfs vfs_template = {
  162575. 1, /* iVersion */
  162576. 0, /* szOsFile */
  162577. 0, /* mxPathname */
  162578. 0, /* pNext */
  162579. 0, /* zName */
  162580. 0, /* pAppData */
  162581. rbuVfsOpen, /* xOpen */
  162582. rbuVfsDelete, /* xDelete */
  162583. rbuVfsAccess, /* xAccess */
  162584. rbuVfsFullPathname, /* xFullPathname */
  162585. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  162586. rbuVfsDlOpen, /* xDlOpen */
  162587. rbuVfsDlError, /* xDlError */
  162588. rbuVfsDlSym, /* xDlSym */
  162589. rbuVfsDlClose, /* xDlClose */
  162590. #else
  162591. 0, 0, 0, 0,
  162592. #endif
  162593. rbuVfsRandomness, /* xRandomness */
  162594. rbuVfsSleep, /* xSleep */
  162595. rbuVfsCurrentTime, /* xCurrentTime */
  162596. rbuVfsGetLastError, /* xGetLastError */
  162597. 0, /* xCurrentTimeInt64 (version 2) */
  162598. 0, 0, 0 /* Unimplemented version 3 methods */
  162599. };
  162600. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  162601. int rc = SQLITE_OK;
  162602. size_t nName;
  162603. size_t nByte;
  162604. nName = strlen(zName);
  162605. nByte = sizeof(rbu_vfs) + nName + 1;
  162606. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  162607. if( pNew==0 ){
  162608. rc = SQLITE_NOMEM;
  162609. }else{
  162610. sqlite3_vfs *pParent; /* Parent VFS */
  162611. memset(pNew, 0, nByte);
  162612. pParent = sqlite3_vfs_find(zParent);
  162613. if( pParent==0 ){
  162614. rc = SQLITE_NOTFOUND;
  162615. }else{
  162616. char *zSpace;
  162617. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  162618. pNew->base.mxPathname = pParent->mxPathname;
  162619. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  162620. pNew->pRealVfs = pParent;
  162621. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  162622. memcpy(zSpace, zName, nName);
  162623. /* Allocate the mutex and register the new VFS (not as the default) */
  162624. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  162625. if( pNew->mutex==0 ){
  162626. rc = SQLITE_NOMEM;
  162627. }else{
  162628. rc = sqlite3_vfs_register(&pNew->base, 0);
  162629. }
  162630. }
  162631. if( rc!=SQLITE_OK ){
  162632. sqlite3_mutex_free(pNew->mutex);
  162633. sqlite3_free(pNew);
  162634. }
  162635. }
  162636. return rc;
  162637. }
  162638. /**************************************************************************/
  162639. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  162640. /************** End of sqlite3rbu.c ******************************************/
  162641. /************** Begin file dbstat.c ******************************************/
  162642. /*
  162643. ** 2010 July 12
  162644. **
  162645. ** The author disclaims copyright to this source code. In place of
  162646. ** a legal notice, here is a blessing:
  162647. **
  162648. ** May you do good and not evil.
  162649. ** May you find forgiveness for yourself and forgive others.
  162650. ** May you share freely, never taking more than you give.
  162651. **
  162652. ******************************************************************************
  162653. **
  162654. ** This file contains an implementation of the "dbstat" virtual table.
  162655. **
  162656. ** The dbstat virtual table is used to extract low-level formatting
  162657. ** information from an SQLite database in order to implement the
  162658. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  162659. ** for an example implementation.
  162660. **
  162661. ** Additional information is available on the "dbstat.html" page of the
  162662. ** official SQLite documentation.
  162663. */
  162664. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  162665. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  162666. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  162667. /*
  162668. ** Page paths:
  162669. **
  162670. ** The value of the 'path' column describes the path taken from the
  162671. ** root-node of the b-tree structure to each page. The value of the
  162672. ** root-node path is '/'.
  162673. **
  162674. ** The value of the path for the left-most child page of the root of
  162675. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  162676. ** so the pages to the left have smaller keys than the pages to the right.)
  162677. ** The next to left-most child of the root page is
  162678. ** '/001', and so on, each sibling page identified by a 3-digit hex
  162679. ** value. The children of the 451st left-most sibling have paths such
  162680. ** as '/1c2/000/, '/1c2/001/' etc.
  162681. **
  162682. ** Overflow pages are specified by appending a '+' character and a
  162683. ** six-digit hexadecimal value to the path to the cell they are linked
  162684. ** from. For example, the three overflow pages in a chain linked from
  162685. ** the left-most cell of the 450th child of the root page are identified
  162686. ** by the paths:
  162687. **
  162688. ** '/1c2/000+000000' // First page in overflow chain
  162689. ** '/1c2/000+000001' // Second page in overflow chain
  162690. ** '/1c2/000+000002' // Third page in overflow chain
  162691. **
  162692. ** If the paths are sorted using the BINARY collation sequence, then
  162693. ** the overflow pages associated with a cell will appear earlier in the
  162694. ** sort-order than its child page:
  162695. **
  162696. ** '/1c2/000/' // Left-most child of 451st child of root
  162697. */
  162698. #define VTAB_SCHEMA \
  162699. "CREATE TABLE xx( " \
  162700. " name TEXT, /* Name of table or index */" \
  162701. " path TEXT, /* Path to page from root */" \
  162702. " pageno INTEGER, /* Page number */" \
  162703. " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
  162704. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  162705. " payload INTEGER, /* Bytes of payload on this page */" \
  162706. " unused INTEGER, /* Bytes of unused space on this page */" \
  162707. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  162708. " pgoffset INTEGER, /* Offset of page in file */" \
  162709. " pgsize INTEGER, /* Size of the page */" \
  162710. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  162711. ");"
  162712. typedef struct StatTable StatTable;
  162713. typedef struct StatCursor StatCursor;
  162714. typedef struct StatPage StatPage;
  162715. typedef struct StatCell StatCell;
  162716. struct StatCell {
  162717. int nLocal; /* Bytes of local payload */
  162718. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  162719. int nOvfl; /* Entries in aOvfl[] */
  162720. u32 *aOvfl; /* Array of overflow page numbers */
  162721. int nLastOvfl; /* Bytes of payload on final overflow page */
  162722. int iOvfl; /* Iterates through aOvfl[] */
  162723. };
  162724. struct StatPage {
  162725. u32 iPgno;
  162726. DbPage *pPg;
  162727. int iCell;
  162728. char *zPath; /* Path to this page */
  162729. /* Variables populated by statDecodePage(): */
  162730. u8 flags; /* Copy of flags byte */
  162731. int nCell; /* Number of cells on page */
  162732. int nUnused; /* Number of unused bytes on page */
  162733. StatCell *aCell; /* Array of parsed cells */
  162734. u32 iRightChildPg; /* Right-child page number (or 0) */
  162735. int nMxPayload; /* Largest payload of any cell on this page */
  162736. };
  162737. struct StatCursor {
  162738. sqlite3_vtab_cursor base;
  162739. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  162740. int isEof; /* After pStmt has returned SQLITE_DONE */
  162741. int iDb; /* Schema used for this query */
  162742. StatPage aPage[32];
  162743. int iPage; /* Current entry in aPage[] */
  162744. /* Values to return. */
  162745. char *zName; /* Value of 'name' column */
  162746. char *zPath; /* Value of 'path' column */
  162747. u32 iPageno; /* Value of 'pageno' column */
  162748. char *zPagetype; /* Value of 'pagetype' column */
  162749. int nCell; /* Value of 'ncell' column */
  162750. int nPayload; /* Value of 'payload' column */
  162751. int nUnused; /* Value of 'unused' column */
  162752. int nMxPayload; /* Value of 'mx_payload' column */
  162753. i64 iOffset; /* Value of 'pgOffset' column */
  162754. int szPage; /* Value of 'pgSize' column */
  162755. };
  162756. struct StatTable {
  162757. sqlite3_vtab base;
  162758. sqlite3 *db;
  162759. int iDb; /* Index of database to analyze */
  162760. };
  162761. #ifndef get2byte
  162762. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  162763. #endif
  162764. /*
  162765. ** Connect to or create a statvfs virtual table.
  162766. */
  162767. static int statConnect(
  162768. sqlite3 *db,
  162769. void *pAux,
  162770. int argc, const char *const*argv,
  162771. sqlite3_vtab **ppVtab,
  162772. char **pzErr
  162773. ){
  162774. StatTable *pTab = 0;
  162775. int rc = SQLITE_OK;
  162776. int iDb;
  162777. if( argc>=4 ){
  162778. Token nm;
  162779. sqlite3TokenInit(&nm, (char*)argv[3]);
  162780. iDb = sqlite3FindDb(db, &nm);
  162781. if( iDb<0 ){
  162782. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  162783. return SQLITE_ERROR;
  162784. }
  162785. }else{
  162786. iDb = 0;
  162787. }
  162788. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  162789. if( rc==SQLITE_OK ){
  162790. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  162791. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  162792. }
  162793. assert( rc==SQLITE_OK || pTab==0 );
  162794. if( rc==SQLITE_OK ){
  162795. memset(pTab, 0, sizeof(StatTable));
  162796. pTab->db = db;
  162797. pTab->iDb = iDb;
  162798. }
  162799. *ppVtab = (sqlite3_vtab*)pTab;
  162800. return rc;
  162801. }
  162802. /*
  162803. ** Disconnect from or destroy a statvfs virtual table.
  162804. */
  162805. static int statDisconnect(sqlite3_vtab *pVtab){
  162806. sqlite3_free(pVtab);
  162807. return SQLITE_OK;
  162808. }
  162809. /*
  162810. ** There is no "best-index". This virtual table always does a linear
  162811. ** scan. However, a schema=? constraint should cause this table to
  162812. ** operate on a different database schema, so check for it.
  162813. **
  162814. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  162815. */
  162816. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  162817. int i;
  162818. pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
  162819. /* Look for a valid schema=? constraint. If found, change the idxNum to
  162820. ** 1 and request the value of that constraint be sent to xFilter. And
  162821. ** lower the cost estimate to encourage the constrained version to be
  162822. ** used.
  162823. */
  162824. for(i=0; i<pIdxInfo->nConstraint; i++){
  162825. if( pIdxInfo->aConstraint[i].usable==0 ) continue;
  162826. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  162827. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  162828. pIdxInfo->idxNum = 1;
  162829. pIdxInfo->estimatedCost = 1.0;
  162830. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  162831. pIdxInfo->aConstraintUsage[i].omit = 1;
  162832. break;
  162833. }
  162834. /* Records are always returned in ascending order of (name, path).
  162835. ** If this will satisfy the client, set the orderByConsumed flag so that
  162836. ** SQLite does not do an external sort.
  162837. */
  162838. if( ( pIdxInfo->nOrderBy==1
  162839. && pIdxInfo->aOrderBy[0].iColumn==0
  162840. && pIdxInfo->aOrderBy[0].desc==0
  162841. ) ||
  162842. ( pIdxInfo->nOrderBy==2
  162843. && pIdxInfo->aOrderBy[0].iColumn==0
  162844. && pIdxInfo->aOrderBy[0].desc==0
  162845. && pIdxInfo->aOrderBy[1].iColumn==1
  162846. && pIdxInfo->aOrderBy[1].desc==0
  162847. )
  162848. ){
  162849. pIdxInfo->orderByConsumed = 1;
  162850. }
  162851. return SQLITE_OK;
  162852. }
  162853. /*
  162854. ** Open a new statvfs cursor.
  162855. */
  162856. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  162857. StatTable *pTab = (StatTable *)pVTab;
  162858. StatCursor *pCsr;
  162859. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  162860. if( pCsr==0 ){
  162861. return SQLITE_NOMEM_BKPT;
  162862. }else{
  162863. memset(pCsr, 0, sizeof(StatCursor));
  162864. pCsr->base.pVtab = pVTab;
  162865. pCsr->iDb = pTab->iDb;
  162866. }
  162867. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  162868. return SQLITE_OK;
  162869. }
  162870. static void statClearPage(StatPage *p){
  162871. int i;
  162872. if( p->aCell ){
  162873. for(i=0; i<p->nCell; i++){
  162874. sqlite3_free(p->aCell[i].aOvfl);
  162875. }
  162876. sqlite3_free(p->aCell);
  162877. }
  162878. sqlite3PagerUnref(p->pPg);
  162879. sqlite3_free(p->zPath);
  162880. memset(p, 0, sizeof(StatPage));
  162881. }
  162882. static void statResetCsr(StatCursor *pCsr){
  162883. int i;
  162884. sqlite3_reset(pCsr->pStmt);
  162885. for(i=0; i<ArraySize(pCsr->aPage); i++){
  162886. statClearPage(&pCsr->aPage[i]);
  162887. }
  162888. pCsr->iPage = 0;
  162889. sqlite3_free(pCsr->zPath);
  162890. pCsr->zPath = 0;
  162891. pCsr->isEof = 0;
  162892. }
  162893. /*
  162894. ** Close a statvfs cursor.
  162895. */
  162896. static int statClose(sqlite3_vtab_cursor *pCursor){
  162897. StatCursor *pCsr = (StatCursor *)pCursor;
  162898. statResetCsr(pCsr);
  162899. sqlite3_finalize(pCsr->pStmt);
  162900. sqlite3_free(pCsr);
  162901. return SQLITE_OK;
  162902. }
  162903. static void getLocalPayload(
  162904. int nUsable, /* Usable bytes per page */
  162905. u8 flags, /* Page flags */
  162906. int nTotal, /* Total record (payload) size */
  162907. int *pnLocal /* OUT: Bytes stored locally */
  162908. ){
  162909. int nLocal;
  162910. int nMinLocal;
  162911. int nMaxLocal;
  162912. if( flags==0x0D ){ /* Table leaf node */
  162913. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  162914. nMaxLocal = nUsable - 35;
  162915. }else{ /* Index interior and leaf nodes */
  162916. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  162917. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  162918. }
  162919. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  162920. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  162921. *pnLocal = nLocal;
  162922. }
  162923. static int statDecodePage(Btree *pBt, StatPage *p){
  162924. int nUnused;
  162925. int iOff;
  162926. int nHdr;
  162927. int isLeaf;
  162928. int szPage;
  162929. u8 *aData = sqlite3PagerGetData(p->pPg);
  162930. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  162931. p->flags = aHdr[0];
  162932. p->nCell = get2byte(&aHdr[3]);
  162933. p->nMxPayload = 0;
  162934. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  162935. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  162936. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  162937. nUnused += (int)aHdr[7];
  162938. iOff = get2byte(&aHdr[1]);
  162939. while( iOff ){
  162940. nUnused += get2byte(&aData[iOff+2]);
  162941. iOff = get2byte(&aData[iOff]);
  162942. }
  162943. p->nUnused = nUnused;
  162944. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  162945. szPage = sqlite3BtreeGetPageSize(pBt);
  162946. if( p->nCell ){
  162947. int i; /* Used to iterate through cells */
  162948. int nUsable; /* Usable bytes per page */
  162949. sqlite3BtreeEnter(pBt);
  162950. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  162951. sqlite3BtreeLeave(pBt);
  162952. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  162953. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  162954. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  162955. for(i=0; i<p->nCell; i++){
  162956. StatCell *pCell = &p->aCell[i];
  162957. iOff = get2byte(&aData[nHdr+i*2]);
  162958. if( !isLeaf ){
  162959. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  162960. iOff += 4;
  162961. }
  162962. if( p->flags==0x05 ){
  162963. /* A table interior node. nPayload==0. */
  162964. }else{
  162965. u32 nPayload; /* Bytes of payload total (local+overflow) */
  162966. int nLocal; /* Bytes of payload stored locally */
  162967. iOff += getVarint32(&aData[iOff], nPayload);
  162968. if( p->flags==0x0D ){
  162969. u64 dummy;
  162970. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  162971. }
  162972. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  162973. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  162974. pCell->nLocal = nLocal;
  162975. assert( nLocal>=0 );
  162976. assert( nPayload>=(u32)nLocal );
  162977. assert( nLocal<=(nUsable-35) );
  162978. if( nPayload>(u32)nLocal ){
  162979. int j;
  162980. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  162981. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  162982. pCell->nOvfl = nOvfl;
  162983. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  162984. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  162985. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  162986. for(j=1; j<nOvfl; j++){
  162987. int rc;
  162988. u32 iPrev = pCell->aOvfl[j-1];
  162989. DbPage *pPg = 0;
  162990. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  162991. if( rc!=SQLITE_OK ){
  162992. assert( pPg==0 );
  162993. return rc;
  162994. }
  162995. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  162996. sqlite3PagerUnref(pPg);
  162997. }
  162998. }
  162999. }
  163000. }
  163001. }
  163002. return SQLITE_OK;
  163003. }
  163004. /*
  163005. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  163006. ** the current value of pCsr->iPageno.
  163007. */
  163008. static void statSizeAndOffset(StatCursor *pCsr){
  163009. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  163010. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  163011. Pager *pPager = sqlite3BtreePager(pBt);
  163012. sqlite3_file *fd;
  163013. sqlite3_int64 x[2];
  163014. /* The default page size and offset */
  163015. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  163016. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  163017. /* If connected to a ZIPVFS backend, override the page size and
  163018. ** offset with actual values obtained from ZIPVFS.
  163019. */
  163020. fd = sqlite3PagerFile(pPager);
  163021. x[0] = pCsr->iPageno;
  163022. if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  163023. pCsr->iOffset = x[0];
  163024. pCsr->szPage = (int)x[1];
  163025. }
  163026. }
  163027. /*
  163028. ** Move a statvfs cursor to the next entry in the file.
  163029. */
  163030. static int statNext(sqlite3_vtab_cursor *pCursor){
  163031. int rc;
  163032. int nPayload;
  163033. char *z;
  163034. StatCursor *pCsr = (StatCursor *)pCursor;
  163035. StatTable *pTab = (StatTable *)pCursor->pVtab;
  163036. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  163037. Pager *pPager = sqlite3BtreePager(pBt);
  163038. sqlite3_free(pCsr->zPath);
  163039. pCsr->zPath = 0;
  163040. statNextRestart:
  163041. if( pCsr->aPage[0].pPg==0 ){
  163042. rc = sqlite3_step(pCsr->pStmt);
  163043. if( rc==SQLITE_ROW ){
  163044. int nPage;
  163045. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  163046. sqlite3PagerPagecount(pPager, &nPage);
  163047. if( nPage==0 ){
  163048. pCsr->isEof = 1;
  163049. return sqlite3_reset(pCsr->pStmt);
  163050. }
  163051. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  163052. pCsr->aPage[0].iPgno = iRoot;
  163053. pCsr->aPage[0].iCell = 0;
  163054. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  163055. pCsr->iPage = 0;
  163056. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  163057. }else{
  163058. pCsr->isEof = 1;
  163059. return sqlite3_reset(pCsr->pStmt);
  163060. }
  163061. }else{
  163062. /* Page p itself has already been visited. */
  163063. StatPage *p = &pCsr->aPage[pCsr->iPage];
  163064. while( p->iCell<p->nCell ){
  163065. StatCell *pCell = &p->aCell[p->iCell];
  163066. if( pCell->iOvfl<pCell->nOvfl ){
  163067. int nUsable;
  163068. sqlite3BtreeEnter(pBt);
  163069. nUsable = sqlite3BtreeGetPageSize(pBt) -
  163070. sqlite3BtreeGetReserveNoMutex(pBt);
  163071. sqlite3BtreeLeave(pBt);
  163072. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  163073. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  163074. pCsr->zPagetype = "overflow";
  163075. pCsr->nCell = 0;
  163076. pCsr->nMxPayload = 0;
  163077. pCsr->zPath = z = sqlite3_mprintf(
  163078. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  163079. );
  163080. if( pCell->iOvfl<pCell->nOvfl-1 ){
  163081. pCsr->nUnused = 0;
  163082. pCsr->nPayload = nUsable - 4;
  163083. }else{
  163084. pCsr->nPayload = pCell->nLastOvfl;
  163085. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  163086. }
  163087. pCell->iOvfl++;
  163088. statSizeAndOffset(pCsr);
  163089. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  163090. }
  163091. if( p->iRightChildPg ) break;
  163092. p->iCell++;
  163093. }
  163094. if( !p->iRightChildPg || p->iCell>p->nCell ){
  163095. statClearPage(p);
  163096. if( pCsr->iPage==0 ) return statNext(pCursor);
  163097. pCsr->iPage--;
  163098. goto statNextRestart; /* Tail recursion */
  163099. }
  163100. pCsr->iPage++;
  163101. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  163102. if( p->iCell==p->nCell ){
  163103. p[1].iPgno = p->iRightChildPg;
  163104. }else{
  163105. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  163106. }
  163107. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  163108. p[1].iCell = 0;
  163109. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  163110. p->iCell++;
  163111. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  163112. }
  163113. /* Populate the StatCursor fields with the values to be returned
  163114. ** by the xColumn() and xRowid() methods.
  163115. */
  163116. if( rc==SQLITE_OK ){
  163117. int i;
  163118. StatPage *p = &pCsr->aPage[pCsr->iPage];
  163119. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  163120. pCsr->iPageno = p->iPgno;
  163121. rc = statDecodePage(pBt, p);
  163122. if( rc==SQLITE_OK ){
  163123. statSizeAndOffset(pCsr);
  163124. switch( p->flags ){
  163125. case 0x05: /* table internal */
  163126. case 0x02: /* index internal */
  163127. pCsr->zPagetype = "internal";
  163128. break;
  163129. case 0x0D: /* table leaf */
  163130. case 0x0A: /* index leaf */
  163131. pCsr->zPagetype = "leaf";
  163132. break;
  163133. default:
  163134. pCsr->zPagetype = "corrupted";
  163135. break;
  163136. }
  163137. pCsr->nCell = p->nCell;
  163138. pCsr->nUnused = p->nUnused;
  163139. pCsr->nMxPayload = p->nMxPayload;
  163140. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  163141. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  163142. nPayload = 0;
  163143. for(i=0; i<p->nCell; i++){
  163144. nPayload += p->aCell[i].nLocal;
  163145. }
  163146. pCsr->nPayload = nPayload;
  163147. }
  163148. }
  163149. return rc;
  163150. }
  163151. static int statEof(sqlite3_vtab_cursor *pCursor){
  163152. StatCursor *pCsr = (StatCursor *)pCursor;
  163153. return pCsr->isEof;
  163154. }
  163155. static int statFilter(
  163156. sqlite3_vtab_cursor *pCursor,
  163157. int idxNum, const char *idxStr,
  163158. int argc, sqlite3_value **argv
  163159. ){
  163160. StatCursor *pCsr = (StatCursor *)pCursor;
  163161. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  163162. char *zSql;
  163163. int rc = SQLITE_OK;
  163164. char *zMaster;
  163165. if( idxNum==1 ){
  163166. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  163167. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  163168. if( pCsr->iDb<0 ){
  163169. sqlite3_free(pCursor->pVtab->zErrMsg);
  163170. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  163171. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
  163172. }
  163173. }else{
  163174. pCsr->iDb = pTab->iDb;
  163175. }
  163176. statResetCsr(pCsr);
  163177. sqlite3_finalize(pCsr->pStmt);
  163178. pCsr->pStmt = 0;
  163179. zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
  163180. zSql = sqlite3_mprintf(
  163181. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  163182. " UNION ALL "
  163183. "SELECT name, rootpage, type"
  163184. " FROM \"%w\".%s WHERE rootpage!=0"
  163185. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
  163186. if( zSql==0 ){
  163187. return SQLITE_NOMEM_BKPT;
  163188. }else{
  163189. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  163190. sqlite3_free(zSql);
  163191. }
  163192. if( rc==SQLITE_OK ){
  163193. rc = statNext(pCursor);
  163194. }
  163195. return rc;
  163196. }
  163197. static int statColumn(
  163198. sqlite3_vtab_cursor *pCursor,
  163199. sqlite3_context *ctx,
  163200. int i
  163201. ){
  163202. StatCursor *pCsr = (StatCursor *)pCursor;
  163203. switch( i ){
  163204. case 0: /* name */
  163205. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  163206. break;
  163207. case 1: /* path */
  163208. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  163209. break;
  163210. case 2: /* pageno */
  163211. sqlite3_result_int64(ctx, pCsr->iPageno);
  163212. break;
  163213. case 3: /* pagetype */
  163214. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  163215. break;
  163216. case 4: /* ncell */
  163217. sqlite3_result_int(ctx, pCsr->nCell);
  163218. break;
  163219. case 5: /* payload */
  163220. sqlite3_result_int(ctx, pCsr->nPayload);
  163221. break;
  163222. case 6: /* unused */
  163223. sqlite3_result_int(ctx, pCsr->nUnused);
  163224. break;
  163225. case 7: /* mx_payload */
  163226. sqlite3_result_int(ctx, pCsr->nMxPayload);
  163227. break;
  163228. case 8: /* pgoffset */
  163229. sqlite3_result_int64(ctx, pCsr->iOffset);
  163230. break;
  163231. case 9: /* pgsize */
  163232. sqlite3_result_int(ctx, pCsr->szPage);
  163233. break;
  163234. default: { /* schema */
  163235. sqlite3 *db = sqlite3_context_db_handle(ctx);
  163236. int iDb = pCsr->iDb;
  163237. sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
  163238. break;
  163239. }
  163240. }
  163241. return SQLITE_OK;
  163242. }
  163243. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  163244. StatCursor *pCsr = (StatCursor *)pCursor;
  163245. *pRowid = pCsr->iPageno;
  163246. return SQLITE_OK;
  163247. }
  163248. /*
  163249. ** Invoke this routine to register the "dbstat" virtual table module
  163250. */
  163251. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  163252. static sqlite3_module dbstat_module = {
  163253. 0, /* iVersion */
  163254. statConnect, /* xCreate */
  163255. statConnect, /* xConnect */
  163256. statBestIndex, /* xBestIndex */
  163257. statDisconnect, /* xDisconnect */
  163258. statDisconnect, /* xDestroy */
  163259. statOpen, /* xOpen - open a cursor */
  163260. statClose, /* xClose - close a cursor */
  163261. statFilter, /* xFilter - configure scan constraints */
  163262. statNext, /* xNext - advance a cursor */
  163263. statEof, /* xEof - check for end of scan */
  163264. statColumn, /* xColumn - read data */
  163265. statRowid, /* xRowid - read data */
  163266. 0, /* xUpdate */
  163267. 0, /* xBegin */
  163268. 0, /* xSync */
  163269. 0, /* xCommit */
  163270. 0, /* xRollback */
  163271. 0, /* xFindMethod */
  163272. 0, /* xRename */
  163273. };
  163274. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  163275. }
  163276. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  163277. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  163278. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  163279. /************** End of dbstat.c **********************************************/
  163280. /************** Begin file sqlite3session.c **********************************/
  163281. #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  163282. /* #include "sqlite3session.h" */
  163283. /* #include <assert.h> */
  163284. /* #include <string.h> */
  163285. #ifndef SQLITE_AMALGAMATION
  163286. /* # include "sqliteInt.h" */
  163287. /* # include "vdbeInt.h" */
  163288. #endif
  163289. typedef struct SessionTable SessionTable;
  163290. typedef struct SessionChange SessionChange;
  163291. typedef struct SessionBuffer SessionBuffer;
  163292. typedef struct SessionInput SessionInput;
  163293. /*
  163294. ** Minimum chunk size used by streaming versions of functions.
  163295. */
  163296. #ifndef SESSIONS_STRM_CHUNK_SIZE
  163297. # ifdef SQLITE_TEST
  163298. # define SESSIONS_STRM_CHUNK_SIZE 64
  163299. # else
  163300. # define SESSIONS_STRM_CHUNK_SIZE 1024
  163301. # endif
  163302. #endif
  163303. typedef struct SessionHook SessionHook;
  163304. struct SessionHook {
  163305. void *pCtx;
  163306. int (*xOld)(void*,int,sqlite3_value**);
  163307. int (*xNew)(void*,int,sqlite3_value**);
  163308. int (*xCount)(void*);
  163309. int (*xDepth)(void*);
  163310. };
  163311. /*
  163312. ** Session handle structure.
  163313. */
  163314. struct sqlite3_session {
  163315. sqlite3 *db; /* Database handle session is attached to */
  163316. char *zDb; /* Name of database session is attached to */
  163317. int bEnable; /* True if currently recording */
  163318. int bIndirect; /* True if all changes are indirect */
  163319. int bAutoAttach; /* True to auto-attach tables */
  163320. int rc; /* Non-zero if an error has occurred */
  163321. void *pFilterCtx; /* First argument to pass to xTableFilter */
  163322. int (*xTableFilter)(void *pCtx, const char *zTab);
  163323. sqlite3_session *pNext; /* Next session object on same db. */
  163324. SessionTable *pTable; /* List of attached tables */
  163325. SessionHook hook; /* APIs to grab new and old data with */
  163326. };
  163327. /*
  163328. ** Instances of this structure are used to build strings or binary records.
  163329. */
  163330. struct SessionBuffer {
  163331. u8 *aBuf; /* Pointer to changeset buffer */
  163332. int nBuf; /* Size of buffer aBuf */
  163333. int nAlloc; /* Size of allocation containing aBuf */
  163334. };
  163335. /*
  163336. ** An object of this type is used internally as an abstraction for
  163337. ** input data. Input data may be supplied either as a single large buffer
  163338. ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
  163339. ** sqlite3changeset_start_strm()).
  163340. */
  163341. struct SessionInput {
  163342. int bNoDiscard; /* If true, discard no data */
  163343. int iCurrent; /* Offset in aData[] of current change */
  163344. int iNext; /* Offset in aData[] of next change */
  163345. u8 *aData; /* Pointer to buffer containing changeset */
  163346. int nData; /* Number of bytes in aData */
  163347. SessionBuffer buf; /* Current read buffer */
  163348. int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
  163349. void *pIn; /* First argument to xInput */
  163350. int bEof; /* Set to true after xInput finished */
  163351. };
  163352. /*
  163353. ** Structure for changeset iterators.
  163354. */
  163355. struct sqlite3_changeset_iter {
  163356. SessionInput in; /* Input buffer or stream */
  163357. SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
  163358. int bPatchset; /* True if this is a patchset */
  163359. int rc; /* Iterator error code */
  163360. sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
  163361. char *zTab; /* Current table */
  163362. int nCol; /* Number of columns in zTab */
  163363. int op; /* Current operation */
  163364. int bIndirect; /* True if current change was indirect */
  163365. u8 *abPK; /* Primary key array */
  163366. sqlite3_value **apValue; /* old.* and new.* values */
  163367. };
  163368. /*
  163369. ** Each session object maintains a set of the following structures, one
  163370. ** for each table the session object is monitoring. The structures are
  163371. ** stored in a linked list starting at sqlite3_session.pTable.
  163372. **
  163373. ** The keys of the SessionTable.aChange[] hash table are all rows that have
  163374. ** been modified in any way since the session object was attached to the
  163375. ** table.
  163376. **
  163377. ** The data associated with each hash-table entry is a structure containing
  163378. ** a subset of the initial values that the modified row contained at the
  163379. ** start of the session. Or no initial values if the row was inserted.
  163380. */
  163381. struct SessionTable {
  163382. SessionTable *pNext;
  163383. char *zName; /* Local name of table */
  163384. int nCol; /* Number of columns in table zName */
  163385. const char **azCol; /* Column names */
  163386. u8 *abPK; /* Array of primary key flags */
  163387. int nEntry; /* Total number of entries in hash table */
  163388. int nChange; /* Size of apChange[] array */
  163389. SessionChange **apChange; /* Hash table buckets */
  163390. };
  163391. /*
  163392. ** RECORD FORMAT:
  163393. **
  163394. ** The following record format is similar to (but not compatible with) that
  163395. ** used in SQLite database files. This format is used as part of the
  163396. ** change-set binary format, and so must be architecture independent.
  163397. **
  163398. ** Unlike the SQLite database record format, each field is self-contained -
  163399. ** there is no separation of header and data. Each field begins with a
  163400. ** single byte describing its type, as follows:
  163401. **
  163402. ** 0x00: Undefined value.
  163403. ** 0x01: Integer value.
  163404. ** 0x02: Real value.
  163405. ** 0x03: Text value.
  163406. ** 0x04: Blob value.
  163407. ** 0x05: SQL NULL value.
  163408. **
  163409. ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
  163410. ** and so on in sqlite3.h. For undefined and NULL values, the field consists
  163411. ** only of the single type byte. For other types of values, the type byte
  163412. ** is followed by:
  163413. **
  163414. ** Text values:
  163415. ** A varint containing the number of bytes in the value (encoded using
  163416. ** UTF-8). Followed by a buffer containing the UTF-8 representation
  163417. ** of the text value. There is no nul terminator.
  163418. **
  163419. ** Blob values:
  163420. ** A varint containing the number of bytes in the value, followed by
  163421. ** a buffer containing the value itself.
  163422. **
  163423. ** Integer values:
  163424. ** An 8-byte big-endian integer value.
  163425. **
  163426. ** Real values:
  163427. ** An 8-byte big-endian IEEE 754-2008 real value.
  163428. **
  163429. ** Varint values are encoded in the same way as varints in the SQLite
  163430. ** record format.
  163431. **
  163432. ** CHANGESET FORMAT:
  163433. **
  163434. ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
  163435. ** one or more tables. Operations on a single table are grouped together,
  163436. ** but may occur in any order (i.e. deletes, updates and inserts are all
  163437. ** mixed together).
  163438. **
  163439. ** Each group of changes begins with a table header:
  163440. **
  163441. ** 1 byte: Constant 0x54 (capital 'T')
  163442. ** Varint: Number of columns in the table.
  163443. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  163444. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  163445. **
  163446. ** Followed by one or more changes to the table.
  163447. **
  163448. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  163449. ** 1 byte: The "indirect-change" flag.
  163450. ** old.* record: (delete and update only)
  163451. ** new.* record: (insert and update only)
  163452. **
  163453. ** The "old.*" and "new.*" records, if present, are N field records in the
  163454. ** format described above under "RECORD FORMAT", where N is the number of
  163455. ** columns in the table. The i'th field of each record is associated with
  163456. ** the i'th column of the table, counting from left to right in the order
  163457. ** in which columns were declared in the CREATE TABLE statement.
  163458. **
  163459. ** The new.* record that is part of each INSERT change contains the values
  163460. ** that make up the new row. Similarly, the old.* record that is part of each
  163461. ** DELETE change contains the values that made up the row that was deleted
  163462. ** from the database. In the changeset format, the records that are part
  163463. ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
  163464. ** fields.
  163465. **
  163466. ** Within the old.* record associated with an UPDATE change, all fields
  163467. ** associated with table columns that are not PRIMARY KEY columns and are
  163468. ** not modified by the UPDATE change are set to "undefined". Other fields
  163469. ** are set to the values that made up the row before the UPDATE that the
  163470. ** change records took place. Within the new.* record, fields associated
  163471. ** with table columns modified by the UPDATE change contain the new
  163472. ** values. Fields associated with table columns that are not modified
  163473. ** are set to "undefined".
  163474. **
  163475. ** PATCHSET FORMAT:
  163476. **
  163477. ** A patchset is also a collection of changes. It is similar to a changeset,
  163478. ** but leaves undefined those fields that are not useful if no conflict
  163479. ** resolution is required when applying the changeset.
  163480. **
  163481. ** Each group of changes begins with a table header:
  163482. **
  163483. ** 1 byte: Constant 0x50 (capital 'P')
  163484. ** Varint: Number of columns in the table.
  163485. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  163486. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  163487. **
  163488. ** Followed by one or more changes to the table.
  163489. **
  163490. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  163491. ** 1 byte: The "indirect-change" flag.
  163492. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
  163493. ** full record for INSERT).
  163494. **
  163495. ** As in the changeset format, each field of the single record that is part
  163496. ** of a patchset change is associated with the correspondingly positioned
  163497. ** table column, counting from left to right within the CREATE TABLE
  163498. ** statement.
  163499. **
  163500. ** For a DELETE change, all fields within the record except those associated
  163501. ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
  163502. ** contain the values identifying the row to delete.
  163503. **
  163504. ** For an UPDATE change, all fields except those associated with PRIMARY KEY
  163505. ** columns and columns that are modified by the UPDATE are set to "undefined".
  163506. ** PRIMARY KEY fields contain the values identifying the table row to update,
  163507. ** and fields associated with modified columns contain the new column values.
  163508. **
  163509. ** The records associated with INSERT changes are in the same format as for
  163510. ** changesets. It is not possible for a record associated with an INSERT
  163511. ** change to contain a field set to "undefined".
  163512. */
  163513. /*
  163514. ** For each row modified during a session, there exists a single instance of
  163515. ** this structure stored in a SessionTable.aChange[] hash table.
  163516. */
  163517. struct SessionChange {
  163518. int op; /* One of UPDATE, DELETE, INSERT */
  163519. int bIndirect; /* True if this change is "indirect" */
  163520. int nRecord; /* Number of bytes in buffer aRecord[] */
  163521. u8 *aRecord; /* Buffer containing old.* record */
  163522. SessionChange *pNext; /* For hash-table collisions */
  163523. };
  163524. /*
  163525. ** Write a varint with value iVal into the buffer at aBuf. Return the
  163526. ** number of bytes written.
  163527. */
  163528. static int sessionVarintPut(u8 *aBuf, int iVal){
  163529. return putVarint32(aBuf, iVal);
  163530. }
  163531. /*
  163532. ** Return the number of bytes required to store value iVal as a varint.
  163533. */
  163534. static int sessionVarintLen(int iVal){
  163535. return sqlite3VarintLen(iVal);
  163536. }
  163537. /*
  163538. ** Read a varint value from aBuf[] into *piVal. Return the number of
  163539. ** bytes read.
  163540. */
  163541. static int sessionVarintGet(u8 *aBuf, int *piVal){
  163542. return getVarint32(aBuf, *piVal);
  163543. }
  163544. /* Load an unaligned and unsigned 32-bit integer */
  163545. #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  163546. /*
  163547. ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
  163548. ** the value read.
  163549. */
  163550. static sqlite3_int64 sessionGetI64(u8 *aRec){
  163551. u64 x = SESSION_UINT32(aRec);
  163552. u32 y = SESSION_UINT32(aRec+4);
  163553. x = (x<<32) + y;
  163554. return (sqlite3_int64)x;
  163555. }
  163556. /*
  163557. ** Write a 64-bit big-endian integer value to the buffer aBuf[].
  163558. */
  163559. static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
  163560. aBuf[0] = (i>>56) & 0xFF;
  163561. aBuf[1] = (i>>48) & 0xFF;
  163562. aBuf[2] = (i>>40) & 0xFF;
  163563. aBuf[3] = (i>>32) & 0xFF;
  163564. aBuf[4] = (i>>24) & 0xFF;
  163565. aBuf[5] = (i>>16) & 0xFF;
  163566. aBuf[6] = (i>> 8) & 0xFF;
  163567. aBuf[7] = (i>> 0) & 0xFF;
  163568. }
  163569. /*
  163570. ** This function is used to serialize the contents of value pValue (see
  163571. ** comment titled "RECORD FORMAT" above).
  163572. **
  163573. ** If it is non-NULL, the serialized form of the value is written to
  163574. ** buffer aBuf. *pnWrite is set to the number of bytes written before
  163575. ** returning. Or, if aBuf is NULL, the only thing this function does is
  163576. ** set *pnWrite.
  163577. **
  163578. ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
  163579. ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
  163580. ** SQLITE_NOMEM is returned.
  163581. */
  163582. static int sessionSerializeValue(
  163583. u8 *aBuf, /* If non-NULL, write serialized value here */
  163584. sqlite3_value *pValue, /* Value to serialize */
  163585. int *pnWrite /* IN/OUT: Increment by bytes written */
  163586. ){
  163587. int nByte; /* Size of serialized value in bytes */
  163588. if( pValue ){
  163589. int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
  163590. eType = sqlite3_value_type(pValue);
  163591. if( aBuf ) aBuf[0] = eType;
  163592. switch( eType ){
  163593. case SQLITE_NULL:
  163594. nByte = 1;
  163595. break;
  163596. case SQLITE_INTEGER:
  163597. case SQLITE_FLOAT:
  163598. if( aBuf ){
  163599. /* TODO: SQLite does something special to deal with mixed-endian
  163600. ** floating point values (e.g. ARM7). This code probably should
  163601. ** too. */
  163602. u64 i;
  163603. if( eType==SQLITE_INTEGER ){
  163604. i = (u64)sqlite3_value_int64(pValue);
  163605. }else{
  163606. double r;
  163607. assert( sizeof(double)==8 && sizeof(u64)==8 );
  163608. r = sqlite3_value_double(pValue);
  163609. memcpy(&i, &r, 8);
  163610. }
  163611. sessionPutI64(&aBuf[1], i);
  163612. }
  163613. nByte = 9;
  163614. break;
  163615. default: {
  163616. u8 *z;
  163617. int n;
  163618. int nVarint;
  163619. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  163620. if( eType==SQLITE_TEXT ){
  163621. z = (u8 *)sqlite3_value_text(pValue);
  163622. }else{
  163623. z = (u8 *)sqlite3_value_blob(pValue);
  163624. }
  163625. n = sqlite3_value_bytes(pValue);
  163626. if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  163627. nVarint = sessionVarintLen(n);
  163628. if( aBuf ){
  163629. sessionVarintPut(&aBuf[1], n);
  163630. if( n ) memcpy(&aBuf[nVarint + 1], z, n);
  163631. }
  163632. nByte = 1 + nVarint + n;
  163633. break;
  163634. }
  163635. }
  163636. }else{
  163637. nByte = 1;
  163638. if( aBuf ) aBuf[0] = '\0';
  163639. }
  163640. if( pnWrite ) *pnWrite += nByte;
  163641. return SQLITE_OK;
  163642. }
  163643. /*
  163644. ** This macro is used to calculate hash key values for data structures. In
  163645. ** order to use this macro, the entire data structure must be represented
  163646. ** as a series of unsigned integers. In order to calculate a hash-key value
  163647. ** for a data structure represented as three such integers, the macro may
  163648. ** then be used as follows:
  163649. **
  163650. ** int hash_key_value;
  163651. ** hash_key_value = HASH_APPEND(0, <value 1>);
  163652. ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
  163653. ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
  163654. **
  163655. ** In practice, the data structures this macro is used for are the primary
  163656. ** key values of modified rows.
  163657. */
  163658. #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
  163659. /*
  163660. ** Append the hash of the 64-bit integer passed as the second argument to the
  163661. ** hash-key value passed as the first. Return the new hash-key value.
  163662. */
  163663. static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
  163664. h = HASH_APPEND(h, i & 0xFFFFFFFF);
  163665. return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
  163666. }
  163667. /*
  163668. ** Append the hash of the blob passed via the second and third arguments to
  163669. ** the hash-key value passed as the first. Return the new hash-key value.
  163670. */
  163671. static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
  163672. int i;
  163673. for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  163674. return h;
  163675. }
  163676. /*
  163677. ** Append the hash of the data type passed as the second argument to the
  163678. ** hash-key value passed as the first. Return the new hash-key value.
  163679. */
  163680. static unsigned int sessionHashAppendType(unsigned int h, int eType){
  163681. return HASH_APPEND(h, eType);
  163682. }
  163683. /*
  163684. ** This function may only be called from within a pre-update callback.
  163685. ** It calculates a hash based on the primary key values of the old.* or
  163686. ** new.* row currently available and, assuming no error occurs, writes it to
  163687. ** *piHash before returning. If the primary key contains one or more NULL
  163688. ** values, *pbNullPK is set to true before returning.
  163689. **
  163690. ** If an error occurs, an SQLite error code is returned and the final values
  163691. ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
  163692. ** and the output variables are set as described above.
  163693. */
  163694. static int sessionPreupdateHash(
  163695. sqlite3_session *pSession, /* Session object that owns pTab */
  163696. SessionTable *pTab, /* Session table handle */
  163697. int bNew, /* True to hash the new.* PK */
  163698. int *piHash, /* OUT: Hash value */
  163699. int *pbNullPK /* OUT: True if there are NULL values in PK */
  163700. ){
  163701. unsigned int h = 0; /* Hash value to return */
  163702. int i; /* Used to iterate through columns */
  163703. assert( *pbNullPK==0 );
  163704. assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  163705. for(i=0; i<pTab->nCol; i++){
  163706. if( pTab->abPK[i] ){
  163707. int rc;
  163708. int eType;
  163709. sqlite3_value *pVal;
  163710. if( bNew ){
  163711. rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
  163712. }else{
  163713. rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
  163714. }
  163715. if( rc!=SQLITE_OK ) return rc;
  163716. eType = sqlite3_value_type(pVal);
  163717. h = sessionHashAppendType(h, eType);
  163718. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  163719. i64 iVal;
  163720. if( eType==SQLITE_INTEGER ){
  163721. iVal = sqlite3_value_int64(pVal);
  163722. }else{
  163723. double rVal = sqlite3_value_double(pVal);
  163724. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  163725. memcpy(&iVal, &rVal, 8);
  163726. }
  163727. h = sessionHashAppendI64(h, iVal);
  163728. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  163729. const u8 *z;
  163730. int n;
  163731. if( eType==SQLITE_TEXT ){
  163732. z = (const u8 *)sqlite3_value_text(pVal);
  163733. }else{
  163734. z = (const u8 *)sqlite3_value_blob(pVal);
  163735. }
  163736. n = sqlite3_value_bytes(pVal);
  163737. if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  163738. h = sessionHashAppendBlob(h, n, z);
  163739. }else{
  163740. assert( eType==SQLITE_NULL );
  163741. *pbNullPK = 1;
  163742. }
  163743. }
  163744. }
  163745. *piHash = (h % pTab->nChange);
  163746. return SQLITE_OK;
  163747. }
  163748. /*
  163749. ** The buffer that the argument points to contains a serialized SQL value.
  163750. ** Return the number of bytes of space occupied by the value (including
  163751. ** the type byte).
  163752. */
  163753. static int sessionSerialLen(u8 *a){
  163754. int e = *a;
  163755. int n;
  163756. if( e==0 ) return 1;
  163757. if( e==SQLITE_NULL ) return 1;
  163758. if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
  163759. return sessionVarintGet(&a[1], &n) + 1 + n;
  163760. }
  163761. /*
  163762. ** Based on the primary key values stored in change aRecord, calculate a
  163763. ** hash key. Assume the has table has nBucket buckets. The hash keys
  163764. ** calculated by this function are compatible with those calculated by
  163765. ** sessionPreupdateHash().
  163766. **
  163767. ** The bPkOnly argument is non-zero if the record at aRecord[] is from
  163768. ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
  163769. */
  163770. static unsigned int sessionChangeHash(
  163771. SessionTable *pTab, /* Table handle */
  163772. int bPkOnly, /* Record consists of PK fields only */
  163773. u8 *aRecord, /* Change record */
  163774. int nBucket /* Assume this many buckets in hash table */
  163775. ){
  163776. unsigned int h = 0; /* Value to return */
  163777. int i; /* Used to iterate through columns */
  163778. u8 *a = aRecord; /* Used to iterate through change record */
  163779. for(i=0; i<pTab->nCol; i++){
  163780. int eType = *a;
  163781. int isPK = pTab->abPK[i];
  163782. if( bPkOnly && isPK==0 ) continue;
  163783. /* It is not possible for eType to be SQLITE_NULL here. The session
  163784. ** module does not record changes for rows with NULL values stored in
  163785. ** primary key columns. */
  163786. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  163787. || eType==SQLITE_TEXT || eType==SQLITE_BLOB
  163788. || eType==SQLITE_NULL || eType==0
  163789. );
  163790. assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
  163791. if( isPK ){
  163792. a++;
  163793. h = sessionHashAppendType(h, eType);
  163794. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  163795. h = sessionHashAppendI64(h, sessionGetI64(a));
  163796. a += 8;
  163797. }else{
  163798. int n;
  163799. a += sessionVarintGet(a, &n);
  163800. h = sessionHashAppendBlob(h, n, a);
  163801. a += n;
  163802. }
  163803. }else{
  163804. a += sessionSerialLen(a);
  163805. }
  163806. }
  163807. return (h % nBucket);
  163808. }
  163809. /*
  163810. ** Arguments aLeft and aRight are pointers to change records for table pTab.
  163811. ** This function returns true if the two records apply to the same row (i.e.
  163812. ** have the same values stored in the primary key columns), or false
  163813. ** otherwise.
  163814. */
  163815. static int sessionChangeEqual(
  163816. SessionTable *pTab, /* Table used for PK definition */
  163817. int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
  163818. u8 *aLeft, /* Change record */
  163819. int bRightPkOnly, /* True if aRight[] contains PK fields only */
  163820. u8 *aRight /* Change record */
  163821. ){
  163822. u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
  163823. u8 *a2 = aRight; /* Cursor to iterate through aRight */
  163824. int iCol; /* Used to iterate through table columns */
  163825. for(iCol=0; iCol<pTab->nCol; iCol++){
  163826. if( pTab->abPK[iCol] ){
  163827. int n1 = sessionSerialLen(a1);
  163828. int n2 = sessionSerialLen(a2);
  163829. if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
  163830. return 0;
  163831. }
  163832. a1 += n1;
  163833. a2 += n2;
  163834. }else{
  163835. if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
  163836. if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
  163837. }
  163838. }
  163839. return 1;
  163840. }
  163841. /*
  163842. ** Arguments aLeft and aRight both point to buffers containing change
  163843. ** records with nCol columns. This function "merges" the two records into
  163844. ** a single records which is written to the buffer at *paOut. *paOut is
  163845. ** then set to point to one byte after the last byte written before
  163846. ** returning.
  163847. **
  163848. ** The merging of records is done as follows: For each column, if the
  163849. ** aRight record contains a value for the column, copy the value from
  163850. ** their. Otherwise, if aLeft contains a value, copy it. If neither
  163851. ** record contains a value for a given column, then neither does the
  163852. ** output record.
  163853. */
  163854. static void sessionMergeRecord(
  163855. u8 **paOut,
  163856. int nCol,
  163857. u8 *aLeft,
  163858. u8 *aRight
  163859. ){
  163860. u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
  163861. u8 *a2 = aRight; /* Cursor used to iterate through aRight */
  163862. u8 *aOut = *paOut; /* Output cursor */
  163863. int iCol; /* Used to iterate from 0 to nCol */
  163864. for(iCol=0; iCol<nCol; iCol++){
  163865. int n1 = sessionSerialLen(a1);
  163866. int n2 = sessionSerialLen(a2);
  163867. if( *a2 ){
  163868. memcpy(aOut, a2, n2);
  163869. aOut += n2;
  163870. }else{
  163871. memcpy(aOut, a1, n1);
  163872. aOut += n1;
  163873. }
  163874. a1 += n1;
  163875. a2 += n2;
  163876. }
  163877. *paOut = aOut;
  163878. }
  163879. /*
  163880. ** This is a helper function used by sessionMergeUpdate().
  163881. **
  163882. ** When this function is called, both *paOne and *paTwo point to a value
  163883. ** within a change record. Before it returns, both have been advanced so
  163884. ** as to point to the next value in the record.
  163885. **
  163886. ** If, when this function is called, *paTwo points to a valid value (i.e.
  163887. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
  163888. ** pointer is returned and *pnVal is set to the number of bytes in the
  163889. ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
  163890. ** set to the number of bytes in the value at *paOne. If *paOne points
  163891. ** to the "no value" placeholder, *pnVal is set to 1. In other words:
  163892. **
  163893. ** if( *paTwo is valid ) return *paTwo;
  163894. ** return *paOne;
  163895. **
  163896. */
  163897. static u8 *sessionMergeValue(
  163898. u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
  163899. u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
  163900. int *pnVal /* OUT: Bytes in returned value */
  163901. ){
  163902. u8 *a1 = *paOne;
  163903. u8 *a2 = *paTwo;
  163904. u8 *pRet = 0;
  163905. int n1;
  163906. assert( a1 );
  163907. if( a2 ){
  163908. int n2 = sessionSerialLen(a2);
  163909. if( *a2 ){
  163910. *pnVal = n2;
  163911. pRet = a2;
  163912. }
  163913. *paTwo = &a2[n2];
  163914. }
  163915. n1 = sessionSerialLen(a1);
  163916. if( pRet==0 ){
  163917. *pnVal = n1;
  163918. pRet = a1;
  163919. }
  163920. *paOne = &a1[n1];
  163921. return pRet;
  163922. }
  163923. /*
  163924. ** This function is used by changeset_concat() to merge two UPDATE changes
  163925. ** on the same row.
  163926. */
  163927. static int sessionMergeUpdate(
  163928. u8 **paOut, /* IN/OUT: Pointer to output buffer */
  163929. SessionTable *pTab, /* Table change pertains to */
  163930. int bPatchset, /* True if records are patchset records */
  163931. u8 *aOldRecord1, /* old.* record for first change */
  163932. u8 *aOldRecord2, /* old.* record for second change */
  163933. u8 *aNewRecord1, /* new.* record for first change */
  163934. u8 *aNewRecord2 /* new.* record for second change */
  163935. ){
  163936. u8 *aOld1 = aOldRecord1;
  163937. u8 *aOld2 = aOldRecord2;
  163938. u8 *aNew1 = aNewRecord1;
  163939. u8 *aNew2 = aNewRecord2;
  163940. u8 *aOut = *paOut;
  163941. int i;
  163942. if( bPatchset==0 ){
  163943. int bRequired = 0;
  163944. assert( aOldRecord1 && aNewRecord1 );
  163945. /* Write the old.* vector first. */
  163946. for(i=0; i<pTab->nCol; i++){
  163947. int nOld;
  163948. u8 *aOld;
  163949. int nNew;
  163950. u8 *aNew;
  163951. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  163952. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  163953. if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
  163954. if( pTab->abPK[i]==0 ) bRequired = 1;
  163955. memcpy(aOut, aOld, nOld);
  163956. aOut += nOld;
  163957. }else{
  163958. *(aOut++) = '\0';
  163959. }
  163960. }
  163961. if( !bRequired ) return 0;
  163962. }
  163963. /* Write the new.* vector */
  163964. aOld1 = aOldRecord1;
  163965. aOld2 = aOldRecord2;
  163966. aNew1 = aNewRecord1;
  163967. aNew2 = aNewRecord2;
  163968. for(i=0; i<pTab->nCol; i++){
  163969. int nOld;
  163970. u8 *aOld;
  163971. int nNew;
  163972. u8 *aNew;
  163973. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  163974. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  163975. if( bPatchset==0
  163976. && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
  163977. ){
  163978. *(aOut++) = '\0';
  163979. }else{
  163980. memcpy(aOut, aNew, nNew);
  163981. aOut += nNew;
  163982. }
  163983. }
  163984. *paOut = aOut;
  163985. return 1;
  163986. }
  163987. /*
  163988. ** This function is only called from within a pre-update-hook callback.
  163989. ** It determines if the current pre-update-hook change affects the same row
  163990. ** as the change stored in argument pChange. If so, it returns true. Otherwise
  163991. ** if the pre-update-hook does not affect the same row as pChange, it returns
  163992. ** false.
  163993. */
  163994. static int sessionPreupdateEqual(
  163995. sqlite3_session *pSession, /* Session object that owns SessionTable */
  163996. SessionTable *pTab, /* Table associated with change */
  163997. SessionChange *pChange, /* Change to compare to */
  163998. int op /* Current pre-update operation */
  163999. ){
  164000. int iCol; /* Used to iterate through columns */
  164001. u8 *a = pChange->aRecord; /* Cursor used to scan change record */
  164002. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  164003. for(iCol=0; iCol<pTab->nCol; iCol++){
  164004. if( !pTab->abPK[iCol] ){
  164005. a += sessionSerialLen(a);
  164006. }else{
  164007. sqlite3_value *pVal; /* Value returned by preupdate_new/old */
  164008. int rc; /* Error code from preupdate_new/old */
  164009. int eType = *a++; /* Type of value from change record */
  164010. /* The following calls to preupdate_new() and preupdate_old() can not
  164011. ** fail. This is because they cache their return values, and by the
  164012. ** time control flows to here they have already been called once from
  164013. ** within sessionPreupdateHash(). The first two asserts below verify
  164014. ** this (that the method has already been called). */
  164015. if( op==SQLITE_INSERT ){
  164016. /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
  164017. rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
  164018. }else{
  164019. /* assert( db->pPreUpdate->pUnpacked ); */
  164020. rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
  164021. }
  164022. assert( rc==SQLITE_OK );
  164023. if( sqlite3_value_type(pVal)!=eType ) return 0;
  164024. /* A SessionChange object never has a NULL value in a PK column */
  164025. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  164026. || eType==SQLITE_BLOB || eType==SQLITE_TEXT
  164027. );
  164028. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  164029. i64 iVal = sessionGetI64(a);
  164030. a += 8;
  164031. if( eType==SQLITE_INTEGER ){
  164032. if( sqlite3_value_int64(pVal)!=iVal ) return 0;
  164033. }else{
  164034. double rVal;
  164035. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  164036. memcpy(&rVal, &iVal, 8);
  164037. if( sqlite3_value_double(pVal)!=rVal ) return 0;
  164038. }
  164039. }else{
  164040. int n;
  164041. const u8 *z;
  164042. a += sessionVarintGet(a, &n);
  164043. if( sqlite3_value_bytes(pVal)!=n ) return 0;
  164044. if( eType==SQLITE_TEXT ){
  164045. z = sqlite3_value_text(pVal);
  164046. }else{
  164047. z = sqlite3_value_blob(pVal);
  164048. }
  164049. if( memcmp(a, z, n) ) return 0;
  164050. a += n;
  164051. break;
  164052. }
  164053. }
  164054. }
  164055. return 1;
  164056. }
  164057. /*
  164058. ** If required, grow the hash table used to store changes on table pTab
  164059. ** (part of the session pSession). If a fatal OOM error occurs, set the
  164060. ** session object to failed and return SQLITE_ERROR. Otherwise, return
  164061. ** SQLITE_OK.
  164062. **
  164063. ** It is possible that a non-fatal OOM error occurs in this function. In
  164064. ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
  164065. ** Growing the hash table in this case is a performance optimization only,
  164066. ** it is not required for correct operation.
  164067. */
  164068. static int sessionGrowHash(int bPatchset, SessionTable *pTab){
  164069. if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
  164070. int i;
  164071. SessionChange **apNew;
  164072. int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
  164073. apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
  164074. if( apNew==0 ){
  164075. if( pTab->nChange==0 ){
  164076. return SQLITE_ERROR;
  164077. }
  164078. return SQLITE_OK;
  164079. }
  164080. memset(apNew, 0, sizeof(SessionChange *) * nNew);
  164081. for(i=0; i<pTab->nChange; i++){
  164082. SessionChange *p;
  164083. SessionChange *pNext;
  164084. for(p=pTab->apChange[i]; p; p=pNext){
  164085. int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
  164086. int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
  164087. pNext = p->pNext;
  164088. p->pNext = apNew[iHash];
  164089. apNew[iHash] = p;
  164090. }
  164091. }
  164092. sqlite3_free(pTab->apChange);
  164093. pTab->nChange = nNew;
  164094. pTab->apChange = apNew;
  164095. }
  164096. return SQLITE_OK;
  164097. }
  164098. /*
  164099. ** This function queries the database for the names of the columns of table
  164100. ** zThis, in schema zDb. It is expected that the table has nCol columns. If
  164101. ** not, SQLITE_SCHEMA is returned and none of the output variables are
  164102. ** populated.
  164103. **
  164104. ** Otherwise, if they are not NULL, variable *pnCol is set to the number
  164105. ** of columns in the database table and variable *pzTab is set to point to a
  164106. ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
  164107. ** point to an array of pointers to column names. And *pabPK (again, if not
  164108. ** NULL) is set to point to an array of booleans - true if the corresponding
  164109. ** column is part of the primary key.
  164110. **
  164111. ** For example, if the table is declared as:
  164112. **
  164113. ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
  164114. **
  164115. ** Then the four output variables are populated as follows:
  164116. **
  164117. ** *pnCol = 4
  164118. ** *pzTab = "tbl1"
  164119. ** *pazCol = {"w", "x", "y", "z"}
  164120. ** *pabPK = {1, 0, 0, 1}
  164121. **
  164122. ** All returned buffers are part of the same single allocation, which must
  164123. ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
  164124. ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
  164125. ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
  164126. */
  164127. static int sessionTableInfo(
  164128. sqlite3 *db, /* Database connection */
  164129. const char *zDb, /* Name of attached database (e.g. "main") */
  164130. const char *zThis, /* Table name */
  164131. int *pnCol, /* OUT: number of columns */
  164132. const char **pzTab, /* OUT: Copy of zThis */
  164133. const char ***pazCol, /* OUT: Array of column names for table */
  164134. u8 **pabPK /* OUT: Array of booleans - true for PK col */
  164135. ){
  164136. char *zPragma;
  164137. sqlite3_stmt *pStmt;
  164138. int rc;
  164139. int nByte;
  164140. int nDbCol = 0;
  164141. int nThis;
  164142. int i;
  164143. u8 *pAlloc = 0;
  164144. char **azCol = 0;
  164145. u8 *abPK = 0;
  164146. assert( pazCol && pabPK );
  164147. nThis = sqlite3Strlen30(zThis);
  164148. zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
  164149. if( !zPragma ) return SQLITE_NOMEM;
  164150. rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  164151. sqlite3_free(zPragma);
  164152. if( rc!=SQLITE_OK ) return rc;
  164153. nByte = nThis + 1;
  164154. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  164155. nByte += sqlite3_column_bytes(pStmt, 1);
  164156. nDbCol++;
  164157. }
  164158. rc = sqlite3_reset(pStmt);
  164159. if( rc==SQLITE_OK ){
  164160. nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
  164161. pAlloc = sqlite3_malloc(nByte);
  164162. if( pAlloc==0 ){
  164163. rc = SQLITE_NOMEM;
  164164. }
  164165. }
  164166. if( rc==SQLITE_OK ){
  164167. azCol = (char **)pAlloc;
  164168. pAlloc = (u8 *)&azCol[nDbCol];
  164169. abPK = (u8 *)pAlloc;
  164170. pAlloc = &abPK[nDbCol];
  164171. if( pzTab ){
  164172. memcpy(pAlloc, zThis, nThis+1);
  164173. *pzTab = (char *)pAlloc;
  164174. pAlloc += nThis+1;
  164175. }
  164176. i = 0;
  164177. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  164178. int nName = sqlite3_column_bytes(pStmt, 1);
  164179. const unsigned char *zName = sqlite3_column_text(pStmt, 1);
  164180. if( zName==0 ) break;
  164181. memcpy(pAlloc, zName, nName+1);
  164182. azCol[i] = (char *)pAlloc;
  164183. pAlloc += nName+1;
  164184. abPK[i] = sqlite3_column_int(pStmt, 5);
  164185. i++;
  164186. }
  164187. rc = sqlite3_reset(pStmt);
  164188. }
  164189. /* If successful, populate the output variables. Otherwise, zero them and
  164190. ** free any allocation made. An error code will be returned in this case.
  164191. */
  164192. if( rc==SQLITE_OK ){
  164193. *pazCol = (const char **)azCol;
  164194. *pabPK = abPK;
  164195. *pnCol = nDbCol;
  164196. }else{
  164197. *pazCol = 0;
  164198. *pabPK = 0;
  164199. *pnCol = 0;
  164200. if( pzTab ) *pzTab = 0;
  164201. sqlite3_free(azCol);
  164202. }
  164203. sqlite3_finalize(pStmt);
  164204. return rc;
  164205. }
  164206. /*
  164207. ** This function is only called from within a pre-update handler for a
  164208. ** write to table pTab, part of session pSession. If this is the first
  164209. ** write to this table, initalize the SessionTable.nCol, azCol[] and
  164210. ** abPK[] arrays accordingly.
  164211. **
  164212. ** If an error occurs, an error code is stored in sqlite3_session.rc and
  164213. ** non-zero returned. Or, if no error occurs but the table has no primary
  164214. ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
  164215. ** indicate that updates on this table should be ignored. SessionTable.abPK
  164216. ** is set to NULL in this case.
  164217. */
  164218. static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  164219. if( pTab->nCol==0 ){
  164220. u8 *abPK;
  164221. assert( pTab->azCol==0 || pTab->abPK==0 );
  164222. pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
  164223. pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
  164224. );
  164225. if( pSession->rc==SQLITE_OK ){
  164226. int i;
  164227. for(i=0; i<pTab->nCol; i++){
  164228. if( abPK[i] ){
  164229. pTab->abPK = abPK;
  164230. break;
  164231. }
  164232. }
  164233. }
  164234. }
  164235. return (pSession->rc || pTab->abPK==0);
  164236. }
  164237. /*
  164238. ** This function is only called from with a pre-update-hook reporting a
  164239. ** change on table pTab (attached to session pSession). The type of change
  164240. ** (UPDATE, INSERT, DELETE) is specified by the first argument.
  164241. **
  164242. ** Unless one is already present or an error occurs, an entry is added
  164243. ** to the changed-rows hash table associated with table pTab.
  164244. */
  164245. static void sessionPreupdateOneChange(
  164246. int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
  164247. sqlite3_session *pSession, /* Session object pTab is attached to */
  164248. SessionTable *pTab /* Table that change applies to */
  164249. ){
  164250. int iHash;
  164251. int bNull = 0;
  164252. int rc = SQLITE_OK;
  164253. if( pSession->rc ) return;
  164254. /* Load table details if required */
  164255. if( sessionInitTable(pSession, pTab) ) return;
  164256. /* Check the number of columns in this xPreUpdate call matches the
  164257. ** number of columns in the table. */
  164258. if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
  164259. pSession->rc = SQLITE_SCHEMA;
  164260. return;
  164261. }
  164262. /* Grow the hash table if required */
  164263. if( sessionGrowHash(0, pTab) ){
  164264. pSession->rc = SQLITE_NOMEM;
  164265. return;
  164266. }
  164267. /* Calculate the hash-key for this change. If the primary key of the row
  164268. ** includes a NULL value, exit early. Such changes are ignored by the
  164269. ** session module. */
  164270. rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
  164271. if( rc!=SQLITE_OK ) goto error_out;
  164272. if( bNull==0 ){
  164273. /* Search the hash table for an existing record for this row. */
  164274. SessionChange *pC;
  164275. for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
  164276. if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
  164277. }
  164278. if( pC==0 ){
  164279. /* Create a new change object containing all the old values (if
  164280. ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
  164281. ** values (if this is an INSERT). */
  164282. SessionChange *pChange; /* New change object */
  164283. int nByte; /* Number of bytes to allocate */
  164284. int i; /* Used to iterate through columns */
  164285. assert( rc==SQLITE_OK );
  164286. pTab->nEntry++;
  164287. /* Figure out how large an allocation is required */
  164288. nByte = sizeof(SessionChange);
  164289. for(i=0; i<pTab->nCol; i++){
  164290. sqlite3_value *p = 0;
  164291. if( op!=SQLITE_INSERT ){
  164292. TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  164293. assert( trc==SQLITE_OK );
  164294. }else if( pTab->abPK[i] ){
  164295. TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  164296. assert( trc==SQLITE_OK );
  164297. }
  164298. /* This may fail if SQLite value p contains a utf-16 string that must
  164299. ** be converted to utf-8 and an OOM error occurs while doing so. */
  164300. rc = sessionSerializeValue(0, p, &nByte);
  164301. if( rc!=SQLITE_OK ) goto error_out;
  164302. }
  164303. /* Allocate the change object */
  164304. pChange = (SessionChange *)sqlite3_malloc(nByte);
  164305. if( !pChange ){
  164306. rc = SQLITE_NOMEM;
  164307. goto error_out;
  164308. }else{
  164309. memset(pChange, 0, sizeof(SessionChange));
  164310. pChange->aRecord = (u8 *)&pChange[1];
  164311. }
  164312. /* Populate the change object. None of the preupdate_old(),
  164313. ** preupdate_new() or SerializeValue() calls below may fail as all
  164314. ** required values and encodings have already been cached in memory.
  164315. ** It is not possible for an OOM to occur in this block. */
  164316. nByte = 0;
  164317. for(i=0; i<pTab->nCol; i++){
  164318. sqlite3_value *p = 0;
  164319. if( op!=SQLITE_INSERT ){
  164320. pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  164321. }else if( pTab->abPK[i] ){
  164322. pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  164323. }
  164324. sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
  164325. }
  164326. /* Add the change to the hash-table */
  164327. if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
  164328. pChange->bIndirect = 1;
  164329. }
  164330. pChange->nRecord = nByte;
  164331. pChange->op = op;
  164332. pChange->pNext = pTab->apChange[iHash];
  164333. pTab->apChange[iHash] = pChange;
  164334. }else if( pC->bIndirect ){
  164335. /* If the existing change is considered "indirect", but this current
  164336. ** change is "direct", mark the change object as direct. */
  164337. if( pSession->hook.xDepth(pSession->hook.pCtx)==0
  164338. && pSession->bIndirect==0
  164339. ){
  164340. pC->bIndirect = 0;
  164341. }
  164342. }
  164343. }
  164344. /* If an error has occurred, mark the session object as failed. */
  164345. error_out:
  164346. if( rc!=SQLITE_OK ){
  164347. pSession->rc = rc;
  164348. }
  164349. }
  164350. static int sessionFindTable(
  164351. sqlite3_session *pSession,
  164352. const char *zName,
  164353. SessionTable **ppTab
  164354. ){
  164355. int rc = SQLITE_OK;
  164356. int nName = sqlite3Strlen30(zName);
  164357. SessionTable *pRet;
  164358. /* Search for an existing table */
  164359. for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
  164360. if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
  164361. }
  164362. if( pRet==0 && pSession->bAutoAttach ){
  164363. /* If there is a table-filter configured, invoke it. If it returns 0,
  164364. ** do not automatically add the new table. */
  164365. if( pSession->xTableFilter==0
  164366. || pSession->xTableFilter(pSession->pFilterCtx, zName)
  164367. ){
  164368. rc = sqlite3session_attach(pSession, zName);
  164369. if( rc==SQLITE_OK ){
  164370. for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
  164371. assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
  164372. }
  164373. }
  164374. }
  164375. assert( rc==SQLITE_OK || pRet==0 );
  164376. *ppTab = pRet;
  164377. return rc;
  164378. }
  164379. /*
  164380. ** The 'pre-update' hook registered by this module with SQLite databases.
  164381. */
  164382. static void xPreUpdate(
  164383. void *pCtx, /* Copy of third arg to preupdate_hook() */
  164384. sqlite3 *db, /* Database handle */
  164385. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  164386. char const *zDb, /* Database name */
  164387. char const *zName, /* Table name */
  164388. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  164389. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  164390. ){
  164391. sqlite3_session *pSession;
  164392. int nDb = sqlite3Strlen30(zDb);
  164393. assert( sqlite3_mutex_held(db->mutex) );
  164394. for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
  164395. SessionTable *pTab;
  164396. /* If this session is attached to a different database ("main", "temp"
  164397. ** etc.), or if it is not currently enabled, there is nothing to do. Skip
  164398. ** to the next session object attached to this database. */
  164399. if( pSession->bEnable==0 ) continue;
  164400. if( pSession->rc ) continue;
  164401. if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
  164402. pSession->rc = sessionFindTable(pSession, zName, &pTab);
  164403. if( pTab ){
  164404. assert( pSession->rc==SQLITE_OK );
  164405. sessionPreupdateOneChange(op, pSession, pTab);
  164406. if( op==SQLITE_UPDATE ){
  164407. sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
  164408. }
  164409. }
  164410. }
  164411. }
  164412. /*
  164413. ** The pre-update hook implementations.
  164414. */
  164415. static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  164416. return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
  164417. }
  164418. static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  164419. return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
  164420. }
  164421. static int sessionPreupdateCount(void *pCtx){
  164422. return sqlite3_preupdate_count((sqlite3*)pCtx);
  164423. }
  164424. static int sessionPreupdateDepth(void *pCtx){
  164425. return sqlite3_preupdate_depth((sqlite3*)pCtx);
  164426. }
  164427. /*
  164428. ** Install the pre-update hooks on the session object passed as the only
  164429. ** argument.
  164430. */
  164431. static void sessionPreupdateHooks(
  164432. sqlite3_session *pSession
  164433. ){
  164434. pSession->hook.pCtx = (void*)pSession->db;
  164435. pSession->hook.xOld = sessionPreupdateOld;
  164436. pSession->hook.xNew = sessionPreupdateNew;
  164437. pSession->hook.xCount = sessionPreupdateCount;
  164438. pSession->hook.xDepth = sessionPreupdateDepth;
  164439. }
  164440. typedef struct SessionDiffCtx SessionDiffCtx;
  164441. struct SessionDiffCtx {
  164442. sqlite3_stmt *pStmt;
  164443. int nOldOff;
  164444. };
  164445. /*
  164446. ** The diff hook implementations.
  164447. */
  164448. static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  164449. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  164450. *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  164451. return SQLITE_OK;
  164452. }
  164453. static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  164454. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  164455. *ppVal = sqlite3_column_value(p->pStmt, iVal);
  164456. return SQLITE_OK;
  164457. }
  164458. static int sessionDiffCount(void *pCtx){
  164459. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  164460. return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
  164461. }
  164462. static int sessionDiffDepth(void *pCtx){
  164463. return 0;
  164464. }
  164465. /*
  164466. ** Install the diff hooks on the session object passed as the only
  164467. ** argument.
  164468. */
  164469. static void sessionDiffHooks(
  164470. sqlite3_session *pSession,
  164471. SessionDiffCtx *pDiffCtx
  164472. ){
  164473. pSession->hook.pCtx = (void*)pDiffCtx;
  164474. pSession->hook.xOld = sessionDiffOld;
  164475. pSession->hook.xNew = sessionDiffNew;
  164476. pSession->hook.xCount = sessionDiffCount;
  164477. pSession->hook.xDepth = sessionDiffDepth;
  164478. }
  164479. static char *sessionExprComparePK(
  164480. int nCol,
  164481. const char *zDb1, const char *zDb2,
  164482. const char *zTab,
  164483. const char **azCol, u8 *abPK
  164484. ){
  164485. int i;
  164486. const char *zSep = "";
  164487. char *zRet = 0;
  164488. for(i=0; i<nCol; i++){
  164489. if( abPK[i] ){
  164490. zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
  164491. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  164492. );
  164493. zSep = " AND ";
  164494. if( zRet==0 ) break;
  164495. }
  164496. }
  164497. return zRet;
  164498. }
  164499. static char *sessionExprCompareOther(
  164500. int nCol,
  164501. const char *zDb1, const char *zDb2,
  164502. const char *zTab,
  164503. const char **azCol, u8 *abPK
  164504. ){
  164505. int i;
  164506. const char *zSep = "";
  164507. char *zRet = 0;
  164508. int bHave = 0;
  164509. for(i=0; i<nCol; i++){
  164510. if( abPK[i]==0 ){
  164511. bHave = 1;
  164512. zRet = sqlite3_mprintf(
  164513. "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
  164514. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  164515. );
  164516. zSep = " OR ";
  164517. if( zRet==0 ) break;
  164518. }
  164519. }
  164520. if( bHave==0 ){
  164521. assert( zRet==0 );
  164522. zRet = sqlite3_mprintf("0");
  164523. }
  164524. return zRet;
  164525. }
  164526. static char *sessionSelectFindNew(
  164527. int nCol,
  164528. const char *zDb1, /* Pick rows in this db only */
  164529. const char *zDb2, /* But not in this one */
  164530. const char *zTbl, /* Table name */
  164531. const char *zExpr
  164532. ){
  164533. char *zRet = sqlite3_mprintf(
  164534. "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
  164535. " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
  164536. ")",
  164537. zDb1, zTbl, zDb2, zTbl, zExpr
  164538. );
  164539. return zRet;
  164540. }
  164541. static int sessionDiffFindNew(
  164542. int op,
  164543. sqlite3_session *pSession,
  164544. SessionTable *pTab,
  164545. const char *zDb1,
  164546. const char *zDb2,
  164547. char *zExpr
  164548. ){
  164549. int rc = SQLITE_OK;
  164550. char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
  164551. if( zStmt==0 ){
  164552. rc = SQLITE_NOMEM;
  164553. }else{
  164554. sqlite3_stmt *pStmt;
  164555. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  164556. if( rc==SQLITE_OK ){
  164557. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  164558. pDiffCtx->pStmt = pStmt;
  164559. pDiffCtx->nOldOff = 0;
  164560. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  164561. sessionPreupdateOneChange(op, pSession, pTab);
  164562. }
  164563. rc = sqlite3_finalize(pStmt);
  164564. }
  164565. sqlite3_free(zStmt);
  164566. }
  164567. return rc;
  164568. }
  164569. static int sessionDiffFindModified(
  164570. sqlite3_session *pSession,
  164571. SessionTable *pTab,
  164572. const char *zFrom,
  164573. const char *zExpr
  164574. ){
  164575. int rc = SQLITE_OK;
  164576. char *zExpr2 = sessionExprCompareOther(pTab->nCol,
  164577. pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  164578. );
  164579. if( zExpr2==0 ){
  164580. rc = SQLITE_NOMEM;
  164581. }else{
  164582. char *zStmt = sqlite3_mprintf(
  164583. "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
  164584. pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
  164585. );
  164586. if( zStmt==0 ){
  164587. rc = SQLITE_NOMEM;
  164588. }else{
  164589. sqlite3_stmt *pStmt;
  164590. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  164591. if( rc==SQLITE_OK ){
  164592. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  164593. pDiffCtx->pStmt = pStmt;
  164594. pDiffCtx->nOldOff = pTab->nCol;
  164595. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  164596. sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
  164597. }
  164598. rc = sqlite3_finalize(pStmt);
  164599. }
  164600. sqlite3_free(zStmt);
  164601. }
  164602. }
  164603. return rc;
  164604. }
  164605. SQLITE_API int sqlite3session_diff(
  164606. sqlite3_session *pSession,
  164607. const char *zFrom,
  164608. const char *zTbl,
  164609. char **pzErrMsg
  164610. ){
  164611. const char *zDb = pSession->zDb;
  164612. int rc = pSession->rc;
  164613. SessionDiffCtx d;
  164614. memset(&d, 0, sizeof(d));
  164615. sessionDiffHooks(pSession, &d);
  164616. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  164617. if( pzErrMsg ) *pzErrMsg = 0;
  164618. if( rc==SQLITE_OK ){
  164619. char *zExpr = 0;
  164620. sqlite3 *db = pSession->db;
  164621. SessionTable *pTo; /* Table zTbl */
  164622. /* Locate and if necessary initialize the target table object */
  164623. rc = sessionFindTable(pSession, zTbl, &pTo);
  164624. if( pTo==0 ) goto diff_out;
  164625. if( sessionInitTable(pSession, pTo) ){
  164626. rc = pSession->rc;
  164627. goto diff_out;
  164628. }
  164629. /* Check the table schemas match */
  164630. if( rc==SQLITE_OK ){
  164631. int bHasPk = 0;
  164632. int bMismatch = 0;
  164633. int nCol; /* Columns in zFrom.zTbl */
  164634. u8 *abPK;
  164635. const char **azCol = 0;
  164636. rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
  164637. if( rc==SQLITE_OK ){
  164638. if( pTo->nCol!=nCol ){
  164639. bMismatch = 1;
  164640. }else{
  164641. int i;
  164642. for(i=0; i<nCol; i++){
  164643. if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
  164644. if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
  164645. if( abPK[i] ) bHasPk = 1;
  164646. }
  164647. }
  164648. }
  164649. sqlite3_free((char*)azCol);
  164650. if( bMismatch ){
  164651. *pzErrMsg = sqlite3_mprintf("table schemas do not match");
  164652. rc = SQLITE_SCHEMA;
  164653. }
  164654. if( bHasPk==0 ){
  164655. /* Ignore tables with no primary keys */
  164656. goto diff_out;
  164657. }
  164658. }
  164659. if( rc==SQLITE_OK ){
  164660. zExpr = sessionExprComparePK(pTo->nCol,
  164661. zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
  164662. );
  164663. }
  164664. /* Find new rows */
  164665. if( rc==SQLITE_OK ){
  164666. rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
  164667. }
  164668. /* Find old rows */
  164669. if( rc==SQLITE_OK ){
  164670. rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
  164671. }
  164672. /* Find modified rows */
  164673. if( rc==SQLITE_OK ){
  164674. rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
  164675. }
  164676. sqlite3_free(zExpr);
  164677. }
  164678. diff_out:
  164679. sessionPreupdateHooks(pSession);
  164680. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  164681. return rc;
  164682. }
  164683. /*
  164684. ** Create a session object. This session object will record changes to
  164685. ** database zDb attached to connection db.
  164686. */
  164687. SQLITE_API int sqlite3session_create(
  164688. sqlite3 *db, /* Database handle */
  164689. const char *zDb, /* Name of db (e.g. "main") */
  164690. sqlite3_session **ppSession /* OUT: New session object */
  164691. ){
  164692. sqlite3_session *pNew; /* Newly allocated session object */
  164693. sqlite3_session *pOld; /* Session object already attached to db */
  164694. int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
  164695. /* Zero the output value in case an error occurs. */
  164696. *ppSession = 0;
  164697. /* Allocate and populate the new session object. */
  164698. pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
  164699. if( !pNew ) return SQLITE_NOMEM;
  164700. memset(pNew, 0, sizeof(sqlite3_session));
  164701. pNew->db = db;
  164702. pNew->zDb = (char *)&pNew[1];
  164703. pNew->bEnable = 1;
  164704. memcpy(pNew->zDb, zDb, nDb+1);
  164705. sessionPreupdateHooks(pNew);
  164706. /* Add the new session object to the linked list of session objects
  164707. ** attached to database handle $db. Do this under the cover of the db
  164708. ** handle mutex. */
  164709. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  164710. pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
  164711. pNew->pNext = pOld;
  164712. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  164713. *ppSession = pNew;
  164714. return SQLITE_OK;
  164715. }
  164716. /*
  164717. ** Free the list of table objects passed as the first argument. The contents
  164718. ** of the changed-rows hash tables are also deleted.
  164719. */
  164720. static void sessionDeleteTable(SessionTable *pList){
  164721. SessionTable *pNext;
  164722. SessionTable *pTab;
  164723. for(pTab=pList; pTab; pTab=pNext){
  164724. int i;
  164725. pNext = pTab->pNext;
  164726. for(i=0; i<pTab->nChange; i++){
  164727. SessionChange *p;
  164728. SessionChange *pNextChange;
  164729. for(p=pTab->apChange[i]; p; p=pNextChange){
  164730. pNextChange = p->pNext;
  164731. sqlite3_free(p);
  164732. }
  164733. }
  164734. sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
  164735. sqlite3_free(pTab->apChange);
  164736. sqlite3_free(pTab);
  164737. }
  164738. }
  164739. /*
  164740. ** Delete a session object previously allocated using sqlite3session_create().
  164741. */
  164742. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
  164743. sqlite3 *db = pSession->db;
  164744. sqlite3_session *pHead;
  164745. sqlite3_session **pp;
  164746. /* Unlink the session from the linked list of sessions attached to the
  164747. ** database handle. Hold the db mutex while doing so. */
  164748. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  164749. pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
  164750. for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
  164751. if( (*pp)==pSession ){
  164752. *pp = (*pp)->pNext;
  164753. if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
  164754. break;
  164755. }
  164756. }
  164757. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  164758. /* Delete all attached table objects. And the contents of their
  164759. ** associated hash-tables. */
  164760. sessionDeleteTable(pSession->pTable);
  164761. /* Free the session object itself. */
  164762. sqlite3_free(pSession);
  164763. }
  164764. /*
  164765. ** Set a table filter on a Session Object.
  164766. */
  164767. SQLITE_API void sqlite3session_table_filter(
  164768. sqlite3_session *pSession,
  164769. int(*xFilter)(void*, const char*),
  164770. void *pCtx /* First argument passed to xFilter */
  164771. ){
  164772. pSession->bAutoAttach = 1;
  164773. pSession->pFilterCtx = pCtx;
  164774. pSession->xTableFilter = xFilter;
  164775. }
  164776. /*
  164777. ** Attach a table to a session. All subsequent changes made to the table
  164778. ** while the session object is enabled will be recorded.
  164779. **
  164780. ** Only tables that have a PRIMARY KEY defined may be attached. It does
  164781. ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
  164782. ** or not.
  164783. */
  164784. SQLITE_API int sqlite3session_attach(
  164785. sqlite3_session *pSession, /* Session object */
  164786. const char *zName /* Table name */
  164787. ){
  164788. int rc = SQLITE_OK;
  164789. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  164790. if( !zName ){
  164791. pSession->bAutoAttach = 1;
  164792. }else{
  164793. SessionTable *pTab; /* New table object (if required) */
  164794. int nName; /* Number of bytes in string zName */
  164795. /* First search for an existing entry. If one is found, this call is
  164796. ** a no-op. Return early. */
  164797. nName = sqlite3Strlen30(zName);
  164798. for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
  164799. if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
  164800. }
  164801. if( !pTab ){
  164802. /* Allocate new SessionTable object. */
  164803. pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
  164804. if( !pTab ){
  164805. rc = SQLITE_NOMEM;
  164806. }else{
  164807. /* Populate the new SessionTable object and link it into the list.
  164808. ** The new object must be linked onto the end of the list, not
  164809. ** simply added to the start of it in order to ensure that tables
  164810. ** appear in the correct order when a changeset or patchset is
  164811. ** eventually generated. */
  164812. SessionTable **ppTab;
  164813. memset(pTab, 0, sizeof(SessionTable));
  164814. pTab->zName = (char *)&pTab[1];
  164815. memcpy(pTab->zName, zName, nName+1);
  164816. for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
  164817. *ppTab = pTab;
  164818. }
  164819. }
  164820. }
  164821. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  164822. return rc;
  164823. }
  164824. /*
  164825. ** Ensure that there is room in the buffer to append nByte bytes of data.
  164826. ** If not, use sqlite3_realloc() to grow the buffer so that there is.
  164827. **
  164828. ** If successful, return zero. Otherwise, if an OOM condition is encountered,
  164829. ** set *pRc to SQLITE_NOMEM and return non-zero.
  164830. */
  164831. static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
  164832. if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
  164833. u8 *aNew;
  164834. int nNew = p->nAlloc ? p->nAlloc : 128;
  164835. do {
  164836. nNew = nNew*2;
  164837. }while( nNew<(p->nBuf+nByte) );
  164838. aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
  164839. if( 0==aNew ){
  164840. *pRc = SQLITE_NOMEM;
  164841. }else{
  164842. p->aBuf = aNew;
  164843. p->nAlloc = nNew;
  164844. }
  164845. }
  164846. return (*pRc!=SQLITE_OK);
  164847. }
  164848. /*
  164849. ** Append the value passed as the second argument to the buffer passed
  164850. ** as the first.
  164851. **
  164852. ** This function is a no-op if *pRc is non-zero when it is called.
  164853. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
  164854. ** before returning.
  164855. */
  164856. static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
  164857. int rc = *pRc;
  164858. if( rc==SQLITE_OK ){
  164859. int nByte = 0;
  164860. rc = sessionSerializeValue(0, pVal, &nByte);
  164861. sessionBufferGrow(p, nByte, &rc);
  164862. if( rc==SQLITE_OK ){
  164863. rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
  164864. p->nBuf += nByte;
  164865. }else{
  164866. *pRc = rc;
  164867. }
  164868. }
  164869. }
  164870. /*
  164871. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164872. ** called. Otherwise, append a single byte to the buffer.
  164873. **
  164874. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164875. ** returning.
  164876. */
  164877. static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
  164878. if( 0==sessionBufferGrow(p, 1, pRc) ){
  164879. p->aBuf[p->nBuf++] = v;
  164880. }
  164881. }
  164882. /*
  164883. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164884. ** called. Otherwise, append a single varint to the buffer.
  164885. **
  164886. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164887. ** returning.
  164888. */
  164889. static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
  164890. if( 0==sessionBufferGrow(p, 9, pRc) ){
  164891. p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
  164892. }
  164893. }
  164894. /*
  164895. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164896. ** called. Otherwise, append a blob of data to the buffer.
  164897. **
  164898. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164899. ** returning.
  164900. */
  164901. static void sessionAppendBlob(
  164902. SessionBuffer *p,
  164903. const u8 *aBlob,
  164904. int nBlob,
  164905. int *pRc
  164906. ){
  164907. if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
  164908. memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
  164909. p->nBuf += nBlob;
  164910. }
  164911. }
  164912. /*
  164913. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164914. ** called. Otherwise, append a string to the buffer. All bytes in the string
  164915. ** up to (but not including) the nul-terminator are written to the buffer.
  164916. **
  164917. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164918. ** returning.
  164919. */
  164920. static void sessionAppendStr(
  164921. SessionBuffer *p,
  164922. const char *zStr,
  164923. int *pRc
  164924. ){
  164925. int nStr = sqlite3Strlen30(zStr);
  164926. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  164927. memcpy(&p->aBuf[p->nBuf], zStr, nStr);
  164928. p->nBuf += nStr;
  164929. }
  164930. }
  164931. /*
  164932. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164933. ** called. Otherwise, append the string representation of integer iVal
  164934. ** to the buffer. No nul-terminator is written.
  164935. **
  164936. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164937. ** returning.
  164938. */
  164939. static void sessionAppendInteger(
  164940. SessionBuffer *p, /* Buffer to append to */
  164941. int iVal, /* Value to write the string rep. of */
  164942. int *pRc /* IN/OUT: Error code */
  164943. ){
  164944. char aBuf[24];
  164945. sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  164946. sessionAppendStr(p, aBuf, pRc);
  164947. }
  164948. /*
  164949. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164950. ** called. Otherwise, append the string zStr enclosed in quotes (") and
  164951. ** with any embedded quote characters escaped to the buffer. No
  164952. ** nul-terminator byte is written.
  164953. **
  164954. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164955. ** returning.
  164956. */
  164957. static void sessionAppendIdent(
  164958. SessionBuffer *p, /* Buffer to a append to */
  164959. const char *zStr, /* String to quote, escape and append */
  164960. int *pRc /* IN/OUT: Error code */
  164961. ){
  164962. int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  164963. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  164964. char *zOut = (char *)&p->aBuf[p->nBuf];
  164965. const char *zIn = zStr;
  164966. *zOut++ = '"';
  164967. while( *zIn ){
  164968. if( *zIn=='"' ) *zOut++ = '"';
  164969. *zOut++ = *(zIn++);
  164970. }
  164971. *zOut++ = '"';
  164972. p->nBuf = (int)((u8 *)zOut - p->aBuf);
  164973. }
  164974. }
  164975. /*
  164976. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164977. ** called. Otherwse, it appends the serialized version of the value stored
  164978. ** in column iCol of the row that SQL statement pStmt currently points
  164979. ** to to the buffer.
  164980. */
  164981. static void sessionAppendCol(
  164982. SessionBuffer *p, /* Buffer to append to */
  164983. sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
  164984. int iCol, /* Column to read value from */
  164985. int *pRc /* IN/OUT: Error code */
  164986. ){
  164987. if( *pRc==SQLITE_OK ){
  164988. int eType = sqlite3_column_type(pStmt, iCol);
  164989. sessionAppendByte(p, (u8)eType, pRc);
  164990. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  164991. sqlite3_int64 i;
  164992. u8 aBuf[8];
  164993. if( eType==SQLITE_INTEGER ){
  164994. i = sqlite3_column_int64(pStmt, iCol);
  164995. }else{
  164996. double r = sqlite3_column_double(pStmt, iCol);
  164997. memcpy(&i, &r, 8);
  164998. }
  164999. sessionPutI64(aBuf, i);
  165000. sessionAppendBlob(p, aBuf, 8, pRc);
  165001. }
  165002. if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
  165003. u8 *z;
  165004. int nByte;
  165005. if( eType==SQLITE_BLOB ){
  165006. z = (u8 *)sqlite3_column_blob(pStmt, iCol);
  165007. }else{
  165008. z = (u8 *)sqlite3_column_text(pStmt, iCol);
  165009. }
  165010. nByte = sqlite3_column_bytes(pStmt, iCol);
  165011. if( z || (eType==SQLITE_BLOB && nByte==0) ){
  165012. sessionAppendVarint(p, nByte, pRc);
  165013. sessionAppendBlob(p, z, nByte, pRc);
  165014. }else{
  165015. *pRc = SQLITE_NOMEM;
  165016. }
  165017. }
  165018. }
  165019. }
  165020. /*
  165021. **
  165022. ** This function appends an update change to the buffer (see the comments
  165023. ** under "CHANGESET FORMAT" at the top of the file). An update change
  165024. ** consists of:
  165025. **
  165026. ** 1 byte: SQLITE_UPDATE (0x17)
  165027. ** n bytes: old.* record (see RECORD FORMAT)
  165028. ** m bytes: new.* record (see RECORD FORMAT)
  165029. **
  165030. ** The SessionChange object passed as the third argument contains the
  165031. ** values that were stored in the row when the session began (the old.*
  165032. ** values). The statement handle passed as the second argument points
  165033. ** at the current version of the row (the new.* values).
  165034. **
  165035. ** If all of the old.* values are equal to their corresponding new.* value
  165036. ** (i.e. nothing has changed), then no data at all is appended to the buffer.
  165037. **
  165038. ** Otherwise, the old.* record contains all primary key values and the
  165039. ** original values of any fields that have been modified. The new.* record
  165040. ** contains the new values of only those fields that have been modified.
  165041. */
  165042. static int sessionAppendUpdate(
  165043. SessionBuffer *pBuf, /* Buffer to append to */
  165044. int bPatchset, /* True for "patchset", 0 for "changeset" */
  165045. sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
  165046. SessionChange *p, /* Object containing old values */
  165047. u8 *abPK /* Boolean array - true for PK columns */
  165048. ){
  165049. int rc = SQLITE_OK;
  165050. SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
  165051. int bNoop = 1; /* Set to zero if any values are modified */
  165052. int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
  165053. int i; /* Used to iterate through columns */
  165054. u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
  165055. sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
  165056. sessionAppendByte(pBuf, p->bIndirect, &rc);
  165057. for(i=0; i<sqlite3_column_count(pStmt); i++){
  165058. int bChanged = 0;
  165059. int nAdvance;
  165060. int eType = *pCsr;
  165061. switch( eType ){
  165062. case SQLITE_NULL:
  165063. nAdvance = 1;
  165064. if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  165065. bChanged = 1;
  165066. }
  165067. break;
  165068. case SQLITE_FLOAT:
  165069. case SQLITE_INTEGER: {
  165070. nAdvance = 9;
  165071. if( eType==sqlite3_column_type(pStmt, i) ){
  165072. sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
  165073. if( eType==SQLITE_INTEGER ){
  165074. if( iVal==sqlite3_column_int64(pStmt, i) ) break;
  165075. }else{
  165076. double dVal;
  165077. memcpy(&dVal, &iVal, 8);
  165078. if( dVal==sqlite3_column_double(pStmt, i) ) break;
  165079. }
  165080. }
  165081. bChanged = 1;
  165082. break;
  165083. }
  165084. default: {
  165085. int n;
  165086. int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
  165087. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  165088. nAdvance = nHdr + n;
  165089. if( eType==sqlite3_column_type(pStmt, i)
  165090. && n==sqlite3_column_bytes(pStmt, i)
  165091. && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
  165092. ){
  165093. break;
  165094. }
  165095. bChanged = 1;
  165096. }
  165097. }
  165098. /* If at least one field has been modified, this is not a no-op. */
  165099. if( bChanged ) bNoop = 0;
  165100. /* Add a field to the old.* record. This is omitted if this modules is
  165101. ** currently generating a patchset. */
  165102. if( bPatchset==0 ){
  165103. if( bChanged || abPK[i] ){
  165104. sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
  165105. }else{
  165106. sessionAppendByte(pBuf, 0, &rc);
  165107. }
  165108. }
  165109. /* Add a field to the new.* record. Or the only record if currently
  165110. ** generating a patchset. */
  165111. if( bChanged || (bPatchset && abPK[i]) ){
  165112. sessionAppendCol(&buf2, pStmt, i, &rc);
  165113. }else{
  165114. sessionAppendByte(&buf2, 0, &rc);
  165115. }
  165116. pCsr += nAdvance;
  165117. }
  165118. if( bNoop ){
  165119. pBuf->nBuf = nRewind;
  165120. }else{
  165121. sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
  165122. }
  165123. sqlite3_free(buf2.aBuf);
  165124. return rc;
  165125. }
  165126. /*
  165127. ** Append a DELETE change to the buffer passed as the first argument. Use
  165128. ** the changeset format if argument bPatchset is zero, or the patchset
  165129. ** format otherwise.
  165130. */
  165131. static int sessionAppendDelete(
  165132. SessionBuffer *pBuf, /* Buffer to append to */
  165133. int bPatchset, /* True for "patchset", 0 for "changeset" */
  165134. SessionChange *p, /* Object containing old values */
  165135. int nCol, /* Number of columns in table */
  165136. u8 *abPK /* Boolean array - true for PK columns */
  165137. ){
  165138. int rc = SQLITE_OK;
  165139. sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
  165140. sessionAppendByte(pBuf, p->bIndirect, &rc);
  165141. if( bPatchset==0 ){
  165142. sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
  165143. }else{
  165144. int i;
  165145. u8 *a = p->aRecord;
  165146. for(i=0; i<nCol; i++){
  165147. u8 *pStart = a;
  165148. int eType = *a++;
  165149. switch( eType ){
  165150. case 0:
  165151. case SQLITE_NULL:
  165152. assert( abPK[i]==0 );
  165153. break;
  165154. case SQLITE_FLOAT:
  165155. case SQLITE_INTEGER:
  165156. a += 8;
  165157. break;
  165158. default: {
  165159. int n;
  165160. a += sessionVarintGet(a, &n);
  165161. a += n;
  165162. break;
  165163. }
  165164. }
  165165. if( abPK[i] ){
  165166. sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
  165167. }
  165168. }
  165169. assert( (a - p->aRecord)==p->nRecord );
  165170. }
  165171. return rc;
  165172. }
  165173. /*
  165174. ** Formulate and prepare a SELECT statement to retrieve a row from table
  165175. ** zTab in database zDb based on its primary key. i.e.
  165176. **
  165177. ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
  165178. */
  165179. static int sessionSelectStmt(
  165180. sqlite3 *db, /* Database handle */
  165181. const char *zDb, /* Database name */
  165182. const char *zTab, /* Table name */
  165183. int nCol, /* Number of columns in table */
  165184. const char **azCol, /* Names of table columns */
  165185. u8 *abPK, /* PRIMARY KEY array */
  165186. sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
  165187. ){
  165188. int rc = SQLITE_OK;
  165189. int i;
  165190. const char *zSep = "";
  165191. SessionBuffer buf = {0, 0, 0};
  165192. sessionAppendStr(&buf, "SELECT * FROM ", &rc);
  165193. sessionAppendIdent(&buf, zDb, &rc);
  165194. sessionAppendStr(&buf, ".", &rc);
  165195. sessionAppendIdent(&buf, zTab, &rc);
  165196. sessionAppendStr(&buf, " WHERE ", &rc);
  165197. for(i=0; i<nCol; i++){
  165198. if( abPK[i] ){
  165199. sessionAppendStr(&buf, zSep, &rc);
  165200. sessionAppendIdent(&buf, azCol[i], &rc);
  165201. sessionAppendStr(&buf, " = ?", &rc);
  165202. sessionAppendInteger(&buf, i+1, &rc);
  165203. zSep = " AND ";
  165204. }
  165205. }
  165206. if( rc==SQLITE_OK ){
  165207. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
  165208. }
  165209. sqlite3_free(buf.aBuf);
  165210. return rc;
  165211. }
  165212. /*
  165213. ** Bind the PRIMARY KEY values from the change passed in argument pChange
  165214. ** to the SELECT statement passed as the first argument. The SELECT statement
  165215. ** is as prepared by function sessionSelectStmt().
  165216. **
  165217. ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
  165218. ** error code (e.g. SQLITE_NOMEM) otherwise.
  165219. */
  165220. static int sessionSelectBind(
  165221. sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
  165222. int nCol, /* Number of columns in table */
  165223. u8 *abPK, /* PRIMARY KEY array */
  165224. SessionChange *pChange /* Change structure */
  165225. ){
  165226. int i;
  165227. int rc = SQLITE_OK;
  165228. u8 *a = pChange->aRecord;
  165229. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  165230. int eType = *a++;
  165231. switch( eType ){
  165232. case 0:
  165233. case SQLITE_NULL:
  165234. assert( abPK[i]==0 );
  165235. break;
  165236. case SQLITE_INTEGER: {
  165237. if( abPK[i] ){
  165238. i64 iVal = sessionGetI64(a);
  165239. rc = sqlite3_bind_int64(pSelect, i+1, iVal);
  165240. }
  165241. a += 8;
  165242. break;
  165243. }
  165244. case SQLITE_FLOAT: {
  165245. if( abPK[i] ){
  165246. double rVal;
  165247. i64 iVal = sessionGetI64(a);
  165248. memcpy(&rVal, &iVal, 8);
  165249. rc = sqlite3_bind_double(pSelect, i+1, rVal);
  165250. }
  165251. a += 8;
  165252. break;
  165253. }
  165254. case SQLITE_TEXT: {
  165255. int n;
  165256. a += sessionVarintGet(a, &n);
  165257. if( abPK[i] ){
  165258. rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
  165259. }
  165260. a += n;
  165261. break;
  165262. }
  165263. default: {
  165264. int n;
  165265. assert( eType==SQLITE_BLOB );
  165266. a += sessionVarintGet(a, &n);
  165267. if( abPK[i] ){
  165268. rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
  165269. }
  165270. a += n;
  165271. break;
  165272. }
  165273. }
  165274. }
  165275. return rc;
  165276. }
  165277. /*
  165278. ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
  165279. ** is called. Otherwise, append a serialized table header (part of the binary
  165280. ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
  165281. ** SQLite error code before returning.
  165282. */
  165283. static void sessionAppendTableHdr(
  165284. SessionBuffer *pBuf, /* Append header to this buffer */
  165285. int bPatchset, /* Use the patchset format if true */
  165286. SessionTable *pTab, /* Table object to append header for */
  165287. int *pRc /* IN/OUT: Error code */
  165288. ){
  165289. /* Write a table header */
  165290. sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
  165291. sessionAppendVarint(pBuf, pTab->nCol, pRc);
  165292. sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
  165293. sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
  165294. }
  165295. /*
  165296. ** Generate either a changeset (if argument bPatchset is zero) or a patchset
  165297. ** (if it is non-zero) based on the current contents of the session object
  165298. ** passed as the first argument.
  165299. **
  165300. ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
  165301. ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
  165302. ** occurs, an SQLite error code is returned and both output variables set
  165303. ** to 0.
  165304. */
  165305. static int sessionGenerateChangeset(
  165306. sqlite3_session *pSession, /* Session object */
  165307. int bPatchset, /* True for patchset, false for changeset */
  165308. int (*xOutput)(void *pOut, const void *pData, int nData),
  165309. void *pOut, /* First argument for xOutput */
  165310. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  165311. void **ppChangeset /* OUT: Buffer containing changeset */
  165312. ){
  165313. sqlite3 *db = pSession->db; /* Source database handle */
  165314. SessionTable *pTab; /* Used to iterate through attached tables */
  165315. SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
  165316. int rc; /* Return code */
  165317. assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
  165318. /* Zero the output variables in case an error occurs. If this session
  165319. ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
  165320. ** this call will be a no-op. */
  165321. if( xOutput==0 ){
  165322. *pnChangeset = 0;
  165323. *ppChangeset = 0;
  165324. }
  165325. if( pSession->rc ) return pSession->rc;
  165326. rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
  165327. if( rc!=SQLITE_OK ) return rc;
  165328. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  165329. for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  165330. if( pTab->nEntry ){
  165331. const char *zName = pTab->zName;
  165332. int nCol; /* Number of columns in table */
  165333. u8 *abPK; /* Primary key array */
  165334. const char **azCol = 0; /* Table columns */
  165335. int i; /* Used to iterate through hash buckets */
  165336. sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
  165337. int nRewind = buf.nBuf; /* Initial size of write buffer */
  165338. int nNoop; /* Size of buffer after writing tbl header */
  165339. /* Check the table schema is still Ok. */
  165340. rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
  165341. if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
  165342. rc = SQLITE_SCHEMA;
  165343. }
  165344. /* Write a table header */
  165345. sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
  165346. /* Build and compile a statement to execute: */
  165347. if( rc==SQLITE_OK ){
  165348. rc = sessionSelectStmt(
  165349. db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
  165350. }
  165351. nNoop = buf.nBuf;
  165352. for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
  165353. SessionChange *p; /* Used to iterate through changes */
  165354. for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
  165355. rc = sessionSelectBind(pSel, nCol, abPK, p);
  165356. if( rc!=SQLITE_OK ) continue;
  165357. if( sqlite3_step(pSel)==SQLITE_ROW ){
  165358. if( p->op==SQLITE_INSERT ){
  165359. int iCol;
  165360. sessionAppendByte(&buf, SQLITE_INSERT, &rc);
  165361. sessionAppendByte(&buf, p->bIndirect, &rc);
  165362. for(iCol=0; iCol<nCol; iCol++){
  165363. sessionAppendCol(&buf, pSel, iCol, &rc);
  165364. }
  165365. }else{
  165366. rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
  165367. }
  165368. }else if( p->op!=SQLITE_INSERT ){
  165369. rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
  165370. }
  165371. if( rc==SQLITE_OK ){
  165372. rc = sqlite3_reset(pSel);
  165373. }
  165374. /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
  165375. ** its contents to the xOutput() callback. */
  165376. if( xOutput
  165377. && rc==SQLITE_OK
  165378. && buf.nBuf>nNoop
  165379. && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
  165380. ){
  165381. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  165382. nNoop = -1;
  165383. buf.nBuf = 0;
  165384. }
  165385. }
  165386. }
  165387. sqlite3_finalize(pSel);
  165388. if( buf.nBuf==nNoop ){
  165389. buf.nBuf = nRewind;
  165390. }
  165391. sqlite3_free((char*)azCol); /* cast works around VC++ bug */
  165392. }
  165393. }
  165394. if( rc==SQLITE_OK ){
  165395. if( xOutput==0 ){
  165396. *pnChangeset = buf.nBuf;
  165397. *ppChangeset = buf.aBuf;
  165398. buf.aBuf = 0;
  165399. }else if( buf.nBuf>0 ){
  165400. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  165401. }
  165402. }
  165403. sqlite3_free(buf.aBuf);
  165404. sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
  165405. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  165406. return rc;
  165407. }
  165408. /*
  165409. ** Obtain a changeset object containing all changes recorded by the
  165410. ** session object passed as the first argument.
  165411. **
  165412. ** It is the responsibility of the caller to eventually free the buffer
  165413. ** using sqlite3_free().
  165414. */
  165415. SQLITE_API int sqlite3session_changeset(
  165416. sqlite3_session *pSession, /* Session object */
  165417. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  165418. void **ppChangeset /* OUT: Buffer containing changeset */
  165419. ){
  165420. return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  165421. }
  165422. /*
  165423. ** Streaming version of sqlite3session_changeset().
  165424. */
  165425. SQLITE_API int sqlite3session_changeset_strm(
  165426. sqlite3_session *pSession,
  165427. int (*xOutput)(void *pOut, const void *pData, int nData),
  165428. void *pOut
  165429. ){
  165430. return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
  165431. }
  165432. /*
  165433. ** Streaming version of sqlite3session_patchset().
  165434. */
  165435. SQLITE_API int sqlite3session_patchset_strm(
  165436. sqlite3_session *pSession,
  165437. int (*xOutput)(void *pOut, const void *pData, int nData),
  165438. void *pOut
  165439. ){
  165440. return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
  165441. }
  165442. /*
  165443. ** Obtain a patchset object containing all changes recorded by the
  165444. ** session object passed as the first argument.
  165445. **
  165446. ** It is the responsibility of the caller to eventually free the buffer
  165447. ** using sqlite3_free().
  165448. */
  165449. SQLITE_API int sqlite3session_patchset(
  165450. sqlite3_session *pSession, /* Session object */
  165451. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  165452. void **ppPatchset /* OUT: Buffer containing changeset */
  165453. ){
  165454. return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
  165455. }
  165456. /*
  165457. ** Enable or disable the session object passed as the first argument.
  165458. */
  165459. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
  165460. int ret;
  165461. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  165462. if( bEnable>=0 ){
  165463. pSession->bEnable = bEnable;
  165464. }
  165465. ret = pSession->bEnable;
  165466. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  165467. return ret;
  165468. }
  165469. /*
  165470. ** Enable or disable the session object passed as the first argument.
  165471. */
  165472. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
  165473. int ret;
  165474. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  165475. if( bIndirect>=0 ){
  165476. pSession->bIndirect = bIndirect;
  165477. }
  165478. ret = pSession->bIndirect;
  165479. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  165480. return ret;
  165481. }
  165482. /*
  165483. ** Return true if there have been no changes to monitored tables recorded
  165484. ** by the session object passed as the only argument.
  165485. */
  165486. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
  165487. int ret = 0;
  165488. SessionTable *pTab;
  165489. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  165490. for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
  165491. ret = (pTab->nEntry>0);
  165492. }
  165493. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  165494. return (ret==0);
  165495. }
  165496. /*
  165497. ** Do the work for either sqlite3changeset_start() or start_strm().
  165498. */
  165499. static int sessionChangesetStart(
  165500. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  165501. int (*xInput)(void *pIn, void *pData, int *pnData),
  165502. void *pIn,
  165503. int nChangeset, /* Size of buffer pChangeset in bytes */
  165504. void *pChangeset /* Pointer to buffer containing changeset */
  165505. ){
  165506. sqlite3_changeset_iter *pRet; /* Iterator to return */
  165507. int nByte; /* Number of bytes to allocate for iterator */
  165508. assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
  165509. /* Zero the output variable in case an error occurs. */
  165510. *pp = 0;
  165511. /* Allocate and initialize the iterator structure. */
  165512. nByte = sizeof(sqlite3_changeset_iter);
  165513. pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
  165514. if( !pRet ) return SQLITE_NOMEM;
  165515. memset(pRet, 0, sizeof(sqlite3_changeset_iter));
  165516. pRet->in.aData = (u8 *)pChangeset;
  165517. pRet->in.nData = nChangeset;
  165518. pRet->in.xInput = xInput;
  165519. pRet->in.pIn = pIn;
  165520. pRet->in.bEof = (xInput ? 0 : 1);
  165521. /* Populate the output variable and return success. */
  165522. *pp = pRet;
  165523. return SQLITE_OK;
  165524. }
  165525. /*
  165526. ** Create an iterator used to iterate through the contents of a changeset.
  165527. */
  165528. SQLITE_API int sqlite3changeset_start(
  165529. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  165530. int nChangeset, /* Size of buffer pChangeset in bytes */
  165531. void *pChangeset /* Pointer to buffer containing changeset */
  165532. ){
  165533. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
  165534. }
  165535. /*
  165536. ** Streaming version of sqlite3changeset_start().
  165537. */
  165538. SQLITE_API int sqlite3changeset_start_strm(
  165539. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  165540. int (*xInput)(void *pIn, void *pData, int *pnData),
  165541. void *pIn
  165542. ){
  165543. return sessionChangesetStart(pp, xInput, pIn, 0, 0);
  165544. }
  165545. /*
  165546. ** If the SessionInput object passed as the only argument is a streaming
  165547. ** object and the buffer is full, discard some data to free up space.
  165548. */
  165549. static void sessionDiscardData(SessionInput *pIn){
  165550. if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
  165551. int nMove = pIn->buf.nBuf - pIn->iNext;
  165552. assert( nMove>=0 );
  165553. if( nMove>0 ){
  165554. memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
  165555. }
  165556. pIn->buf.nBuf -= pIn->iNext;
  165557. pIn->iNext = 0;
  165558. pIn->nData = pIn->buf.nBuf;
  165559. }
  165560. }
  165561. /*
  165562. ** Ensure that there are at least nByte bytes available in the buffer. Or,
  165563. ** if there are not nByte bytes remaining in the input, that all available
  165564. ** data is in the buffer.
  165565. **
  165566. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  165567. */
  165568. static int sessionInputBuffer(SessionInput *pIn, int nByte){
  165569. int rc = SQLITE_OK;
  165570. if( pIn->xInput ){
  165571. while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
  165572. int nNew = SESSIONS_STRM_CHUNK_SIZE;
  165573. if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
  165574. if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
  165575. rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
  165576. if( nNew==0 ){
  165577. pIn->bEof = 1;
  165578. }else{
  165579. pIn->buf.nBuf += nNew;
  165580. }
  165581. }
  165582. pIn->aData = pIn->buf.aBuf;
  165583. pIn->nData = pIn->buf.nBuf;
  165584. }
  165585. }
  165586. return rc;
  165587. }
  165588. /*
  165589. ** When this function is called, *ppRec points to the start of a record
  165590. ** that contains nCol values. This function advances the pointer *ppRec
  165591. ** until it points to the byte immediately following that record.
  165592. */
  165593. static void sessionSkipRecord(
  165594. u8 **ppRec, /* IN/OUT: Record pointer */
  165595. int nCol /* Number of values in record */
  165596. ){
  165597. u8 *aRec = *ppRec;
  165598. int i;
  165599. for(i=0; i<nCol; i++){
  165600. int eType = *aRec++;
  165601. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  165602. int nByte;
  165603. aRec += sessionVarintGet((u8*)aRec, &nByte);
  165604. aRec += nByte;
  165605. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165606. aRec += 8;
  165607. }
  165608. }
  165609. *ppRec = aRec;
  165610. }
  165611. /*
  165612. ** This function sets the value of the sqlite3_value object passed as the
  165613. ** first argument to a copy of the string or blob held in the aData[]
  165614. ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
  165615. ** error occurs.
  165616. */
  165617. static int sessionValueSetStr(
  165618. sqlite3_value *pVal, /* Set the value of this object */
  165619. u8 *aData, /* Buffer containing string or blob data */
  165620. int nData, /* Size of buffer aData[] in bytes */
  165621. u8 enc /* String encoding (0 for blobs) */
  165622. ){
  165623. /* In theory this code could just pass SQLITE_TRANSIENT as the final
  165624. ** argument to sqlite3ValueSetStr() and have the copy created
  165625. ** automatically. But doing so makes it difficult to detect any OOM
  165626. ** error. Hence the code to create the copy externally. */
  165627. u8 *aCopy = sqlite3_malloc(nData+1);
  165628. if( aCopy==0 ) return SQLITE_NOMEM;
  165629. memcpy(aCopy, aData, nData);
  165630. sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
  165631. return SQLITE_OK;
  165632. }
  165633. /*
  165634. ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
  165635. ** for details.
  165636. **
  165637. ** When this function is called, *paChange points to the start of the record
  165638. ** to deserialize. Assuming no error occurs, *paChange is set to point to
  165639. ** one byte after the end of the same record before this function returns.
  165640. ** If the argument abPK is NULL, then the record contains nCol values. Or,
  165641. ** if abPK is other than NULL, then the record contains only the PK fields
  165642. ** (in other words, it is a patchset DELETE record).
  165643. **
  165644. ** If successful, each element of the apOut[] array (allocated by the caller)
  165645. ** is set to point to an sqlite3_value object containing the value read
  165646. ** from the corresponding position in the record. If that value is not
  165647. ** included in the record (i.e. because the record is part of an UPDATE change
  165648. ** and the field was not modified), the corresponding element of apOut[] is
  165649. ** set to NULL.
  165650. **
  165651. ** It is the responsibility of the caller to free all sqlite_value structures
  165652. ** using sqlite3_free().
  165653. **
  165654. ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  165655. ** The apOut[] array may have been partially populated in this case.
  165656. */
  165657. static int sessionReadRecord(
  165658. SessionInput *pIn, /* Input data */
  165659. int nCol, /* Number of values in record */
  165660. u8 *abPK, /* Array of primary key flags, or NULL */
  165661. sqlite3_value **apOut /* Write values to this array */
  165662. ){
  165663. int i; /* Used to iterate through columns */
  165664. int rc = SQLITE_OK;
  165665. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  165666. int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
  165667. if( abPK && abPK[i]==0 ) continue;
  165668. rc = sessionInputBuffer(pIn, 9);
  165669. if( rc==SQLITE_OK ){
  165670. eType = pIn->aData[pIn->iNext++];
  165671. }
  165672. assert( apOut[i]==0 );
  165673. if( eType ){
  165674. apOut[i] = sqlite3ValueNew(0);
  165675. if( !apOut[i] ) rc = SQLITE_NOMEM;
  165676. }
  165677. if( rc==SQLITE_OK ){
  165678. u8 *aVal = &pIn->aData[pIn->iNext];
  165679. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  165680. int nByte;
  165681. pIn->iNext += sessionVarintGet(aVal, &nByte);
  165682. rc = sessionInputBuffer(pIn, nByte);
  165683. if( rc==SQLITE_OK ){
  165684. u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
  165685. rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
  165686. }
  165687. pIn->iNext += nByte;
  165688. }
  165689. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165690. sqlite3_int64 v = sessionGetI64(aVal);
  165691. if( eType==SQLITE_INTEGER ){
  165692. sqlite3VdbeMemSetInt64(apOut[i], v);
  165693. }else{
  165694. double d;
  165695. memcpy(&d, &v, 8);
  165696. sqlite3VdbeMemSetDouble(apOut[i], d);
  165697. }
  165698. pIn->iNext += 8;
  165699. }
  165700. }
  165701. }
  165702. return rc;
  165703. }
  165704. /*
  165705. ** The input pointer currently points to the second byte of a table-header.
  165706. ** Specifically, to the following:
  165707. **
  165708. ** + number of columns in table (varint)
  165709. ** + array of PK flags (1 byte per column),
  165710. ** + table name (nul terminated).
  165711. **
  165712. ** This function ensures that all of the above is present in the input
  165713. ** buffer (i.e. that it can be accessed without any calls to xInput()).
  165714. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  165715. ** The input pointer is not moved.
  165716. */
  165717. static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
  165718. int rc = SQLITE_OK;
  165719. int nCol = 0;
  165720. int nRead = 0;
  165721. rc = sessionInputBuffer(pIn, 9);
  165722. if( rc==SQLITE_OK ){
  165723. nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
  165724. rc = sessionInputBuffer(pIn, nRead+nCol+100);
  165725. nRead += nCol;
  165726. }
  165727. while( rc==SQLITE_OK ){
  165728. while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
  165729. nRead++;
  165730. }
  165731. if( (pIn->iNext + nRead)<pIn->nData ) break;
  165732. rc = sessionInputBuffer(pIn, nRead + 100);
  165733. }
  165734. *pnByte = nRead+1;
  165735. return rc;
  165736. }
  165737. /*
  165738. ** The input pointer currently points to the first byte of the first field
  165739. ** of a record consisting of nCol columns. This function ensures the entire
  165740. ** record is buffered. It does not move the input pointer.
  165741. **
  165742. ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
  165743. ** the record in bytes. Otherwise, an SQLite error code is returned. The
  165744. ** final value of *pnByte is undefined in this case.
  165745. */
  165746. static int sessionChangesetBufferRecord(
  165747. SessionInput *pIn, /* Input data */
  165748. int nCol, /* Number of columns in record */
  165749. int *pnByte /* OUT: Size of record in bytes */
  165750. ){
  165751. int rc = SQLITE_OK;
  165752. int nByte = 0;
  165753. int i;
  165754. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  165755. int eType;
  165756. rc = sessionInputBuffer(pIn, nByte + 10);
  165757. if( rc==SQLITE_OK ){
  165758. eType = pIn->aData[pIn->iNext + nByte++];
  165759. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  165760. int n;
  165761. nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
  165762. nByte += n;
  165763. rc = sessionInputBuffer(pIn, nByte);
  165764. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165765. nByte += 8;
  165766. }
  165767. }
  165768. }
  165769. *pnByte = nByte;
  165770. return rc;
  165771. }
  165772. /*
  165773. ** The input pointer currently points to the second byte of a table-header.
  165774. ** Specifically, to the following:
  165775. **
  165776. ** + number of columns in table (varint)
  165777. ** + array of PK flags (1 byte per column),
  165778. ** + table name (nul terminated).
  165779. **
  165780. ** This function decodes the table-header and populates the p->nCol,
  165781. ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
  165782. ** also allocated or resized according to the new value of p->nCol. The
  165783. ** input pointer is left pointing to the byte following the table header.
  165784. **
  165785. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
  165786. ** is returned and the final values of the various fields enumerated above
  165787. ** are undefined.
  165788. */
  165789. static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
  165790. int rc;
  165791. int nCopy;
  165792. assert( p->rc==SQLITE_OK );
  165793. rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
  165794. if( rc==SQLITE_OK ){
  165795. int nByte;
  165796. int nVarint;
  165797. nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
  165798. nCopy -= nVarint;
  165799. p->in.iNext += nVarint;
  165800. nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
  165801. p->tblhdr.nBuf = 0;
  165802. sessionBufferGrow(&p->tblhdr, nByte, &rc);
  165803. }
  165804. if( rc==SQLITE_OK ){
  165805. int iPK = sizeof(sqlite3_value*)*p->nCol*2;
  165806. memset(p->tblhdr.aBuf, 0, iPK);
  165807. memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
  165808. p->in.iNext += nCopy;
  165809. }
  165810. p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
  165811. p->abPK = (u8*)&p->apValue[p->nCol*2];
  165812. p->zTab = (char*)&p->abPK[p->nCol];
  165813. return (p->rc = rc);
  165814. }
  165815. /*
  165816. ** Advance the changeset iterator to the next change.
  165817. **
  165818. ** If both paRec and pnRec are NULL, then this function works like the public
  165819. ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
  165820. ** sqlite3changeset_new() and old() APIs may be used to query for values.
  165821. **
  165822. ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
  165823. ** record is written to *paRec before returning and the number of bytes in
  165824. ** the record to *pnRec.
  165825. **
  165826. ** Either way, this function returns SQLITE_ROW if the iterator is
  165827. ** successfully advanced to the next change in the changeset, an SQLite
  165828. ** error code if an error occurs, or SQLITE_DONE if there are no further
  165829. ** changes in the changeset.
  165830. */
  165831. static int sessionChangesetNext(
  165832. sqlite3_changeset_iter *p, /* Changeset iterator */
  165833. u8 **paRec, /* If non-NULL, store record pointer here */
  165834. int *pnRec /* If non-NULL, store size of record here */
  165835. ){
  165836. int i;
  165837. u8 op;
  165838. assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
  165839. /* If the iterator is in the error-state, return immediately. */
  165840. if( p->rc!=SQLITE_OK ) return p->rc;
  165841. /* Free the current contents of p->apValue[], if any. */
  165842. if( p->apValue ){
  165843. for(i=0; i<p->nCol*2; i++){
  165844. sqlite3ValueFree(p->apValue[i]);
  165845. }
  165846. memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
  165847. }
  165848. /* Make sure the buffer contains at least 10 bytes of input data, or all
  165849. ** remaining data if there are less than 10 bytes available. This is
  165850. ** sufficient either for the 'T' or 'P' byte and the varint that follows
  165851. ** it, or for the two single byte values otherwise. */
  165852. p->rc = sessionInputBuffer(&p->in, 2);
  165853. if( p->rc!=SQLITE_OK ) return p->rc;
  165854. /* If the iterator is already at the end of the changeset, return DONE. */
  165855. if( p->in.iNext>=p->in.nData ){
  165856. return SQLITE_DONE;
  165857. }
  165858. sessionDiscardData(&p->in);
  165859. p->in.iCurrent = p->in.iNext;
  165860. op = p->in.aData[p->in.iNext++];
  165861. if( op=='T' || op=='P' ){
  165862. p->bPatchset = (op=='P');
  165863. if( sessionChangesetReadTblhdr(p) ) return p->rc;
  165864. if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
  165865. p->in.iCurrent = p->in.iNext;
  165866. op = p->in.aData[p->in.iNext++];
  165867. }
  165868. p->op = op;
  165869. p->bIndirect = p->in.aData[p->in.iNext++];
  165870. if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
  165871. return (p->rc = SQLITE_CORRUPT_BKPT);
  165872. }
  165873. if( paRec ){
  165874. int nVal; /* Number of values to buffer */
  165875. if( p->bPatchset==0 && op==SQLITE_UPDATE ){
  165876. nVal = p->nCol * 2;
  165877. }else if( p->bPatchset && op==SQLITE_DELETE ){
  165878. nVal = 0;
  165879. for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
  165880. }else{
  165881. nVal = p->nCol;
  165882. }
  165883. p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
  165884. if( p->rc!=SQLITE_OK ) return p->rc;
  165885. *paRec = &p->in.aData[p->in.iNext];
  165886. p->in.iNext += *pnRec;
  165887. }else{
  165888. /* If this is an UPDATE or DELETE, read the old.* record. */
  165889. if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
  165890. u8 *abPK = p->bPatchset ? p->abPK : 0;
  165891. p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
  165892. if( p->rc!=SQLITE_OK ) return p->rc;
  165893. }
  165894. /* If this is an INSERT or UPDATE, read the new.* record. */
  165895. if( p->op!=SQLITE_DELETE ){
  165896. p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
  165897. if( p->rc!=SQLITE_OK ) return p->rc;
  165898. }
  165899. if( p->bPatchset && p->op==SQLITE_UPDATE ){
  165900. /* If this is an UPDATE that is part of a patchset, then all PK and
  165901. ** modified fields are present in the new.* record. The old.* record
  165902. ** is currently completely empty. This block shifts the PK fields from
  165903. ** new.* to old.*, to accommodate the code that reads these arrays. */
  165904. for(i=0; i<p->nCol; i++){
  165905. assert( p->apValue[i]==0 );
  165906. assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
  165907. if( p->abPK[i] ){
  165908. p->apValue[i] = p->apValue[i+p->nCol];
  165909. p->apValue[i+p->nCol] = 0;
  165910. }
  165911. }
  165912. }
  165913. }
  165914. return SQLITE_ROW;
  165915. }
  165916. /*
  165917. ** Advance an iterator created by sqlite3changeset_start() to the next
  165918. ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
  165919. ** or SQLITE_CORRUPT.
  165920. **
  165921. ** This function may not be called on iterators passed to a conflict handler
  165922. ** callback by changeset_apply().
  165923. */
  165924. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
  165925. return sessionChangesetNext(p, 0, 0);
  165926. }
  165927. /*
  165928. ** The following function extracts information on the current change
  165929. ** from a changeset iterator. It may only be called after changeset_next()
  165930. ** has returned SQLITE_ROW.
  165931. */
  165932. SQLITE_API int sqlite3changeset_op(
  165933. sqlite3_changeset_iter *pIter, /* Iterator handle */
  165934. const char **pzTab, /* OUT: Pointer to table name */
  165935. int *pnCol, /* OUT: Number of columns in table */
  165936. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  165937. int *pbIndirect /* OUT: True if change is indirect */
  165938. ){
  165939. *pOp = pIter->op;
  165940. *pnCol = pIter->nCol;
  165941. *pzTab = pIter->zTab;
  165942. if( pbIndirect ) *pbIndirect = pIter->bIndirect;
  165943. return SQLITE_OK;
  165944. }
  165945. /*
  165946. ** Return information regarding the PRIMARY KEY and number of columns in
  165947. ** the database table affected by the change that pIter currently points
  165948. ** to. This function may only be called after changeset_next() returns
  165949. ** SQLITE_ROW.
  165950. */
  165951. SQLITE_API int sqlite3changeset_pk(
  165952. sqlite3_changeset_iter *pIter, /* Iterator object */
  165953. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  165954. int *pnCol /* OUT: Number of entries in output array */
  165955. ){
  165956. *pabPK = pIter->abPK;
  165957. if( pnCol ) *pnCol = pIter->nCol;
  165958. return SQLITE_OK;
  165959. }
  165960. /*
  165961. ** This function may only be called while the iterator is pointing to an
  165962. ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
  165963. ** Otherwise, SQLITE_MISUSE is returned.
  165964. **
  165965. ** It sets *ppValue to point to an sqlite3_value structure containing the
  165966. ** iVal'th value in the old.* record. Or, if that particular value is not
  165967. ** included in the record (because the change is an UPDATE and the field
  165968. ** was not modified and is not a PK column), set *ppValue to NULL.
  165969. **
  165970. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  165971. ** not modified. Otherwise, SQLITE_OK.
  165972. */
  165973. SQLITE_API int sqlite3changeset_old(
  165974. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  165975. int iVal, /* Index of old.* value to retrieve */
  165976. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  165977. ){
  165978. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
  165979. return SQLITE_MISUSE;
  165980. }
  165981. if( iVal<0 || iVal>=pIter->nCol ){
  165982. return SQLITE_RANGE;
  165983. }
  165984. *ppValue = pIter->apValue[iVal];
  165985. return SQLITE_OK;
  165986. }
  165987. /*
  165988. ** This function may only be called while the iterator is pointing to an
  165989. ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
  165990. ** Otherwise, SQLITE_MISUSE is returned.
  165991. **
  165992. ** It sets *ppValue to point to an sqlite3_value structure containing the
  165993. ** iVal'th value in the new.* record. Or, if that particular value is not
  165994. ** included in the record (because the change is an UPDATE and the field
  165995. ** was not modified), set *ppValue to NULL.
  165996. **
  165997. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  165998. ** not modified. Otherwise, SQLITE_OK.
  165999. */
  166000. SQLITE_API int sqlite3changeset_new(
  166001. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166002. int iVal, /* Index of new.* value to retrieve */
  166003. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  166004. ){
  166005. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
  166006. return SQLITE_MISUSE;
  166007. }
  166008. if( iVal<0 || iVal>=pIter->nCol ){
  166009. return SQLITE_RANGE;
  166010. }
  166011. *ppValue = pIter->apValue[pIter->nCol+iVal];
  166012. return SQLITE_OK;
  166013. }
  166014. /*
  166015. ** The following two macros are used internally. They are similar to the
  166016. ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
  166017. ** they omit all error checking and return a pointer to the requested value.
  166018. */
  166019. #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
  166020. #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
  166021. /*
  166022. ** This function may only be called with a changeset iterator that has been
  166023. ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
  166024. ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
  166025. **
  166026. ** If successful, *ppValue is set to point to an sqlite3_value structure
  166027. ** containing the iVal'th value of the conflicting record.
  166028. **
  166029. ** If value iVal is out-of-range or some other error occurs, an SQLite error
  166030. ** code is returned. Otherwise, SQLITE_OK.
  166031. */
  166032. SQLITE_API int sqlite3changeset_conflict(
  166033. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166034. int iVal, /* Index of conflict record value to fetch */
  166035. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  166036. ){
  166037. if( !pIter->pConflict ){
  166038. return SQLITE_MISUSE;
  166039. }
  166040. if( iVal<0 || iVal>=pIter->nCol ){
  166041. return SQLITE_RANGE;
  166042. }
  166043. *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  166044. return SQLITE_OK;
  166045. }
  166046. /*
  166047. ** This function may only be called with an iterator passed to an
  166048. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  166049. ** it sets the output variable to the total number of known foreign key
  166050. ** violations in the destination database and returns SQLITE_OK.
  166051. **
  166052. ** In all other cases this function returns SQLITE_MISUSE.
  166053. */
  166054. SQLITE_API int sqlite3changeset_fk_conflicts(
  166055. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166056. int *pnOut /* OUT: Number of FK violations */
  166057. ){
  166058. if( pIter->pConflict || pIter->apValue ){
  166059. return SQLITE_MISUSE;
  166060. }
  166061. *pnOut = pIter->nCol;
  166062. return SQLITE_OK;
  166063. }
  166064. /*
  166065. ** Finalize an iterator allocated with sqlite3changeset_start().
  166066. **
  166067. ** This function may not be called on iterators passed to a conflict handler
  166068. ** callback by changeset_apply().
  166069. */
  166070. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
  166071. int rc = SQLITE_OK;
  166072. if( p ){
  166073. int i; /* Used to iterate through p->apValue[] */
  166074. rc = p->rc;
  166075. if( p->apValue ){
  166076. for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
  166077. }
  166078. sqlite3_free(p->tblhdr.aBuf);
  166079. sqlite3_free(p->in.buf.aBuf);
  166080. sqlite3_free(p);
  166081. }
  166082. return rc;
  166083. }
  166084. static int sessionChangesetInvert(
  166085. SessionInput *pInput, /* Input changeset */
  166086. int (*xOutput)(void *pOut, const void *pData, int nData),
  166087. void *pOut,
  166088. int *pnInverted, /* OUT: Number of bytes in output changeset */
  166089. void **ppInverted /* OUT: Inverse of pChangeset */
  166090. ){
  166091. int rc = SQLITE_OK; /* Return value */
  166092. SessionBuffer sOut; /* Output buffer */
  166093. int nCol = 0; /* Number of cols in current table */
  166094. u8 *abPK = 0; /* PK array for current table */
  166095. sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
  166096. SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
  166097. /* Initialize the output buffer */
  166098. memset(&sOut, 0, sizeof(SessionBuffer));
  166099. /* Zero the output variables in case an error occurs. */
  166100. if( ppInverted ){
  166101. *ppInverted = 0;
  166102. *pnInverted = 0;
  166103. }
  166104. while( 1 ){
  166105. u8 eType;
  166106. /* Test for EOF. */
  166107. if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
  166108. if( pInput->iNext>=pInput->nData ) break;
  166109. eType = pInput->aData[pInput->iNext];
  166110. switch( eType ){
  166111. case 'T': {
  166112. /* A 'table' record consists of:
  166113. **
  166114. ** * A constant 'T' character,
  166115. ** * Number of columns in said table (a varint),
  166116. ** * An array of nCol bytes (sPK),
  166117. ** * A nul-terminated table name.
  166118. */
  166119. int nByte;
  166120. int nVar;
  166121. pInput->iNext++;
  166122. if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
  166123. goto finished_invert;
  166124. }
  166125. nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
  166126. sPK.nBuf = 0;
  166127. sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
  166128. sessionAppendByte(&sOut, eType, &rc);
  166129. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  166130. if( rc ) goto finished_invert;
  166131. pInput->iNext += nByte;
  166132. sqlite3_free(apVal);
  166133. apVal = 0;
  166134. abPK = sPK.aBuf;
  166135. break;
  166136. }
  166137. case SQLITE_INSERT:
  166138. case SQLITE_DELETE: {
  166139. int nByte;
  166140. int bIndirect = pInput->aData[pInput->iNext+1];
  166141. int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
  166142. pInput->iNext += 2;
  166143. assert( rc==SQLITE_OK );
  166144. rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
  166145. sessionAppendByte(&sOut, eType2, &rc);
  166146. sessionAppendByte(&sOut, bIndirect, &rc);
  166147. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  166148. pInput->iNext += nByte;
  166149. if( rc ) goto finished_invert;
  166150. break;
  166151. }
  166152. case SQLITE_UPDATE: {
  166153. int iCol;
  166154. if( 0==apVal ){
  166155. apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
  166156. if( 0==apVal ){
  166157. rc = SQLITE_NOMEM;
  166158. goto finished_invert;
  166159. }
  166160. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  166161. }
  166162. /* Write the header for the new UPDATE change. Same as the original. */
  166163. sessionAppendByte(&sOut, eType, &rc);
  166164. sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
  166165. /* Read the old.* and new.* records for the update change. */
  166166. pInput->iNext += 2;
  166167. rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
  166168. if( rc==SQLITE_OK ){
  166169. rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
  166170. }
  166171. /* Write the new old.* record. Consists of the PK columns from the
  166172. ** original old.* record, and the other values from the original
  166173. ** new.* record. */
  166174. for(iCol=0; iCol<nCol; iCol++){
  166175. sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
  166176. sessionAppendValue(&sOut, pVal, &rc);
  166177. }
  166178. /* Write the new new.* record. Consists of a copy of all values
  166179. ** from the original old.* record, except for the PK columns, which
  166180. ** are set to "undefined". */
  166181. for(iCol=0; iCol<nCol; iCol++){
  166182. sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
  166183. sessionAppendValue(&sOut, pVal, &rc);
  166184. }
  166185. for(iCol=0; iCol<nCol*2; iCol++){
  166186. sqlite3ValueFree(apVal[iCol]);
  166187. }
  166188. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  166189. if( rc!=SQLITE_OK ){
  166190. goto finished_invert;
  166191. }
  166192. break;
  166193. }
  166194. default:
  166195. rc = SQLITE_CORRUPT_BKPT;
  166196. goto finished_invert;
  166197. }
  166198. assert( rc==SQLITE_OK );
  166199. if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  166200. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  166201. sOut.nBuf = 0;
  166202. if( rc!=SQLITE_OK ) goto finished_invert;
  166203. }
  166204. }
  166205. assert( rc==SQLITE_OK );
  166206. if( pnInverted ){
  166207. *pnInverted = sOut.nBuf;
  166208. *ppInverted = sOut.aBuf;
  166209. sOut.aBuf = 0;
  166210. }else if( sOut.nBuf>0 ){
  166211. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  166212. }
  166213. finished_invert:
  166214. sqlite3_free(sOut.aBuf);
  166215. sqlite3_free(apVal);
  166216. sqlite3_free(sPK.aBuf);
  166217. return rc;
  166218. }
  166219. /*
  166220. ** Invert a changeset object.
  166221. */
  166222. SQLITE_API int sqlite3changeset_invert(
  166223. int nChangeset, /* Number of bytes in input */
  166224. const void *pChangeset, /* Input changeset */
  166225. int *pnInverted, /* OUT: Number of bytes in output changeset */
  166226. void **ppInverted /* OUT: Inverse of pChangeset */
  166227. ){
  166228. SessionInput sInput;
  166229. /* Set up the input stream */
  166230. memset(&sInput, 0, sizeof(SessionInput));
  166231. sInput.nData = nChangeset;
  166232. sInput.aData = (u8*)pChangeset;
  166233. return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
  166234. }
  166235. /*
  166236. ** Streaming version of sqlite3changeset_invert().
  166237. */
  166238. SQLITE_API int sqlite3changeset_invert_strm(
  166239. int (*xInput)(void *pIn, void *pData, int *pnData),
  166240. void *pIn,
  166241. int (*xOutput)(void *pOut, const void *pData, int nData),
  166242. void *pOut
  166243. ){
  166244. SessionInput sInput;
  166245. int rc;
  166246. /* Set up the input stream */
  166247. memset(&sInput, 0, sizeof(SessionInput));
  166248. sInput.xInput = xInput;
  166249. sInput.pIn = pIn;
  166250. rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
  166251. sqlite3_free(sInput.buf.aBuf);
  166252. return rc;
  166253. }
  166254. typedef struct SessionApplyCtx SessionApplyCtx;
  166255. struct SessionApplyCtx {
  166256. sqlite3 *db;
  166257. sqlite3_stmt *pDelete; /* DELETE statement */
  166258. sqlite3_stmt *pUpdate; /* UPDATE statement */
  166259. sqlite3_stmt *pInsert; /* INSERT statement */
  166260. sqlite3_stmt *pSelect; /* SELECT statement */
  166261. int nCol; /* Size of azCol[] and abPK[] arrays */
  166262. const char **azCol; /* Array of column names */
  166263. u8 *abPK; /* Boolean array - true if column is in PK */
  166264. int bDeferConstraints; /* True to defer constraints */
  166265. SessionBuffer constraints; /* Deferred constraints are stored here */
  166266. };
  166267. /*
  166268. ** Formulate a statement to DELETE a row from database db. Assuming a table
  166269. ** structure like this:
  166270. **
  166271. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  166272. **
  166273. ** The DELETE statement looks like this:
  166274. **
  166275. ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
  166276. **
  166277. ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
  166278. ** matching b and d values, or 1 otherwise. The second case comes up if the
  166279. ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
  166280. **
  166281. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
  166282. ** pointing to the prepared version of the SQL statement.
  166283. */
  166284. static int sessionDeleteRow(
  166285. sqlite3 *db, /* Database handle */
  166286. const char *zTab, /* Table name */
  166287. SessionApplyCtx *p /* Session changeset-apply context */
  166288. ){
  166289. int i;
  166290. const char *zSep = "";
  166291. int rc = SQLITE_OK;
  166292. SessionBuffer buf = {0, 0, 0};
  166293. int nPk = 0;
  166294. sessionAppendStr(&buf, "DELETE FROM ", &rc);
  166295. sessionAppendIdent(&buf, zTab, &rc);
  166296. sessionAppendStr(&buf, " WHERE ", &rc);
  166297. for(i=0; i<p->nCol; i++){
  166298. if( p->abPK[i] ){
  166299. nPk++;
  166300. sessionAppendStr(&buf, zSep, &rc);
  166301. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166302. sessionAppendStr(&buf, " = ?", &rc);
  166303. sessionAppendInteger(&buf, i+1, &rc);
  166304. zSep = " AND ";
  166305. }
  166306. }
  166307. if( nPk<p->nCol ){
  166308. sessionAppendStr(&buf, " AND (?", &rc);
  166309. sessionAppendInteger(&buf, p->nCol+1, &rc);
  166310. sessionAppendStr(&buf, " OR ", &rc);
  166311. zSep = "";
  166312. for(i=0; i<p->nCol; i++){
  166313. if( !p->abPK[i] ){
  166314. sessionAppendStr(&buf, zSep, &rc);
  166315. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166316. sessionAppendStr(&buf, " IS ?", &rc);
  166317. sessionAppendInteger(&buf, i+1, &rc);
  166318. zSep = "AND ";
  166319. }
  166320. }
  166321. sessionAppendStr(&buf, ")", &rc);
  166322. }
  166323. if( rc==SQLITE_OK ){
  166324. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
  166325. }
  166326. sqlite3_free(buf.aBuf);
  166327. return rc;
  166328. }
  166329. /*
  166330. ** Formulate and prepare a statement to UPDATE a row from database db.
  166331. ** Assuming a table structure like this:
  166332. **
  166333. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  166334. **
  166335. ** The UPDATE statement looks like this:
  166336. **
  166337. ** UPDATE x SET
  166338. ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
  166339. ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
  166340. ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
  166341. ** d = CASE WHEN ?11 THEN ?12 ELSE d END
  166342. ** WHERE a = ?1 AND c = ?7 AND (?13 OR
  166343. ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
  166344. ** )
  166345. **
  166346. ** For each column in the table, there are three variables to bind:
  166347. **
  166348. ** ?(i*3+1) The old.* value of the column, if any.
  166349. ** ?(i*3+2) A boolean flag indicating that the value is being modified.
  166350. ** ?(i*3+3) The new.* value of the column, if any.
  166351. **
  166352. ** Also, a boolean flag that, if set to true, causes the statement to update
  166353. ** a row even if the non-PK values do not match. This is required if the
  166354. ** conflict-handler is invoked with CHANGESET_DATA and returns
  166355. ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
  166356. **
  166357. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
  166358. ** pointing to the prepared version of the SQL statement.
  166359. */
  166360. static int sessionUpdateRow(
  166361. sqlite3 *db, /* Database handle */
  166362. const char *zTab, /* Table name */
  166363. SessionApplyCtx *p /* Session changeset-apply context */
  166364. ){
  166365. int rc = SQLITE_OK;
  166366. int i;
  166367. const char *zSep = "";
  166368. SessionBuffer buf = {0, 0, 0};
  166369. /* Append "UPDATE tbl SET " */
  166370. sessionAppendStr(&buf, "UPDATE ", &rc);
  166371. sessionAppendIdent(&buf, zTab, &rc);
  166372. sessionAppendStr(&buf, " SET ", &rc);
  166373. /* Append the assignments */
  166374. for(i=0; i<p->nCol; i++){
  166375. sessionAppendStr(&buf, zSep, &rc);
  166376. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166377. sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
  166378. sessionAppendInteger(&buf, i*3+2, &rc);
  166379. sessionAppendStr(&buf, " THEN ?", &rc);
  166380. sessionAppendInteger(&buf, i*3+3, &rc);
  166381. sessionAppendStr(&buf, " ELSE ", &rc);
  166382. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166383. sessionAppendStr(&buf, " END", &rc);
  166384. zSep = ", ";
  166385. }
  166386. /* Append the PK part of the WHERE clause */
  166387. sessionAppendStr(&buf, " WHERE ", &rc);
  166388. for(i=0; i<p->nCol; i++){
  166389. if( p->abPK[i] ){
  166390. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166391. sessionAppendStr(&buf, " = ?", &rc);
  166392. sessionAppendInteger(&buf, i*3+1, &rc);
  166393. sessionAppendStr(&buf, " AND ", &rc);
  166394. }
  166395. }
  166396. /* Append the non-PK part of the WHERE clause */
  166397. sessionAppendStr(&buf, " (?", &rc);
  166398. sessionAppendInteger(&buf, p->nCol*3+1, &rc);
  166399. sessionAppendStr(&buf, " OR 1", &rc);
  166400. for(i=0; i<p->nCol; i++){
  166401. if( !p->abPK[i] ){
  166402. sessionAppendStr(&buf, " AND (?", &rc);
  166403. sessionAppendInteger(&buf, i*3+2, &rc);
  166404. sessionAppendStr(&buf, "=0 OR ", &rc);
  166405. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166406. sessionAppendStr(&buf, " IS ?", &rc);
  166407. sessionAppendInteger(&buf, i*3+1, &rc);
  166408. sessionAppendStr(&buf, ")", &rc);
  166409. }
  166410. }
  166411. sessionAppendStr(&buf, ")", &rc);
  166412. if( rc==SQLITE_OK ){
  166413. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
  166414. }
  166415. sqlite3_free(buf.aBuf);
  166416. return rc;
  166417. }
  166418. /*
  166419. ** Formulate and prepare an SQL statement to query table zTab by primary
  166420. ** key. Assuming the following table structure:
  166421. **
  166422. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  166423. **
  166424. ** The SELECT statement looks like this:
  166425. **
  166426. ** SELECT * FROM x WHERE a = ?1 AND c = ?3
  166427. **
  166428. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
  166429. ** pointing to the prepared version of the SQL statement.
  166430. */
  166431. static int sessionSelectRow(
  166432. sqlite3 *db, /* Database handle */
  166433. const char *zTab, /* Table name */
  166434. SessionApplyCtx *p /* Session changeset-apply context */
  166435. ){
  166436. return sessionSelectStmt(
  166437. db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
  166438. }
  166439. /*
  166440. ** Formulate and prepare an INSERT statement to add a record to table zTab.
  166441. ** For example:
  166442. **
  166443. ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
  166444. **
  166445. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
  166446. ** pointing to the prepared version of the SQL statement.
  166447. */
  166448. static int sessionInsertRow(
  166449. sqlite3 *db, /* Database handle */
  166450. const char *zTab, /* Table name */
  166451. SessionApplyCtx *p /* Session changeset-apply context */
  166452. ){
  166453. int rc = SQLITE_OK;
  166454. int i;
  166455. SessionBuffer buf = {0, 0, 0};
  166456. sessionAppendStr(&buf, "INSERT INTO main.", &rc);
  166457. sessionAppendIdent(&buf, zTab, &rc);
  166458. sessionAppendStr(&buf, "(", &rc);
  166459. for(i=0; i<p->nCol; i++){
  166460. if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
  166461. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166462. }
  166463. sessionAppendStr(&buf, ") VALUES(?", &rc);
  166464. for(i=1; i<p->nCol; i++){
  166465. sessionAppendStr(&buf, ", ?", &rc);
  166466. }
  166467. sessionAppendStr(&buf, ")", &rc);
  166468. if( rc==SQLITE_OK ){
  166469. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
  166470. }
  166471. sqlite3_free(buf.aBuf);
  166472. return rc;
  166473. }
  166474. /*
  166475. ** A wrapper around sqlite3_bind_value() that detects an extra problem.
  166476. ** See comments in the body of this function for details.
  166477. */
  166478. static int sessionBindValue(
  166479. sqlite3_stmt *pStmt, /* Statement to bind value to */
  166480. int i, /* Parameter number to bind to */
  166481. sqlite3_value *pVal /* Value to bind */
  166482. ){
  166483. int eType = sqlite3_value_type(pVal);
  166484. /* COVERAGE: The (pVal->z==0) branch is never true using current versions
  166485. ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
  166486. ** the (pVal->z) variable remains as it was or the type of the value is
  166487. ** set to SQLITE_NULL. */
  166488. if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
  166489. /* This condition occurs when an earlier OOM in a call to
  166490. ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
  166491. ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
  166492. return SQLITE_NOMEM;
  166493. }
  166494. return sqlite3_bind_value(pStmt, i, pVal);
  166495. }
  166496. /*
  166497. ** Iterator pIter must point to an SQLITE_INSERT entry. This function
  166498. ** transfers new.* values from the current iterator entry to statement
  166499. ** pStmt. The table being inserted into has nCol columns.
  166500. **
  166501. ** New.* value $i from the iterator is bound to variable ($i+1) of
  166502. ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
  166503. ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
  166504. ** to an array nCol elements in size. In this case only those values for
  166505. ** which abPK[$i] is true are read from the iterator and bound to the
  166506. ** statement.
  166507. **
  166508. ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
  166509. */
  166510. static int sessionBindRow(
  166511. sqlite3_changeset_iter *pIter, /* Iterator to read values from */
  166512. int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
  166513. int nCol, /* Number of columns */
  166514. u8 *abPK, /* If not NULL, bind only if true */
  166515. sqlite3_stmt *pStmt /* Bind values to this statement */
  166516. ){
  166517. int i;
  166518. int rc = SQLITE_OK;
  166519. /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
  166520. ** argument iterator points to a suitable entry. Make sure that xValue
  166521. ** is one of these to guarantee that it is safe to ignore the return
  166522. ** in the code below. */
  166523. assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
  166524. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  166525. if( !abPK || abPK[i] ){
  166526. sqlite3_value *pVal;
  166527. (void)xValue(pIter, i, &pVal);
  166528. rc = sessionBindValue(pStmt, i+1, pVal);
  166529. }
  166530. }
  166531. return rc;
  166532. }
  166533. /*
  166534. ** SQL statement pSelect is as generated by the sessionSelectRow() function.
  166535. ** This function binds the primary key values from the change that changeset
  166536. ** iterator pIter points to to the SELECT and attempts to seek to the table
  166537. ** entry. If a row is found, the SELECT statement left pointing at the row
  166538. ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
  166539. ** has occured, the statement is reset and SQLITE_OK is returned. If an
  166540. ** error occurs, the statement is reset and an SQLite error code is returned.
  166541. **
  166542. ** If this function returns SQLITE_ROW, the caller must eventually reset()
  166543. ** statement pSelect. If any other value is returned, the statement does
  166544. ** not require a reset().
  166545. **
  166546. ** If the iterator currently points to an INSERT record, bind values from the
  166547. ** new.* record to the SELECT statement. Or, if it points to a DELETE or
  166548. ** UPDATE, bind values from the old.* record.
  166549. */
  166550. static int sessionSeekToRow(
  166551. sqlite3 *db, /* Database handle */
  166552. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166553. u8 *abPK, /* Primary key flags array */
  166554. sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
  166555. ){
  166556. int rc; /* Return code */
  166557. int nCol; /* Number of columns in table */
  166558. int op; /* Changset operation (SQLITE_UPDATE etc.) */
  166559. const char *zDummy; /* Unused */
  166560. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  166561. rc = sessionBindRow(pIter,
  166562. op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
  166563. nCol, abPK, pSelect
  166564. );
  166565. if( rc==SQLITE_OK ){
  166566. rc = sqlite3_step(pSelect);
  166567. if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  166568. }
  166569. return rc;
  166570. }
  166571. /*
  166572. ** Invoke the conflict handler for the change that the changeset iterator
  166573. ** currently points to.
  166574. **
  166575. ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
  166576. ** If argument pbReplace is NULL, then the type of conflict handler invoked
  166577. ** depends solely on eType, as follows:
  166578. **
  166579. ** eType value Value passed to xConflict
  166580. ** -------------------------------------------------
  166581. ** CHANGESET_DATA CHANGESET_NOTFOUND
  166582. ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
  166583. **
  166584. ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
  166585. ** record with the same primary key as the record about to be deleted, updated
  166586. ** or inserted. If such a record can be found, it is available to the conflict
  166587. ** handler as the "conflicting" record. In this case the type of conflict
  166588. ** handler invoked is as follows:
  166589. **
  166590. ** eType value PK Record found? Value passed to xConflict
  166591. ** ----------------------------------------------------------------
  166592. ** CHANGESET_DATA Yes CHANGESET_DATA
  166593. ** CHANGESET_DATA No CHANGESET_NOTFOUND
  166594. ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
  166595. ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
  166596. **
  166597. ** If pbReplace is not NULL, and a record with a matching PK is found, and
  166598. ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
  166599. ** is set to non-zero before returning SQLITE_OK.
  166600. **
  166601. ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
  166602. ** returned. Or, if the conflict handler returns an invalid value,
  166603. ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
  166604. ** this function returns SQLITE_OK.
  166605. */
  166606. static int sessionConflictHandler(
  166607. int eType, /* Either CHANGESET_DATA or CONFLICT */
  166608. SessionApplyCtx *p, /* changeset_apply() context */
  166609. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166610. int(*xConflict)(void *, int, sqlite3_changeset_iter*),
  166611. void *pCtx, /* First argument for conflict handler */
  166612. int *pbReplace /* OUT: Set to true if PK row is found */
  166613. ){
  166614. int res = 0; /* Value returned by conflict handler */
  166615. int rc;
  166616. int nCol;
  166617. int op;
  166618. const char *zDummy;
  166619. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  166620. assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  166621. assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  166622. assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
  166623. /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  166624. if( pbReplace ){
  166625. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  166626. }else{
  166627. rc = SQLITE_OK;
  166628. }
  166629. if( rc==SQLITE_ROW ){
  166630. /* There exists another row with the new.* primary key. */
  166631. pIter->pConflict = p->pSelect;
  166632. res = xConflict(pCtx, eType, pIter);
  166633. pIter->pConflict = 0;
  166634. rc = sqlite3_reset(p->pSelect);
  166635. }else if( rc==SQLITE_OK ){
  166636. if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
  166637. /* Instead of invoking the conflict handler, append the change blob
  166638. ** to the SessionApplyCtx.constraints buffer. */
  166639. u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
  166640. int nBlob = pIter->in.iNext - pIter->in.iCurrent;
  166641. sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
  166642. res = SQLITE_CHANGESET_OMIT;
  166643. }else{
  166644. /* No other row with the new.* primary key. */
  166645. res = xConflict(pCtx, eType+1, pIter);
  166646. if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
  166647. }
  166648. }
  166649. if( rc==SQLITE_OK ){
  166650. switch( res ){
  166651. case SQLITE_CHANGESET_REPLACE:
  166652. assert( pbReplace );
  166653. *pbReplace = 1;
  166654. break;
  166655. case SQLITE_CHANGESET_OMIT:
  166656. break;
  166657. case SQLITE_CHANGESET_ABORT:
  166658. rc = SQLITE_ABORT;
  166659. break;
  166660. default:
  166661. rc = SQLITE_MISUSE;
  166662. break;
  166663. }
  166664. }
  166665. return rc;
  166666. }
  166667. /*
  166668. ** Attempt to apply the change that the iterator passed as the first argument
  166669. ** currently points to to the database. If a conflict is encountered, invoke
  166670. ** the conflict handler callback.
  166671. **
  166672. ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
  166673. ** one is encountered, update or delete the row with the matching primary key
  166674. ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
  166675. ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
  166676. ** to true before returning. In this case the caller will invoke this function
  166677. ** again, this time with pbRetry set to NULL.
  166678. **
  166679. ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
  166680. ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
  166681. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
  166682. ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
  166683. ** before retrying. In this case the caller attempts to remove the conflicting
  166684. ** row before invoking this function again, this time with pbReplace set
  166685. ** to NULL.
  166686. **
  166687. ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
  166688. ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
  166689. ** returned.
  166690. */
  166691. static int sessionApplyOneOp(
  166692. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166693. SessionApplyCtx *p, /* changeset_apply() context */
  166694. int(*xConflict)(void *, int, sqlite3_changeset_iter *),
  166695. void *pCtx, /* First argument for the conflict handler */
  166696. int *pbReplace, /* OUT: True to remove PK row and retry */
  166697. int *pbRetry /* OUT: True to retry. */
  166698. ){
  166699. const char *zDummy;
  166700. int op;
  166701. int nCol;
  166702. int rc = SQLITE_OK;
  166703. assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
  166704. assert( p->azCol && p->abPK );
  166705. assert( !pbReplace || *pbReplace==0 );
  166706. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  166707. if( op==SQLITE_DELETE ){
  166708. /* Bind values to the DELETE statement. If conflict handling is required,
  166709. ** bind values for all columns and set bound variable (nCol+1) to true.
  166710. ** Or, if conflict handling is not required, bind just the PK column
  166711. ** values and, if it exists, set (nCol+1) to false. Conflict handling
  166712. ** is not required if:
  166713. **
  166714. ** * this is a patchset, or
  166715. ** * (pbRetry==0), or
  166716. ** * all columns of the table are PK columns (in this case there is
  166717. ** no (nCol+1) variable to bind to).
  166718. */
  166719. u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
  166720. rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
  166721. if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
  166722. rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
  166723. }
  166724. if( rc!=SQLITE_OK ) return rc;
  166725. sqlite3_step(p->pDelete);
  166726. rc = sqlite3_reset(p->pDelete);
  166727. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  166728. rc = sessionConflictHandler(
  166729. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  166730. );
  166731. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  166732. rc = sessionConflictHandler(
  166733. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  166734. );
  166735. }
  166736. }else if( op==SQLITE_UPDATE ){
  166737. int i;
  166738. /* Bind values to the UPDATE statement. */
  166739. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  166740. sqlite3_value *pOld = sessionChangesetOld(pIter, i);
  166741. sqlite3_value *pNew = sessionChangesetNew(pIter, i);
  166742. sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
  166743. if( pOld ){
  166744. rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
  166745. }
  166746. if( rc==SQLITE_OK && pNew ){
  166747. rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
  166748. }
  166749. }
  166750. if( rc==SQLITE_OK ){
  166751. sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
  166752. }
  166753. if( rc!=SQLITE_OK ) return rc;
  166754. /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
  166755. ** the result will be SQLITE_OK with 0 rows modified. */
  166756. sqlite3_step(p->pUpdate);
  166757. rc = sqlite3_reset(p->pUpdate);
  166758. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  166759. /* A NOTFOUND or DATA error. Search the table to see if it contains
  166760. ** a row with a matching primary key. If so, this is a DATA conflict.
  166761. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
  166762. rc = sessionConflictHandler(
  166763. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  166764. );
  166765. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  166766. /* This is always a CONSTRAINT conflict. */
  166767. rc = sessionConflictHandler(
  166768. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  166769. );
  166770. }
  166771. }else{
  166772. assert( op==SQLITE_INSERT );
  166773. rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
  166774. if( rc!=SQLITE_OK ) return rc;
  166775. sqlite3_step(p->pInsert);
  166776. rc = sqlite3_reset(p->pInsert);
  166777. if( (rc&0xff)==SQLITE_CONSTRAINT ){
  166778. rc = sessionConflictHandler(
  166779. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
  166780. );
  166781. }
  166782. }
  166783. return rc;
  166784. }
  166785. /*
  166786. ** Attempt to apply the change that the iterator passed as the first argument
  166787. ** currently points to to the database. If a conflict is encountered, invoke
  166788. ** the conflict handler callback.
  166789. **
  166790. ** The difference between this function and sessionApplyOne() is that this
  166791. ** function handles the case where the conflict-handler is invoked and
  166792. ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
  166793. ** retried in some manner.
  166794. */
  166795. static int sessionApplyOneWithRetry(
  166796. sqlite3 *db, /* Apply change to "main" db of this handle */
  166797. sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
  166798. SessionApplyCtx *pApply, /* Apply context */
  166799. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  166800. void *pCtx /* First argument passed to xConflict */
  166801. ){
  166802. int bReplace = 0;
  166803. int bRetry = 0;
  166804. int rc;
  166805. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
  166806. assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
  166807. /* If the bRetry flag is set, the change has not been applied due to an
  166808. ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
  166809. ** a row with the correct PK is present in the db, but one or more other
  166810. ** fields do not contain the expected values) and the conflict handler
  166811. ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
  166812. ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
  166813. ** the SQLITE_CHANGESET_DATA problem. */
  166814. if( bRetry ){
  166815. assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
  166816. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  166817. }
  166818. /* If the bReplace flag is set, the change is an INSERT that has not
  166819. ** been performed because the database already contains a row with the
  166820. ** specified primary key and the conflict handler returned
  166821. ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
  166822. ** before reattempting the INSERT. */
  166823. else if( bReplace ){
  166824. assert( pIter->op==SQLITE_INSERT );
  166825. rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
  166826. if( rc==SQLITE_OK ){
  166827. rc = sessionBindRow(pIter,
  166828. sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
  166829. sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
  166830. }
  166831. if( rc==SQLITE_OK ){
  166832. sqlite3_step(pApply->pDelete);
  166833. rc = sqlite3_reset(pApply->pDelete);
  166834. }
  166835. if( rc==SQLITE_OK ){
  166836. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  166837. }
  166838. if( rc==SQLITE_OK ){
  166839. rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
  166840. }
  166841. }
  166842. return rc;
  166843. }
  166844. /*
  166845. ** Retry the changes accumulated in the pApply->constraints buffer.
  166846. */
  166847. static int sessionRetryConstraints(
  166848. sqlite3 *db,
  166849. int bPatchset,
  166850. const char *zTab,
  166851. SessionApplyCtx *pApply,
  166852. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  166853. void *pCtx /* First argument passed to xConflict */
  166854. ){
  166855. int rc = SQLITE_OK;
  166856. while( pApply->constraints.nBuf ){
  166857. sqlite3_changeset_iter *pIter2 = 0;
  166858. SessionBuffer cons = pApply->constraints;
  166859. memset(&pApply->constraints, 0, sizeof(SessionBuffer));
  166860. rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
  166861. if( rc==SQLITE_OK ){
  166862. int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
  166863. int rc2;
  166864. pIter2->bPatchset = bPatchset;
  166865. pIter2->zTab = (char*)zTab;
  166866. pIter2->nCol = pApply->nCol;
  166867. pIter2->abPK = pApply->abPK;
  166868. sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
  166869. pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
  166870. if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
  166871. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
  166872. rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
  166873. }
  166874. rc2 = sqlite3changeset_finalize(pIter2);
  166875. if( rc==SQLITE_OK ) rc = rc2;
  166876. }
  166877. assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
  166878. sqlite3_free(cons.aBuf);
  166879. if( rc!=SQLITE_OK ) break;
  166880. if( pApply->constraints.nBuf>=cons.nBuf ){
  166881. /* No progress was made on the last round. */
  166882. pApply->bDeferConstraints = 0;
  166883. }
  166884. }
  166885. return rc;
  166886. }
  166887. /*
  166888. ** Argument pIter is a changeset iterator that has been initialized, but
  166889. ** not yet passed to sqlite3changeset_next(). This function applies the
  166890. ** changeset to the main database attached to handle "db". The supplied
  166891. ** conflict handler callback is invoked to resolve any conflicts encountered
  166892. ** while applying the change.
  166893. */
  166894. static int sessionChangesetApply(
  166895. sqlite3 *db, /* Apply change to "main" db of this handle */
  166896. sqlite3_changeset_iter *pIter, /* Changeset to apply */
  166897. int(*xFilter)(
  166898. void *pCtx, /* Copy of sixth arg to _apply() */
  166899. const char *zTab /* Table name */
  166900. ),
  166901. int(*xConflict)(
  166902. void *pCtx, /* Copy of fifth arg to _apply() */
  166903. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  166904. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  166905. ),
  166906. void *pCtx /* First argument passed to xConflict */
  166907. ){
  166908. int schemaMismatch = 0;
  166909. int rc; /* Return code */
  166910. const char *zTab = 0; /* Name of current table */
  166911. int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
  166912. SessionApplyCtx sApply; /* changeset_apply() context object */
  166913. int bPatchset;
  166914. assert( xConflict!=0 );
  166915. pIter->in.bNoDiscard = 1;
  166916. memset(&sApply, 0, sizeof(sApply));
  166917. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  166918. rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  166919. if( rc==SQLITE_OK ){
  166920. rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  166921. }
  166922. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
  166923. int nCol;
  166924. int op;
  166925. const char *zNew;
  166926. sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
  166927. if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
  166928. u8 *abPK;
  166929. rc = sessionRetryConstraints(
  166930. db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
  166931. );
  166932. if( rc!=SQLITE_OK ) break;
  166933. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  166934. sqlite3_finalize(sApply.pDelete);
  166935. sqlite3_finalize(sApply.pUpdate);
  166936. sqlite3_finalize(sApply.pInsert);
  166937. sqlite3_finalize(sApply.pSelect);
  166938. memset(&sApply, 0, sizeof(sApply));
  166939. sApply.db = db;
  166940. sApply.bDeferConstraints = 1;
  166941. /* If an xFilter() callback was specified, invoke it now. If the
  166942. ** xFilter callback returns zero, skip this table. If it returns
  166943. ** non-zero, proceed. */
  166944. schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
  166945. if( schemaMismatch ){
  166946. zTab = sqlite3_mprintf("%s", zNew);
  166947. if( zTab==0 ){
  166948. rc = SQLITE_NOMEM;
  166949. break;
  166950. }
  166951. nTab = (int)strlen(zTab);
  166952. sApply.azCol = (const char **)zTab;
  166953. }else{
  166954. int nMinCol = 0;
  166955. int i;
  166956. sqlite3changeset_pk(pIter, &abPK, 0);
  166957. rc = sessionTableInfo(
  166958. db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
  166959. );
  166960. if( rc!=SQLITE_OK ) break;
  166961. for(i=0; i<sApply.nCol; i++){
  166962. if( sApply.abPK[i] ) nMinCol = i+1;
  166963. }
  166964. if( sApply.nCol==0 ){
  166965. schemaMismatch = 1;
  166966. sqlite3_log(SQLITE_SCHEMA,
  166967. "sqlite3changeset_apply(): no such table: %s", zTab
  166968. );
  166969. }
  166970. else if( sApply.nCol<nCol ){
  166971. schemaMismatch = 1;
  166972. sqlite3_log(SQLITE_SCHEMA,
  166973. "sqlite3changeset_apply(): table %s has %d columns, "
  166974. "expected %d or more",
  166975. zTab, sApply.nCol, nCol
  166976. );
  166977. }
  166978. else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
  166979. schemaMismatch = 1;
  166980. sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
  166981. "primary key mismatch for table %s", zTab
  166982. );
  166983. }
  166984. else{
  166985. sApply.nCol = nCol;
  166986. if((rc = sessionSelectRow(db, zTab, &sApply))
  166987. || (rc = sessionUpdateRow(db, zTab, &sApply))
  166988. || (rc = sessionDeleteRow(db, zTab, &sApply))
  166989. || (rc = sessionInsertRow(db, zTab, &sApply))
  166990. ){
  166991. break;
  166992. }
  166993. }
  166994. nTab = sqlite3Strlen30(zTab);
  166995. }
  166996. }
  166997. /* If there is a schema mismatch on the current table, proceed to the
  166998. ** next change. A log message has already been issued. */
  166999. if( schemaMismatch ) continue;
  167000. rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
  167001. }
  167002. bPatchset = pIter->bPatchset;
  167003. if( rc==SQLITE_OK ){
  167004. rc = sqlite3changeset_finalize(pIter);
  167005. }else{
  167006. sqlite3changeset_finalize(pIter);
  167007. }
  167008. if( rc==SQLITE_OK ){
  167009. rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
  167010. }
  167011. if( rc==SQLITE_OK ){
  167012. int nFk, notUsed;
  167013. sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
  167014. if( nFk!=0 ){
  167015. int res = SQLITE_CHANGESET_ABORT;
  167016. sqlite3_changeset_iter sIter;
  167017. memset(&sIter, 0, sizeof(sIter));
  167018. sIter.nCol = nFk;
  167019. res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
  167020. if( res!=SQLITE_CHANGESET_OMIT ){
  167021. rc = SQLITE_CONSTRAINT;
  167022. }
  167023. }
  167024. }
  167025. sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
  167026. if( rc==SQLITE_OK ){
  167027. rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  167028. }else{
  167029. sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
  167030. sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  167031. }
  167032. sqlite3_finalize(sApply.pInsert);
  167033. sqlite3_finalize(sApply.pDelete);
  167034. sqlite3_finalize(sApply.pUpdate);
  167035. sqlite3_finalize(sApply.pSelect);
  167036. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  167037. sqlite3_free((char*)sApply.constraints.aBuf);
  167038. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  167039. return rc;
  167040. }
  167041. /*
  167042. ** Apply the changeset passed via pChangeset/nChangeset to the main database
  167043. ** attached to handle "db". Invoke the supplied conflict handler callback
  167044. ** to resolve any conflicts encountered while applying the change.
  167045. */
  167046. SQLITE_API int sqlite3changeset_apply(
  167047. sqlite3 *db, /* Apply change to "main" db of this handle */
  167048. int nChangeset, /* Size of changeset in bytes */
  167049. void *pChangeset, /* Changeset blob */
  167050. int(*xFilter)(
  167051. void *pCtx, /* Copy of sixth arg to _apply() */
  167052. const char *zTab /* Table name */
  167053. ),
  167054. int(*xConflict)(
  167055. void *pCtx, /* Copy of fifth arg to _apply() */
  167056. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  167057. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  167058. ),
  167059. void *pCtx /* First argument passed to xConflict */
  167060. ){
  167061. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  167062. int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
  167063. if( rc==SQLITE_OK ){
  167064. rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
  167065. }
  167066. return rc;
  167067. }
  167068. /*
  167069. ** Apply the changeset passed via xInput/pIn to the main database
  167070. ** attached to handle "db". Invoke the supplied conflict handler callback
  167071. ** to resolve any conflicts encountered while applying the change.
  167072. */
  167073. SQLITE_API int sqlite3changeset_apply_strm(
  167074. sqlite3 *db, /* Apply change to "main" db of this handle */
  167075. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  167076. void *pIn, /* First arg for xInput */
  167077. int(*xFilter)(
  167078. void *pCtx, /* Copy of sixth arg to _apply() */
  167079. const char *zTab /* Table name */
  167080. ),
  167081. int(*xConflict)(
  167082. void *pCtx, /* Copy of sixth arg to _apply() */
  167083. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  167084. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  167085. ),
  167086. void *pCtx /* First argument passed to xConflict */
  167087. ){
  167088. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  167089. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  167090. if( rc==SQLITE_OK ){
  167091. rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
  167092. }
  167093. return rc;
  167094. }
  167095. /*
  167096. ** sqlite3_changegroup handle.
  167097. */
  167098. struct sqlite3_changegroup {
  167099. int rc; /* Error code */
  167100. int bPatch; /* True to accumulate patchsets */
  167101. SessionTable *pList; /* List of tables in current patch */
  167102. };
  167103. /*
  167104. ** This function is called to merge two changes to the same row together as
  167105. ** part of an sqlite3changeset_concat() operation. A new change object is
  167106. ** allocated and a pointer to it stored in *ppNew.
  167107. */
  167108. static int sessionChangeMerge(
  167109. SessionTable *pTab, /* Table structure */
  167110. int bPatchset, /* True for patchsets */
  167111. SessionChange *pExist, /* Existing change */
  167112. int op2, /* Second change operation */
  167113. int bIndirect, /* True if second change is indirect */
  167114. u8 *aRec, /* Second change record */
  167115. int nRec, /* Number of bytes in aRec */
  167116. SessionChange **ppNew /* OUT: Merged change */
  167117. ){
  167118. SessionChange *pNew = 0;
  167119. if( !pExist ){
  167120. pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
  167121. if( !pNew ){
  167122. return SQLITE_NOMEM;
  167123. }
  167124. memset(pNew, 0, sizeof(SessionChange));
  167125. pNew->op = op2;
  167126. pNew->bIndirect = bIndirect;
  167127. pNew->nRecord = nRec;
  167128. pNew->aRecord = (u8*)&pNew[1];
  167129. memcpy(pNew->aRecord, aRec, nRec);
  167130. }else{
  167131. int op1 = pExist->op;
  167132. /*
  167133. ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
  167134. ** op1=INSERT, op2=UPDATE -> INSERT.
  167135. ** op1=INSERT, op2=DELETE -> (none)
  167136. **
  167137. ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
  167138. ** op1=UPDATE, op2=UPDATE -> UPDATE.
  167139. ** op1=UPDATE, op2=DELETE -> DELETE.
  167140. **
  167141. ** op1=DELETE, op2=INSERT -> UPDATE.
  167142. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
  167143. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
  167144. */
  167145. if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
  167146. || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
  167147. || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
  167148. || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
  167149. ){
  167150. pNew = pExist;
  167151. }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
  167152. sqlite3_free(pExist);
  167153. assert( pNew==0 );
  167154. }else{
  167155. u8 *aExist = pExist->aRecord;
  167156. int nByte;
  167157. u8 *aCsr;
  167158. /* Allocate a new SessionChange object. Ensure that the aRecord[]
  167159. ** buffer of the new object is large enough to hold any record that
  167160. ** may be generated by combining the input records. */
  167161. nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
  167162. pNew = (SessionChange *)sqlite3_malloc(nByte);
  167163. if( !pNew ){
  167164. sqlite3_free(pExist);
  167165. return SQLITE_NOMEM;
  167166. }
  167167. memset(pNew, 0, sizeof(SessionChange));
  167168. pNew->bIndirect = (bIndirect && pExist->bIndirect);
  167169. aCsr = pNew->aRecord = (u8 *)&pNew[1];
  167170. if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
  167171. u8 *a1 = aRec;
  167172. assert( op2==SQLITE_UPDATE );
  167173. pNew->op = SQLITE_INSERT;
  167174. if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
  167175. sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
  167176. }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
  167177. assert( op2==SQLITE_INSERT );
  167178. pNew->op = SQLITE_UPDATE;
  167179. if( bPatchset ){
  167180. memcpy(aCsr, aRec, nRec);
  167181. aCsr += nRec;
  167182. }else{
  167183. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
  167184. sqlite3_free(pNew);
  167185. pNew = 0;
  167186. }
  167187. }
  167188. }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
  167189. u8 *a1 = aExist;
  167190. u8 *a2 = aRec;
  167191. assert( op1==SQLITE_UPDATE );
  167192. if( bPatchset==0 ){
  167193. sessionSkipRecord(&a1, pTab->nCol);
  167194. sessionSkipRecord(&a2, pTab->nCol);
  167195. }
  167196. pNew->op = SQLITE_UPDATE;
  167197. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
  167198. sqlite3_free(pNew);
  167199. pNew = 0;
  167200. }
  167201. }else{ /* UPDATE + DELETE */
  167202. assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
  167203. pNew->op = SQLITE_DELETE;
  167204. if( bPatchset ){
  167205. memcpy(aCsr, aRec, nRec);
  167206. aCsr += nRec;
  167207. }else{
  167208. sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
  167209. }
  167210. }
  167211. if( pNew ){
  167212. pNew->nRecord = (int)(aCsr - pNew->aRecord);
  167213. }
  167214. sqlite3_free(pExist);
  167215. }
  167216. }
  167217. *ppNew = pNew;
  167218. return SQLITE_OK;
  167219. }
  167220. /*
  167221. ** Add all changes in the changeset traversed by the iterator passed as
  167222. ** the first argument to the changegroup hash tables.
  167223. */
  167224. static int sessionChangesetToHash(
  167225. sqlite3_changeset_iter *pIter, /* Iterator to read from */
  167226. sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
  167227. ){
  167228. u8 *aRec;
  167229. int nRec;
  167230. int rc = SQLITE_OK;
  167231. SessionTable *pTab = 0;
  167232. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
  167233. const char *zNew;
  167234. int nCol;
  167235. int op;
  167236. int iHash;
  167237. int bIndirect;
  167238. SessionChange *pChange;
  167239. SessionChange *pExist = 0;
  167240. SessionChange **pp;
  167241. if( pGrp->pList==0 ){
  167242. pGrp->bPatch = pIter->bPatchset;
  167243. }else if( pIter->bPatchset!=pGrp->bPatch ){
  167244. rc = SQLITE_ERROR;
  167245. break;
  167246. }
  167247. sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
  167248. if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
  167249. /* Search the list for a matching table */
  167250. int nNew = (int)strlen(zNew);
  167251. u8 *abPK;
  167252. sqlite3changeset_pk(pIter, &abPK, 0);
  167253. for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
  167254. if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
  167255. }
  167256. if( !pTab ){
  167257. SessionTable **ppTab;
  167258. pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
  167259. if( !pTab ){
  167260. rc = SQLITE_NOMEM;
  167261. break;
  167262. }
  167263. memset(pTab, 0, sizeof(SessionTable));
  167264. pTab->nCol = nCol;
  167265. pTab->abPK = (u8*)&pTab[1];
  167266. memcpy(pTab->abPK, abPK, nCol);
  167267. pTab->zName = (char*)&pTab->abPK[nCol];
  167268. memcpy(pTab->zName, zNew, nNew+1);
  167269. /* The new object must be linked on to the end of the list, not
  167270. ** simply added to the start of it. This is to ensure that the
  167271. ** tables within the output of sqlite3changegroup_output() are in
  167272. ** the right order. */
  167273. for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
  167274. *ppTab = pTab;
  167275. }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
  167276. rc = SQLITE_SCHEMA;
  167277. break;
  167278. }
  167279. }
  167280. if( sessionGrowHash(pIter->bPatchset, pTab) ){
  167281. rc = SQLITE_NOMEM;
  167282. break;
  167283. }
  167284. iHash = sessionChangeHash(
  167285. pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
  167286. );
  167287. /* Search for existing entry. If found, remove it from the hash table.
  167288. ** Code below may link it back in.
  167289. */
  167290. for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
  167291. int bPkOnly1 = 0;
  167292. int bPkOnly2 = 0;
  167293. if( pIter->bPatchset ){
  167294. bPkOnly1 = (*pp)->op==SQLITE_DELETE;
  167295. bPkOnly2 = op==SQLITE_DELETE;
  167296. }
  167297. if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
  167298. pExist = *pp;
  167299. *pp = (*pp)->pNext;
  167300. pTab->nEntry--;
  167301. break;
  167302. }
  167303. }
  167304. rc = sessionChangeMerge(pTab,
  167305. pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
  167306. );
  167307. if( rc ) break;
  167308. if( pChange ){
  167309. pChange->pNext = pTab->apChange[iHash];
  167310. pTab->apChange[iHash] = pChange;
  167311. pTab->nEntry++;
  167312. }
  167313. }
  167314. if( rc==SQLITE_OK ) rc = pIter->rc;
  167315. return rc;
  167316. }
  167317. /*
  167318. ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
  167319. ** added to the changegroup object passed as the first argument.
  167320. **
  167321. ** If xOutput is not NULL, then the changeset/patchset is returned to the
  167322. ** user via one or more calls to xOutput, as with the other streaming
  167323. ** interfaces.
  167324. **
  167325. ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
  167326. ** buffer containing the output changeset before this function returns. In
  167327. ** this case (*pnOut) is set to the size of the output buffer in bytes. It
  167328. ** is the responsibility of the caller to free the output buffer using
  167329. ** sqlite3_free() when it is no longer required.
  167330. **
  167331. ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
  167332. ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
  167333. ** are both set to 0 before returning.
  167334. */
  167335. static int sessionChangegroupOutput(
  167336. sqlite3_changegroup *pGrp,
  167337. int (*xOutput)(void *pOut, const void *pData, int nData),
  167338. void *pOut,
  167339. int *pnOut,
  167340. void **ppOut
  167341. ){
  167342. int rc = SQLITE_OK;
  167343. SessionBuffer buf = {0, 0, 0};
  167344. SessionTable *pTab;
  167345. assert( xOutput==0 || (ppOut==0 && pnOut==0) );
  167346. /* Create the serialized output changeset based on the contents of the
  167347. ** hash tables attached to the SessionTable objects in list p->pList.
  167348. */
  167349. for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  167350. int i;
  167351. if( pTab->nEntry==0 ) continue;
  167352. sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
  167353. for(i=0; i<pTab->nChange; i++){
  167354. SessionChange *p;
  167355. for(p=pTab->apChange[i]; p; p=p->pNext){
  167356. sessionAppendByte(&buf, p->op, &rc);
  167357. sessionAppendByte(&buf, p->bIndirect, &rc);
  167358. sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
  167359. }
  167360. }
  167361. if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  167362. rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  167363. buf.nBuf = 0;
  167364. }
  167365. }
  167366. if( rc==SQLITE_OK ){
  167367. if( xOutput ){
  167368. if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  167369. }else{
  167370. *ppOut = buf.aBuf;
  167371. *pnOut = buf.nBuf;
  167372. buf.aBuf = 0;
  167373. }
  167374. }
  167375. sqlite3_free(buf.aBuf);
  167376. return rc;
  167377. }
  167378. /*
  167379. ** Allocate a new, empty, sqlite3_changegroup.
  167380. */
  167381. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
  167382. int rc = SQLITE_OK; /* Return code */
  167383. sqlite3_changegroup *p; /* New object */
  167384. p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
  167385. if( p==0 ){
  167386. rc = SQLITE_NOMEM;
  167387. }else{
  167388. memset(p, 0, sizeof(sqlite3_changegroup));
  167389. }
  167390. *pp = p;
  167391. return rc;
  167392. }
  167393. /*
  167394. ** Add the changeset currently stored in buffer pData, size nData bytes,
  167395. ** to changeset-group p.
  167396. */
  167397. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
  167398. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  167399. int rc; /* Return code */
  167400. rc = sqlite3changeset_start(&pIter, nData, pData);
  167401. if( rc==SQLITE_OK ){
  167402. rc = sessionChangesetToHash(pIter, pGrp);
  167403. }
  167404. sqlite3changeset_finalize(pIter);
  167405. return rc;
  167406. }
  167407. /*
  167408. ** Obtain a buffer containing a changeset representing the concatenation
  167409. ** of all changesets added to the group so far.
  167410. */
  167411. SQLITE_API int sqlite3changegroup_output(
  167412. sqlite3_changegroup *pGrp,
  167413. int *pnData,
  167414. void **ppData
  167415. ){
  167416. return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
  167417. }
  167418. /*
  167419. ** Streaming versions of changegroup_add().
  167420. */
  167421. SQLITE_API int sqlite3changegroup_add_strm(
  167422. sqlite3_changegroup *pGrp,
  167423. int (*xInput)(void *pIn, void *pData, int *pnData),
  167424. void *pIn
  167425. ){
  167426. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  167427. int rc; /* Return code */
  167428. rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  167429. if( rc==SQLITE_OK ){
  167430. rc = sessionChangesetToHash(pIter, pGrp);
  167431. }
  167432. sqlite3changeset_finalize(pIter);
  167433. return rc;
  167434. }
  167435. /*
  167436. ** Streaming versions of changegroup_output().
  167437. */
  167438. SQLITE_API int sqlite3changegroup_output_strm(
  167439. sqlite3_changegroup *pGrp,
  167440. int (*xOutput)(void *pOut, const void *pData, int nData),
  167441. void *pOut
  167442. ){
  167443. return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
  167444. }
  167445. /*
  167446. ** Delete a changegroup object.
  167447. */
  167448. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  167449. if( pGrp ){
  167450. sessionDeleteTable(pGrp->pList);
  167451. sqlite3_free(pGrp);
  167452. }
  167453. }
  167454. /*
  167455. ** Combine two changesets together.
  167456. */
  167457. SQLITE_API int sqlite3changeset_concat(
  167458. int nLeft, /* Number of bytes in lhs input */
  167459. void *pLeft, /* Lhs input changeset */
  167460. int nRight /* Number of bytes in rhs input */,
  167461. void *pRight, /* Rhs input changeset */
  167462. int *pnOut, /* OUT: Number of bytes in output changeset */
  167463. void **ppOut /* OUT: changeset (left <concat> right) */
  167464. ){
  167465. sqlite3_changegroup *pGrp;
  167466. int rc;
  167467. rc = sqlite3changegroup_new(&pGrp);
  167468. if( rc==SQLITE_OK ){
  167469. rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
  167470. }
  167471. if( rc==SQLITE_OK ){
  167472. rc = sqlite3changegroup_add(pGrp, nRight, pRight);
  167473. }
  167474. if( rc==SQLITE_OK ){
  167475. rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  167476. }
  167477. sqlite3changegroup_delete(pGrp);
  167478. return rc;
  167479. }
  167480. /*
  167481. ** Streaming version of sqlite3changeset_concat().
  167482. */
  167483. SQLITE_API int sqlite3changeset_concat_strm(
  167484. int (*xInputA)(void *pIn, void *pData, int *pnData),
  167485. void *pInA,
  167486. int (*xInputB)(void *pIn, void *pData, int *pnData),
  167487. void *pInB,
  167488. int (*xOutput)(void *pOut, const void *pData, int nData),
  167489. void *pOut
  167490. ){
  167491. sqlite3_changegroup *pGrp;
  167492. int rc;
  167493. rc = sqlite3changegroup_new(&pGrp);
  167494. if( rc==SQLITE_OK ){
  167495. rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
  167496. }
  167497. if( rc==SQLITE_OK ){
  167498. rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
  167499. }
  167500. if( rc==SQLITE_OK ){
  167501. rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
  167502. }
  167503. sqlite3changegroup_delete(pGrp);
  167504. return rc;
  167505. }
  167506. #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
  167507. /************** End of sqlite3session.c **************************************/
  167508. /************** Begin file json1.c *******************************************/
  167509. /*
  167510. ** 2015-08-12
  167511. **
  167512. ** The author disclaims copyright to this source code. In place of
  167513. ** a legal notice, here is a blessing:
  167514. **
  167515. ** May you do good and not evil.
  167516. ** May you find forgiveness for yourself and forgive others.
  167517. ** May you share freely, never taking more than you give.
  167518. **
  167519. ******************************************************************************
  167520. **
  167521. ** This SQLite extension implements JSON functions. The interface is
  167522. ** modeled after MySQL JSON functions:
  167523. **
  167524. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  167525. **
  167526. ** For the time being, all JSON is stored as pure text. (We might add
  167527. ** a JSONB type in the future which stores a binary encoding of JSON in
  167528. ** a BLOB, but there is no support for JSONB in the current implementation.
  167529. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  167530. ** how JSONB might improve on that.)
  167531. */
  167532. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  167533. #if !defined(SQLITEINT_H)
  167534. /* #include "sqlite3ext.h" */
  167535. #endif
  167536. SQLITE_EXTENSION_INIT1
  167537. /* #include <assert.h> */
  167538. /* #include <string.h> */
  167539. /* #include <stdlib.h> */
  167540. /* #include <stdarg.h> */
  167541. /* Mark a function parameter as unused, to suppress nuisance compiler
  167542. ** warnings. */
  167543. #ifndef UNUSED_PARAM
  167544. # define UNUSED_PARAM(X) (void)(X)
  167545. #endif
  167546. #ifndef LARGEST_INT64
  167547. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  167548. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  167549. #endif
  167550. /*
  167551. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  167552. ** to pass signed char values.
  167553. */
  167554. #ifdef sqlite3Isdigit
  167555. /* Use the SQLite core versions if this routine is part of the
  167556. ** SQLite amalgamation */
  167557. # define safe_isdigit(x) sqlite3Isdigit(x)
  167558. # define safe_isalnum(x) sqlite3Isalnum(x)
  167559. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  167560. #else
  167561. /* Use the standard library for separate compilation */
  167562. #include <ctype.h> /* amalgamator: keep */
  167563. # define safe_isdigit(x) isdigit((unsigned char)(x))
  167564. # define safe_isalnum(x) isalnum((unsigned char)(x))
  167565. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  167566. #endif
  167567. /*
  167568. ** Growing our own isspace() routine this way is twice as fast as
  167569. ** the library isspace() function, resulting in a 7% overall performance
  167570. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  167571. */
  167572. static const char jsonIsSpace[] = {
  167573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  167574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167575. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167589. };
  167590. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  167591. #ifndef SQLITE_AMALGAMATION
  167592. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  167593. ** but the definitions need to be repeated for separate compilation. */
  167594. typedef sqlite3_uint64 u64;
  167595. typedef unsigned int u32;
  167596. typedef unsigned short int u16;
  167597. typedef unsigned char u8;
  167598. #endif
  167599. /* Objects */
  167600. typedef struct JsonString JsonString;
  167601. typedef struct JsonNode JsonNode;
  167602. typedef struct JsonParse JsonParse;
  167603. /* An instance of this object represents a JSON string
  167604. ** under construction. Really, this is a generic string accumulator
  167605. ** that can be and is used to create strings other than JSON.
  167606. */
  167607. struct JsonString {
  167608. sqlite3_context *pCtx; /* Function context - put error messages here */
  167609. char *zBuf; /* Append JSON content here */
  167610. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  167611. u64 nUsed; /* Bytes of zBuf[] currently used */
  167612. u8 bStatic; /* True if zBuf is static space */
  167613. u8 bErr; /* True if an error has been encountered */
  167614. char zSpace[100]; /* Initial static space */
  167615. };
  167616. /* JSON type values
  167617. */
  167618. #define JSON_NULL 0
  167619. #define JSON_TRUE 1
  167620. #define JSON_FALSE 2
  167621. #define JSON_INT 3
  167622. #define JSON_REAL 4
  167623. #define JSON_STRING 5
  167624. #define JSON_ARRAY 6
  167625. #define JSON_OBJECT 7
  167626. /* The "subtype" set for JSON values */
  167627. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  167628. /*
  167629. ** Names of the various JSON types:
  167630. */
  167631. static const char * const jsonType[] = {
  167632. "null", "true", "false", "integer", "real", "text", "array", "object"
  167633. };
  167634. /* Bit values for the JsonNode.jnFlag field
  167635. */
  167636. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  167637. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  167638. #define JNODE_REMOVE 0x04 /* Do not output */
  167639. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
  167640. #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
  167641. #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
  167642. #define JNODE_LABEL 0x40 /* Is a label of an object */
  167643. /* A single node of parsed JSON
  167644. */
  167645. struct JsonNode {
  167646. u8 eType; /* One of the JSON_ type values */
  167647. u8 jnFlags; /* JNODE flags */
  167648. u32 n; /* Bytes of content, or number of sub-nodes */
  167649. union {
  167650. const char *zJContent; /* Content for INT, REAL, and STRING */
  167651. u32 iAppend; /* More terms for ARRAY and OBJECT */
  167652. u32 iKey; /* Key for ARRAY objects in json_tree() */
  167653. u32 iReplace; /* Replacement content for JNODE_REPLACE */
  167654. JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
  167655. } u;
  167656. };
  167657. /* A completely parsed JSON string
  167658. */
  167659. struct JsonParse {
  167660. u32 nNode; /* Number of slots of aNode[] used */
  167661. u32 nAlloc; /* Number of slots of aNode[] allocated */
  167662. JsonNode *aNode; /* Array of nodes containing the parse */
  167663. const char *zJson; /* Original JSON string */
  167664. u32 *aUp; /* Index of parent of each node */
  167665. u8 oom; /* Set to true if out of memory */
  167666. u8 nErr; /* Number of errors seen */
  167667. u16 iDepth; /* Nesting depth */
  167668. int nJson; /* Length of the zJson string in bytes */
  167669. };
  167670. /*
  167671. ** Maximum nesting depth of JSON for this implementation.
  167672. **
  167673. ** This limit is needed to avoid a stack overflow in the recursive
  167674. ** descent parser. A depth of 2000 is far deeper than any sane JSON
  167675. ** should go.
  167676. */
  167677. #define JSON_MAX_DEPTH 2000
  167678. /**************************************************************************
  167679. ** Utility routines for dealing with JsonString objects
  167680. **************************************************************************/
  167681. /* Set the JsonString object to an empty string
  167682. */
  167683. static void jsonZero(JsonString *p){
  167684. p->zBuf = p->zSpace;
  167685. p->nAlloc = sizeof(p->zSpace);
  167686. p->nUsed = 0;
  167687. p->bStatic = 1;
  167688. }
  167689. /* Initialize the JsonString object
  167690. */
  167691. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  167692. p->pCtx = pCtx;
  167693. p->bErr = 0;
  167694. jsonZero(p);
  167695. }
  167696. /* Free all allocated memory and reset the JsonString object back to its
  167697. ** initial state.
  167698. */
  167699. static void jsonReset(JsonString *p){
  167700. if( !p->bStatic ) sqlite3_free(p->zBuf);
  167701. jsonZero(p);
  167702. }
  167703. /* Report an out-of-memory (OOM) condition
  167704. */
  167705. static void jsonOom(JsonString *p){
  167706. p->bErr = 1;
  167707. sqlite3_result_error_nomem(p->pCtx);
  167708. jsonReset(p);
  167709. }
  167710. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  167711. ** Return zero on success. Return non-zero on an OOM error
  167712. */
  167713. static int jsonGrow(JsonString *p, u32 N){
  167714. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  167715. char *zNew;
  167716. if( p->bStatic ){
  167717. if( p->bErr ) return 1;
  167718. zNew = sqlite3_malloc64(nTotal);
  167719. if( zNew==0 ){
  167720. jsonOom(p);
  167721. return SQLITE_NOMEM;
  167722. }
  167723. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  167724. p->zBuf = zNew;
  167725. p->bStatic = 0;
  167726. }else{
  167727. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  167728. if( zNew==0 ){
  167729. jsonOom(p);
  167730. return SQLITE_NOMEM;
  167731. }
  167732. p->zBuf = zNew;
  167733. }
  167734. p->nAlloc = nTotal;
  167735. return SQLITE_OK;
  167736. }
  167737. /* Append N bytes from zIn onto the end of the JsonString string.
  167738. */
  167739. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  167740. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  167741. memcpy(p->zBuf+p->nUsed, zIn, N);
  167742. p->nUsed += N;
  167743. }
  167744. /* Append formatted text (not to exceed N bytes) to the JsonString.
  167745. */
  167746. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  167747. va_list ap;
  167748. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  167749. va_start(ap, zFormat);
  167750. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  167751. va_end(ap);
  167752. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  167753. }
  167754. /* Append a single character
  167755. */
  167756. static void jsonAppendChar(JsonString *p, char c){
  167757. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  167758. p->zBuf[p->nUsed++] = c;
  167759. }
  167760. /* Append a comma separator to the output buffer, if the previous
  167761. ** character is not '[' or '{'.
  167762. */
  167763. static void jsonAppendSeparator(JsonString *p){
  167764. char c;
  167765. if( p->nUsed==0 ) return;
  167766. c = p->zBuf[p->nUsed-1];
  167767. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  167768. }
  167769. /* Append the N-byte string in zIn to the end of the JsonString string
  167770. ** under construction. Enclose the string in "..." and escape
  167771. ** any double-quotes or backslash characters contained within the
  167772. ** string.
  167773. */
  167774. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  167775. u32 i;
  167776. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  167777. p->zBuf[p->nUsed++] = '"';
  167778. for(i=0; i<N; i++){
  167779. unsigned char c = ((unsigned const char*)zIn)[i];
  167780. if( c=='"' || c=='\\' ){
  167781. json_simple_escape:
  167782. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  167783. p->zBuf[p->nUsed++] = '\\';
  167784. }else if( c<=0x1f ){
  167785. static const char aSpecial[] = {
  167786. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  167787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  167788. };
  167789. assert( sizeof(aSpecial)==32 );
  167790. assert( aSpecial['\b']=='b' );
  167791. assert( aSpecial['\f']=='f' );
  167792. assert( aSpecial['\n']=='n' );
  167793. assert( aSpecial['\r']=='r' );
  167794. assert( aSpecial['\t']=='t' );
  167795. if( aSpecial[c] ){
  167796. c = aSpecial[c];
  167797. goto json_simple_escape;
  167798. }
  167799. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  167800. p->zBuf[p->nUsed++] = '\\';
  167801. p->zBuf[p->nUsed++] = 'u';
  167802. p->zBuf[p->nUsed++] = '0';
  167803. p->zBuf[p->nUsed++] = '0';
  167804. p->zBuf[p->nUsed++] = '0' + (c>>4);
  167805. c = "0123456789abcdef"[c&0xf];
  167806. }
  167807. p->zBuf[p->nUsed++] = c;
  167808. }
  167809. p->zBuf[p->nUsed++] = '"';
  167810. assert( p->nUsed<p->nAlloc );
  167811. }
  167812. /*
  167813. ** Append a function parameter value to the JSON string under
  167814. ** construction.
  167815. */
  167816. static void jsonAppendValue(
  167817. JsonString *p, /* Append to this JSON string */
  167818. sqlite3_value *pValue /* Value to append */
  167819. ){
  167820. switch( sqlite3_value_type(pValue) ){
  167821. case SQLITE_NULL: {
  167822. jsonAppendRaw(p, "null", 4);
  167823. break;
  167824. }
  167825. case SQLITE_INTEGER:
  167826. case SQLITE_FLOAT: {
  167827. const char *z = (const char*)sqlite3_value_text(pValue);
  167828. u32 n = (u32)sqlite3_value_bytes(pValue);
  167829. jsonAppendRaw(p, z, n);
  167830. break;
  167831. }
  167832. case SQLITE_TEXT: {
  167833. const char *z = (const char*)sqlite3_value_text(pValue);
  167834. u32 n = (u32)sqlite3_value_bytes(pValue);
  167835. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  167836. jsonAppendRaw(p, z, n);
  167837. }else{
  167838. jsonAppendString(p, z, n);
  167839. }
  167840. break;
  167841. }
  167842. default: {
  167843. if( p->bErr==0 ){
  167844. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  167845. p->bErr = 2;
  167846. jsonReset(p);
  167847. }
  167848. break;
  167849. }
  167850. }
  167851. }
  167852. /* Make the JSON in p the result of the SQL function.
  167853. */
  167854. static void jsonResult(JsonString *p){
  167855. if( p->bErr==0 ){
  167856. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  167857. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  167858. SQLITE_UTF8);
  167859. jsonZero(p);
  167860. }
  167861. assert( p->bStatic );
  167862. }
  167863. /**************************************************************************
  167864. ** Utility routines for dealing with JsonNode and JsonParse objects
  167865. **************************************************************************/
  167866. /*
  167867. ** Return the number of consecutive JsonNode slots need to represent
  167868. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  167869. ** OBJECT types, the number might be larger.
  167870. **
  167871. ** Appended elements are not counted. The value returned is the number
  167872. ** by which the JsonNode counter should increment in order to go to the
  167873. ** next peer value.
  167874. */
  167875. static u32 jsonNodeSize(JsonNode *pNode){
  167876. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  167877. }
  167878. /*
  167879. ** Reclaim all memory allocated by a JsonParse object. But do not
  167880. ** delete the JsonParse object itself.
  167881. */
  167882. static void jsonParseReset(JsonParse *pParse){
  167883. sqlite3_free(pParse->aNode);
  167884. pParse->aNode = 0;
  167885. pParse->nNode = 0;
  167886. pParse->nAlloc = 0;
  167887. sqlite3_free(pParse->aUp);
  167888. pParse->aUp = 0;
  167889. }
  167890. /*
  167891. ** Free a JsonParse object that was obtained from sqlite3_malloc().
  167892. */
  167893. static void jsonParseFree(JsonParse *pParse){
  167894. jsonParseReset(pParse);
  167895. sqlite3_free(pParse);
  167896. }
  167897. /*
  167898. ** Convert the JsonNode pNode into a pure JSON string and
  167899. ** append to pOut. Subsubstructure is also included. Return
  167900. ** the number of JsonNode objects that are encoded.
  167901. */
  167902. static void jsonRenderNode(
  167903. JsonNode *pNode, /* The node to render */
  167904. JsonString *pOut, /* Write JSON here */
  167905. sqlite3_value **aReplace /* Replacement values */
  167906. ){
  167907. if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
  167908. if( pNode->jnFlags & JNODE_REPLACE ){
  167909. jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
  167910. return;
  167911. }
  167912. pNode = pNode->u.pPatch;
  167913. }
  167914. switch( pNode->eType ){
  167915. default: {
  167916. assert( pNode->eType==JSON_NULL );
  167917. jsonAppendRaw(pOut, "null", 4);
  167918. break;
  167919. }
  167920. case JSON_TRUE: {
  167921. jsonAppendRaw(pOut, "true", 4);
  167922. break;
  167923. }
  167924. case JSON_FALSE: {
  167925. jsonAppendRaw(pOut, "false", 5);
  167926. break;
  167927. }
  167928. case JSON_STRING: {
  167929. if( pNode->jnFlags & JNODE_RAW ){
  167930. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  167931. break;
  167932. }
  167933. /* Fall through into the next case */
  167934. }
  167935. case JSON_REAL:
  167936. case JSON_INT: {
  167937. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  167938. break;
  167939. }
  167940. case JSON_ARRAY: {
  167941. u32 j = 1;
  167942. jsonAppendChar(pOut, '[');
  167943. for(;;){
  167944. while( j<=pNode->n ){
  167945. if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
  167946. jsonAppendSeparator(pOut);
  167947. jsonRenderNode(&pNode[j], pOut, aReplace);
  167948. }
  167949. j += jsonNodeSize(&pNode[j]);
  167950. }
  167951. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  167952. pNode = &pNode[pNode->u.iAppend];
  167953. j = 1;
  167954. }
  167955. jsonAppendChar(pOut, ']');
  167956. break;
  167957. }
  167958. case JSON_OBJECT: {
  167959. u32 j = 1;
  167960. jsonAppendChar(pOut, '{');
  167961. for(;;){
  167962. while( j<=pNode->n ){
  167963. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  167964. jsonAppendSeparator(pOut);
  167965. jsonRenderNode(&pNode[j], pOut, aReplace);
  167966. jsonAppendChar(pOut, ':');
  167967. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  167968. }
  167969. j += 1 + jsonNodeSize(&pNode[j+1]);
  167970. }
  167971. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  167972. pNode = &pNode[pNode->u.iAppend];
  167973. j = 1;
  167974. }
  167975. jsonAppendChar(pOut, '}');
  167976. break;
  167977. }
  167978. }
  167979. }
  167980. /*
  167981. ** Return a JsonNode and all its descendents as a JSON string.
  167982. */
  167983. static void jsonReturnJson(
  167984. JsonNode *pNode, /* Node to return */
  167985. sqlite3_context *pCtx, /* Return value for this function */
  167986. sqlite3_value **aReplace /* Array of replacement values */
  167987. ){
  167988. JsonString s;
  167989. jsonInit(&s, pCtx);
  167990. jsonRenderNode(pNode, &s, aReplace);
  167991. jsonResult(&s);
  167992. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  167993. }
  167994. /*
  167995. ** Make the JsonNode the return value of the function.
  167996. */
  167997. static void jsonReturn(
  167998. JsonNode *pNode, /* Node to return */
  167999. sqlite3_context *pCtx, /* Return value for this function */
  168000. sqlite3_value **aReplace /* Array of replacement values */
  168001. ){
  168002. switch( pNode->eType ){
  168003. default: {
  168004. assert( pNode->eType==JSON_NULL );
  168005. sqlite3_result_null(pCtx);
  168006. break;
  168007. }
  168008. case JSON_TRUE: {
  168009. sqlite3_result_int(pCtx, 1);
  168010. break;
  168011. }
  168012. case JSON_FALSE: {
  168013. sqlite3_result_int(pCtx, 0);
  168014. break;
  168015. }
  168016. case JSON_INT: {
  168017. sqlite3_int64 i = 0;
  168018. const char *z = pNode->u.zJContent;
  168019. if( z[0]=='-' ){ z++; }
  168020. while( z[0]>='0' && z[0]<='9' ){
  168021. unsigned v = *(z++) - '0';
  168022. if( i>=LARGEST_INT64/10 ){
  168023. if( i>LARGEST_INT64/10 ) goto int_as_real;
  168024. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  168025. if( v==9 ) goto int_as_real;
  168026. if( v==8 ){
  168027. if( pNode->u.zJContent[0]=='-' ){
  168028. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  168029. goto int_done;
  168030. }else{
  168031. goto int_as_real;
  168032. }
  168033. }
  168034. }
  168035. i = i*10 + v;
  168036. }
  168037. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  168038. sqlite3_result_int64(pCtx, i);
  168039. int_done:
  168040. break;
  168041. int_as_real: /* fall through to real */;
  168042. }
  168043. case JSON_REAL: {
  168044. double r;
  168045. #ifdef SQLITE_AMALGAMATION
  168046. const char *z = pNode->u.zJContent;
  168047. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  168048. #else
  168049. r = strtod(pNode->u.zJContent, 0);
  168050. #endif
  168051. sqlite3_result_double(pCtx, r);
  168052. break;
  168053. }
  168054. case JSON_STRING: {
  168055. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  168056. ** json_insert() and json_replace() and those routines do not
  168057. ** call jsonReturn() */
  168058. if( pNode->jnFlags & JNODE_RAW ){
  168059. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  168060. SQLITE_TRANSIENT);
  168061. }else
  168062. #endif
  168063. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  168064. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  168065. /* JSON formatted without any backslash-escapes */
  168066. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  168067. SQLITE_TRANSIENT);
  168068. }else{
  168069. /* Translate JSON formatted string into raw text */
  168070. u32 i;
  168071. u32 n = pNode->n;
  168072. const char *z = pNode->u.zJContent;
  168073. char *zOut;
  168074. u32 j;
  168075. zOut = sqlite3_malloc( n+1 );
  168076. if( zOut==0 ){
  168077. sqlite3_result_error_nomem(pCtx);
  168078. break;
  168079. }
  168080. for(i=1, j=0; i<n-1; i++){
  168081. char c = z[i];
  168082. if( c!='\\' ){
  168083. zOut[j++] = c;
  168084. }else{
  168085. c = z[++i];
  168086. if( c=='u' ){
  168087. u32 v = 0, k;
  168088. for(k=0; k<4; i++, k++){
  168089. assert( i<n-2 );
  168090. c = z[i+1];
  168091. assert( safe_isxdigit(c) );
  168092. if( c<='9' ) v = v*16 + c - '0';
  168093. else if( c<='F' ) v = v*16 + c - 'A' + 10;
  168094. else v = v*16 + c - 'a' + 10;
  168095. }
  168096. if( v==0 ) break;
  168097. if( v<=0x7f ){
  168098. zOut[j++] = (char)v;
  168099. }else if( v<=0x7ff ){
  168100. zOut[j++] = (char)(0xc0 | (v>>6));
  168101. zOut[j++] = 0x80 | (v&0x3f);
  168102. }else{
  168103. zOut[j++] = (char)(0xe0 | (v>>12));
  168104. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  168105. zOut[j++] = 0x80 | (v&0x3f);
  168106. }
  168107. }else{
  168108. if( c=='b' ){
  168109. c = '\b';
  168110. }else if( c=='f' ){
  168111. c = '\f';
  168112. }else if( c=='n' ){
  168113. c = '\n';
  168114. }else if( c=='r' ){
  168115. c = '\r';
  168116. }else if( c=='t' ){
  168117. c = '\t';
  168118. }
  168119. zOut[j++] = c;
  168120. }
  168121. }
  168122. }
  168123. zOut[j] = 0;
  168124. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  168125. }
  168126. break;
  168127. }
  168128. case JSON_ARRAY:
  168129. case JSON_OBJECT: {
  168130. jsonReturnJson(pNode, pCtx, aReplace);
  168131. break;
  168132. }
  168133. }
  168134. }
  168135. /* Forward reference */
  168136. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  168137. /*
  168138. ** A macro to hint to the compiler that a function should not be
  168139. ** inlined.
  168140. */
  168141. #if defined(__GNUC__)
  168142. # define JSON_NOINLINE __attribute__((noinline))
  168143. #elif defined(_MSC_VER) && _MSC_VER>=1310
  168144. # define JSON_NOINLINE __declspec(noinline)
  168145. #else
  168146. # define JSON_NOINLINE
  168147. #endif
  168148. static JSON_NOINLINE int jsonParseAddNodeExpand(
  168149. JsonParse *pParse, /* Append the node to this object */
  168150. u32 eType, /* Node type */
  168151. u32 n, /* Content size or sub-node count */
  168152. const char *zContent /* Content */
  168153. ){
  168154. u32 nNew;
  168155. JsonNode *pNew;
  168156. assert( pParse->nNode>=pParse->nAlloc );
  168157. if( pParse->oom ) return -1;
  168158. nNew = pParse->nAlloc*2 + 10;
  168159. pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
  168160. if( pNew==0 ){
  168161. pParse->oom = 1;
  168162. return -1;
  168163. }
  168164. pParse->nAlloc = nNew;
  168165. pParse->aNode = pNew;
  168166. assert( pParse->nNode<pParse->nAlloc );
  168167. return jsonParseAddNode(pParse, eType, n, zContent);
  168168. }
  168169. /*
  168170. ** Create a new JsonNode instance based on the arguments and append that
  168171. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  168172. ** new node, or -1 if a memory allocation fails.
  168173. */
  168174. static int jsonParseAddNode(
  168175. JsonParse *pParse, /* Append the node to this object */
  168176. u32 eType, /* Node type */
  168177. u32 n, /* Content size or sub-node count */
  168178. const char *zContent /* Content */
  168179. ){
  168180. JsonNode *p;
  168181. if( pParse->nNode>=pParse->nAlloc ){
  168182. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  168183. }
  168184. p = &pParse->aNode[pParse->nNode];
  168185. p->eType = (u8)eType;
  168186. p->jnFlags = 0;
  168187. p->n = n;
  168188. p->u.zJContent = zContent;
  168189. return pParse->nNode++;
  168190. }
  168191. /*
  168192. ** Return true if z[] begins with 4 (or more) hexadecimal digits
  168193. */
  168194. static int jsonIs4Hex(const char *z){
  168195. int i;
  168196. for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
  168197. return 1;
  168198. }
  168199. /*
  168200. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  168201. ** index of the first character past the end of the value parsed.
  168202. **
  168203. ** Return negative for a syntax error. Special cases: return -2 if the
  168204. ** first non-whitespace character is '}' and return -3 if the first
  168205. ** non-whitespace character is ']'.
  168206. */
  168207. static int jsonParseValue(JsonParse *pParse, u32 i){
  168208. char c;
  168209. u32 j;
  168210. int iThis;
  168211. int x;
  168212. JsonNode *pNode;
  168213. const char *z = pParse->zJson;
  168214. while( safe_isspace(z[i]) ){ i++; }
  168215. if( (c = z[i])=='{' ){
  168216. /* Parse object */
  168217. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  168218. if( iThis<0 ) return -1;
  168219. for(j=i+1;;j++){
  168220. while( safe_isspace(z[j]) ){ j++; }
  168221. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  168222. x = jsonParseValue(pParse, j);
  168223. if( x<0 ){
  168224. pParse->iDepth--;
  168225. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  168226. return -1;
  168227. }
  168228. if( pParse->oom ) return -1;
  168229. pNode = &pParse->aNode[pParse->nNode-1];
  168230. if( pNode->eType!=JSON_STRING ) return -1;
  168231. pNode->jnFlags |= JNODE_LABEL;
  168232. j = x;
  168233. while( safe_isspace(z[j]) ){ j++; }
  168234. if( z[j]!=':' ) return -1;
  168235. j++;
  168236. x = jsonParseValue(pParse, j);
  168237. pParse->iDepth--;
  168238. if( x<0 ) return -1;
  168239. j = x;
  168240. while( safe_isspace(z[j]) ){ j++; }
  168241. c = z[j];
  168242. if( c==',' ) continue;
  168243. if( c!='}' ) return -1;
  168244. break;
  168245. }
  168246. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  168247. return j+1;
  168248. }else if( c=='[' ){
  168249. /* Parse array */
  168250. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  168251. if( iThis<0 ) return -1;
  168252. for(j=i+1;;j++){
  168253. while( safe_isspace(z[j]) ){ j++; }
  168254. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  168255. x = jsonParseValue(pParse, j);
  168256. pParse->iDepth--;
  168257. if( x<0 ){
  168258. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  168259. return -1;
  168260. }
  168261. j = x;
  168262. while( safe_isspace(z[j]) ){ j++; }
  168263. c = z[j];
  168264. if( c==',' ) continue;
  168265. if( c!=']' ) return -1;
  168266. break;
  168267. }
  168268. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  168269. return j+1;
  168270. }else if( c=='"' ){
  168271. /* Parse string */
  168272. u8 jnFlags = 0;
  168273. j = i+1;
  168274. for(;;){
  168275. c = z[j];
  168276. if( (c & ~0x1f)==0 ){
  168277. /* Control characters are not allowed in strings */
  168278. return -1;
  168279. }
  168280. if( c=='\\' ){
  168281. c = z[++j];
  168282. if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
  168283. || c=='n' || c=='r' || c=='t'
  168284. || (c=='u' && jsonIs4Hex(z+j+1)) ){
  168285. jnFlags = JNODE_ESCAPE;
  168286. }else{
  168287. return -1;
  168288. }
  168289. }else if( c=='"' ){
  168290. break;
  168291. }
  168292. j++;
  168293. }
  168294. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
  168295. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  168296. return j+1;
  168297. }else if( c=='n'
  168298. && strncmp(z+i,"null",4)==0
  168299. && !safe_isalnum(z[i+4]) ){
  168300. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  168301. return i+4;
  168302. }else if( c=='t'
  168303. && strncmp(z+i,"true",4)==0
  168304. && !safe_isalnum(z[i+4]) ){
  168305. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  168306. return i+4;
  168307. }else if( c=='f'
  168308. && strncmp(z+i,"false",5)==0
  168309. && !safe_isalnum(z[i+5]) ){
  168310. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  168311. return i+5;
  168312. }else if( c=='-' || (c>='0' && c<='9') ){
  168313. /* Parse number */
  168314. u8 seenDP = 0;
  168315. u8 seenE = 0;
  168316. assert( '-' < '0' );
  168317. if( c<='0' ){
  168318. j = c=='-' ? i+1 : i;
  168319. if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
  168320. }
  168321. j = i+1;
  168322. for(;; j++){
  168323. c = z[j];
  168324. if( c>='0' && c<='9' ) continue;
  168325. if( c=='.' ){
  168326. if( z[j-1]=='-' ) return -1;
  168327. if( seenDP ) return -1;
  168328. seenDP = 1;
  168329. continue;
  168330. }
  168331. if( c=='e' || c=='E' ){
  168332. if( z[j-1]<'0' ) return -1;
  168333. if( seenE ) return -1;
  168334. seenDP = seenE = 1;
  168335. c = z[j+1];
  168336. if( c=='+' || c=='-' ){
  168337. j++;
  168338. c = z[j+1];
  168339. }
  168340. if( c<'0' || c>'9' ) return -1;
  168341. continue;
  168342. }
  168343. break;
  168344. }
  168345. if( z[j-1]<'0' ) return -1;
  168346. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  168347. j - i, &z[i]);
  168348. return j;
  168349. }else if( c=='}' ){
  168350. return -2; /* End of {...} */
  168351. }else if( c==']' ){
  168352. return -3; /* End of [...] */
  168353. }else if( c==0 ){
  168354. return 0; /* End of file */
  168355. }else{
  168356. return -1; /* Syntax error */
  168357. }
  168358. }
  168359. /*
  168360. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  168361. ** are any errors. If an error occurs, free all memory associated with
  168362. ** pParse.
  168363. **
  168364. ** pParse is uninitialized when this routine is called.
  168365. */
  168366. static int jsonParse(
  168367. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  168368. sqlite3_context *pCtx, /* Report errors here */
  168369. const char *zJson /* Input JSON text to be parsed */
  168370. ){
  168371. int i;
  168372. memset(pParse, 0, sizeof(*pParse));
  168373. if( zJson==0 ) return 1;
  168374. pParse->zJson = zJson;
  168375. i = jsonParseValue(pParse, 0);
  168376. if( pParse->oom ) i = -1;
  168377. if( i>0 ){
  168378. assert( pParse->iDepth==0 );
  168379. while( safe_isspace(zJson[i]) ) i++;
  168380. if( zJson[i] ) i = -1;
  168381. }
  168382. if( i<=0 ){
  168383. if( pCtx!=0 ){
  168384. if( pParse->oom ){
  168385. sqlite3_result_error_nomem(pCtx);
  168386. }else{
  168387. sqlite3_result_error(pCtx, "malformed JSON", -1);
  168388. }
  168389. }
  168390. jsonParseReset(pParse);
  168391. return 1;
  168392. }
  168393. return 0;
  168394. }
  168395. /* Mark node i of pParse as being a child of iParent. Call recursively
  168396. ** to fill in all the descendants of node i.
  168397. */
  168398. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  168399. JsonNode *pNode = &pParse->aNode[i];
  168400. u32 j;
  168401. pParse->aUp[i] = iParent;
  168402. switch( pNode->eType ){
  168403. case JSON_ARRAY: {
  168404. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  168405. jsonParseFillInParentage(pParse, i+j, i);
  168406. }
  168407. break;
  168408. }
  168409. case JSON_OBJECT: {
  168410. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  168411. pParse->aUp[i+j] = i;
  168412. jsonParseFillInParentage(pParse, i+j+1, i);
  168413. }
  168414. break;
  168415. }
  168416. default: {
  168417. break;
  168418. }
  168419. }
  168420. }
  168421. /*
  168422. ** Compute the parentage of all nodes in a completed parse.
  168423. */
  168424. static int jsonParseFindParents(JsonParse *pParse){
  168425. u32 *aUp;
  168426. assert( pParse->aUp==0 );
  168427. aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
  168428. if( aUp==0 ){
  168429. pParse->oom = 1;
  168430. return SQLITE_NOMEM;
  168431. }
  168432. jsonParseFillInParentage(pParse, 0, 0);
  168433. return SQLITE_OK;
  168434. }
  168435. /*
  168436. ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
  168437. */
  168438. #define JSON_CACHE_ID (-429938)
  168439. /*
  168440. ** Obtain a complete parse of the JSON found in the first argument
  168441. ** of the argv array. Use the sqlite3_get_auxdata() cache for this
  168442. ** parse if it is available. If the cache is not available or if it
  168443. ** is no longer valid, parse the JSON again and return the new parse,
  168444. ** and also register the new parse so that it will be available for
  168445. ** future sqlite3_get_auxdata() calls.
  168446. */
  168447. static JsonParse *jsonParseCached(
  168448. sqlite3_context *pCtx,
  168449. sqlite3_value **argv
  168450. ){
  168451. const char *zJson = (const char*)sqlite3_value_text(argv[0]);
  168452. int nJson = sqlite3_value_bytes(argv[0]);
  168453. JsonParse *p;
  168454. if( zJson==0 ) return 0;
  168455. p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  168456. if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
  168457. p->nErr = 0;
  168458. return p; /* The cached entry matches, so return it */
  168459. }
  168460. p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
  168461. if( p==0 ){
  168462. sqlite3_result_error_nomem(pCtx);
  168463. return 0;
  168464. }
  168465. memset(p, 0, sizeof(*p));
  168466. p->zJson = (char*)&p[1];
  168467. memcpy((char*)p->zJson, zJson, nJson+1);
  168468. if( jsonParse(p, pCtx, p->zJson) ){
  168469. sqlite3_free(p);
  168470. return 0;
  168471. }
  168472. p->nJson = nJson;
  168473. sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
  168474. return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  168475. }
  168476. /*
  168477. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  168478. ** a match.
  168479. */
  168480. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  168481. if( pNode->jnFlags & JNODE_RAW ){
  168482. if( pNode->n!=nKey ) return 0;
  168483. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  168484. }else{
  168485. if( pNode->n!=nKey+2 ) return 0;
  168486. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  168487. }
  168488. }
  168489. /* forward declaration */
  168490. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  168491. /*
  168492. ** Search along zPath to find the node specified. Return a pointer
  168493. ** to that node, or NULL if zPath is malformed or if there is no such
  168494. ** node.
  168495. **
  168496. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  168497. ** possible to do so and if no existing node corresponds to zPath. If
  168498. ** new nodes are appended *pApnd is set to 1.
  168499. */
  168500. static JsonNode *jsonLookupStep(
  168501. JsonParse *pParse, /* The JSON to search */
  168502. u32 iRoot, /* Begin the search at this node */
  168503. const char *zPath, /* The path to search */
  168504. int *pApnd, /* Append nodes to complete path if not NULL */
  168505. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  168506. ){
  168507. u32 i, j, nKey;
  168508. const char *zKey;
  168509. JsonNode *pRoot = &pParse->aNode[iRoot];
  168510. if( zPath[0]==0 ) return pRoot;
  168511. if( zPath[0]=='.' ){
  168512. if( pRoot->eType!=JSON_OBJECT ) return 0;
  168513. zPath++;
  168514. if( zPath[0]=='"' ){
  168515. zKey = zPath + 1;
  168516. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  168517. nKey = i-1;
  168518. if( zPath[i] ){
  168519. i++;
  168520. }else{
  168521. *pzErr = zPath;
  168522. return 0;
  168523. }
  168524. }else{
  168525. zKey = zPath;
  168526. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  168527. nKey = i;
  168528. }
  168529. if( nKey==0 ){
  168530. *pzErr = zPath;
  168531. return 0;
  168532. }
  168533. j = 1;
  168534. for(;;){
  168535. while( j<=pRoot->n ){
  168536. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  168537. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  168538. }
  168539. j++;
  168540. j += jsonNodeSize(&pRoot[j]);
  168541. }
  168542. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  168543. iRoot += pRoot->u.iAppend;
  168544. pRoot = &pParse->aNode[iRoot];
  168545. j = 1;
  168546. }
  168547. if( pApnd ){
  168548. u32 iStart, iLabel;
  168549. JsonNode *pNode;
  168550. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  168551. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  168552. zPath += i;
  168553. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  168554. if( pParse->oom ) return 0;
  168555. if( pNode ){
  168556. pRoot = &pParse->aNode[iRoot];
  168557. pRoot->u.iAppend = iStart - iRoot;
  168558. pRoot->jnFlags |= JNODE_APPEND;
  168559. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  168560. }
  168561. return pNode;
  168562. }
  168563. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  168564. if( pRoot->eType!=JSON_ARRAY ) return 0;
  168565. i = 0;
  168566. j = 1;
  168567. while( safe_isdigit(zPath[j]) ){
  168568. i = i*10 + zPath[j] - '0';
  168569. j++;
  168570. }
  168571. if( zPath[j]!=']' ){
  168572. *pzErr = zPath;
  168573. return 0;
  168574. }
  168575. zPath += j + 1;
  168576. j = 1;
  168577. for(;;){
  168578. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  168579. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  168580. j += jsonNodeSize(&pRoot[j]);
  168581. }
  168582. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  168583. iRoot += pRoot->u.iAppend;
  168584. pRoot = &pParse->aNode[iRoot];
  168585. j = 1;
  168586. }
  168587. if( j<=pRoot->n ){
  168588. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  168589. }
  168590. if( i==0 && pApnd ){
  168591. u32 iStart;
  168592. JsonNode *pNode;
  168593. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  168594. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  168595. if( pParse->oom ) return 0;
  168596. if( pNode ){
  168597. pRoot = &pParse->aNode[iRoot];
  168598. pRoot->u.iAppend = iStart - iRoot;
  168599. pRoot->jnFlags |= JNODE_APPEND;
  168600. }
  168601. return pNode;
  168602. }
  168603. }else{
  168604. *pzErr = zPath;
  168605. }
  168606. return 0;
  168607. }
  168608. /*
  168609. ** Append content to pParse that will complete zPath. Return a pointer
  168610. ** to the inserted node, or return NULL if the append fails.
  168611. */
  168612. static JsonNode *jsonLookupAppend(
  168613. JsonParse *pParse, /* Append content to the JSON parse */
  168614. const char *zPath, /* Description of content to append */
  168615. int *pApnd, /* Set this flag to 1 */
  168616. const char **pzErr /* Make this point to any syntax error */
  168617. ){
  168618. *pApnd = 1;
  168619. if( zPath[0]==0 ){
  168620. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  168621. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  168622. }
  168623. if( zPath[0]=='.' ){
  168624. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  168625. }else if( strncmp(zPath,"[0]",3)==0 ){
  168626. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  168627. }else{
  168628. return 0;
  168629. }
  168630. if( pParse->oom ) return 0;
  168631. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  168632. }
  168633. /*
  168634. ** Return the text of a syntax error message on a JSON path. Space is
  168635. ** obtained from sqlite3_malloc().
  168636. */
  168637. static char *jsonPathSyntaxError(const char *zErr){
  168638. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  168639. }
  168640. /*
  168641. ** Do a node lookup using zPath. Return a pointer to the node on success.
  168642. ** Return NULL if not found or if there is an error.
  168643. **
  168644. ** On an error, write an error message into pCtx and increment the
  168645. ** pParse->nErr counter.
  168646. **
  168647. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  168648. ** nodes are appended.
  168649. */
  168650. static JsonNode *jsonLookup(
  168651. JsonParse *pParse, /* The JSON to search */
  168652. const char *zPath, /* The path to search */
  168653. int *pApnd, /* Append nodes to complete path if not NULL */
  168654. sqlite3_context *pCtx /* Report errors here, if not NULL */
  168655. ){
  168656. const char *zErr = 0;
  168657. JsonNode *pNode = 0;
  168658. char *zMsg;
  168659. if( zPath==0 ) return 0;
  168660. if( zPath[0]!='$' ){
  168661. zErr = zPath;
  168662. goto lookup_err;
  168663. }
  168664. zPath++;
  168665. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  168666. if( zErr==0 ) return pNode;
  168667. lookup_err:
  168668. pParse->nErr++;
  168669. assert( zErr!=0 && pCtx!=0 );
  168670. zMsg = jsonPathSyntaxError(zErr);
  168671. if( zMsg ){
  168672. sqlite3_result_error(pCtx, zMsg, -1);
  168673. sqlite3_free(zMsg);
  168674. }else{
  168675. sqlite3_result_error_nomem(pCtx);
  168676. }
  168677. return 0;
  168678. }
  168679. /*
  168680. ** Report the wrong number of arguments for json_insert(), json_replace()
  168681. ** or json_set().
  168682. */
  168683. static void jsonWrongNumArgs(
  168684. sqlite3_context *pCtx,
  168685. const char *zFuncName
  168686. ){
  168687. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  168688. zFuncName);
  168689. sqlite3_result_error(pCtx, zMsg, -1);
  168690. sqlite3_free(zMsg);
  168691. }
  168692. /*
  168693. ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  168694. */
  168695. static void jsonRemoveAllNulls(JsonNode *pNode){
  168696. int i, n;
  168697. assert( pNode->eType==JSON_OBJECT );
  168698. n = pNode->n;
  168699. for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  168700. switch( pNode[i].eType ){
  168701. case JSON_NULL:
  168702. pNode[i].jnFlags |= JNODE_REMOVE;
  168703. break;
  168704. case JSON_OBJECT:
  168705. jsonRemoveAllNulls(&pNode[i]);
  168706. break;
  168707. }
  168708. }
  168709. }
  168710. /****************************************************************************
  168711. ** SQL functions used for testing and debugging
  168712. ****************************************************************************/
  168713. #ifdef SQLITE_DEBUG
  168714. /*
  168715. ** The json_parse(JSON) function returns a string which describes
  168716. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  168717. ** well-formed.
  168718. */
  168719. static void jsonParseFunc(
  168720. sqlite3_context *ctx,
  168721. int argc,
  168722. sqlite3_value **argv
  168723. ){
  168724. JsonString s; /* Output string - not real JSON */
  168725. JsonParse x; /* The parse */
  168726. u32 i;
  168727. assert( argc==1 );
  168728. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  168729. jsonParseFindParents(&x);
  168730. jsonInit(&s, ctx);
  168731. for(i=0; i<x.nNode; i++){
  168732. const char *zType;
  168733. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  168734. assert( x.aNode[i].eType==JSON_STRING );
  168735. zType = "label";
  168736. }else{
  168737. zType = jsonType[x.aNode[i].eType];
  168738. }
  168739. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  168740. i, zType, x.aNode[i].n, x.aUp[i]);
  168741. if( x.aNode[i].u.zJContent!=0 ){
  168742. jsonAppendRaw(&s, " ", 1);
  168743. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  168744. }
  168745. jsonAppendRaw(&s, "\n", 1);
  168746. }
  168747. jsonParseReset(&x);
  168748. jsonResult(&s);
  168749. }
  168750. /*
  168751. ** The json_test1(JSON) function return true (1) if the input is JSON
  168752. ** text generated by another json function. It returns (0) if the input
  168753. ** is not known to be JSON.
  168754. */
  168755. static void jsonTest1Func(
  168756. sqlite3_context *ctx,
  168757. int argc,
  168758. sqlite3_value **argv
  168759. ){
  168760. UNUSED_PARAM(argc);
  168761. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  168762. }
  168763. #endif /* SQLITE_DEBUG */
  168764. /****************************************************************************
  168765. ** Scalar SQL function implementations
  168766. ****************************************************************************/
  168767. /*
  168768. ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
  168769. ** corresponding to the SQL value input. Mostly this means putting
  168770. ** double-quotes around strings and returning the unquoted string "null"
  168771. ** when given a NULL input.
  168772. */
  168773. static void jsonQuoteFunc(
  168774. sqlite3_context *ctx,
  168775. int argc,
  168776. sqlite3_value **argv
  168777. ){
  168778. JsonString jx;
  168779. UNUSED_PARAM(argc);
  168780. jsonInit(&jx, ctx);
  168781. jsonAppendValue(&jx, argv[0]);
  168782. jsonResult(&jx);
  168783. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  168784. }
  168785. /*
  168786. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  168787. ** array that contains all values given in arguments. Or if any argument
  168788. ** is a BLOB, throw an error.
  168789. */
  168790. static void jsonArrayFunc(
  168791. sqlite3_context *ctx,
  168792. int argc,
  168793. sqlite3_value **argv
  168794. ){
  168795. int i;
  168796. JsonString jx;
  168797. jsonInit(&jx, ctx);
  168798. jsonAppendChar(&jx, '[');
  168799. for(i=0; i<argc; i++){
  168800. jsonAppendSeparator(&jx);
  168801. jsonAppendValue(&jx, argv[i]);
  168802. }
  168803. jsonAppendChar(&jx, ']');
  168804. jsonResult(&jx);
  168805. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  168806. }
  168807. /*
  168808. ** json_array_length(JSON)
  168809. ** json_array_length(JSON, PATH)
  168810. **
  168811. ** Return the number of elements in the top-level JSON array.
  168812. ** Return 0 if the input is not a well-formed JSON array.
  168813. */
  168814. static void jsonArrayLengthFunc(
  168815. sqlite3_context *ctx,
  168816. int argc,
  168817. sqlite3_value **argv
  168818. ){
  168819. JsonParse *p; /* The parse */
  168820. sqlite3_int64 n = 0;
  168821. u32 i;
  168822. JsonNode *pNode;
  168823. p = jsonParseCached(ctx, argv);
  168824. if( p==0 ) return;
  168825. assert( p->nNode );
  168826. if( argc==2 ){
  168827. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  168828. pNode = jsonLookup(p, zPath, 0, ctx);
  168829. }else{
  168830. pNode = p->aNode;
  168831. }
  168832. if( pNode==0 ){
  168833. return;
  168834. }
  168835. if( pNode->eType==JSON_ARRAY ){
  168836. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  168837. for(i=1; i<=pNode->n; n++){
  168838. i += jsonNodeSize(&pNode[i]);
  168839. }
  168840. }
  168841. sqlite3_result_int64(ctx, n);
  168842. }
  168843. /*
  168844. ** json_extract(JSON, PATH, ...)
  168845. **
  168846. ** Return the element described by PATH. Return NULL if there is no
  168847. ** PATH element. If there are multiple PATHs, then return a JSON array
  168848. ** with the result from each path. Throw an error if the JSON or any PATH
  168849. ** is malformed.
  168850. */
  168851. static void jsonExtractFunc(
  168852. sqlite3_context *ctx,
  168853. int argc,
  168854. sqlite3_value **argv
  168855. ){
  168856. JsonParse *p; /* The parse */
  168857. JsonNode *pNode;
  168858. const char *zPath;
  168859. JsonString jx;
  168860. int i;
  168861. if( argc<2 ) return;
  168862. p = jsonParseCached(ctx, argv);
  168863. if( p==0 ) return;
  168864. jsonInit(&jx, ctx);
  168865. jsonAppendChar(&jx, '[');
  168866. for(i=1; i<argc; i++){
  168867. zPath = (const char*)sqlite3_value_text(argv[i]);
  168868. pNode = jsonLookup(p, zPath, 0, ctx);
  168869. if( p->nErr ) break;
  168870. if( argc>2 ){
  168871. jsonAppendSeparator(&jx);
  168872. if( pNode ){
  168873. jsonRenderNode(pNode, &jx, 0);
  168874. }else{
  168875. jsonAppendRaw(&jx, "null", 4);
  168876. }
  168877. }else if( pNode ){
  168878. jsonReturn(pNode, ctx, 0);
  168879. }
  168880. }
  168881. if( argc>2 && i==argc ){
  168882. jsonAppendChar(&jx, ']');
  168883. jsonResult(&jx);
  168884. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  168885. }
  168886. jsonReset(&jx);
  168887. }
  168888. /* This is the RFC 7396 MergePatch algorithm.
  168889. */
  168890. static JsonNode *jsonMergePatch(
  168891. JsonParse *pParse, /* The JSON parser that contains the TARGET */
  168892. u32 iTarget, /* Node of the TARGET in pParse */
  168893. JsonNode *pPatch /* The PATCH */
  168894. ){
  168895. u32 i, j;
  168896. u32 iRoot;
  168897. JsonNode *pTarget;
  168898. if( pPatch->eType!=JSON_OBJECT ){
  168899. return pPatch;
  168900. }
  168901. assert( iTarget>=0 && iTarget<pParse->nNode );
  168902. pTarget = &pParse->aNode[iTarget];
  168903. assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  168904. if( pTarget->eType!=JSON_OBJECT ){
  168905. jsonRemoveAllNulls(pPatch);
  168906. return pPatch;
  168907. }
  168908. iRoot = iTarget;
  168909. for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  168910. u32 nKey;
  168911. const char *zKey;
  168912. assert( pPatch[i].eType==JSON_STRING );
  168913. assert( pPatch[i].jnFlags & JNODE_LABEL );
  168914. nKey = pPatch[i].n;
  168915. zKey = pPatch[i].u.zJContent;
  168916. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  168917. for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  168918. assert( pTarget[j].eType==JSON_STRING );
  168919. assert( pTarget[j].jnFlags & JNODE_LABEL );
  168920. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  168921. if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  168922. if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  168923. if( pPatch[i+1].eType==JSON_NULL ){
  168924. pTarget[j+1].jnFlags |= JNODE_REMOVE;
  168925. }else{
  168926. JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  168927. if( pNew==0 ) return 0;
  168928. pTarget = &pParse->aNode[iTarget];
  168929. if( pNew!=&pTarget[j+1] ){
  168930. pTarget[j+1].u.pPatch = pNew;
  168931. pTarget[j+1].jnFlags |= JNODE_PATCH;
  168932. }
  168933. }
  168934. break;
  168935. }
  168936. }
  168937. if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  168938. int iStart, iPatch;
  168939. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  168940. jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  168941. iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  168942. if( pParse->oom ) return 0;
  168943. jsonRemoveAllNulls(pPatch);
  168944. pTarget = &pParse->aNode[iTarget];
  168945. pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  168946. pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  168947. iRoot = iStart;
  168948. pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  168949. pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  168950. }
  168951. }
  168952. return pTarget;
  168953. }
  168954. /*
  168955. ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
  168956. ** object that is the result of running the RFC 7396 MergePatch() algorithm
  168957. ** on the two arguments.
  168958. */
  168959. static void jsonPatchFunc(
  168960. sqlite3_context *ctx,
  168961. int argc,
  168962. sqlite3_value **argv
  168963. ){
  168964. JsonParse x; /* The JSON that is being patched */
  168965. JsonParse y; /* The patch */
  168966. JsonNode *pResult; /* The result of the merge */
  168967. UNUSED_PARAM(argc);
  168968. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  168969. if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  168970. jsonParseReset(&x);
  168971. return;
  168972. }
  168973. pResult = jsonMergePatch(&x, 0, y.aNode);
  168974. assert( pResult!=0 || x.oom );
  168975. if( pResult ){
  168976. jsonReturnJson(pResult, ctx, 0);
  168977. }else{
  168978. sqlite3_result_error_nomem(ctx);
  168979. }
  168980. jsonParseReset(&x);
  168981. jsonParseReset(&y);
  168982. }
  168983. /*
  168984. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  168985. ** object that contains all name/value given in arguments. Or if any name
  168986. ** is not a string or if any value is a BLOB, throw an error.
  168987. */
  168988. static void jsonObjectFunc(
  168989. sqlite3_context *ctx,
  168990. int argc,
  168991. sqlite3_value **argv
  168992. ){
  168993. int i;
  168994. JsonString jx;
  168995. const char *z;
  168996. u32 n;
  168997. if( argc&1 ){
  168998. sqlite3_result_error(ctx, "json_object() requires an even number "
  168999. "of arguments", -1);
  169000. return;
  169001. }
  169002. jsonInit(&jx, ctx);
  169003. jsonAppendChar(&jx, '{');
  169004. for(i=0; i<argc; i+=2){
  169005. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  169006. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  169007. jsonReset(&jx);
  169008. return;
  169009. }
  169010. jsonAppendSeparator(&jx);
  169011. z = (const char*)sqlite3_value_text(argv[i]);
  169012. n = (u32)sqlite3_value_bytes(argv[i]);
  169013. jsonAppendString(&jx, z, n);
  169014. jsonAppendChar(&jx, ':');
  169015. jsonAppendValue(&jx, argv[i+1]);
  169016. }
  169017. jsonAppendChar(&jx, '}');
  169018. jsonResult(&jx);
  169019. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169020. }
  169021. /*
  169022. ** json_remove(JSON, PATH, ...)
  169023. **
  169024. ** Remove the named elements from JSON and return the result. malformed
  169025. ** JSON or PATH arguments result in an error.
  169026. */
  169027. static void jsonRemoveFunc(
  169028. sqlite3_context *ctx,
  169029. int argc,
  169030. sqlite3_value **argv
  169031. ){
  169032. JsonParse x; /* The parse */
  169033. JsonNode *pNode;
  169034. const char *zPath;
  169035. u32 i;
  169036. if( argc<1 ) return;
  169037. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169038. assert( x.nNode );
  169039. for(i=1; i<(u32)argc; i++){
  169040. zPath = (const char*)sqlite3_value_text(argv[i]);
  169041. if( zPath==0 ) goto remove_done;
  169042. pNode = jsonLookup(&x, zPath, 0, ctx);
  169043. if( x.nErr ) goto remove_done;
  169044. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  169045. }
  169046. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  169047. jsonReturnJson(x.aNode, ctx, 0);
  169048. }
  169049. remove_done:
  169050. jsonParseReset(&x);
  169051. }
  169052. /*
  169053. ** json_replace(JSON, PATH, VALUE, ...)
  169054. **
  169055. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  169056. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  169057. */
  169058. static void jsonReplaceFunc(
  169059. sqlite3_context *ctx,
  169060. int argc,
  169061. sqlite3_value **argv
  169062. ){
  169063. JsonParse x; /* The parse */
  169064. JsonNode *pNode;
  169065. const char *zPath;
  169066. u32 i;
  169067. if( argc<1 ) return;
  169068. if( (argc&1)==0 ) {
  169069. jsonWrongNumArgs(ctx, "replace");
  169070. return;
  169071. }
  169072. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169073. assert( x.nNode );
  169074. for(i=1; i<(u32)argc; i+=2){
  169075. zPath = (const char*)sqlite3_value_text(argv[i]);
  169076. pNode = jsonLookup(&x, zPath, 0, ctx);
  169077. if( x.nErr ) goto replace_err;
  169078. if( pNode ){
  169079. pNode->jnFlags |= (u8)JNODE_REPLACE;
  169080. pNode->u.iReplace = i + 1;
  169081. }
  169082. }
  169083. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  169084. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  169085. }else{
  169086. jsonReturnJson(x.aNode, ctx, argv);
  169087. }
  169088. replace_err:
  169089. jsonParseReset(&x);
  169090. }
  169091. /*
  169092. ** json_set(JSON, PATH, VALUE, ...)
  169093. **
  169094. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  169095. ** exist. Overwrite existing values that do exist.
  169096. ** If JSON or PATH is malformed, throw an error.
  169097. **
  169098. ** json_insert(JSON, PATH, VALUE, ...)
  169099. **
  169100. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  169101. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  169102. */
  169103. static void jsonSetFunc(
  169104. sqlite3_context *ctx,
  169105. int argc,
  169106. sqlite3_value **argv
  169107. ){
  169108. JsonParse x; /* The parse */
  169109. JsonNode *pNode;
  169110. const char *zPath;
  169111. u32 i;
  169112. int bApnd;
  169113. int bIsSet = *(int*)sqlite3_user_data(ctx);
  169114. if( argc<1 ) return;
  169115. if( (argc&1)==0 ) {
  169116. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  169117. return;
  169118. }
  169119. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169120. assert( x.nNode );
  169121. for(i=1; i<(u32)argc; i+=2){
  169122. zPath = (const char*)sqlite3_value_text(argv[i]);
  169123. bApnd = 0;
  169124. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  169125. if( x.oom ){
  169126. sqlite3_result_error_nomem(ctx);
  169127. goto jsonSetDone;
  169128. }else if( x.nErr ){
  169129. goto jsonSetDone;
  169130. }else if( pNode && (bApnd || bIsSet) ){
  169131. pNode->jnFlags |= (u8)JNODE_REPLACE;
  169132. pNode->u.iReplace = i + 1;
  169133. }
  169134. }
  169135. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  169136. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  169137. }else{
  169138. jsonReturnJson(x.aNode, ctx, argv);
  169139. }
  169140. jsonSetDone:
  169141. jsonParseReset(&x);
  169142. }
  169143. /*
  169144. ** json_type(JSON)
  169145. ** json_type(JSON, PATH)
  169146. **
  169147. ** Return the top-level "type" of a JSON string. Throw an error if
  169148. ** either the JSON or PATH inputs are not well-formed.
  169149. */
  169150. static void jsonTypeFunc(
  169151. sqlite3_context *ctx,
  169152. int argc,
  169153. sqlite3_value **argv
  169154. ){
  169155. JsonParse x; /* The parse */
  169156. const char *zPath;
  169157. JsonNode *pNode;
  169158. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169159. assert( x.nNode );
  169160. if( argc==2 ){
  169161. zPath = (const char*)sqlite3_value_text(argv[1]);
  169162. pNode = jsonLookup(&x, zPath, 0, ctx);
  169163. }else{
  169164. pNode = x.aNode;
  169165. }
  169166. if( pNode ){
  169167. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  169168. }
  169169. jsonParseReset(&x);
  169170. }
  169171. /*
  169172. ** json_valid(JSON)
  169173. **
  169174. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  169175. ** Return 0 otherwise.
  169176. */
  169177. static void jsonValidFunc(
  169178. sqlite3_context *ctx,
  169179. int argc,
  169180. sqlite3_value **argv
  169181. ){
  169182. JsonParse x; /* The parse */
  169183. int rc = 0;
  169184. UNUSED_PARAM(argc);
  169185. if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
  169186. rc = 1;
  169187. }
  169188. jsonParseReset(&x);
  169189. sqlite3_result_int(ctx, rc);
  169190. }
  169191. /****************************************************************************
  169192. ** Aggregate SQL function implementations
  169193. ****************************************************************************/
  169194. /*
  169195. ** json_group_array(VALUE)
  169196. **
  169197. ** Return a JSON array composed of all values in the aggregate.
  169198. */
  169199. static void jsonArrayStep(
  169200. sqlite3_context *ctx,
  169201. int argc,
  169202. sqlite3_value **argv
  169203. ){
  169204. JsonString *pStr;
  169205. UNUSED_PARAM(argc);
  169206. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  169207. if( pStr ){
  169208. if( pStr->zBuf==0 ){
  169209. jsonInit(pStr, ctx);
  169210. jsonAppendChar(pStr, '[');
  169211. }else{
  169212. jsonAppendChar(pStr, ',');
  169213. pStr->pCtx = ctx;
  169214. }
  169215. jsonAppendValue(pStr, argv[0]);
  169216. }
  169217. }
  169218. static void jsonArrayFinal(sqlite3_context *ctx){
  169219. JsonString *pStr;
  169220. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  169221. if( pStr ){
  169222. pStr->pCtx = ctx;
  169223. jsonAppendChar(pStr, ']');
  169224. if( pStr->bErr ){
  169225. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  169226. assert( pStr->bStatic );
  169227. }else{
  169228. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  169229. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  169230. pStr->bStatic = 1;
  169231. }
  169232. }else{
  169233. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  169234. }
  169235. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169236. }
  169237. /*
  169238. ** json_group_obj(NAME,VALUE)
  169239. **
  169240. ** Return a JSON object composed of all names and values in the aggregate.
  169241. */
  169242. static void jsonObjectStep(
  169243. sqlite3_context *ctx,
  169244. int argc,
  169245. sqlite3_value **argv
  169246. ){
  169247. JsonString *pStr;
  169248. const char *z;
  169249. u32 n;
  169250. UNUSED_PARAM(argc);
  169251. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  169252. if( pStr ){
  169253. if( pStr->zBuf==0 ){
  169254. jsonInit(pStr, ctx);
  169255. jsonAppendChar(pStr, '{');
  169256. }else{
  169257. jsonAppendChar(pStr, ',');
  169258. pStr->pCtx = ctx;
  169259. }
  169260. z = (const char*)sqlite3_value_text(argv[0]);
  169261. n = (u32)sqlite3_value_bytes(argv[0]);
  169262. jsonAppendString(pStr, z, n);
  169263. jsonAppendChar(pStr, ':');
  169264. jsonAppendValue(pStr, argv[1]);
  169265. }
  169266. }
  169267. static void jsonObjectFinal(sqlite3_context *ctx){
  169268. JsonString *pStr;
  169269. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  169270. if( pStr ){
  169271. jsonAppendChar(pStr, '}');
  169272. if( pStr->bErr ){
  169273. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  169274. assert( pStr->bStatic );
  169275. }else{
  169276. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  169277. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  169278. pStr->bStatic = 1;
  169279. }
  169280. }else{
  169281. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  169282. }
  169283. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169284. }
  169285. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169286. /****************************************************************************
  169287. ** The json_each virtual table
  169288. ****************************************************************************/
  169289. typedef struct JsonEachCursor JsonEachCursor;
  169290. struct JsonEachCursor {
  169291. sqlite3_vtab_cursor base; /* Base class - must be first */
  169292. u32 iRowid; /* The rowid */
  169293. u32 iBegin; /* The first node of the scan */
  169294. u32 i; /* Index in sParse.aNode[] of current row */
  169295. u32 iEnd; /* EOF when i equals or exceeds this value */
  169296. u8 eType; /* Type of top-level element */
  169297. u8 bRecursive; /* True for json_tree(). False for json_each() */
  169298. char *zJson; /* Input JSON */
  169299. char *zRoot; /* Path by which to filter zJson */
  169300. JsonParse sParse; /* Parse of the input JSON */
  169301. };
  169302. /* Constructor for the json_each virtual table */
  169303. static int jsonEachConnect(
  169304. sqlite3 *db,
  169305. void *pAux,
  169306. int argc, const char *const*argv,
  169307. sqlite3_vtab **ppVtab,
  169308. char **pzErr
  169309. ){
  169310. sqlite3_vtab *pNew;
  169311. int rc;
  169312. /* Column numbers */
  169313. #define JEACH_KEY 0
  169314. #define JEACH_VALUE 1
  169315. #define JEACH_TYPE 2
  169316. #define JEACH_ATOM 3
  169317. #define JEACH_ID 4
  169318. #define JEACH_PARENT 5
  169319. #define JEACH_FULLKEY 6
  169320. #define JEACH_PATH 7
  169321. #define JEACH_JSON 8
  169322. #define JEACH_ROOT 9
  169323. UNUSED_PARAM(pzErr);
  169324. UNUSED_PARAM(argv);
  169325. UNUSED_PARAM(argc);
  169326. UNUSED_PARAM(pAux);
  169327. rc = sqlite3_declare_vtab(db,
  169328. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  169329. "json HIDDEN,root HIDDEN)");
  169330. if( rc==SQLITE_OK ){
  169331. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  169332. if( pNew==0 ) return SQLITE_NOMEM;
  169333. memset(pNew, 0, sizeof(*pNew));
  169334. }
  169335. return rc;
  169336. }
  169337. /* destructor for json_each virtual table */
  169338. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  169339. sqlite3_free(pVtab);
  169340. return SQLITE_OK;
  169341. }
  169342. /* constructor for a JsonEachCursor object for json_each(). */
  169343. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  169344. JsonEachCursor *pCur;
  169345. UNUSED_PARAM(p);
  169346. pCur = sqlite3_malloc( sizeof(*pCur) );
  169347. if( pCur==0 ) return SQLITE_NOMEM;
  169348. memset(pCur, 0, sizeof(*pCur));
  169349. *ppCursor = &pCur->base;
  169350. return SQLITE_OK;
  169351. }
  169352. /* constructor for a JsonEachCursor object for json_tree(). */
  169353. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  169354. int rc = jsonEachOpenEach(p, ppCursor);
  169355. if( rc==SQLITE_OK ){
  169356. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  169357. pCur->bRecursive = 1;
  169358. }
  169359. return rc;
  169360. }
  169361. /* Reset a JsonEachCursor back to its original state. Free any memory
  169362. ** held. */
  169363. static void jsonEachCursorReset(JsonEachCursor *p){
  169364. sqlite3_free(p->zJson);
  169365. sqlite3_free(p->zRoot);
  169366. jsonParseReset(&p->sParse);
  169367. p->iRowid = 0;
  169368. p->i = 0;
  169369. p->iEnd = 0;
  169370. p->eType = 0;
  169371. p->zJson = 0;
  169372. p->zRoot = 0;
  169373. }
  169374. /* Destructor for a jsonEachCursor object */
  169375. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  169376. JsonEachCursor *p = (JsonEachCursor*)cur;
  169377. jsonEachCursorReset(p);
  169378. sqlite3_free(cur);
  169379. return SQLITE_OK;
  169380. }
  169381. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  169382. ** of the JSON object */
  169383. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  169384. JsonEachCursor *p = (JsonEachCursor*)cur;
  169385. return p->i >= p->iEnd;
  169386. }
  169387. /* Advance the cursor to the next element for json_tree() */
  169388. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  169389. JsonEachCursor *p = (JsonEachCursor*)cur;
  169390. if( p->bRecursive ){
  169391. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  169392. p->i++;
  169393. p->iRowid++;
  169394. if( p->i<p->iEnd ){
  169395. u32 iUp = p->sParse.aUp[p->i];
  169396. JsonNode *pUp = &p->sParse.aNode[iUp];
  169397. p->eType = pUp->eType;
  169398. if( pUp->eType==JSON_ARRAY ){
  169399. if( iUp==p->i-1 ){
  169400. pUp->u.iKey = 0;
  169401. }else{
  169402. pUp->u.iKey++;
  169403. }
  169404. }
  169405. }
  169406. }else{
  169407. switch( p->eType ){
  169408. case JSON_ARRAY: {
  169409. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  169410. p->iRowid++;
  169411. break;
  169412. }
  169413. case JSON_OBJECT: {
  169414. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  169415. p->iRowid++;
  169416. break;
  169417. }
  169418. default: {
  169419. p->i = p->iEnd;
  169420. break;
  169421. }
  169422. }
  169423. }
  169424. return SQLITE_OK;
  169425. }
  169426. /* Append the name of the path for element i to pStr
  169427. */
  169428. static void jsonEachComputePath(
  169429. JsonEachCursor *p, /* The cursor */
  169430. JsonString *pStr, /* Write the path here */
  169431. u32 i /* Path to this element */
  169432. ){
  169433. JsonNode *pNode, *pUp;
  169434. u32 iUp;
  169435. if( i==0 ){
  169436. jsonAppendChar(pStr, '$');
  169437. return;
  169438. }
  169439. iUp = p->sParse.aUp[i];
  169440. jsonEachComputePath(p, pStr, iUp);
  169441. pNode = &p->sParse.aNode[i];
  169442. pUp = &p->sParse.aNode[iUp];
  169443. if( pUp->eType==JSON_ARRAY ){
  169444. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  169445. }else{
  169446. assert( pUp->eType==JSON_OBJECT );
  169447. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  169448. assert( pNode->eType==JSON_STRING );
  169449. assert( pNode->jnFlags & JNODE_LABEL );
  169450. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  169451. }
  169452. }
  169453. /* Return the value of a column */
  169454. static int jsonEachColumn(
  169455. sqlite3_vtab_cursor *cur, /* The cursor */
  169456. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  169457. int i /* Which column to return */
  169458. ){
  169459. JsonEachCursor *p = (JsonEachCursor*)cur;
  169460. JsonNode *pThis = &p->sParse.aNode[p->i];
  169461. switch( i ){
  169462. case JEACH_KEY: {
  169463. if( p->i==0 ) break;
  169464. if( p->eType==JSON_OBJECT ){
  169465. jsonReturn(pThis, ctx, 0);
  169466. }else if( p->eType==JSON_ARRAY ){
  169467. u32 iKey;
  169468. if( p->bRecursive ){
  169469. if( p->iRowid==0 ) break;
  169470. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  169471. }else{
  169472. iKey = p->iRowid;
  169473. }
  169474. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  169475. }
  169476. break;
  169477. }
  169478. case JEACH_VALUE: {
  169479. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  169480. jsonReturn(pThis, ctx, 0);
  169481. break;
  169482. }
  169483. case JEACH_TYPE: {
  169484. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  169485. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  169486. break;
  169487. }
  169488. case JEACH_ATOM: {
  169489. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  169490. if( pThis->eType>=JSON_ARRAY ) break;
  169491. jsonReturn(pThis, ctx, 0);
  169492. break;
  169493. }
  169494. case JEACH_ID: {
  169495. sqlite3_result_int64(ctx,
  169496. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  169497. break;
  169498. }
  169499. case JEACH_PARENT: {
  169500. if( p->i>p->iBegin && p->bRecursive ){
  169501. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  169502. }
  169503. break;
  169504. }
  169505. case JEACH_FULLKEY: {
  169506. JsonString x;
  169507. jsonInit(&x, ctx);
  169508. if( p->bRecursive ){
  169509. jsonEachComputePath(p, &x, p->i);
  169510. }else{
  169511. if( p->zRoot ){
  169512. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  169513. }else{
  169514. jsonAppendChar(&x, '$');
  169515. }
  169516. if( p->eType==JSON_ARRAY ){
  169517. jsonPrintf(30, &x, "[%d]", p->iRowid);
  169518. }else{
  169519. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  169520. }
  169521. }
  169522. jsonResult(&x);
  169523. break;
  169524. }
  169525. case JEACH_PATH: {
  169526. if( p->bRecursive ){
  169527. JsonString x;
  169528. jsonInit(&x, ctx);
  169529. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  169530. jsonResult(&x);
  169531. break;
  169532. }
  169533. /* For json_each() path and root are the same so fall through
  169534. ** into the root case */
  169535. }
  169536. default: {
  169537. const char *zRoot = p->zRoot;
  169538. if( zRoot==0 ) zRoot = "$";
  169539. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  169540. break;
  169541. }
  169542. case JEACH_JSON: {
  169543. assert( i==JEACH_JSON );
  169544. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  169545. break;
  169546. }
  169547. }
  169548. return SQLITE_OK;
  169549. }
  169550. /* Return the current rowid value */
  169551. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  169552. JsonEachCursor *p = (JsonEachCursor*)cur;
  169553. *pRowid = p->iRowid;
  169554. return SQLITE_OK;
  169555. }
  169556. /* The query strategy is to look for an equality constraint on the json
  169557. ** column. Without such a constraint, the table cannot operate. idxNum is
  169558. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  169559. ** and 0 otherwise.
  169560. */
  169561. static int jsonEachBestIndex(
  169562. sqlite3_vtab *tab,
  169563. sqlite3_index_info *pIdxInfo
  169564. ){
  169565. int i;
  169566. int jsonIdx = -1;
  169567. int rootIdx = -1;
  169568. const struct sqlite3_index_constraint *pConstraint;
  169569. UNUSED_PARAM(tab);
  169570. pConstraint = pIdxInfo->aConstraint;
  169571. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  169572. if( pConstraint->usable==0 ) continue;
  169573. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  169574. switch( pConstraint->iColumn ){
  169575. case JEACH_JSON: jsonIdx = i; break;
  169576. case JEACH_ROOT: rootIdx = i; break;
  169577. default: /* no-op */ break;
  169578. }
  169579. }
  169580. if( jsonIdx<0 ){
  169581. pIdxInfo->idxNum = 0;
  169582. pIdxInfo->estimatedCost = 1e99;
  169583. }else{
  169584. pIdxInfo->estimatedCost = 1.0;
  169585. pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
  169586. pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
  169587. if( rootIdx<0 ){
  169588. pIdxInfo->idxNum = 1;
  169589. }else{
  169590. pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
  169591. pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
  169592. pIdxInfo->idxNum = 3;
  169593. }
  169594. }
  169595. return SQLITE_OK;
  169596. }
  169597. /* Start a search on a new JSON string */
  169598. static int jsonEachFilter(
  169599. sqlite3_vtab_cursor *cur,
  169600. int idxNum, const char *idxStr,
  169601. int argc, sqlite3_value **argv
  169602. ){
  169603. JsonEachCursor *p = (JsonEachCursor*)cur;
  169604. const char *z;
  169605. const char *zRoot = 0;
  169606. sqlite3_int64 n;
  169607. UNUSED_PARAM(idxStr);
  169608. UNUSED_PARAM(argc);
  169609. jsonEachCursorReset(p);
  169610. if( idxNum==0 ) return SQLITE_OK;
  169611. z = (const char*)sqlite3_value_text(argv[0]);
  169612. if( z==0 ) return SQLITE_OK;
  169613. n = sqlite3_value_bytes(argv[0]);
  169614. p->zJson = sqlite3_malloc64( n+1 );
  169615. if( p->zJson==0 ) return SQLITE_NOMEM;
  169616. memcpy(p->zJson, z, (size_t)n+1);
  169617. if( jsonParse(&p->sParse, 0, p->zJson) ){
  169618. int rc = SQLITE_NOMEM;
  169619. if( p->sParse.oom==0 ){
  169620. sqlite3_free(cur->pVtab->zErrMsg);
  169621. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  169622. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  169623. }
  169624. jsonEachCursorReset(p);
  169625. return rc;
  169626. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  169627. jsonEachCursorReset(p);
  169628. return SQLITE_NOMEM;
  169629. }else{
  169630. JsonNode *pNode = 0;
  169631. if( idxNum==3 ){
  169632. const char *zErr = 0;
  169633. zRoot = (const char*)sqlite3_value_text(argv[1]);
  169634. if( zRoot==0 ) return SQLITE_OK;
  169635. n = sqlite3_value_bytes(argv[1]);
  169636. p->zRoot = sqlite3_malloc64( n+1 );
  169637. if( p->zRoot==0 ) return SQLITE_NOMEM;
  169638. memcpy(p->zRoot, zRoot, (size_t)n+1);
  169639. if( zRoot[0]!='$' ){
  169640. zErr = zRoot;
  169641. }else{
  169642. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  169643. }
  169644. if( zErr ){
  169645. sqlite3_free(cur->pVtab->zErrMsg);
  169646. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  169647. jsonEachCursorReset(p);
  169648. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  169649. }else if( pNode==0 ){
  169650. return SQLITE_OK;
  169651. }
  169652. }else{
  169653. pNode = p->sParse.aNode;
  169654. }
  169655. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  169656. p->eType = pNode->eType;
  169657. if( p->eType>=JSON_ARRAY ){
  169658. pNode->u.iKey = 0;
  169659. p->iEnd = p->i + pNode->n + 1;
  169660. if( p->bRecursive ){
  169661. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  169662. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  169663. p->i--;
  169664. }
  169665. }else{
  169666. p->i++;
  169667. }
  169668. }else{
  169669. p->iEnd = p->i+1;
  169670. }
  169671. }
  169672. return SQLITE_OK;
  169673. }
  169674. /* The methods of the json_each virtual table */
  169675. static sqlite3_module jsonEachModule = {
  169676. 0, /* iVersion */
  169677. 0, /* xCreate */
  169678. jsonEachConnect, /* xConnect */
  169679. jsonEachBestIndex, /* xBestIndex */
  169680. jsonEachDisconnect, /* xDisconnect */
  169681. 0, /* xDestroy */
  169682. jsonEachOpenEach, /* xOpen - open a cursor */
  169683. jsonEachClose, /* xClose - close a cursor */
  169684. jsonEachFilter, /* xFilter - configure scan constraints */
  169685. jsonEachNext, /* xNext - advance a cursor */
  169686. jsonEachEof, /* xEof - check for end of scan */
  169687. jsonEachColumn, /* xColumn - read data */
  169688. jsonEachRowid, /* xRowid - read data */
  169689. 0, /* xUpdate */
  169690. 0, /* xBegin */
  169691. 0, /* xSync */
  169692. 0, /* xCommit */
  169693. 0, /* xRollback */
  169694. 0, /* xFindMethod */
  169695. 0, /* xRename */
  169696. 0, /* xSavepoint */
  169697. 0, /* xRelease */
  169698. 0 /* xRollbackTo */
  169699. };
  169700. /* The methods of the json_tree virtual table. */
  169701. static sqlite3_module jsonTreeModule = {
  169702. 0, /* iVersion */
  169703. 0, /* xCreate */
  169704. jsonEachConnect, /* xConnect */
  169705. jsonEachBestIndex, /* xBestIndex */
  169706. jsonEachDisconnect, /* xDisconnect */
  169707. 0, /* xDestroy */
  169708. jsonEachOpenTree, /* xOpen - open a cursor */
  169709. jsonEachClose, /* xClose - close a cursor */
  169710. jsonEachFilter, /* xFilter - configure scan constraints */
  169711. jsonEachNext, /* xNext - advance a cursor */
  169712. jsonEachEof, /* xEof - check for end of scan */
  169713. jsonEachColumn, /* xColumn - read data */
  169714. jsonEachRowid, /* xRowid - read data */
  169715. 0, /* xUpdate */
  169716. 0, /* xBegin */
  169717. 0, /* xSync */
  169718. 0, /* xCommit */
  169719. 0, /* xRollback */
  169720. 0, /* xFindMethod */
  169721. 0, /* xRename */
  169722. 0, /* xSavepoint */
  169723. 0, /* xRelease */
  169724. 0 /* xRollbackTo */
  169725. };
  169726. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  169727. /****************************************************************************
  169728. ** The following routines are the only publically visible identifiers in this
  169729. ** file. Call the following routines in order to register the various SQL
  169730. ** functions and the virtual table implemented by this file.
  169731. ****************************************************************************/
  169732. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  169733. int rc = SQLITE_OK;
  169734. unsigned int i;
  169735. static const struct {
  169736. const char *zName;
  169737. int nArg;
  169738. int flag;
  169739. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  169740. } aFunc[] = {
  169741. { "json", 1, 0, jsonRemoveFunc },
  169742. { "json_array", -1, 0, jsonArrayFunc },
  169743. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  169744. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  169745. { "json_extract", -1, 0, jsonExtractFunc },
  169746. { "json_insert", -1, 0, jsonSetFunc },
  169747. { "json_object", -1, 0, jsonObjectFunc },
  169748. { "json_patch", 2, 0, jsonPatchFunc },
  169749. { "json_quote", 1, 0, jsonQuoteFunc },
  169750. { "json_remove", -1, 0, jsonRemoveFunc },
  169751. { "json_replace", -1, 0, jsonReplaceFunc },
  169752. { "json_set", -1, 1, jsonSetFunc },
  169753. { "json_type", 1, 0, jsonTypeFunc },
  169754. { "json_type", 2, 0, jsonTypeFunc },
  169755. { "json_valid", 1, 0, jsonValidFunc },
  169756. #if SQLITE_DEBUG
  169757. /* DEBUG and TESTING functions */
  169758. { "json_parse", 1, 0, jsonParseFunc },
  169759. { "json_test1", 1, 0, jsonTest1Func },
  169760. #endif
  169761. };
  169762. static const struct {
  169763. const char *zName;
  169764. int nArg;
  169765. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  169766. void (*xFinal)(sqlite3_context*);
  169767. } aAgg[] = {
  169768. { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
  169769. { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
  169770. };
  169771. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169772. static const struct {
  169773. const char *zName;
  169774. sqlite3_module *pModule;
  169775. } aMod[] = {
  169776. { "json_each", &jsonEachModule },
  169777. { "json_tree", &jsonTreeModule },
  169778. };
  169779. #endif
  169780. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  169781. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  169782. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  169783. (void*)&aFunc[i].flag,
  169784. aFunc[i].xFunc, 0, 0);
  169785. }
  169786. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  169787. rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
  169788. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  169789. 0, aAgg[i].xStep, aAgg[i].xFinal);
  169790. }
  169791. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169792. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  169793. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  169794. }
  169795. #endif
  169796. return rc;
  169797. }
  169798. #ifndef SQLITE_CORE
  169799. #ifdef _WIN32
  169800. __declspec(dllexport)
  169801. #endif
  169802. SQLITE_API int sqlite3_json_init(
  169803. sqlite3 *db,
  169804. char **pzErrMsg,
  169805. const sqlite3_api_routines *pApi
  169806. ){
  169807. SQLITE_EXTENSION_INIT2(pApi);
  169808. (void)pzErrMsg; /* Unused parameter */
  169809. return sqlite3Json1Init(db);
  169810. }
  169811. #endif
  169812. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  169813. /************** End of json1.c ***********************************************/
  169814. /************** Begin file fts5.c ********************************************/
  169815. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  169816. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  169817. # define NDEBUG 1
  169818. #endif
  169819. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  169820. # undef NDEBUG
  169821. #endif
  169822. /*
  169823. ** 2014 May 31
  169824. **
  169825. ** The author disclaims copyright to this source code. In place of
  169826. ** a legal notice, here is a blessing:
  169827. **
  169828. ** May you do good and not evil.
  169829. ** May you find forgiveness for yourself and forgive others.
  169830. ** May you share freely, never taking more than you give.
  169831. **
  169832. ******************************************************************************
  169833. **
  169834. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  169835. ** FTS5 may be extended with:
  169836. **
  169837. ** * custom tokenizers, and
  169838. ** * custom auxiliary functions.
  169839. */
  169840. #ifndef _FTS5_H
  169841. #define _FTS5_H
  169842. /* #include "sqlite3.h" */
  169843. #if 0
  169844. extern "C" {
  169845. #endif
  169846. /*************************************************************************
  169847. ** CUSTOM AUXILIARY FUNCTIONS
  169848. **
  169849. ** Virtual table implementations may overload SQL functions by implementing
  169850. ** the sqlite3_module.xFindFunction() method.
  169851. */
  169852. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  169853. typedef struct Fts5Context Fts5Context;
  169854. typedef struct Fts5PhraseIter Fts5PhraseIter;
  169855. typedef void (*fts5_extension_function)(
  169856. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  169857. Fts5Context *pFts, /* First arg to pass to pApi functions */
  169858. sqlite3_context *pCtx, /* Context for returning result/error */
  169859. int nVal, /* Number of values in apVal[] array */
  169860. sqlite3_value **apVal /* Array of trailing arguments */
  169861. );
  169862. struct Fts5PhraseIter {
  169863. const unsigned char *a;
  169864. const unsigned char *b;
  169865. };
  169866. /*
  169867. ** EXTENSION API FUNCTIONS
  169868. **
  169869. ** xUserData(pFts):
  169870. ** Return a copy of the context pointer the extension function was
  169871. ** registered with.
  169872. **
  169873. ** xColumnTotalSize(pFts, iCol, pnToken):
  169874. ** If parameter iCol is less than zero, set output variable *pnToken
  169875. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  169876. ** non-negative but less than the number of columns in the table, return
  169877. ** the total number of tokens in column iCol, considering all rows in
  169878. ** the FTS5 table.
  169879. **
  169880. ** If parameter iCol is greater than or equal to the number of columns
  169881. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  169882. ** an OOM condition or IO error), an appropriate SQLite error code is
  169883. ** returned.
  169884. **
  169885. ** xColumnCount(pFts):
  169886. ** Return the number of columns in the table.
  169887. **
  169888. ** xColumnSize(pFts, iCol, pnToken):
  169889. ** If parameter iCol is less than zero, set output variable *pnToken
  169890. ** to the total number of tokens in the current row. Or, if iCol is
  169891. ** non-negative but less than the number of columns in the table, set
  169892. ** *pnToken to the number of tokens in column iCol of the current row.
  169893. **
  169894. ** If parameter iCol is greater than or equal to the number of columns
  169895. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  169896. ** an OOM condition or IO error), an appropriate SQLite error code is
  169897. ** returned.
  169898. **
  169899. ** This function may be quite inefficient if used with an FTS5 table
  169900. ** created with the "columnsize=0" option.
  169901. **
  169902. ** xColumnText:
  169903. ** This function attempts to retrieve the text of column iCol of the
  169904. ** current document. If successful, (*pz) is set to point to a buffer
  169905. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  169906. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  169907. ** if an error occurs, an SQLite error code is returned and the final values
  169908. ** of (*pz) and (*pn) are undefined.
  169909. **
  169910. ** xPhraseCount:
  169911. ** Returns the number of phrases in the current query expression.
  169912. **
  169913. ** xPhraseSize:
  169914. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  169915. ** are numbered starting from zero.
  169916. **
  169917. ** xInstCount:
  169918. ** Set *pnInst to the total number of occurrences of all phrases within
  169919. ** the query within the current row. Return SQLITE_OK if successful, or
  169920. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  169921. **
  169922. ** This API can be quite slow if used with an FTS5 table created with the
  169923. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  169924. ** with either "detail=none" or "detail=column" and "content=" option
  169925. ** (i.e. if it is a contentless table), then this API always returns 0.
  169926. **
  169927. ** xInst:
  169928. ** Query for the details of phrase match iIdx within the current row.
  169929. ** Phrase matches are numbered starting from zero, so the iIdx argument
  169930. ** should be greater than or equal to zero and smaller than the value
  169931. ** output by xInstCount().
  169932. **
  169933. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  169934. ** to the column in which it occurs and *piOff the token offset of the
  169935. ** first token of the phrase. The exception is if the table was created
  169936. ** with the offsets=0 option specified. In this case *piOff is always
  169937. ** set to -1.
  169938. **
  169939. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  169940. ** if an error occurs.
  169941. **
  169942. ** This API can be quite slow if used with an FTS5 table created with the
  169943. ** "detail=none" or "detail=column" option.
  169944. **
  169945. ** xRowid:
  169946. ** Returns the rowid of the current row.
  169947. **
  169948. ** xTokenize:
  169949. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  169950. **
  169951. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  169952. ** This API function is used to query the FTS table for phrase iPhrase
  169953. ** of the current query. Specifically, a query equivalent to:
  169954. **
  169955. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  169956. **
  169957. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  169958. ** current query is executed. Any column filter that applies to
  169959. ** phrase iPhrase of the current query is included in $p. For each
  169960. ** row visited, the callback function passed as the fourth argument
  169961. ** is invoked. The context and API objects passed to the callback
  169962. ** function may be used to access the properties of each matched row.
  169963. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  169964. ** the third argument to pUserData.
  169965. **
  169966. ** If the callback function returns any value other than SQLITE_OK, the
  169967. ** query is abandoned and the xQueryPhrase function returns immediately.
  169968. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  169969. ** Otherwise, the error code is propagated upwards.
  169970. **
  169971. ** If the query runs to completion without incident, SQLITE_OK is returned.
  169972. ** Or, if some error occurs before the query completes or is aborted by
  169973. ** the callback, an SQLite error code is returned.
  169974. **
  169975. **
  169976. ** xSetAuxdata(pFts5, pAux, xDelete)
  169977. **
  169978. ** Save the pointer passed as the second argument as the extension functions
  169979. ** "auxiliary data". The pointer may then be retrieved by the current or any
  169980. ** future invocation of the same fts5 extension function made as part of
  169981. ** of the same MATCH query using the xGetAuxdata() API.
  169982. **
  169983. ** Each extension function is allocated a single auxiliary data slot for
  169984. ** each FTS query (MATCH expression). If the extension function is invoked
  169985. ** more than once for a single FTS query, then all invocations share a
  169986. ** single auxiliary data context.
  169987. **
  169988. ** If there is already an auxiliary data pointer when this function is
  169989. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  169990. ** was specified along with the original pointer, it is invoked at this
  169991. ** point.
  169992. **
  169993. ** The xDelete callback, if one is specified, is also invoked on the
  169994. ** auxiliary data pointer after the FTS5 query has finished.
  169995. **
  169996. ** If an error (e.g. an OOM condition) occurs within this function, an
  169997. ** the auxiliary data is set to NULL and an error code returned. If the
  169998. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  169999. ** pointer before returning.
  170000. **
  170001. **
  170002. ** xGetAuxdata(pFts5, bClear)
  170003. **
  170004. ** Returns the current auxiliary data pointer for the fts5 extension
  170005. ** function. See the xSetAuxdata() method for details.
  170006. **
  170007. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  170008. ** (set to NULL) before this function returns. In this case the xDelete,
  170009. ** if any, is not invoked.
  170010. **
  170011. **
  170012. ** xRowCount(pFts5, pnRow)
  170013. **
  170014. ** This function is used to retrieve the total number of rows in the table.
  170015. ** In other words, the same value that would be returned by:
  170016. **
  170017. ** SELECT count(*) FROM ftstable;
  170018. **
  170019. ** xPhraseFirst()
  170020. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  170021. ** method, to iterate through all instances of a single query phrase within
  170022. ** the current row. This is the same information as is accessible via the
  170023. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  170024. ** to use, this API may be faster under some circumstances. To iterate
  170025. ** through instances of phrase iPhrase, use the following code:
  170026. **
  170027. ** Fts5PhraseIter iter;
  170028. ** int iCol, iOff;
  170029. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  170030. ** iCol>=0;
  170031. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  170032. ** ){
  170033. ** // An instance of phrase iPhrase at offset iOff of column iCol
  170034. ** }
  170035. **
  170036. ** The Fts5PhraseIter structure is defined above. Applications should not
  170037. ** modify this structure directly - it should only be used as shown above
  170038. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  170039. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  170040. **
  170041. ** This API can be quite slow if used with an FTS5 table created with the
  170042. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  170043. ** with either "detail=none" or "detail=column" and "content=" option
  170044. ** (i.e. if it is a contentless table), then this API always iterates
  170045. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  170046. **
  170047. ** xPhraseNext()
  170048. ** See xPhraseFirst above.
  170049. **
  170050. ** xPhraseFirstColumn()
  170051. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  170052. ** and xPhraseNext() APIs described above. The difference is that instead
  170053. ** of iterating through all instances of a phrase in the current row, these
  170054. ** APIs are used to iterate through the set of columns in the current row
  170055. ** that contain one or more instances of a specified phrase. For example:
  170056. **
  170057. ** Fts5PhraseIter iter;
  170058. ** int iCol;
  170059. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  170060. ** iCol>=0;
  170061. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  170062. ** ){
  170063. ** // Column iCol contains at least one instance of phrase iPhrase
  170064. ** }
  170065. **
  170066. ** This API can be quite slow if used with an FTS5 table created with the
  170067. ** "detail=none" option. If the FTS5 table is created with either
  170068. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  170069. ** then this API always iterates through an empty set (all calls to
  170070. ** xPhraseFirstColumn() set iCol to -1).
  170071. **
  170072. ** The information accessed using this API and its companion
  170073. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  170074. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  170075. ** significantly more efficient than those alternatives when used with
  170076. ** "detail=column" tables.
  170077. **
  170078. ** xPhraseNextColumn()
  170079. ** See xPhraseFirstColumn above.
  170080. */
  170081. struct Fts5ExtensionApi {
  170082. int iVersion; /* Currently always set to 3 */
  170083. void *(*xUserData)(Fts5Context*);
  170084. int (*xColumnCount)(Fts5Context*);
  170085. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  170086. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  170087. int (*xTokenize)(Fts5Context*,
  170088. const char *pText, int nText, /* Text to tokenize */
  170089. void *pCtx, /* Context passed to xToken() */
  170090. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  170091. );
  170092. int (*xPhraseCount)(Fts5Context*);
  170093. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  170094. int (*xInstCount)(Fts5Context*, int *pnInst);
  170095. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  170096. sqlite3_int64 (*xRowid)(Fts5Context*);
  170097. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  170098. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  170099. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  170100. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  170101. );
  170102. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  170103. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  170104. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  170105. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  170106. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  170107. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  170108. };
  170109. /*
  170110. ** CUSTOM AUXILIARY FUNCTIONS
  170111. *************************************************************************/
  170112. /*************************************************************************
  170113. ** CUSTOM TOKENIZERS
  170114. **
  170115. ** Applications may also register custom tokenizer types. A tokenizer
  170116. ** is registered by providing fts5 with a populated instance of the
  170117. ** following structure. All structure methods must be defined, setting
  170118. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  170119. ** behaviour. The structure methods are expected to function as follows:
  170120. **
  170121. ** xCreate:
  170122. ** This function is used to allocate and initialize a tokenizer instance.
  170123. ** A tokenizer instance is required to actually tokenize text.
  170124. **
  170125. ** The first argument passed to this function is a copy of the (void*)
  170126. ** pointer provided by the application when the fts5_tokenizer object
  170127. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  170128. ** The second and third arguments are an array of nul-terminated strings
  170129. ** containing the tokenizer arguments, if any, specified following the
  170130. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  170131. ** to create the FTS5 table.
  170132. **
  170133. ** The final argument is an output variable. If successful, (*ppOut)
  170134. ** should be set to point to the new tokenizer handle and SQLITE_OK
  170135. ** returned. If an error occurs, some value other than SQLITE_OK should
  170136. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  170137. ** is undefined.
  170138. **
  170139. ** xDelete:
  170140. ** This function is invoked to delete a tokenizer handle previously
  170141. ** allocated using xCreate(). Fts5 guarantees that this function will
  170142. ** be invoked exactly once for each successful call to xCreate().
  170143. **
  170144. ** xTokenize:
  170145. ** This function is expected to tokenize the nText byte string indicated
  170146. ** by argument pText. pText may or may not be nul-terminated. The first
  170147. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  170148. ** returned by an earlier call to xCreate().
  170149. **
  170150. ** The second argument indicates the reason that FTS5 is requesting
  170151. ** tokenization of the supplied text. This is always one of the following
  170152. ** four values:
  170153. **
  170154. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  170155. ** or removed from the FTS table. The tokenizer is being invoked to
  170156. ** determine the set of tokens to add to (or delete from) the
  170157. ** FTS index.
  170158. **
  170159. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  170160. ** against the FTS index. The tokenizer is being called to tokenize
  170161. ** a bareword or quoted string specified as part of the query.
  170162. **
  170163. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  170164. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  170165. ** followed by a "*" character, indicating that the last token
  170166. ** returned by the tokenizer will be treated as a token prefix.
  170167. **
  170168. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  170169. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  170170. ** function. Or an fts5_api.xColumnSize() request made by the same
  170171. ** on a columnsize=0 database.
  170172. ** </ul>
  170173. **
  170174. ** For each token in the input string, the supplied callback xToken() must
  170175. ** be invoked. The first argument to it should be a copy of the pointer
  170176. ** passed as the second argument to xTokenize(). The third and fourth
  170177. ** arguments are a pointer to a buffer containing the token text, and the
  170178. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  170179. ** of the first byte of and first byte immediately following the text from
  170180. ** which the token is derived within the input.
  170181. **
  170182. ** The second argument passed to the xToken() callback ("tflags") should
  170183. ** normally be set to 0. The exception is if the tokenizer supports
  170184. ** synonyms. In this case see the discussion below for details.
  170185. **
  170186. ** FTS5 assumes the xToken() callback is invoked for each token in the
  170187. ** order that they occur within the input text.
  170188. **
  170189. ** If an xToken() callback returns any value other than SQLITE_OK, then
  170190. ** the tokenization should be abandoned and the xTokenize() method should
  170191. ** immediately return a copy of the xToken() return value. Or, if the
  170192. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  170193. ** if an error occurs with the xTokenize() implementation itself, it
  170194. ** may abandon the tokenization and return any error code other than
  170195. ** SQLITE_OK or SQLITE_DONE.
  170196. **
  170197. ** SYNONYM SUPPORT
  170198. **
  170199. ** Custom tokenizers may also support synonyms. Consider a case in which a
  170200. ** user wishes to query for a phrase such as "first place". Using the
  170201. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  170202. ** of "first place" within the document set, but not alternative forms
  170203. ** such as "1st place". In some applications, it would be better to match
  170204. ** all instances of "first place" or "1st place" regardless of which form
  170205. ** the user specified in the MATCH query text.
  170206. **
  170207. ** There are several ways to approach this in FTS5:
  170208. **
  170209. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  170210. ** In the above example, this means that the tokenizer returns the
  170211. ** same token for inputs "first" and "1st". Say that token is in
  170212. ** fact "first", so that when the user inserts the document "I won
  170213. ** 1st place" entries are added to the index for tokens "i", "won",
  170214. ** "first" and "place". If the user then queries for '1st + place',
  170215. ** the tokenizer substitutes "first" for "1st" and the query works
  170216. ** as expected.
  170217. **
  170218. ** <li> By adding multiple synonyms for a single term to the FTS index.
  170219. ** In this case, when tokenizing query text, the tokenizer may
  170220. ** provide multiple synonyms for a single term within the document.
  170221. ** FTS5 then queries the index for each synonym individually. For
  170222. ** example, faced with the query:
  170223. **
  170224. ** <codeblock>
  170225. ** ... MATCH 'first place'</codeblock>
  170226. **
  170227. ** the tokenizer offers both "1st" and "first" as synonyms for the
  170228. ** first token in the MATCH query and FTS5 effectively runs a query
  170229. ** similar to:
  170230. **
  170231. ** <codeblock>
  170232. ** ... MATCH '(first OR 1st) place'</codeblock>
  170233. **
  170234. ** except that, for the purposes of auxiliary functions, the query
  170235. ** still appears to contain just two phrases - "(first OR 1st)"
  170236. ** being treated as a single phrase.
  170237. **
  170238. ** <li> By adding multiple synonyms for a single term to the FTS index.
  170239. ** Using this method, when tokenizing document text, the tokenizer
  170240. ** provides multiple synonyms for each token. So that when a
  170241. ** document such as "I won first place" is tokenized, entries are
  170242. ** added to the FTS index for "i", "won", "first", "1st" and
  170243. ** "place".
  170244. **
  170245. ** This way, even if the tokenizer does not provide synonyms
  170246. ** when tokenizing query text (it should not - to do would be
  170247. ** inefficient), it doesn't matter if the user queries for
  170248. ** 'first + place' or '1st + place', as there are entires in the
  170249. ** FTS index corresponding to both forms of the first token.
  170250. ** </ol>
  170251. **
  170252. ** Whether it is parsing document or query text, any call to xToken that
  170253. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  170254. ** is considered to supply a synonym for the previous token. For example,
  170255. ** when parsing the document "I won first place", a tokenizer that supports
  170256. ** synonyms would call xToken() 5 times, as follows:
  170257. **
  170258. ** <codeblock>
  170259. ** xToken(pCtx, 0, "i", 1, 0, 1);
  170260. ** xToken(pCtx, 0, "won", 3, 2, 5);
  170261. ** xToken(pCtx, 0, "first", 5, 6, 11);
  170262. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  170263. ** xToken(pCtx, 0, "place", 5, 12, 17);
  170264. **</codeblock>
  170265. **
  170266. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  170267. ** xToken() is called. Multiple synonyms may be specified for a single token
  170268. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  170269. ** There is no limit to the number of synonyms that may be provided for a
  170270. ** single token.
  170271. **
  170272. ** In many cases, method (1) above is the best approach. It does not add
  170273. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  170274. ** so it is efficient in terms of disk space and query speed. However, it
  170275. ** does not support prefix queries very well. If, as suggested above, the
  170276. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  170277. **
  170278. ** <codeblock>
  170279. ** ... MATCH '1s*'</codeblock>
  170280. **
  170281. ** will not match documents that contain the token "1st" (as the tokenizer
  170282. ** will probably not map "1s" to any prefix of "first").
  170283. **
  170284. ** For full prefix support, method (3) may be preferred. In this case,
  170285. ** because the index contains entries for both "first" and "1st", prefix
  170286. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  170287. ** extra entries are added to the FTS index, this method uses more space
  170288. ** within the database.
  170289. **
  170290. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  170291. ** a query such as '1s*' will match documents that contain the literal
  170292. ** token "1st", but not "first" (assuming the tokenizer is not able to
  170293. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  170294. ** will match against "1st" and "first". This method does not require
  170295. ** extra disk space, as no extra entries are added to the FTS index.
  170296. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  170297. ** as separate queries of the FTS index are required for each synonym.
  170298. **
  170299. ** When using methods (2) or (3), it is important that the tokenizer only
  170300. ** provide synonyms when tokenizing document text (method (2)) or query
  170301. ** text (method (3)), not both. Doing so will not cause any errors, but is
  170302. ** inefficient.
  170303. */
  170304. typedef struct Fts5Tokenizer Fts5Tokenizer;
  170305. typedef struct fts5_tokenizer fts5_tokenizer;
  170306. struct fts5_tokenizer {
  170307. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  170308. void (*xDelete)(Fts5Tokenizer*);
  170309. int (*xTokenize)(Fts5Tokenizer*,
  170310. void *pCtx,
  170311. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  170312. const char *pText, int nText,
  170313. int (*xToken)(
  170314. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  170315. int tflags, /* Mask of FTS5_TOKEN_* flags */
  170316. const char *pToken, /* Pointer to buffer containing token */
  170317. int nToken, /* Size of token in bytes */
  170318. int iStart, /* Byte offset of token within input text */
  170319. int iEnd /* Byte offset of end of token within input text */
  170320. )
  170321. );
  170322. };
  170323. /* Flags that may be passed as the third argument to xTokenize() */
  170324. #define FTS5_TOKENIZE_QUERY 0x0001
  170325. #define FTS5_TOKENIZE_PREFIX 0x0002
  170326. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  170327. #define FTS5_TOKENIZE_AUX 0x0008
  170328. /* Flags that may be passed by the tokenizer implementation back to FTS5
  170329. ** as the third argument to the supplied xToken callback. */
  170330. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  170331. /*
  170332. ** END OF CUSTOM TOKENIZERS
  170333. *************************************************************************/
  170334. /*************************************************************************
  170335. ** FTS5 EXTENSION REGISTRATION API
  170336. */
  170337. typedef struct fts5_api fts5_api;
  170338. struct fts5_api {
  170339. int iVersion; /* Currently always set to 2 */
  170340. /* Create a new tokenizer */
  170341. int (*xCreateTokenizer)(
  170342. fts5_api *pApi,
  170343. const char *zName,
  170344. void *pContext,
  170345. fts5_tokenizer *pTokenizer,
  170346. void (*xDestroy)(void*)
  170347. );
  170348. /* Find an existing tokenizer */
  170349. int (*xFindTokenizer)(
  170350. fts5_api *pApi,
  170351. const char *zName,
  170352. void **ppContext,
  170353. fts5_tokenizer *pTokenizer
  170354. );
  170355. /* Create a new auxiliary function */
  170356. int (*xCreateFunction)(
  170357. fts5_api *pApi,
  170358. const char *zName,
  170359. void *pContext,
  170360. fts5_extension_function xFunction,
  170361. void (*xDestroy)(void*)
  170362. );
  170363. };
  170364. /*
  170365. ** END OF REGISTRATION API
  170366. *************************************************************************/
  170367. #if 0
  170368. } /* end of the 'extern "C"' block */
  170369. #endif
  170370. #endif /* _FTS5_H */
  170371. /*
  170372. ** 2014 May 31
  170373. **
  170374. ** The author disclaims copyright to this source code. In place of
  170375. ** a legal notice, here is a blessing:
  170376. **
  170377. ** May you do good and not evil.
  170378. ** May you find forgiveness for yourself and forgive others.
  170379. ** May you share freely, never taking more than you give.
  170380. **
  170381. ******************************************************************************
  170382. **
  170383. */
  170384. #ifndef _FTS5INT_H
  170385. #define _FTS5INT_H
  170386. /* #include "fts5.h" */
  170387. /* #include "sqlite3ext.h" */
  170388. SQLITE_EXTENSION_INIT1
  170389. /* #include <string.h> */
  170390. /* #include <assert.h> */
  170391. #ifndef SQLITE_AMALGAMATION
  170392. typedef unsigned char u8;
  170393. typedef unsigned int u32;
  170394. typedef unsigned short u16;
  170395. typedef short i16;
  170396. typedef sqlite3_int64 i64;
  170397. typedef sqlite3_uint64 u64;
  170398. #ifndef ArraySize
  170399. # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  170400. #endif
  170401. #define testcase(x)
  170402. #define ALWAYS(x) 1
  170403. #define NEVER(x) 0
  170404. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  170405. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  170406. /*
  170407. ** Constants for the largest and smallest possible 64-bit signed integers.
  170408. */
  170409. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  170410. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  170411. #endif
  170412. /* Truncate very long tokens to this many bytes. Hard limit is
  170413. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  170414. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  170415. #define FTS5_MAX_TOKEN_SIZE 32768
  170416. /*
  170417. ** Maximum number of prefix indexes on single FTS5 table. This must be
  170418. ** less than 32. If it is set to anything large than that, an #error
  170419. ** directive in fts5_index.c will cause the build to fail.
  170420. */
  170421. #define FTS5_MAX_PREFIX_INDEXES 31
  170422. #define FTS5_DEFAULT_NEARDIST 10
  170423. #define FTS5_DEFAULT_RANK "bm25"
  170424. /* Name of rank and rowid columns */
  170425. #define FTS5_RANK_NAME "rank"
  170426. #define FTS5_ROWID_NAME "rowid"
  170427. #ifdef SQLITE_DEBUG
  170428. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  170429. static int sqlite3Fts5Corrupt(void);
  170430. #else
  170431. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  170432. #endif
  170433. /*
  170434. ** The assert_nc() macro is similar to the assert() macro, except that it
  170435. ** is used for assert() conditions that are true only if it can be
  170436. ** guranteed that the database is not corrupt.
  170437. */
  170438. #ifdef SQLITE_DEBUG
  170439. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  170440. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  170441. #else
  170442. # define assert_nc(x) assert(x)
  170443. #endif
  170444. /* Mark a function parameter as unused, to suppress nuisance compiler
  170445. ** warnings. */
  170446. #ifndef UNUSED_PARAM
  170447. # define UNUSED_PARAM(X) (void)(X)
  170448. #endif
  170449. #ifndef UNUSED_PARAM2
  170450. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  170451. #endif
  170452. typedef struct Fts5Global Fts5Global;
  170453. typedef struct Fts5Colset Fts5Colset;
  170454. /* If a NEAR() clump or phrase may only match a specific set of columns,
  170455. ** then an object of the following type is used to record the set of columns.
  170456. ** Each entry in the aiCol[] array is a column that may be matched.
  170457. **
  170458. ** This object is used by fts5_expr.c and fts5_index.c.
  170459. */
  170460. struct Fts5Colset {
  170461. int nCol;
  170462. int aiCol[1];
  170463. };
  170464. /**************************************************************************
  170465. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  170466. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  170467. */
  170468. typedef struct Fts5Config Fts5Config;
  170469. /*
  170470. ** An instance of the following structure encodes all information that can
  170471. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  170472. **
  170473. ** And all information loaded from the %_config table.
  170474. **
  170475. ** nAutomerge:
  170476. ** The minimum number of segments that an auto-merge operation should
  170477. ** attempt to merge together. A value of 1 sets the object to use the
  170478. ** compile time default. Zero disables auto-merge altogether.
  170479. **
  170480. ** zContent:
  170481. **
  170482. ** zContentRowid:
  170483. ** The value of the content_rowid= option, if one was specified. Or
  170484. ** the string "rowid" otherwise. This text is not quoted - if it is
  170485. ** used as part of an SQL statement it needs to be quoted appropriately.
  170486. **
  170487. ** zContentExprlist:
  170488. **
  170489. ** pzErrmsg:
  170490. ** This exists in order to allow the fts5_index.c module to return a
  170491. ** decent error message if it encounters a file-format version it does
  170492. ** not understand.
  170493. **
  170494. ** bColumnsize:
  170495. ** True if the %_docsize table is created.
  170496. **
  170497. ** bPrefixIndex:
  170498. ** This is only used for debugging. If set to false, any prefix indexes
  170499. ** are ignored. This value is configured using:
  170500. **
  170501. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  170502. **
  170503. */
  170504. struct Fts5Config {
  170505. sqlite3 *db; /* Database handle */
  170506. char *zDb; /* Database holding FTS index (e.g. "main") */
  170507. char *zName; /* Name of FTS index */
  170508. int nCol; /* Number of columns */
  170509. char **azCol; /* Column names */
  170510. u8 *abUnindexed; /* True for unindexed columns */
  170511. int nPrefix; /* Number of prefix indexes */
  170512. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  170513. int eContent; /* An FTS5_CONTENT value */
  170514. char *zContent; /* content table */
  170515. char *zContentRowid; /* "content_rowid=" option value */
  170516. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  170517. int eDetail; /* FTS5_DETAIL_XXX value */
  170518. char *zContentExprlist;
  170519. Fts5Tokenizer *pTok;
  170520. fts5_tokenizer *pTokApi;
  170521. /* Values loaded from the %_config table */
  170522. int iCookie; /* Incremented when %_config is modified */
  170523. int pgsz; /* Approximate page size used in %_data */
  170524. int nAutomerge; /* 'automerge' setting */
  170525. int nCrisisMerge; /* Maximum allowed segments per level */
  170526. int nUsermerge; /* 'usermerge' setting */
  170527. int nHashSize; /* Bytes of memory for in-memory hash */
  170528. char *zRank; /* Name of rank function */
  170529. char *zRankArgs; /* Arguments to rank function */
  170530. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  170531. char **pzErrmsg;
  170532. #ifdef SQLITE_DEBUG
  170533. int bPrefixIndex; /* True to use prefix-indexes */
  170534. #endif
  170535. };
  170536. /* Current expected value of %_config table 'version' field */
  170537. #define FTS5_CURRENT_VERSION 4
  170538. #define FTS5_CONTENT_NORMAL 0
  170539. #define FTS5_CONTENT_NONE 1
  170540. #define FTS5_CONTENT_EXTERNAL 2
  170541. #define FTS5_DETAIL_FULL 0
  170542. #define FTS5_DETAIL_NONE 1
  170543. #define FTS5_DETAIL_COLUMNS 2
  170544. static int sqlite3Fts5ConfigParse(
  170545. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  170546. );
  170547. static void sqlite3Fts5ConfigFree(Fts5Config*);
  170548. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  170549. static int sqlite3Fts5Tokenize(
  170550. Fts5Config *pConfig, /* FTS5 Configuration object */
  170551. int flags, /* FTS5_TOKENIZE_* flags */
  170552. const char *pText, int nText, /* Text to tokenize */
  170553. void *pCtx, /* Context passed to xToken() */
  170554. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  170555. );
  170556. static void sqlite3Fts5Dequote(char *z);
  170557. /* Load the contents of the %_config table */
  170558. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  170559. /* Set the value of a single config attribute */
  170560. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  170561. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  170562. /*
  170563. ** End of interface to code in fts5_config.c.
  170564. **************************************************************************/
  170565. /**************************************************************************
  170566. ** Interface to code in fts5_buffer.c.
  170567. */
  170568. /*
  170569. ** Buffer object for the incremental building of string data.
  170570. */
  170571. typedef struct Fts5Buffer Fts5Buffer;
  170572. struct Fts5Buffer {
  170573. u8 *p;
  170574. int n;
  170575. int nSpace;
  170576. };
  170577. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  170578. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  170579. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  170580. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  170581. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  170582. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  170583. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  170584. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  170585. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  170586. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  170587. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  170588. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  170589. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  170590. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  170591. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  170592. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  170593. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  170594. )
  170595. /* Write and decode big-endian 32-bit integer values */
  170596. static void sqlite3Fts5Put32(u8*, int);
  170597. static int sqlite3Fts5Get32(const u8*);
  170598. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  170599. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
  170600. typedef struct Fts5PoslistReader Fts5PoslistReader;
  170601. struct Fts5PoslistReader {
  170602. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  170603. const u8 *a; /* Position list to iterate through */
  170604. int n; /* Size of buffer at a[] in bytes */
  170605. int i; /* Current offset in a[] */
  170606. u8 bFlag; /* For client use (any custom purpose) */
  170607. /* Output variables */
  170608. u8 bEof; /* Set to true at EOF */
  170609. i64 iPos; /* (iCol<<32) + iPos */
  170610. };
  170611. static int sqlite3Fts5PoslistReaderInit(
  170612. const u8 *a, int n, /* Poslist buffer to iterate through */
  170613. Fts5PoslistReader *pIter /* Iterator object to initialize */
  170614. );
  170615. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  170616. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  170617. struct Fts5PoslistWriter {
  170618. i64 iPrev;
  170619. };
  170620. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  170621. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  170622. static int sqlite3Fts5PoslistNext64(
  170623. const u8 *a, int n, /* Buffer containing poslist */
  170624. int *pi, /* IN/OUT: Offset within a[] */
  170625. i64 *piOff /* IN/OUT: Current offset */
  170626. );
  170627. /* Malloc utility */
  170628. static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
  170629. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  170630. /* Character set tests (like isspace(), isalpha() etc.) */
  170631. static int sqlite3Fts5IsBareword(char t);
  170632. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  170633. typedef struct Fts5Termset Fts5Termset;
  170634. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  170635. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  170636. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  170637. /*
  170638. ** End of interface to code in fts5_buffer.c.
  170639. **************************************************************************/
  170640. /**************************************************************************
  170641. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  170642. ** to access the data stored in the %_data table.
  170643. */
  170644. typedef struct Fts5Index Fts5Index;
  170645. typedef struct Fts5IndexIter Fts5IndexIter;
  170646. struct Fts5IndexIter {
  170647. i64 iRowid;
  170648. const u8 *pData;
  170649. int nData;
  170650. u8 bEof;
  170651. };
  170652. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  170653. /*
  170654. ** Values used as part of the flags argument passed to IndexQuery().
  170655. */
  170656. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  170657. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  170658. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  170659. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  170660. /* The following are used internally by the fts5_index.c module. They are
  170661. ** defined here only to make it easier to avoid clashes with the flags
  170662. ** above. */
  170663. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  170664. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  170665. /*
  170666. ** Create/destroy an Fts5Index object.
  170667. */
  170668. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  170669. static int sqlite3Fts5IndexClose(Fts5Index *p);
  170670. /*
  170671. ** Return a simple checksum value based on the arguments.
  170672. */
  170673. static u64 sqlite3Fts5IndexEntryCksum(
  170674. i64 iRowid,
  170675. int iCol,
  170676. int iPos,
  170677. int iIdx,
  170678. const char *pTerm,
  170679. int nTerm
  170680. );
  170681. /*
  170682. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  170683. ** size. Return the number of bytes in the nChar character prefix of the
  170684. ** buffer, or 0 if there are less than nChar characters in total.
  170685. */
  170686. static int sqlite3Fts5IndexCharlenToBytelen(
  170687. const char *p,
  170688. int nByte,
  170689. int nChar
  170690. );
  170691. /*
  170692. ** Open a new iterator to iterate though all rowids that match the
  170693. ** specified token or token prefix.
  170694. */
  170695. static int sqlite3Fts5IndexQuery(
  170696. Fts5Index *p, /* FTS index to query */
  170697. const char *pToken, int nToken, /* Token (or prefix) to query for */
  170698. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  170699. Fts5Colset *pColset, /* Match these columns only */
  170700. Fts5IndexIter **ppIter /* OUT: New iterator object */
  170701. );
  170702. /*
  170703. ** The various operations on open token or token prefix iterators opened
  170704. ** using sqlite3Fts5IndexQuery().
  170705. */
  170706. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  170707. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  170708. /*
  170709. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  170710. */
  170711. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  170712. /*
  170713. ** This interface is used by the fts5vocab module.
  170714. */
  170715. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  170716. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  170717. /*
  170718. ** Insert or remove data to or from the index. Each time a document is
  170719. ** added to or removed from the index, this function is called one or more
  170720. ** times.
  170721. **
  170722. ** For an insert, it must be called once for each token in the new document.
  170723. ** If the operation is a delete, it must be called (at least) once for each
  170724. ** unique token in the document with an iCol value less than zero. The iPos
  170725. ** argument is ignored for a delete.
  170726. */
  170727. static int sqlite3Fts5IndexWrite(
  170728. Fts5Index *p, /* Index to write to */
  170729. int iCol, /* Column token appears in (-ve -> delete) */
  170730. int iPos, /* Position of token within column */
  170731. const char *pToken, int nToken /* Token to add or remove to or from index */
  170732. );
  170733. /*
  170734. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  170735. ** document iDocid.
  170736. */
  170737. static int sqlite3Fts5IndexBeginWrite(
  170738. Fts5Index *p, /* Index to write to */
  170739. int bDelete, /* True if current operation is a delete */
  170740. i64 iDocid /* Docid to add or remove data from */
  170741. );
  170742. /*
  170743. ** Flush any data stored in the in-memory hash tables to the database.
  170744. ** Also close any open blob handles.
  170745. */
  170746. static int sqlite3Fts5IndexSync(Fts5Index *p);
  170747. /*
  170748. ** Discard any data stored in the in-memory hash tables. Do not write it
  170749. ** to the database. Additionally, assume that the contents of the %_data
  170750. ** table may have changed on disk. So any in-memory caches of %_data
  170751. ** records must be invalidated.
  170752. */
  170753. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  170754. /*
  170755. ** Get or set the "averages" values.
  170756. */
  170757. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  170758. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  170759. /*
  170760. ** Functions called by the storage module as part of integrity-check.
  170761. */
  170762. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  170763. /*
  170764. ** Called during virtual module initialization to register UDF
  170765. ** fts5_decode() with SQLite
  170766. */
  170767. static int sqlite3Fts5IndexInit(sqlite3*);
  170768. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  170769. /*
  170770. ** Return the total number of entries read from the %_data table by
  170771. ** this connection since it was created.
  170772. */
  170773. static int sqlite3Fts5IndexReads(Fts5Index *p);
  170774. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  170775. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  170776. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  170777. static int sqlite3Fts5IndexReset(Fts5Index *p);
  170778. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  170779. /*
  170780. ** End of interface to code in fts5_index.c.
  170781. **************************************************************************/
  170782. /**************************************************************************
  170783. ** Interface to code in fts5_varint.c.
  170784. */
  170785. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  170786. static int sqlite3Fts5GetVarintLen(u32 iVal);
  170787. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  170788. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  170789. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  170790. #define fts5GetVarint sqlite3Fts5GetVarint
  170791. #define fts5FastGetVarint32(a, iOff, nVal) { \
  170792. nVal = (a)[iOff++]; \
  170793. if( nVal & 0x80 ){ \
  170794. iOff--; \
  170795. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  170796. } \
  170797. }
  170798. /*
  170799. ** End of interface to code in fts5_varint.c.
  170800. **************************************************************************/
  170801. /**************************************************************************
  170802. ** Interface to code in fts5.c.
  170803. */
  170804. static int sqlite3Fts5GetTokenizer(
  170805. Fts5Global*,
  170806. const char **azArg,
  170807. int nArg,
  170808. Fts5Tokenizer**,
  170809. fts5_tokenizer**,
  170810. char **pzErr
  170811. );
  170812. static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
  170813. /*
  170814. ** End of interface to code in fts5.c.
  170815. **************************************************************************/
  170816. /**************************************************************************
  170817. ** Interface to code in fts5_hash.c.
  170818. */
  170819. typedef struct Fts5Hash Fts5Hash;
  170820. /*
  170821. ** Create a hash table, free a hash table.
  170822. */
  170823. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  170824. static void sqlite3Fts5HashFree(Fts5Hash*);
  170825. static int sqlite3Fts5HashWrite(
  170826. Fts5Hash*,
  170827. i64 iRowid, /* Rowid for this entry */
  170828. int iCol, /* Column token appears in (-ve -> delete) */
  170829. int iPos, /* Position of token within column */
  170830. char bByte,
  170831. const char *pToken, int nToken /* Token to add or remove to or from index */
  170832. );
  170833. /*
  170834. ** Empty (but do not delete) a hash table.
  170835. */
  170836. static void sqlite3Fts5HashClear(Fts5Hash*);
  170837. static int sqlite3Fts5HashQuery(
  170838. Fts5Hash*, /* Hash table to query */
  170839. const char *pTerm, int nTerm, /* Query term */
  170840. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  170841. int *pnDoclist /* OUT: Size of doclist in bytes */
  170842. );
  170843. static int sqlite3Fts5HashScanInit(
  170844. Fts5Hash*, /* Hash table to query */
  170845. const char *pTerm, int nTerm /* Query prefix */
  170846. );
  170847. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  170848. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  170849. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  170850. const char **pzTerm, /* OUT: term (nul-terminated) */
  170851. const u8 **ppDoclist, /* OUT: pointer to doclist */
  170852. int *pnDoclist /* OUT: size of doclist in bytes */
  170853. );
  170854. /*
  170855. ** End of interface to code in fts5_hash.c.
  170856. **************************************************************************/
  170857. /**************************************************************************
  170858. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  170859. ** code to access the data stored in the %_content and %_docsize tables.
  170860. */
  170861. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  170862. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  170863. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  170864. typedef struct Fts5Storage Fts5Storage;
  170865. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  170866. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  170867. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  170868. static int sqlite3Fts5DropAll(Fts5Config*);
  170869. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  170870. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  170871. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  170872. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  170873. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  170874. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  170875. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  170876. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  170877. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  170878. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  170879. static int sqlite3Fts5StorageSync(Fts5Storage *p);
  170880. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  170881. static int sqlite3Fts5StorageConfigValue(
  170882. Fts5Storage *p, const char*, sqlite3_value*, int
  170883. );
  170884. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  170885. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  170886. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  170887. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  170888. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  170889. /*
  170890. ** End of interface to code in fts5_storage.c.
  170891. **************************************************************************/
  170892. /**************************************************************************
  170893. ** Interface to code in fts5_expr.c.
  170894. */
  170895. typedef struct Fts5Expr Fts5Expr;
  170896. typedef struct Fts5ExprNode Fts5ExprNode;
  170897. typedef struct Fts5Parse Fts5Parse;
  170898. typedef struct Fts5Token Fts5Token;
  170899. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  170900. typedef struct Fts5ExprNearset Fts5ExprNearset;
  170901. struct Fts5Token {
  170902. const char *p; /* Token text (not NULL terminated) */
  170903. int n; /* Size of buffer p in bytes */
  170904. };
  170905. /* Parse a MATCH expression. */
  170906. static int sqlite3Fts5ExprNew(
  170907. Fts5Config *pConfig,
  170908. int iCol, /* Column on LHS of MATCH operator */
  170909. const char *zExpr,
  170910. Fts5Expr **ppNew,
  170911. char **pzErr
  170912. );
  170913. /*
  170914. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  170915. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  170916. ** rc = sqlite3Fts5ExprNext(pExpr)
  170917. ** ){
  170918. ** // The document with rowid iRowid matches the expression!
  170919. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  170920. ** }
  170921. */
  170922. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  170923. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  170924. static int sqlite3Fts5ExprEof(Fts5Expr*);
  170925. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  170926. static void sqlite3Fts5ExprFree(Fts5Expr*);
  170927. /* Called during startup to register a UDF with SQLite */
  170928. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  170929. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  170930. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  170931. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  170932. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  170933. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  170934. static int sqlite3Fts5ExprPopulatePoslists(
  170935. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  170936. );
  170937. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  170938. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  170939. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  170940. /*******************************************
  170941. ** The fts5_expr.c API above this point is used by the other hand-written
  170942. ** C code in this module. The interfaces below this point are called by
  170943. ** the parser code in fts5parse.y. */
  170944. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  170945. static Fts5ExprNode *sqlite3Fts5ParseNode(
  170946. Fts5Parse *pParse,
  170947. int eType,
  170948. Fts5ExprNode *pLeft,
  170949. Fts5ExprNode *pRight,
  170950. Fts5ExprNearset *pNear
  170951. );
  170952. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  170953. Fts5Parse *pParse,
  170954. Fts5ExprNode *pLeft,
  170955. Fts5ExprNode *pRight
  170956. );
  170957. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  170958. Fts5Parse *pParse,
  170959. Fts5ExprPhrase *pPhrase,
  170960. Fts5Token *pToken,
  170961. int bPrefix
  170962. );
  170963. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  170964. Fts5Parse*,
  170965. Fts5ExprNearset*,
  170966. Fts5ExprPhrase*
  170967. );
  170968. static Fts5Colset *sqlite3Fts5ParseColset(
  170969. Fts5Parse*,
  170970. Fts5Colset*,
  170971. Fts5Token *
  170972. );
  170973. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  170974. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  170975. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  170976. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  170977. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
  170978. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
  170979. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  170980. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  170981. /*
  170982. ** End of interface to code in fts5_expr.c.
  170983. **************************************************************************/
  170984. /**************************************************************************
  170985. ** Interface to code in fts5_aux.c.
  170986. */
  170987. static int sqlite3Fts5AuxInit(fts5_api*);
  170988. /*
  170989. ** End of interface to code in fts5_aux.c.
  170990. **************************************************************************/
  170991. /**************************************************************************
  170992. ** Interface to code in fts5_tokenizer.c.
  170993. */
  170994. static int sqlite3Fts5TokenizerInit(fts5_api*);
  170995. /*
  170996. ** End of interface to code in fts5_tokenizer.c.
  170997. **************************************************************************/
  170998. /**************************************************************************
  170999. ** Interface to code in fts5_vocab.c.
  171000. */
  171001. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  171002. /*
  171003. ** End of interface to code in fts5_vocab.c.
  171004. **************************************************************************/
  171005. /**************************************************************************
  171006. ** Interface to automatically generated code in fts5_unicode2.c.
  171007. */
  171008. static int sqlite3Fts5UnicodeIsalnum(int c);
  171009. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  171010. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  171011. /*
  171012. ** End of interface to code in fts5_unicode2.c.
  171013. **************************************************************************/
  171014. #endif
  171015. #define FTS5_OR 1
  171016. #define FTS5_AND 2
  171017. #define FTS5_NOT 3
  171018. #define FTS5_TERM 4
  171019. #define FTS5_COLON 5
  171020. #define FTS5_MINUS 6
  171021. #define FTS5_LCP 7
  171022. #define FTS5_RCP 8
  171023. #define FTS5_STRING 9
  171024. #define FTS5_LP 10
  171025. #define FTS5_RP 11
  171026. #define FTS5_COMMA 12
  171027. #define FTS5_PLUS 13
  171028. #define FTS5_STAR 14
  171029. /*
  171030. ** 2000-05-29
  171031. **
  171032. ** The author disclaims copyright to this source code. In place of
  171033. ** a legal notice, here is a blessing:
  171034. **
  171035. ** May you do good and not evil.
  171036. ** May you find forgiveness for yourself and forgive others.
  171037. ** May you share freely, never taking more than you give.
  171038. **
  171039. *************************************************************************
  171040. ** Driver template for the LEMON parser generator.
  171041. **
  171042. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  171043. ** this template to construct a parser. The "lemon" program inserts text
  171044. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  171045. ** interstitial "-" characters) contained in this template is changed into
  171046. ** the value of the %name directive from the grammar. Otherwise, the content
  171047. ** of this template is copied straight through into the generate parser
  171048. ** source file.
  171049. **
  171050. ** The following is the concatenation of all %include directives from the
  171051. ** input grammar file:
  171052. */
  171053. /* #include <stdio.h> */
  171054. /************ Begin %include sections from the grammar ************************/
  171055. /* #include "fts5Int.h" */
  171056. /* #include "fts5parse.h" */
  171057. /*
  171058. ** Disable all error recovery processing in the parser push-down
  171059. ** automaton.
  171060. */
  171061. #define fts5YYNOERRORRECOVERY 1
  171062. /*
  171063. ** Make fts5yytestcase() the same as testcase()
  171064. */
  171065. #define fts5yytestcase(X) testcase(X)
  171066. /*
  171067. ** Indicate that sqlite3ParserFree() will never be called with a null
  171068. ** pointer.
  171069. */
  171070. #define fts5YYPARSEFREENOTNULL 1
  171071. /*
  171072. ** Alternative datatype for the argument to the malloc() routine passed
  171073. ** into sqlite3ParserAlloc(). The default is size_t.
  171074. */
  171075. #define fts5YYMALLOCARGTYPE u64
  171076. /**************** End of %include directives **********************************/
  171077. /* These constants specify the various numeric values for terminal symbols
  171078. ** in a format understandable to "makeheaders". This section is blank unless
  171079. ** "lemon" is run with the "-m" command-line option.
  171080. ***************** Begin makeheaders token definitions *************************/
  171081. /**************** End makeheaders token definitions ***************************/
  171082. /* The next sections is a series of control #defines.
  171083. ** various aspects of the generated parser.
  171084. ** fts5YYCODETYPE is the data type used to store the integer codes
  171085. ** that represent terminal and non-terminal symbols.
  171086. ** "unsigned char" is used if there are fewer than
  171087. ** 256 symbols. Larger types otherwise.
  171088. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  171089. ** any terminal or nonterminal symbol.
  171090. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  171091. ** (also known as: "terminal symbols") have fall-back
  171092. ** values which should be used if the original symbol
  171093. ** would not parse. This permits keywords to sometimes
  171094. ** be used as identifiers, for example.
  171095. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  171096. ** that indicate what to do in response to the next
  171097. ** token.
  171098. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  171099. ** symbols. Background: A "minor type" is a semantic
  171100. ** value associated with a terminal or non-terminal
  171101. ** symbols. For example, for an "ID" terminal symbol,
  171102. ** the minor type might be the name of the identifier.
  171103. ** Each non-terminal can have a different minor type.
  171104. ** Terminal symbols all have the same minor type, though.
  171105. ** This macros defines the minor type for terminal
  171106. ** symbols.
  171107. ** fts5YYMINORTYPE is the data type used for all minor types.
  171108. ** This is typically a union of many types, one of
  171109. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  171110. ** for terminal symbols is called "fts5yy0".
  171111. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  171112. ** zero the stack is dynamically sized using realloc()
  171113. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  171114. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  171115. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  171116. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  171117. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  171118. ** defined, then do no error processing.
  171119. ** fts5YYNSTATE the combined number of states.
  171120. ** fts5YYNRULE the number of rules in the grammar
  171121. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  171122. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  171123. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  171124. ** fts5YY_MIN_REDUCE Maximum value for reduce actions
  171125. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  171126. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  171127. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  171128. */
  171129. #ifndef INTERFACE
  171130. # define INTERFACE 1
  171131. #endif
  171132. /************* Begin control #defines *****************************************/
  171133. #define fts5YYCODETYPE unsigned char
  171134. #define fts5YYNOCODE 28
  171135. #define fts5YYACTIONTYPE unsigned char
  171136. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  171137. typedef union {
  171138. int fts5yyinit;
  171139. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  171140. int fts5yy4;
  171141. Fts5Colset* fts5yy11;
  171142. Fts5ExprNode* fts5yy24;
  171143. Fts5ExprNearset* fts5yy46;
  171144. Fts5ExprPhrase* fts5yy53;
  171145. } fts5YYMINORTYPE;
  171146. #ifndef fts5YYSTACKDEPTH
  171147. #define fts5YYSTACKDEPTH 100
  171148. #endif
  171149. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  171150. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  171151. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
  171152. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
  171153. #define fts5YYNSTATE 33
  171154. #define fts5YYNRULE 27
  171155. #define fts5YY_MAX_SHIFT 32
  171156. #define fts5YY_MIN_SHIFTREDUCE 50
  171157. #define fts5YY_MAX_SHIFTREDUCE 76
  171158. #define fts5YY_MIN_REDUCE 77
  171159. #define fts5YY_MAX_REDUCE 103
  171160. #define fts5YY_ERROR_ACTION 104
  171161. #define fts5YY_ACCEPT_ACTION 105
  171162. #define fts5YY_NO_ACTION 106
  171163. /************* End control #defines *******************************************/
  171164. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  171165. ** otherwise.
  171166. **
  171167. ** Applications can choose to define fts5yytestcase() in the %include section
  171168. ** to a macro that can assist in verifying code coverage. For production
  171169. ** code the fts5yytestcase() macro should be turned off. But it is useful
  171170. ** for testing.
  171171. */
  171172. #ifndef fts5yytestcase
  171173. # define fts5yytestcase(X)
  171174. #endif
  171175. /* Next are the tables used to determine what action to take based on the
  171176. ** current state and lookahead token. These tables are used to implement
  171177. ** functions that take a state number and lookahead value and return an
  171178. ** action integer.
  171179. **
  171180. ** Suppose the action integer is N. Then the action is determined as
  171181. ** follows
  171182. **
  171183. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  171184. ** token onto the stack and goto state N.
  171185. **
  171186. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  171187. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  171188. **
  171189. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  171190. ** and fts5YY_MAX_REDUCE
  171191. **
  171192. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  171193. **
  171194. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  171195. **
  171196. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  171197. ** slots in the fts5yy_action[] table.
  171198. **
  171199. ** The action table is constructed as a single large table named fts5yy_action[].
  171200. ** Given state S and lookahead X, the action is computed as either:
  171201. **
  171202. ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  171203. ** (B) N = fts5yy_default[S]
  171204. **
  171205. ** The (A) formula is preferred. The B formula is used instead if:
  171206. ** (1) The fts5yy_shift_ofst[S]+X value is out of range, or
  171207. ** (2) fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or
  171208. ** (3) fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT.
  171209. ** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that
  171210. ** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
  171211. ** Hence only tests (1) and (2) need to be evaluated.)
  171212. **
  171213. ** The formulas above are for computing the action when the lookahead is
  171214. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  171215. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  171216. ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
  171217. ** fts5YY_SHIFT_USE_DFLT.
  171218. **
  171219. ** The following are the tables generated in this section:
  171220. **
  171221. ** fts5yy_action[] A single table containing all actions.
  171222. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  171223. ** fts5yy_action. Used to detect hash collisions.
  171224. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  171225. ** shifting terminals.
  171226. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  171227. ** shifting non-terminals after a reduce.
  171228. ** fts5yy_default[] Default action for each state.
  171229. **
  171230. *********** Begin parsing tables **********************************************/
  171231. #define fts5YY_ACTTAB_COUNT (98)
  171232. static const fts5YYACTIONTYPE fts5yy_action[] = {
  171233. /* 0 */ 105, 19, 63, 6, 26, 66, 65, 24, 24, 17,
  171234. /* 10 */ 63, 6, 26, 16, 65, 54, 24, 18, 63, 6,
  171235. /* 20 */ 26, 10, 65, 12, 24, 75, 59, 63, 6, 26,
  171236. /* 30 */ 13, 65, 75, 24, 20, 63, 6, 26, 74, 65,
  171237. /* 40 */ 56, 24, 27, 63, 6, 26, 73, 65, 21, 24,
  171238. /* 50 */ 23, 15, 30, 11, 1, 64, 22, 25, 9, 65,
  171239. /* 60 */ 7, 24, 3, 4, 5, 3, 4, 5, 3, 77,
  171240. /* 70 */ 4, 5, 3, 61, 23, 15, 60, 11, 80, 12,
  171241. /* 80 */ 2, 13, 68, 10, 29, 52, 55, 75, 31, 32,
  171242. /* 90 */ 8, 28, 5, 3, 51, 55, 72, 14,
  171243. };
  171244. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  171245. /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
  171246. /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
  171247. /* 20 */ 20, 10, 22, 9, 24, 14, 17, 18, 19, 20,
  171248. /* 30 */ 9, 22, 14, 24, 17, 18, 19, 20, 26, 22,
  171249. /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
  171250. /* 50 */ 6, 7, 13, 9, 10, 18, 21, 20, 5, 22,
  171251. /* 60 */ 5, 24, 3, 1, 2, 3, 1, 2, 3, 0,
  171252. /* 70 */ 1, 2, 3, 11, 6, 7, 11, 9, 5, 9,
  171253. /* 80 */ 10, 9, 11, 10, 12, 8, 9, 14, 24, 25,
  171254. /* 90 */ 23, 24, 2, 3, 8, 9, 9, 9,
  171255. };
  171256. #define fts5YY_SHIFT_USE_DFLT (98)
  171257. #define fts5YY_SHIFT_COUNT (32)
  171258. #define fts5YY_SHIFT_MIN (0)
  171259. #define fts5YY_SHIFT_MAX (90)
  171260. static const unsigned char fts5yy_shift_ofst[] = {
  171261. /* 0 */ 44, 44, 44, 44, 44, 44, 68, 70, 72, 14,
  171262. /* 10 */ 21, 73, 11, 18, 18, 31, 31, 62, 65, 69,
  171263. /* 20 */ 90, 77, 86, 6, 39, 53, 55, 59, 39, 87,
  171264. /* 30 */ 88, 39, 71,
  171265. };
  171266. #define fts5YY_REDUCE_USE_DFLT (-18)
  171267. #define fts5YY_REDUCE_COUNT (16)
  171268. #define fts5YY_REDUCE_MIN (-17)
  171269. #define fts5YY_REDUCE_MAX (67)
  171270. static const signed char fts5yy_reduce_ofst[] = {
  171271. /* 0 */ -16, -8, 0, 9, 17, 25, 37, -17, 64, -17,
  171272. /* 10 */ 67, 12, 12, 12, 20, 27, 35,
  171273. };
  171274. static const fts5YYACTIONTYPE fts5yy_default[] = {
  171275. /* 0 */ 104, 104, 104, 104, 104, 104, 89, 104, 98, 104,
  171276. /* 10 */ 104, 103, 103, 103, 103, 104, 104, 104, 104, 104,
  171277. /* 20 */ 85, 104, 104, 104, 94, 104, 104, 84, 96, 104,
  171278. /* 30 */ 104, 97, 104,
  171279. };
  171280. /********** End of lemon-generated parsing tables *****************************/
  171281. /* The next table maps tokens (terminal symbols) into fallback tokens.
  171282. ** If a construct like the following:
  171283. **
  171284. ** %fallback ID X Y Z.
  171285. **
  171286. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  171287. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  171288. ** but it does not parse, the type of the token is changed to ID and
  171289. ** the parse is retried before an error is thrown.
  171290. **
  171291. ** This feature can be used, for example, to cause some keywords in a language
  171292. ** to revert to identifiers if they keyword does not apply in the context where
  171293. ** it appears.
  171294. */
  171295. #ifdef fts5YYFALLBACK
  171296. static const fts5YYCODETYPE fts5yyFallback[] = {
  171297. };
  171298. #endif /* fts5YYFALLBACK */
  171299. /* The following structure represents a single element of the
  171300. ** parser's stack. Information stored includes:
  171301. **
  171302. ** + The state number for the parser at this level of the stack.
  171303. **
  171304. ** + The value of the token stored at this level of the stack.
  171305. ** (In other words, the "major" token.)
  171306. **
  171307. ** + The semantic value stored at this level of the stack. This is
  171308. ** the information used by the action routines in the grammar.
  171309. ** It is sometimes called the "minor" token.
  171310. **
  171311. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  171312. ** actually contains the reduce action for the second half of the
  171313. ** SHIFTREDUCE.
  171314. */
  171315. struct fts5yyStackEntry {
  171316. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  171317. fts5YYCODETYPE major; /* The major token value. This is the code
  171318. ** number for the token at this stack level */
  171319. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  171320. ** is the value of the token */
  171321. };
  171322. typedef struct fts5yyStackEntry fts5yyStackEntry;
  171323. /* The state of the parser is completely contained in an instance of
  171324. ** the following structure */
  171325. struct fts5yyParser {
  171326. fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
  171327. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171328. int fts5yyhwm; /* High-water mark of the stack */
  171329. #endif
  171330. #ifndef fts5YYNOERRORRECOVERY
  171331. int fts5yyerrcnt; /* Shifts left before out of the error */
  171332. #endif
  171333. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  171334. #if fts5YYSTACKDEPTH<=0
  171335. int fts5yystksz; /* Current side of the stack */
  171336. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  171337. fts5yyStackEntry fts5yystk0; /* First stack entry */
  171338. #else
  171339. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  171340. #endif
  171341. };
  171342. typedef struct fts5yyParser fts5yyParser;
  171343. #ifndef NDEBUG
  171344. /* #include <stdio.h> */
  171345. static FILE *fts5yyTraceFILE = 0;
  171346. static char *fts5yyTracePrompt = 0;
  171347. #endif /* NDEBUG */
  171348. #ifndef NDEBUG
  171349. /*
  171350. ** Turn parser tracing on by giving a stream to which to write the trace
  171351. ** and a prompt to preface each trace message. Tracing is turned off
  171352. ** by making either argument NULL
  171353. **
  171354. ** Inputs:
  171355. ** <ul>
  171356. ** <li> A FILE* to which trace output should be written.
  171357. ** If NULL, then tracing is turned off.
  171358. ** <li> A prefix string written at the beginning of every
  171359. ** line of trace output. If NULL, then tracing is
  171360. ** turned off.
  171361. ** </ul>
  171362. **
  171363. ** Outputs:
  171364. ** None.
  171365. */
  171366. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  171367. fts5yyTraceFILE = TraceFILE;
  171368. fts5yyTracePrompt = zTracePrompt;
  171369. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  171370. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  171371. }
  171372. #endif /* NDEBUG */
  171373. #ifndef NDEBUG
  171374. /* For tracing shifts, the names of all terminals and nonterminals
  171375. ** are required. The following table supplies these names */
  171376. static const char *const fts5yyTokenName[] = {
  171377. "$", "OR", "AND", "NOT",
  171378. "TERM", "COLON", "MINUS", "LCP",
  171379. "RCP", "STRING", "LP", "RP",
  171380. "COMMA", "PLUS", "STAR", "error",
  171381. "input", "expr", "cnearset", "exprlist",
  171382. "colset", "colsetlist", "nearset", "nearphrases",
  171383. "phrase", "neardist_opt", "star_opt",
  171384. };
  171385. #endif /* NDEBUG */
  171386. #ifndef NDEBUG
  171387. /* For tracing reduce actions, the names of all rules are required.
  171388. */
  171389. static const char *const fts5yyRuleName[] = {
  171390. /* 0 */ "input ::= expr",
  171391. /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
  171392. /* 2 */ "colset ::= LCP colsetlist RCP",
  171393. /* 3 */ "colset ::= STRING",
  171394. /* 4 */ "colset ::= MINUS STRING",
  171395. /* 5 */ "colsetlist ::= colsetlist STRING",
  171396. /* 6 */ "colsetlist ::= STRING",
  171397. /* 7 */ "expr ::= expr AND expr",
  171398. /* 8 */ "expr ::= expr OR expr",
  171399. /* 9 */ "expr ::= expr NOT expr",
  171400. /* 10 */ "expr ::= colset COLON LP expr RP",
  171401. /* 11 */ "expr ::= LP expr RP",
  171402. /* 12 */ "expr ::= exprlist",
  171403. /* 13 */ "exprlist ::= cnearset",
  171404. /* 14 */ "exprlist ::= exprlist cnearset",
  171405. /* 15 */ "cnearset ::= nearset",
  171406. /* 16 */ "cnearset ::= colset COLON nearset",
  171407. /* 17 */ "nearset ::= phrase",
  171408. /* 18 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  171409. /* 19 */ "nearphrases ::= phrase",
  171410. /* 20 */ "nearphrases ::= nearphrases phrase",
  171411. /* 21 */ "neardist_opt ::=",
  171412. /* 22 */ "neardist_opt ::= COMMA STRING",
  171413. /* 23 */ "phrase ::= phrase PLUS STRING star_opt",
  171414. /* 24 */ "phrase ::= STRING star_opt",
  171415. /* 25 */ "star_opt ::= STAR",
  171416. /* 26 */ "star_opt ::=",
  171417. };
  171418. #endif /* NDEBUG */
  171419. #if fts5YYSTACKDEPTH<=0
  171420. /*
  171421. ** Try to increase the size of the parser stack. Return the number
  171422. ** of errors. Return 0 on success.
  171423. */
  171424. static int fts5yyGrowStack(fts5yyParser *p){
  171425. int newSize;
  171426. int idx;
  171427. fts5yyStackEntry *pNew;
  171428. newSize = p->fts5yystksz*2 + 100;
  171429. idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
  171430. if( p->fts5yystack==&p->fts5yystk0 ){
  171431. pNew = malloc(newSize*sizeof(pNew[0]));
  171432. if( pNew ) pNew[0] = p->fts5yystk0;
  171433. }else{
  171434. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  171435. }
  171436. if( pNew ){
  171437. p->fts5yystack = pNew;
  171438. p->fts5yytos = &p->fts5yystack[idx];
  171439. #ifndef NDEBUG
  171440. if( fts5yyTraceFILE ){
  171441. fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  171442. fts5yyTracePrompt, p->fts5yystksz, newSize);
  171443. }
  171444. #endif
  171445. p->fts5yystksz = newSize;
  171446. }
  171447. return pNew==0;
  171448. }
  171449. #endif
  171450. /* Datatype of the argument to the memory allocated passed as the
  171451. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  171452. ** putting an appropriate #define in the %include section of the input
  171453. ** grammar.
  171454. */
  171455. #ifndef fts5YYMALLOCARGTYPE
  171456. # define fts5YYMALLOCARGTYPE size_t
  171457. #endif
  171458. /* Initialize a new parser that has already been allocated.
  171459. */
  171460. static void sqlite3Fts5ParserInit(void *fts5yypParser){
  171461. fts5yyParser *pParser = (fts5yyParser*)fts5yypParser;
  171462. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171463. pParser->fts5yyhwm = 0;
  171464. #endif
  171465. #if fts5YYSTACKDEPTH<=0
  171466. pParser->fts5yytos = NULL;
  171467. pParser->fts5yystack = NULL;
  171468. pParser->fts5yystksz = 0;
  171469. if( fts5yyGrowStack(pParser) ){
  171470. pParser->fts5yystack = &pParser->fts5yystk0;
  171471. pParser->fts5yystksz = 1;
  171472. }
  171473. #endif
  171474. #ifndef fts5YYNOERRORRECOVERY
  171475. pParser->fts5yyerrcnt = -1;
  171476. #endif
  171477. pParser->fts5yytos = pParser->fts5yystack;
  171478. pParser->fts5yystack[0].stateno = 0;
  171479. pParser->fts5yystack[0].major = 0;
  171480. }
  171481. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  171482. /*
  171483. ** This function allocates a new parser.
  171484. ** The only argument is a pointer to a function which works like
  171485. ** malloc.
  171486. **
  171487. ** Inputs:
  171488. ** A pointer to the function used to allocate memory.
  171489. **
  171490. ** Outputs:
  171491. ** A pointer to a parser. This pointer is used in subsequent calls
  171492. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  171493. */
  171494. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
  171495. fts5yyParser *pParser;
  171496. pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  171497. if( pParser ) sqlite3Fts5ParserInit(pParser);
  171498. return pParser;
  171499. }
  171500. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  171501. /* The following function deletes the "minor type" or semantic value
  171502. ** associated with a symbol. The symbol can be either a terminal
  171503. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  171504. ** a pointer to the value to be deleted. The code used to do the
  171505. ** deletions is derived from the %destructor and/or %token_destructor
  171506. ** directives of the input grammar.
  171507. */
  171508. static void fts5yy_destructor(
  171509. fts5yyParser *fts5yypParser, /* The parser */
  171510. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  171511. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  171512. ){
  171513. sqlite3Fts5ParserARG_FETCH;
  171514. switch( fts5yymajor ){
  171515. /* Here is inserted the actions which take place when a
  171516. ** terminal or non-terminal is destroyed. This can happen
  171517. ** when the symbol is popped from the stack during a
  171518. ** reduce or during error processing or when a parser is
  171519. ** being destroyed before it is finished parsing.
  171520. **
  171521. ** Note: during a reduce, the only symbols destroyed are those
  171522. ** which appear on the RHS of the rule, but which are *not* used
  171523. ** inside the C code.
  171524. */
  171525. /********* Begin destructor definitions ***************************************/
  171526. case 16: /* input */
  171527. {
  171528. (void)pParse;
  171529. }
  171530. break;
  171531. case 17: /* expr */
  171532. case 18: /* cnearset */
  171533. case 19: /* exprlist */
  171534. {
  171535. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
  171536. }
  171537. break;
  171538. case 20: /* colset */
  171539. case 21: /* colsetlist */
  171540. {
  171541. sqlite3_free((fts5yypminor->fts5yy11));
  171542. }
  171543. break;
  171544. case 22: /* nearset */
  171545. case 23: /* nearphrases */
  171546. {
  171547. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
  171548. }
  171549. break;
  171550. case 24: /* phrase */
  171551. {
  171552. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
  171553. }
  171554. break;
  171555. /********* End destructor definitions *****************************************/
  171556. default: break; /* If no destructor action specified: do nothing */
  171557. }
  171558. }
  171559. /*
  171560. ** Pop the parser's stack once.
  171561. **
  171562. ** If there is a destructor routine associated with the token which
  171563. ** is popped from the stack, then call it.
  171564. */
  171565. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  171566. fts5yyStackEntry *fts5yytos;
  171567. assert( pParser->fts5yytos!=0 );
  171568. assert( pParser->fts5yytos > pParser->fts5yystack );
  171569. fts5yytos = pParser->fts5yytos--;
  171570. #ifndef NDEBUG
  171571. if( fts5yyTraceFILE ){
  171572. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  171573. fts5yyTracePrompt,
  171574. fts5yyTokenName[fts5yytos->major]);
  171575. }
  171576. #endif
  171577. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  171578. }
  171579. /*
  171580. ** Clear all secondary memory allocations from the parser
  171581. */
  171582. static void sqlite3Fts5ParserFinalize(void *p){
  171583. fts5yyParser *pParser = (fts5yyParser*)p;
  171584. while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
  171585. #if fts5YYSTACKDEPTH<=0
  171586. if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
  171587. #endif
  171588. }
  171589. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  171590. /*
  171591. ** Deallocate and destroy a parser. Destructors are called for
  171592. ** all stack elements before shutting the parser down.
  171593. **
  171594. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  171595. ** is defined in a %include section of the input grammar) then it is
  171596. ** assumed that the input pointer is never NULL.
  171597. */
  171598. static void sqlite3Fts5ParserFree(
  171599. void *p, /* The parser to be deleted */
  171600. void (*freeProc)(void*) /* Function used to reclaim memory */
  171601. ){
  171602. #ifndef fts5YYPARSEFREENEVERNULL
  171603. if( p==0 ) return;
  171604. #endif
  171605. sqlite3Fts5ParserFinalize(p);
  171606. (*freeProc)(p);
  171607. }
  171608. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  171609. /*
  171610. ** Return the peak depth of the stack for a parser.
  171611. */
  171612. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171613. static int sqlite3Fts5ParserStackPeak(void *p){
  171614. fts5yyParser *pParser = (fts5yyParser*)p;
  171615. return pParser->fts5yyhwm;
  171616. }
  171617. #endif
  171618. /*
  171619. ** Find the appropriate action for a parser given the terminal
  171620. ** look-ahead token iLookAhead.
  171621. */
  171622. static unsigned int fts5yy_find_shift_action(
  171623. fts5yyParser *pParser, /* The parser */
  171624. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  171625. ){
  171626. int i;
  171627. int stateno = pParser->fts5yytos->stateno;
  171628. if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
  171629. assert( stateno <= fts5YY_SHIFT_COUNT );
  171630. do{
  171631. i = fts5yy_shift_ofst[stateno];
  171632. assert( iLookAhead!=fts5YYNOCODE );
  171633. i += iLookAhead;
  171634. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  171635. #ifdef fts5YYFALLBACK
  171636. fts5YYCODETYPE iFallback; /* Fallback token */
  171637. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  171638. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  171639. #ifndef NDEBUG
  171640. if( fts5yyTraceFILE ){
  171641. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  171642. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  171643. }
  171644. #endif
  171645. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  171646. iLookAhead = iFallback;
  171647. continue;
  171648. }
  171649. #endif
  171650. #ifdef fts5YYWILDCARD
  171651. {
  171652. int j = i - iLookAhead + fts5YYWILDCARD;
  171653. if(
  171654. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  171655. j>=0 &&
  171656. #endif
  171657. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  171658. j<fts5YY_ACTTAB_COUNT &&
  171659. #endif
  171660. fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
  171661. ){
  171662. #ifndef NDEBUG
  171663. if( fts5yyTraceFILE ){
  171664. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  171665. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  171666. fts5yyTokenName[fts5YYWILDCARD]);
  171667. }
  171668. #endif /* NDEBUG */
  171669. return fts5yy_action[j];
  171670. }
  171671. }
  171672. #endif /* fts5YYWILDCARD */
  171673. return fts5yy_default[stateno];
  171674. }else{
  171675. return fts5yy_action[i];
  171676. }
  171677. }while(1);
  171678. }
  171679. /*
  171680. ** Find the appropriate action for a parser given the non-terminal
  171681. ** look-ahead token iLookAhead.
  171682. */
  171683. static int fts5yy_find_reduce_action(
  171684. int stateno, /* Current state number */
  171685. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  171686. ){
  171687. int i;
  171688. #ifdef fts5YYERRORSYMBOL
  171689. if( stateno>fts5YY_REDUCE_COUNT ){
  171690. return fts5yy_default[stateno];
  171691. }
  171692. #else
  171693. assert( stateno<=fts5YY_REDUCE_COUNT );
  171694. #endif
  171695. i = fts5yy_reduce_ofst[stateno];
  171696. assert( i!=fts5YY_REDUCE_USE_DFLT );
  171697. assert( iLookAhead!=fts5YYNOCODE );
  171698. i += iLookAhead;
  171699. #ifdef fts5YYERRORSYMBOL
  171700. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  171701. return fts5yy_default[stateno];
  171702. }
  171703. #else
  171704. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  171705. assert( fts5yy_lookahead[i]==iLookAhead );
  171706. #endif
  171707. return fts5yy_action[i];
  171708. }
  171709. /*
  171710. ** The following routine is called if the stack overflows.
  171711. */
  171712. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  171713. sqlite3Fts5ParserARG_FETCH;
  171714. #ifndef NDEBUG
  171715. if( fts5yyTraceFILE ){
  171716. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  171717. }
  171718. #endif
  171719. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  171720. /* Here code is inserted which will execute if the parser
  171721. ** stack every overflows */
  171722. /******** Begin %stack_overflow code ******************************************/
  171723. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  171724. /******** End %stack_overflow code ********************************************/
  171725. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  171726. }
  171727. /*
  171728. ** Print tracing information for a SHIFT action
  171729. */
  171730. #ifndef NDEBUG
  171731. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
  171732. if( fts5yyTraceFILE ){
  171733. if( fts5yyNewState<fts5YYNSTATE ){
  171734. fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
  171735. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
  171736. fts5yyNewState);
  171737. }else{
  171738. fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
  171739. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
  171740. }
  171741. }
  171742. }
  171743. #else
  171744. # define fts5yyTraceShift(X,Y)
  171745. #endif
  171746. /*
  171747. ** Perform a shift action.
  171748. */
  171749. static void fts5yy_shift(
  171750. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  171751. int fts5yyNewState, /* The new state to shift in */
  171752. int fts5yyMajor, /* The major token to shift in */
  171753. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  171754. ){
  171755. fts5yyStackEntry *fts5yytos;
  171756. fts5yypParser->fts5yytos++;
  171757. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171758. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  171759. fts5yypParser->fts5yyhwm++;
  171760. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
  171761. }
  171762. #endif
  171763. #if fts5YYSTACKDEPTH>0
  171764. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){
  171765. fts5yypParser->fts5yytos--;
  171766. fts5yyStackOverflow(fts5yypParser);
  171767. return;
  171768. }
  171769. #else
  171770. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
  171771. if( fts5yyGrowStack(fts5yypParser) ){
  171772. fts5yypParser->fts5yytos--;
  171773. fts5yyStackOverflow(fts5yypParser);
  171774. return;
  171775. }
  171776. }
  171777. #endif
  171778. if( fts5yyNewState > fts5YY_MAX_SHIFT ){
  171779. fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  171780. }
  171781. fts5yytos = fts5yypParser->fts5yytos;
  171782. fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
  171783. fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
  171784. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  171785. fts5yyTraceShift(fts5yypParser, fts5yyNewState);
  171786. }
  171787. /* The following table contains information about every rule that
  171788. ** is used during the reduce.
  171789. */
  171790. static const struct {
  171791. fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  171792. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  171793. } fts5yyRuleInfo[] = {
  171794. { 16, 1 },
  171795. { 20, 4 },
  171796. { 20, 3 },
  171797. { 20, 1 },
  171798. { 20, 2 },
  171799. { 21, 2 },
  171800. { 21, 1 },
  171801. { 17, 3 },
  171802. { 17, 3 },
  171803. { 17, 3 },
  171804. { 17, 5 },
  171805. { 17, 3 },
  171806. { 17, 1 },
  171807. { 19, 1 },
  171808. { 19, 2 },
  171809. { 18, 1 },
  171810. { 18, 3 },
  171811. { 22, 1 },
  171812. { 22, 5 },
  171813. { 23, 1 },
  171814. { 23, 2 },
  171815. { 25, 0 },
  171816. { 25, 2 },
  171817. { 24, 4 },
  171818. { 24, 2 },
  171819. { 26, 1 },
  171820. { 26, 0 },
  171821. };
  171822. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  171823. /*
  171824. ** Perform a reduce action and the shift that must immediately
  171825. ** follow the reduce.
  171826. */
  171827. static void fts5yy_reduce(
  171828. fts5yyParser *fts5yypParser, /* The parser */
  171829. unsigned int fts5yyruleno /* Number of the rule by which to reduce */
  171830. ){
  171831. int fts5yygoto; /* The next state */
  171832. int fts5yyact; /* The next action */
  171833. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  171834. int fts5yysize; /* Amount to pop the stack */
  171835. sqlite3Fts5ParserARG_FETCH;
  171836. fts5yymsp = fts5yypParser->fts5yytos;
  171837. #ifndef NDEBUG
  171838. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  171839. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  171840. fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
  171841. fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
  171842. }
  171843. #endif /* NDEBUG */
  171844. /* Check that the stack is large enough to grow by a single entry
  171845. ** if the RHS of the rule is empty. This ensures that there is room
  171846. ** enough on the stack to push the LHS value */
  171847. if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
  171848. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171849. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  171850. fts5yypParser->fts5yyhwm++;
  171851. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
  171852. }
  171853. #endif
  171854. #if fts5YYSTACKDEPTH>0
  171855. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){
  171856. fts5yyStackOverflow(fts5yypParser);
  171857. return;
  171858. }
  171859. #else
  171860. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
  171861. if( fts5yyGrowStack(fts5yypParser) ){
  171862. fts5yyStackOverflow(fts5yypParser);
  171863. return;
  171864. }
  171865. fts5yymsp = fts5yypParser->fts5yytos;
  171866. }
  171867. #endif
  171868. }
  171869. switch( fts5yyruleno ){
  171870. /* Beginning here are the reduction cases. A typical example
  171871. ** follows:
  171872. ** case 0:
  171873. ** #line <lineno> <grammarfile>
  171874. ** { ... } // User supplied code
  171875. ** #line <lineno> <thisfile>
  171876. ** break;
  171877. */
  171878. /********** Begin reduce actions **********************************************/
  171879. fts5YYMINORTYPE fts5yylhsminor;
  171880. case 0: /* input ::= expr */
  171881. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
  171882. break;
  171883. case 1: /* colset ::= MINUS LCP colsetlist RCP */
  171884. {
  171885. fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  171886. }
  171887. break;
  171888. case 2: /* colset ::= LCP colsetlist RCP */
  171889. { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
  171890. break;
  171891. case 3: /* colset ::= STRING */
  171892. {
  171893. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  171894. }
  171895. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  171896. break;
  171897. case 4: /* colset ::= MINUS STRING */
  171898. {
  171899. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  171900. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  171901. }
  171902. break;
  171903. case 5: /* colsetlist ::= colsetlist STRING */
  171904. {
  171905. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
  171906. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  171907. break;
  171908. case 6: /* colsetlist ::= STRING */
  171909. {
  171910. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  171911. }
  171912. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  171913. break;
  171914. case 7: /* expr ::= expr AND expr */
  171915. {
  171916. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  171917. }
  171918. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171919. break;
  171920. case 8: /* expr ::= expr OR expr */
  171921. {
  171922. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  171923. }
  171924. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171925. break;
  171926. case 9: /* expr ::= expr NOT expr */
  171927. {
  171928. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  171929. }
  171930. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171931. break;
  171932. case 10: /* expr ::= colset COLON LP expr RP */
  171933. {
  171934. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
  171935. fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
  171936. }
  171937. fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171938. break;
  171939. case 11: /* expr ::= LP expr RP */
  171940. {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
  171941. break;
  171942. case 12: /* expr ::= exprlist */
  171943. case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
  171944. {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
  171945. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171946. break;
  171947. case 14: /* exprlist ::= exprlist cnearset */
  171948. {
  171949. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
  171950. }
  171951. fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171952. break;
  171953. case 15: /* cnearset ::= nearset */
  171954. {
  171955. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  171956. }
  171957. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171958. break;
  171959. case 16: /* cnearset ::= colset COLON nearset */
  171960. {
  171961. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  171962. sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
  171963. }
  171964. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171965. break;
  171966. case 17: /* nearset ::= phrase */
  171967. { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
  171968. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  171969. break;
  171970. case 18: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  171971. {
  171972. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  171973. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
  171974. fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
  171975. }
  171976. fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  171977. break;
  171978. case 19: /* nearphrases ::= phrase */
  171979. {
  171980. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  171981. }
  171982. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  171983. break;
  171984. case 20: /* nearphrases ::= nearphrases phrase */
  171985. {
  171986. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
  171987. }
  171988. fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  171989. break;
  171990. case 21: /* neardist_opt ::= */
  171991. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  171992. break;
  171993. case 22: /* neardist_opt ::= COMMA STRING */
  171994. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  171995. break;
  171996. case 23: /* phrase ::= phrase PLUS STRING star_opt */
  171997. {
  171998. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  171999. }
  172000. fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  172001. break;
  172002. case 24: /* phrase ::= STRING star_opt */
  172003. {
  172004. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  172005. }
  172006. fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  172007. break;
  172008. case 25: /* star_opt ::= STAR */
  172009. { fts5yymsp[0].minor.fts5yy4 = 1; }
  172010. break;
  172011. case 26: /* star_opt ::= */
  172012. { fts5yymsp[1].minor.fts5yy4 = 0; }
  172013. break;
  172014. default:
  172015. break;
  172016. /********** End reduce actions ************************************************/
  172017. };
  172018. assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
  172019. fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
  172020. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  172021. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  172022. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  172023. if( fts5yyact>fts5YY_MAX_SHIFT ){
  172024. fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  172025. }
  172026. fts5yymsp -= fts5yysize-1;
  172027. fts5yypParser->fts5yytos = fts5yymsp;
  172028. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  172029. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  172030. fts5yyTraceShift(fts5yypParser, fts5yyact);
  172031. }else{
  172032. assert( fts5yyact == fts5YY_ACCEPT_ACTION );
  172033. fts5yypParser->fts5yytos -= fts5yysize;
  172034. fts5yy_accept(fts5yypParser);
  172035. }
  172036. }
  172037. /*
  172038. ** The following code executes when the parse fails
  172039. */
  172040. #ifndef fts5YYNOERRORRECOVERY
  172041. static void fts5yy_parse_failed(
  172042. fts5yyParser *fts5yypParser /* The parser */
  172043. ){
  172044. sqlite3Fts5ParserARG_FETCH;
  172045. #ifndef NDEBUG
  172046. if( fts5yyTraceFILE ){
  172047. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  172048. }
  172049. #endif
  172050. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  172051. /* Here code is inserted which will be executed whenever the
  172052. ** parser fails */
  172053. /************ Begin %parse_failure code ***************************************/
  172054. /************ End %parse_failure code *****************************************/
  172055. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  172056. }
  172057. #endif /* fts5YYNOERRORRECOVERY */
  172058. /*
  172059. ** The following code executes when a syntax error first occurs.
  172060. */
  172061. static void fts5yy_syntax_error(
  172062. fts5yyParser *fts5yypParser, /* The parser */
  172063. int fts5yymajor, /* The major type of the error token */
  172064. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  172065. ){
  172066. sqlite3Fts5ParserARG_FETCH;
  172067. #define FTS5TOKEN fts5yyminor
  172068. /************ Begin %syntax_error code ****************************************/
  172069. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  172070. sqlite3Fts5ParseError(
  172071. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  172072. );
  172073. /************ End %syntax_error code ******************************************/
  172074. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  172075. }
  172076. /*
  172077. ** The following is executed when the parser accepts
  172078. */
  172079. static void fts5yy_accept(
  172080. fts5yyParser *fts5yypParser /* The parser */
  172081. ){
  172082. sqlite3Fts5ParserARG_FETCH;
  172083. #ifndef NDEBUG
  172084. if( fts5yyTraceFILE ){
  172085. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  172086. }
  172087. #endif
  172088. #ifndef fts5YYNOERRORRECOVERY
  172089. fts5yypParser->fts5yyerrcnt = -1;
  172090. #endif
  172091. assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
  172092. /* Here code is inserted which will be executed whenever the
  172093. ** parser accepts */
  172094. /*********** Begin %parse_accept code *****************************************/
  172095. /*********** End %parse_accept code *******************************************/
  172096. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  172097. }
  172098. /* The main parser program.
  172099. ** The first argument is a pointer to a structure obtained from
  172100. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  172101. ** The second argument is the major token number. The third is
  172102. ** the minor token. The fourth optional argument is whatever the
  172103. ** user wants (and specified in the grammar) and is available for
  172104. ** use by the action routines.
  172105. **
  172106. ** Inputs:
  172107. ** <ul>
  172108. ** <li> A pointer to the parser (an opaque structure.)
  172109. ** <li> The major token number.
  172110. ** <li> The minor token number.
  172111. ** <li> An option argument of a grammar-specified type.
  172112. ** </ul>
  172113. **
  172114. ** Outputs:
  172115. ** None.
  172116. */
  172117. static void sqlite3Fts5Parser(
  172118. void *fts5yyp, /* The parser */
  172119. int fts5yymajor, /* The major token code number */
  172120. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  172121. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  172122. ){
  172123. fts5YYMINORTYPE fts5yyminorunion;
  172124. unsigned int fts5yyact; /* The parser action. */
  172125. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  172126. int fts5yyendofinput; /* True if we are at the end of input */
  172127. #endif
  172128. #ifdef fts5YYERRORSYMBOL
  172129. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  172130. #endif
  172131. fts5yyParser *fts5yypParser; /* The parser */
  172132. fts5yypParser = (fts5yyParser*)fts5yyp;
  172133. assert( fts5yypParser->fts5yytos!=0 );
  172134. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  172135. fts5yyendofinput = (fts5yymajor==0);
  172136. #endif
  172137. sqlite3Fts5ParserARG_STORE;
  172138. #ifndef NDEBUG
  172139. if( fts5yyTraceFILE ){
  172140. fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  172141. }
  172142. #endif
  172143. do{
  172144. fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
  172145. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  172146. fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
  172147. #ifndef fts5YYNOERRORRECOVERY
  172148. fts5yypParser->fts5yyerrcnt--;
  172149. #endif
  172150. fts5yymajor = fts5YYNOCODE;
  172151. }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
  172152. fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
  172153. }else{
  172154. assert( fts5yyact == fts5YY_ERROR_ACTION );
  172155. fts5yyminorunion.fts5yy0 = fts5yyminor;
  172156. #ifdef fts5YYERRORSYMBOL
  172157. int fts5yymx;
  172158. #endif
  172159. #ifndef NDEBUG
  172160. if( fts5yyTraceFILE ){
  172161. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  172162. }
  172163. #endif
  172164. #ifdef fts5YYERRORSYMBOL
  172165. /* A syntax error has occurred.
  172166. ** The response to an error depends upon whether or not the
  172167. ** grammar defines an error token "ERROR".
  172168. **
  172169. ** This is what we do if the grammar does define ERROR:
  172170. **
  172171. ** * Call the %syntax_error function.
  172172. **
  172173. ** * Begin popping the stack until we enter a state where
  172174. ** it is legal to shift the error symbol, then shift
  172175. ** the error symbol.
  172176. **
  172177. ** * Set the error count to three.
  172178. **
  172179. ** * Begin accepting and shifting new tokens. No new error
  172180. ** processing will occur until three tokens have been
  172181. ** shifted successfully.
  172182. **
  172183. */
  172184. if( fts5yypParser->fts5yyerrcnt<0 ){
  172185. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  172186. }
  172187. fts5yymx = fts5yypParser->fts5yytos->major;
  172188. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  172189. #ifndef NDEBUG
  172190. if( fts5yyTraceFILE ){
  172191. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  172192. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  172193. }
  172194. #endif
  172195. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  172196. fts5yymajor = fts5YYNOCODE;
  172197. }else{
  172198. while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
  172199. && fts5yymx != fts5YYERRORSYMBOL
  172200. && (fts5yyact = fts5yy_find_reduce_action(
  172201. fts5yypParser->fts5yytos->stateno,
  172202. fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
  172203. ){
  172204. fts5yy_pop_parser_stack(fts5yypParser);
  172205. }
  172206. if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
  172207. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  172208. fts5yy_parse_failed(fts5yypParser);
  172209. #ifndef fts5YYNOERRORRECOVERY
  172210. fts5yypParser->fts5yyerrcnt = -1;
  172211. #endif
  172212. fts5yymajor = fts5YYNOCODE;
  172213. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  172214. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  172215. }
  172216. }
  172217. fts5yypParser->fts5yyerrcnt = 3;
  172218. fts5yyerrorhit = 1;
  172219. #elif defined(fts5YYNOERRORRECOVERY)
  172220. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  172221. ** do any kind of error recovery. Instead, simply invoke the syntax
  172222. ** error routine and continue going as if nothing had happened.
  172223. **
  172224. ** Applications can set this macro (for example inside %include) if
  172225. ** they intend to abandon the parse upon the first syntax error seen.
  172226. */
  172227. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  172228. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  172229. fts5yymajor = fts5YYNOCODE;
  172230. #else /* fts5YYERRORSYMBOL is not defined */
  172231. /* This is what we do if the grammar does not define ERROR:
  172232. **
  172233. ** * Report an error message, and throw away the input token.
  172234. **
  172235. ** * If the input token is $, then fail the parse.
  172236. **
  172237. ** As before, subsequent error messages are suppressed until
  172238. ** three input tokens have been successfully shifted.
  172239. */
  172240. if( fts5yypParser->fts5yyerrcnt<=0 ){
  172241. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  172242. }
  172243. fts5yypParser->fts5yyerrcnt = 3;
  172244. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  172245. if( fts5yyendofinput ){
  172246. fts5yy_parse_failed(fts5yypParser);
  172247. #ifndef fts5YYNOERRORRECOVERY
  172248. fts5yypParser->fts5yyerrcnt = -1;
  172249. #endif
  172250. }
  172251. fts5yymajor = fts5YYNOCODE;
  172252. #endif
  172253. }
  172254. }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
  172255. #ifndef NDEBUG
  172256. if( fts5yyTraceFILE ){
  172257. fts5yyStackEntry *i;
  172258. char cDiv = '[';
  172259. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  172260. for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
  172261. fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
  172262. cDiv = ' ';
  172263. }
  172264. fprintf(fts5yyTraceFILE,"]\n");
  172265. }
  172266. #endif
  172267. return;
  172268. }
  172269. /*
  172270. ** 2014 May 31
  172271. **
  172272. ** The author disclaims copyright to this source code. In place of
  172273. ** a legal notice, here is a blessing:
  172274. **
  172275. ** May you do good and not evil.
  172276. ** May you find forgiveness for yourself and forgive others.
  172277. ** May you share freely, never taking more than you give.
  172278. **
  172279. ******************************************************************************
  172280. */
  172281. /* #include "fts5Int.h" */
  172282. #include <math.h> /* amalgamator: keep */
  172283. /*
  172284. ** Object used to iterate through all "coalesced phrase instances" in
  172285. ** a single column of the current row. If the phrase instances in the
  172286. ** column being considered do not overlap, this object simply iterates
  172287. ** through them. Or, if they do overlap (share one or more tokens in
  172288. ** common), each set of overlapping instances is treated as a single
  172289. ** match. See documentation for the highlight() auxiliary function for
  172290. ** details.
  172291. **
  172292. ** Usage is:
  172293. **
  172294. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  172295. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  172296. ** rc = fts5CInstIterNext(&iter)
  172297. ** ){
  172298. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  172299. ** }
  172300. **
  172301. */
  172302. typedef struct CInstIter CInstIter;
  172303. struct CInstIter {
  172304. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  172305. Fts5Context *pFts; /* First arg to pass to pApi functions */
  172306. int iCol; /* Column to search */
  172307. int iInst; /* Next phrase instance index */
  172308. int nInst; /* Total number of phrase instances */
  172309. /* Output variables */
  172310. int iStart; /* First token in coalesced phrase instance */
  172311. int iEnd; /* Last token in coalesced phrase instance */
  172312. };
  172313. /*
  172314. ** Advance the iterator to the next coalesced phrase instance. Return
  172315. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  172316. */
  172317. static int fts5CInstIterNext(CInstIter *pIter){
  172318. int rc = SQLITE_OK;
  172319. pIter->iStart = -1;
  172320. pIter->iEnd = -1;
  172321. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  172322. int ip; int ic; int io;
  172323. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  172324. if( rc==SQLITE_OK ){
  172325. if( ic==pIter->iCol ){
  172326. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  172327. if( pIter->iStart<0 ){
  172328. pIter->iStart = io;
  172329. pIter->iEnd = iEnd;
  172330. }else if( io<=pIter->iEnd ){
  172331. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  172332. }else{
  172333. break;
  172334. }
  172335. }
  172336. pIter->iInst++;
  172337. }
  172338. }
  172339. return rc;
  172340. }
  172341. /*
  172342. ** Initialize the iterator object indicated by the final parameter to
  172343. ** iterate through coalesced phrase instances in column iCol.
  172344. */
  172345. static int fts5CInstIterInit(
  172346. const Fts5ExtensionApi *pApi,
  172347. Fts5Context *pFts,
  172348. int iCol,
  172349. CInstIter *pIter
  172350. ){
  172351. int rc;
  172352. memset(pIter, 0, sizeof(CInstIter));
  172353. pIter->pApi = pApi;
  172354. pIter->pFts = pFts;
  172355. pIter->iCol = iCol;
  172356. rc = pApi->xInstCount(pFts, &pIter->nInst);
  172357. if( rc==SQLITE_OK ){
  172358. rc = fts5CInstIterNext(pIter);
  172359. }
  172360. return rc;
  172361. }
  172362. /*************************************************************************
  172363. ** Start of highlight() implementation.
  172364. */
  172365. typedef struct HighlightContext HighlightContext;
  172366. struct HighlightContext {
  172367. CInstIter iter; /* Coalesced Instance Iterator */
  172368. int iPos; /* Current token offset in zIn[] */
  172369. int iRangeStart; /* First token to include */
  172370. int iRangeEnd; /* If non-zero, last token to include */
  172371. const char *zOpen; /* Opening highlight */
  172372. const char *zClose; /* Closing highlight */
  172373. const char *zIn; /* Input text */
  172374. int nIn; /* Size of input text in bytes */
  172375. int iOff; /* Current offset within zIn[] */
  172376. char *zOut; /* Output value */
  172377. };
  172378. /*
  172379. ** Append text to the HighlightContext output string - p->zOut. Argument
  172380. ** z points to a buffer containing n bytes of text to append. If n is
  172381. ** negative, everything up until the first '\0' is appended to the output.
  172382. **
  172383. ** If *pRc is set to any value other than SQLITE_OK when this function is
  172384. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  172385. ** *pRc is set to an error code before returning.
  172386. */
  172387. static void fts5HighlightAppend(
  172388. int *pRc,
  172389. HighlightContext *p,
  172390. const char *z, int n
  172391. ){
  172392. if( *pRc==SQLITE_OK ){
  172393. if( n<0 ) n = (int)strlen(z);
  172394. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  172395. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  172396. }
  172397. }
  172398. /*
  172399. ** Tokenizer callback used by implementation of highlight() function.
  172400. */
  172401. static int fts5HighlightCb(
  172402. void *pContext, /* Pointer to HighlightContext object */
  172403. int tflags, /* Mask of FTS5_TOKEN_* flags */
  172404. const char *pToken, /* Buffer containing token */
  172405. int nToken, /* Size of token in bytes */
  172406. int iStartOff, /* Start offset of token */
  172407. int iEndOff /* End offset of token */
  172408. ){
  172409. HighlightContext *p = (HighlightContext*)pContext;
  172410. int rc = SQLITE_OK;
  172411. int iPos;
  172412. UNUSED_PARAM2(pToken, nToken);
  172413. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  172414. iPos = p->iPos++;
  172415. if( p->iRangeEnd>0 ){
  172416. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  172417. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  172418. }
  172419. if( iPos==p->iter.iStart ){
  172420. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  172421. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  172422. p->iOff = iStartOff;
  172423. }
  172424. if( iPos==p->iter.iEnd ){
  172425. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  172426. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  172427. }
  172428. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  172429. fts5HighlightAppend(&rc, p, p->zClose, -1);
  172430. p->iOff = iEndOff;
  172431. if( rc==SQLITE_OK ){
  172432. rc = fts5CInstIterNext(&p->iter);
  172433. }
  172434. }
  172435. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  172436. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  172437. p->iOff = iEndOff;
  172438. if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
  172439. fts5HighlightAppend(&rc, p, p->zClose, -1);
  172440. }
  172441. }
  172442. return rc;
  172443. }
  172444. /*
  172445. ** Implementation of highlight() function.
  172446. */
  172447. static void fts5HighlightFunction(
  172448. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  172449. Fts5Context *pFts, /* First arg to pass to pApi functions */
  172450. sqlite3_context *pCtx, /* Context for returning result/error */
  172451. int nVal, /* Number of values in apVal[] array */
  172452. sqlite3_value **apVal /* Array of trailing arguments */
  172453. ){
  172454. HighlightContext ctx;
  172455. int rc;
  172456. int iCol;
  172457. if( nVal!=3 ){
  172458. const char *zErr = "wrong number of arguments to function highlight()";
  172459. sqlite3_result_error(pCtx, zErr, -1);
  172460. return;
  172461. }
  172462. iCol = sqlite3_value_int(apVal[0]);
  172463. memset(&ctx, 0, sizeof(HighlightContext));
  172464. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  172465. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  172466. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  172467. if( ctx.zIn ){
  172468. if( rc==SQLITE_OK ){
  172469. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  172470. }
  172471. if( rc==SQLITE_OK ){
  172472. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  172473. }
  172474. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  172475. if( rc==SQLITE_OK ){
  172476. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  172477. }
  172478. sqlite3_free(ctx.zOut);
  172479. }
  172480. if( rc!=SQLITE_OK ){
  172481. sqlite3_result_error_code(pCtx, rc);
  172482. }
  172483. }
  172484. /*
  172485. ** End of highlight() implementation.
  172486. **************************************************************************/
  172487. /*
  172488. ** Context object passed to the fts5SentenceFinderCb() function.
  172489. */
  172490. typedef struct Fts5SFinder Fts5SFinder;
  172491. struct Fts5SFinder {
  172492. int iPos; /* Current token position */
  172493. int nFirstAlloc; /* Allocated size of aFirst[] */
  172494. int nFirst; /* Number of entries in aFirst[] */
  172495. int *aFirst; /* Array of first token in each sentence */
  172496. const char *zDoc; /* Document being tokenized */
  172497. };
  172498. /*
  172499. ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
  172500. ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
  172501. ** error occurs.
  172502. */
  172503. static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
  172504. if( p->nFirstAlloc==p->nFirst ){
  172505. int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
  172506. int *aNew;
  172507. aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
  172508. if( aNew==0 ) return SQLITE_NOMEM;
  172509. p->aFirst = aNew;
  172510. p->nFirstAlloc = nNew;
  172511. }
  172512. p->aFirst[p->nFirst++] = iAdd;
  172513. return SQLITE_OK;
  172514. }
  172515. /*
  172516. ** This function is an xTokenize() callback used by the auxiliary snippet()
  172517. ** function. Its job is to identify tokens that are the first in a sentence.
  172518. ** For each such token, an entry is added to the SFinder.aFirst[] array.
  172519. */
  172520. static int fts5SentenceFinderCb(
  172521. void *pContext, /* Pointer to HighlightContext object */
  172522. int tflags, /* Mask of FTS5_TOKEN_* flags */
  172523. const char *pToken, /* Buffer containing token */
  172524. int nToken, /* Size of token in bytes */
  172525. int iStartOff, /* Start offset of token */
  172526. int iEndOff /* End offset of token */
  172527. ){
  172528. int rc = SQLITE_OK;
  172529. UNUSED_PARAM2(pToken, nToken);
  172530. UNUSED_PARAM(iEndOff);
  172531. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  172532. Fts5SFinder *p = (Fts5SFinder*)pContext;
  172533. if( p->iPos>0 ){
  172534. int i;
  172535. char c = 0;
  172536. for(i=iStartOff-1; i>=0; i--){
  172537. c = p->zDoc[i];
  172538. if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
  172539. }
  172540. if( i!=iStartOff-1 && (c=='.' || c==':') ){
  172541. rc = fts5SentenceFinderAdd(p, p->iPos);
  172542. }
  172543. }else{
  172544. rc = fts5SentenceFinderAdd(p, 0);
  172545. }
  172546. p->iPos++;
  172547. }
  172548. return rc;
  172549. }
  172550. static int fts5SnippetScore(
  172551. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  172552. Fts5Context *pFts, /* First arg to pass to pApi functions */
  172553. int nDocsize, /* Size of column in tokens */
  172554. unsigned char *aSeen, /* Array with one element per query phrase */
  172555. int iCol, /* Column to score */
  172556. int iPos, /* Starting offset to score */
  172557. int nToken, /* Max tokens per snippet */
  172558. int *pnScore, /* OUT: Score */
  172559. int *piPos /* OUT: Adjusted offset */
  172560. ){
  172561. int rc;
  172562. int i;
  172563. int ip = 0;
  172564. int ic = 0;
  172565. int iOff = 0;
  172566. int iFirst = -1;
  172567. int nInst;
  172568. int nScore = 0;
  172569. int iLast = 0;
  172570. rc = pApi->xInstCount(pFts, &nInst);
  172571. for(i=0; i<nInst && rc==SQLITE_OK; i++){
  172572. rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
  172573. if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
  172574. nScore += (aSeen[ip] ? 1 : 1000);
  172575. aSeen[ip] = 1;
  172576. if( iFirst<0 ) iFirst = iOff;
  172577. iLast = iOff + pApi->xPhraseSize(pFts, ip);
  172578. }
  172579. }
  172580. *pnScore = nScore;
  172581. if( piPos ){
  172582. int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
  172583. if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
  172584. if( iAdj<0 ) iAdj = 0;
  172585. *piPos = iAdj;
  172586. }
  172587. return rc;
  172588. }
  172589. /*
  172590. ** Implementation of snippet() function.
  172591. */
  172592. static void fts5SnippetFunction(
  172593. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  172594. Fts5Context *pFts, /* First arg to pass to pApi functions */
  172595. sqlite3_context *pCtx, /* Context for returning result/error */
  172596. int nVal, /* Number of values in apVal[] array */
  172597. sqlite3_value **apVal /* Array of trailing arguments */
  172598. ){
  172599. HighlightContext ctx;
  172600. int rc = SQLITE_OK; /* Return code */
  172601. int iCol; /* 1st argument to snippet() */
  172602. const char *zEllips; /* 4th argument to snippet() */
  172603. int nToken; /* 5th argument to snippet() */
  172604. int nInst = 0; /* Number of instance matches this row */
  172605. int i; /* Used to iterate through instances */
  172606. int nPhrase; /* Number of phrases in query */
  172607. unsigned char *aSeen; /* Array of "seen instance" flags */
  172608. int iBestCol; /* Column containing best snippet */
  172609. int iBestStart = 0; /* First token of best snippet */
  172610. int nBestScore = 0; /* Score of best snippet */
  172611. int nColSize = 0; /* Total size of iBestCol in tokens */
  172612. Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
  172613. int nCol;
  172614. if( nVal!=5 ){
  172615. const char *zErr = "wrong number of arguments to function snippet()";
  172616. sqlite3_result_error(pCtx, zErr, -1);
  172617. return;
  172618. }
  172619. nCol = pApi->xColumnCount(pFts);
  172620. memset(&ctx, 0, sizeof(HighlightContext));
  172621. iCol = sqlite3_value_int(apVal[0]);
  172622. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  172623. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  172624. zEllips = (const char*)sqlite3_value_text(apVal[3]);
  172625. nToken = sqlite3_value_int(apVal[4]);
  172626. iBestCol = (iCol>=0 ? iCol : 0);
  172627. nPhrase = pApi->xPhraseCount(pFts);
  172628. aSeen = sqlite3_malloc(nPhrase);
  172629. if( aSeen==0 ){
  172630. rc = SQLITE_NOMEM;
  172631. }
  172632. if( rc==SQLITE_OK ){
  172633. rc = pApi->xInstCount(pFts, &nInst);
  172634. }
  172635. memset(&sFinder, 0, sizeof(Fts5SFinder));
  172636. for(i=0; i<nCol; i++){
  172637. if( iCol<0 || iCol==i ){
  172638. int nDoc;
  172639. int nDocsize;
  172640. int ii;
  172641. sFinder.iPos = 0;
  172642. sFinder.nFirst = 0;
  172643. rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
  172644. if( rc!=SQLITE_OK ) break;
  172645. rc = pApi->xTokenize(pFts,
  172646. sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
  172647. );
  172648. if( rc!=SQLITE_OK ) break;
  172649. rc = pApi->xColumnSize(pFts, i, &nDocsize);
  172650. if( rc!=SQLITE_OK ) break;
  172651. for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
  172652. int ip, ic, io;
  172653. int iAdj;
  172654. int nScore;
  172655. int jj;
  172656. rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
  172657. if( ic!=i || rc!=SQLITE_OK ) continue;
  172658. memset(aSeen, 0, nPhrase);
  172659. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  172660. io, nToken, &nScore, &iAdj
  172661. );
  172662. if( rc==SQLITE_OK && nScore>nBestScore ){
  172663. nBestScore = nScore;
  172664. iBestCol = i;
  172665. iBestStart = iAdj;
  172666. nColSize = nDocsize;
  172667. }
  172668. if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
  172669. for(jj=0; jj<(sFinder.nFirst-1); jj++){
  172670. if( sFinder.aFirst[jj+1]>io ) break;
  172671. }
  172672. if( sFinder.aFirst[jj]<io ){
  172673. memset(aSeen, 0, nPhrase);
  172674. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  172675. sFinder.aFirst[jj], nToken, &nScore, 0
  172676. );
  172677. nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
  172678. if( rc==SQLITE_OK && nScore>nBestScore ){
  172679. nBestScore = nScore;
  172680. iBestCol = i;
  172681. iBestStart = sFinder.aFirst[jj];
  172682. nColSize = nDocsize;
  172683. }
  172684. }
  172685. }
  172686. }
  172687. }
  172688. }
  172689. if( rc==SQLITE_OK ){
  172690. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  172691. }
  172692. if( rc==SQLITE_OK && nColSize==0 ){
  172693. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  172694. }
  172695. if( ctx.zIn ){
  172696. if( rc==SQLITE_OK ){
  172697. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  172698. }
  172699. ctx.iRangeStart = iBestStart;
  172700. ctx.iRangeEnd = iBestStart + nToken - 1;
  172701. if( iBestStart>0 ){
  172702. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  172703. }
  172704. /* Advance iterator ctx.iter so that it points to the first coalesced
  172705. ** phrase instance at or following position iBestStart. */
  172706. while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
  172707. rc = fts5CInstIterNext(&ctx.iter);
  172708. }
  172709. if( rc==SQLITE_OK ){
  172710. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  172711. }
  172712. if( ctx.iRangeEnd>=(nColSize-1) ){
  172713. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  172714. }else{
  172715. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  172716. }
  172717. }
  172718. if( rc==SQLITE_OK ){
  172719. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  172720. }else{
  172721. sqlite3_result_error_code(pCtx, rc);
  172722. }
  172723. sqlite3_free(ctx.zOut);
  172724. sqlite3_free(aSeen);
  172725. sqlite3_free(sFinder.aFirst);
  172726. }
  172727. /************************************************************************/
  172728. /*
  172729. ** The first time the bm25() function is called for a query, an instance
  172730. ** of the following structure is allocated and populated.
  172731. */
  172732. typedef struct Fts5Bm25Data Fts5Bm25Data;
  172733. struct Fts5Bm25Data {
  172734. int nPhrase; /* Number of phrases in query */
  172735. double avgdl; /* Average number of tokens in each row */
  172736. double *aIDF; /* IDF for each phrase */
  172737. double *aFreq; /* Array used to calculate phrase freq. */
  172738. };
  172739. /*
  172740. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  172741. ** table matched by each individual phrase within the query.
  172742. */
  172743. static int fts5CountCb(
  172744. const Fts5ExtensionApi *pApi,
  172745. Fts5Context *pFts,
  172746. void *pUserData /* Pointer to sqlite3_int64 variable */
  172747. ){
  172748. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  172749. UNUSED_PARAM2(pApi, pFts);
  172750. (*pn)++;
  172751. return SQLITE_OK;
  172752. }
  172753. /*
  172754. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  172755. ** If the object has not already been allocated, allocate and populate it
  172756. ** now.
  172757. */
  172758. static int fts5Bm25GetData(
  172759. const Fts5ExtensionApi *pApi,
  172760. Fts5Context *pFts,
  172761. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  172762. ){
  172763. int rc = SQLITE_OK; /* Return code */
  172764. Fts5Bm25Data *p; /* Object to return */
  172765. p = pApi->xGetAuxdata(pFts, 0);
  172766. if( p==0 ){
  172767. int nPhrase; /* Number of phrases in query */
  172768. sqlite3_int64 nRow = 0; /* Number of rows in table */
  172769. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  172770. int nByte; /* Bytes of space to allocate */
  172771. int i;
  172772. /* Allocate the Fts5Bm25Data object */
  172773. nPhrase = pApi->xPhraseCount(pFts);
  172774. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  172775. p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
  172776. if( p==0 ){
  172777. rc = SQLITE_NOMEM;
  172778. }else{
  172779. memset(p, 0, nByte);
  172780. p->nPhrase = nPhrase;
  172781. p->aIDF = (double*)&p[1];
  172782. p->aFreq = &p->aIDF[nPhrase];
  172783. }
  172784. /* Calculate the average document length for this FTS5 table */
  172785. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  172786. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  172787. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  172788. /* Calculate an IDF for each phrase in the query */
  172789. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  172790. sqlite3_int64 nHit = 0;
  172791. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  172792. if( rc==SQLITE_OK ){
  172793. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  172794. ** This is done using the standard BM25 formula as found on wikipedia:
  172795. **
  172796. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  172797. **
  172798. ** where "N" is the total number of documents in the set and nHit
  172799. ** is the number that contain at least one instance of the phrase
  172800. ** under consideration.
  172801. **
  172802. ** The problem with this is that if (N < 2*nHit), the IDF is
  172803. ** negative. Which is undesirable. So the mimimum allowable IDF is
  172804. ** (1e-6) - roughly the same as a term that appears in just over
  172805. ** half of set of 5,000,000 documents. */
  172806. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  172807. if( idf<=0.0 ) idf = 1e-6;
  172808. p->aIDF[i] = idf;
  172809. }
  172810. }
  172811. if( rc!=SQLITE_OK ){
  172812. sqlite3_free(p);
  172813. }else{
  172814. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  172815. }
  172816. if( rc!=SQLITE_OK ) p = 0;
  172817. }
  172818. *ppData = p;
  172819. return rc;
  172820. }
  172821. /*
  172822. ** Implementation of bm25() function.
  172823. */
  172824. static void fts5Bm25Function(
  172825. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  172826. Fts5Context *pFts, /* First arg to pass to pApi functions */
  172827. sqlite3_context *pCtx, /* Context for returning result/error */
  172828. int nVal, /* Number of values in apVal[] array */
  172829. sqlite3_value **apVal /* Array of trailing arguments */
  172830. ){
  172831. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  172832. const double b = 0.75; /* Constant "b" from BM25 formula */
  172833. int rc = SQLITE_OK; /* Error code */
  172834. double score = 0.0; /* SQL function return value */
  172835. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  172836. int i; /* Iterator variable */
  172837. int nInst = 0; /* Value returned by xInstCount() */
  172838. double D = 0.0; /* Total number of tokens in row */
  172839. double *aFreq = 0; /* Array of phrase freq. for current row */
  172840. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  172841. ** for each phrase in the query for the current row. */
  172842. rc = fts5Bm25GetData(pApi, pFts, &pData);
  172843. if( rc==SQLITE_OK ){
  172844. aFreq = pData->aFreq;
  172845. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  172846. rc = pApi->xInstCount(pFts, &nInst);
  172847. }
  172848. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  172849. int ip; int ic; int io;
  172850. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  172851. if( rc==SQLITE_OK ){
  172852. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  172853. aFreq[ip] += w;
  172854. }
  172855. }
  172856. /* Figure out the total size of the current row in tokens. */
  172857. if( rc==SQLITE_OK ){
  172858. int nTok;
  172859. rc = pApi->xColumnSize(pFts, -1, &nTok);
  172860. D = (double)nTok;
  172861. }
  172862. /* Determine the BM25 score for the current row. */
  172863. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  172864. score += pData->aIDF[i] * (
  172865. ( aFreq[i] * (k1 + 1.0) ) /
  172866. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  172867. );
  172868. }
  172869. /* If no error has occurred, return the calculated score. Otherwise,
  172870. ** throw an SQL exception. */
  172871. if( rc==SQLITE_OK ){
  172872. sqlite3_result_double(pCtx, -1.0 * score);
  172873. }else{
  172874. sqlite3_result_error_code(pCtx, rc);
  172875. }
  172876. }
  172877. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  172878. struct Builtin {
  172879. const char *zFunc; /* Function name (nul-terminated) */
  172880. void *pUserData; /* User-data pointer */
  172881. fts5_extension_function xFunc;/* Callback function */
  172882. void (*xDestroy)(void*); /* Destructor function */
  172883. } aBuiltin [] = {
  172884. { "snippet", 0, fts5SnippetFunction, 0 },
  172885. { "highlight", 0, fts5HighlightFunction, 0 },
  172886. { "bm25", 0, fts5Bm25Function, 0 },
  172887. };
  172888. int rc = SQLITE_OK; /* Return code */
  172889. int i; /* To iterate through builtin functions */
  172890. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  172891. rc = pApi->xCreateFunction(pApi,
  172892. aBuiltin[i].zFunc,
  172893. aBuiltin[i].pUserData,
  172894. aBuiltin[i].xFunc,
  172895. aBuiltin[i].xDestroy
  172896. );
  172897. }
  172898. return rc;
  172899. }
  172900. /*
  172901. ** 2014 May 31
  172902. **
  172903. ** The author disclaims copyright to this source code. In place of
  172904. ** a legal notice, here is a blessing:
  172905. **
  172906. ** May you do good and not evil.
  172907. ** May you find forgiveness for yourself and forgive others.
  172908. ** May you share freely, never taking more than you give.
  172909. **
  172910. ******************************************************************************
  172911. */
  172912. /* #include "fts5Int.h" */
  172913. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  172914. if( (u32)pBuf->nSpace<nByte ){
  172915. u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  172916. u8 *pNew;
  172917. while( nNew<nByte ){
  172918. nNew = nNew * 2;
  172919. }
  172920. pNew = sqlite3_realloc(pBuf->p, nNew);
  172921. if( pNew==0 ){
  172922. *pRc = SQLITE_NOMEM;
  172923. return 1;
  172924. }else{
  172925. pBuf->nSpace = nNew;
  172926. pBuf->p = pNew;
  172927. }
  172928. }
  172929. return 0;
  172930. }
  172931. /*
  172932. ** Encode value iVal as an SQLite varint and append it to the buffer object
  172933. ** pBuf. If an OOM error occurs, set the error code in p.
  172934. */
  172935. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  172936. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  172937. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  172938. }
  172939. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  172940. aBuf[0] = (iVal>>24) & 0x00FF;
  172941. aBuf[1] = (iVal>>16) & 0x00FF;
  172942. aBuf[2] = (iVal>> 8) & 0x00FF;
  172943. aBuf[3] = (iVal>> 0) & 0x00FF;
  172944. }
  172945. static int sqlite3Fts5Get32(const u8 *aBuf){
  172946. return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
  172947. }
  172948. /*
  172949. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  172950. ** the error code in p. If an error has already occurred when this function
  172951. ** is called, it is a no-op.
  172952. */
  172953. static void sqlite3Fts5BufferAppendBlob(
  172954. int *pRc,
  172955. Fts5Buffer *pBuf,
  172956. u32 nData,
  172957. const u8 *pData
  172958. ){
  172959. assert_nc( *pRc || nData>=0 );
  172960. if( nData ){
  172961. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  172962. memcpy(&pBuf->p[pBuf->n], pData, nData);
  172963. pBuf->n += nData;
  172964. }
  172965. }
  172966. /*
  172967. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  172968. ** ensures that the byte following the buffer data is set to 0x00, even
  172969. ** though this byte is not included in the pBuf->n count.
  172970. */
  172971. static void sqlite3Fts5BufferAppendString(
  172972. int *pRc,
  172973. Fts5Buffer *pBuf,
  172974. const char *zStr
  172975. ){
  172976. int nStr = (int)strlen(zStr);
  172977. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  172978. pBuf->n--;
  172979. }
  172980. /*
  172981. ** Argument zFmt is a printf() style format string. This function performs
  172982. ** the printf() style processing, then appends the results to buffer pBuf.
  172983. **
  172984. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  172985. ** following the buffer data is set to 0x00, even though this byte is not
  172986. ** included in the pBuf->n count.
  172987. */
  172988. static void sqlite3Fts5BufferAppendPrintf(
  172989. int *pRc,
  172990. Fts5Buffer *pBuf,
  172991. char *zFmt, ...
  172992. ){
  172993. if( *pRc==SQLITE_OK ){
  172994. char *zTmp;
  172995. va_list ap;
  172996. va_start(ap, zFmt);
  172997. zTmp = sqlite3_vmprintf(zFmt, ap);
  172998. va_end(ap);
  172999. if( zTmp==0 ){
  173000. *pRc = SQLITE_NOMEM;
  173001. }else{
  173002. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  173003. sqlite3_free(zTmp);
  173004. }
  173005. }
  173006. }
  173007. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  173008. char *zRet = 0;
  173009. if( *pRc==SQLITE_OK ){
  173010. va_list ap;
  173011. va_start(ap, zFmt);
  173012. zRet = sqlite3_vmprintf(zFmt, ap);
  173013. va_end(ap);
  173014. if( zRet==0 ){
  173015. *pRc = SQLITE_NOMEM;
  173016. }
  173017. }
  173018. return zRet;
  173019. }
  173020. /*
  173021. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  173022. */
  173023. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  173024. sqlite3_free(pBuf->p);
  173025. memset(pBuf, 0, sizeof(Fts5Buffer));
  173026. }
  173027. /*
  173028. ** Zero the contents of the buffer object. But do not free the associated
  173029. ** memory allocation.
  173030. */
  173031. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  173032. pBuf->n = 0;
  173033. }
  173034. /*
  173035. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  173036. ** the error code in p. If an error has already occurred when this function
  173037. ** is called, it is a no-op.
  173038. */
  173039. static void sqlite3Fts5BufferSet(
  173040. int *pRc,
  173041. Fts5Buffer *pBuf,
  173042. int nData,
  173043. const u8 *pData
  173044. ){
  173045. pBuf->n = 0;
  173046. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  173047. }
  173048. static int sqlite3Fts5PoslistNext64(
  173049. const u8 *a, int n, /* Buffer containing poslist */
  173050. int *pi, /* IN/OUT: Offset within a[] */
  173051. i64 *piOff /* IN/OUT: Current offset */
  173052. ){
  173053. int i = *pi;
  173054. if( i>=n ){
  173055. /* EOF */
  173056. *piOff = -1;
  173057. return 1;
  173058. }else{
  173059. i64 iOff = *piOff;
  173060. int iVal;
  173061. fts5FastGetVarint32(a, i, iVal);
  173062. if( iVal==1 ){
  173063. fts5FastGetVarint32(a, i, iVal);
  173064. iOff = ((i64)iVal) << 32;
  173065. fts5FastGetVarint32(a, i, iVal);
  173066. }
  173067. *piOff = iOff + (iVal-2);
  173068. *pi = i;
  173069. return 0;
  173070. }
  173071. }
  173072. /*
  173073. ** Advance the iterator object passed as the only argument. Return true
  173074. ** if the iterator reaches EOF, or false otherwise.
  173075. */
  173076. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  173077. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  173078. pIter->bEof = 1;
  173079. }
  173080. return pIter->bEof;
  173081. }
  173082. static int sqlite3Fts5PoslistReaderInit(
  173083. const u8 *a, int n, /* Poslist buffer to iterate through */
  173084. Fts5PoslistReader *pIter /* Iterator object to initialize */
  173085. ){
  173086. memset(pIter, 0, sizeof(*pIter));
  173087. pIter->a = a;
  173088. pIter->n = n;
  173089. sqlite3Fts5PoslistReaderNext(pIter);
  173090. return pIter->bEof;
  173091. }
  173092. /*
  173093. ** Append position iPos to the position list being accumulated in buffer
  173094. ** pBuf, which must be already be large enough to hold the new data.
  173095. ** The previous position written to this list is *piPrev. *piPrev is set
  173096. ** to iPos before returning.
  173097. */
  173098. static void sqlite3Fts5PoslistSafeAppend(
  173099. Fts5Buffer *pBuf,
  173100. i64 *piPrev,
  173101. i64 iPos
  173102. ){
  173103. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  173104. if( (iPos & colmask) != (*piPrev & colmask) ){
  173105. pBuf->p[pBuf->n++] = 1;
  173106. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  173107. *piPrev = (iPos & colmask);
  173108. }
  173109. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  173110. *piPrev = iPos;
  173111. }
  173112. static int sqlite3Fts5PoslistWriterAppend(
  173113. Fts5Buffer *pBuf,
  173114. Fts5PoslistWriter *pWriter,
  173115. i64 iPos
  173116. ){
  173117. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  173118. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  173119. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  173120. return SQLITE_OK;
  173121. }
  173122. static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
  173123. void *pRet = 0;
  173124. if( *pRc==SQLITE_OK ){
  173125. pRet = sqlite3_malloc(nByte);
  173126. if( pRet==0 ){
  173127. if( nByte>0 ) *pRc = SQLITE_NOMEM;
  173128. }else{
  173129. memset(pRet, 0, nByte);
  173130. }
  173131. }
  173132. return pRet;
  173133. }
  173134. /*
  173135. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  173136. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  173137. ** the length of the string is determined using strlen().
  173138. **
  173139. ** It is the responsibility of the caller to eventually free the returned
  173140. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  173141. */
  173142. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  173143. char *zRet = 0;
  173144. if( *pRc==SQLITE_OK ){
  173145. if( nIn<0 ){
  173146. nIn = (int)strlen(pIn);
  173147. }
  173148. zRet = (char*)sqlite3_malloc(nIn+1);
  173149. if( zRet ){
  173150. memcpy(zRet, pIn, nIn);
  173151. zRet[nIn] = '\0';
  173152. }else{
  173153. *pRc = SQLITE_NOMEM;
  173154. }
  173155. }
  173156. return zRet;
  173157. }
  173158. /*
  173159. ** Return true if character 't' may be part of an FTS5 bareword, or false
  173160. ** otherwise. Characters that may be part of barewords:
  173161. **
  173162. ** * All non-ASCII characters,
  173163. ** * The 52 upper and lower case ASCII characters, and
  173164. ** * The 10 integer ASCII characters.
  173165. ** * The underscore character "_" (0x5F).
  173166. ** * The unicode "subsitute" character (0x1A).
  173167. */
  173168. static int sqlite3Fts5IsBareword(char t){
  173169. u8 aBareword[128] = {
  173170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  173171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  173172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  173173. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  173174. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  173175. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  173176. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  173177. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  173178. };
  173179. return (t & 0x80) || aBareword[(int)t];
  173180. }
  173181. /*************************************************************************
  173182. */
  173183. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  173184. struct Fts5TermsetEntry {
  173185. char *pTerm;
  173186. int nTerm;
  173187. int iIdx; /* Index (main or aPrefix[] entry) */
  173188. Fts5TermsetEntry *pNext;
  173189. };
  173190. struct Fts5Termset {
  173191. Fts5TermsetEntry *apHash[512];
  173192. };
  173193. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  173194. int rc = SQLITE_OK;
  173195. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  173196. return rc;
  173197. }
  173198. static int sqlite3Fts5TermsetAdd(
  173199. Fts5Termset *p,
  173200. int iIdx,
  173201. const char *pTerm, int nTerm,
  173202. int *pbPresent
  173203. ){
  173204. int rc = SQLITE_OK;
  173205. *pbPresent = 0;
  173206. if( p ){
  173207. int i;
  173208. u32 hash = 13;
  173209. Fts5TermsetEntry *pEntry;
  173210. /* Calculate a hash value for this term. This is the same hash checksum
  173211. ** used by the fts5_hash.c module. This is not important for correct
  173212. ** operation of the module, but is necessary to ensure that some tests
  173213. ** designed to produce hash table collisions really do work. */
  173214. for(i=nTerm-1; i>=0; i--){
  173215. hash = (hash << 3) ^ hash ^ pTerm[i];
  173216. }
  173217. hash = (hash << 3) ^ hash ^ iIdx;
  173218. hash = hash % ArraySize(p->apHash);
  173219. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  173220. if( pEntry->iIdx==iIdx
  173221. && pEntry->nTerm==nTerm
  173222. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  173223. ){
  173224. *pbPresent = 1;
  173225. break;
  173226. }
  173227. }
  173228. if( pEntry==0 ){
  173229. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  173230. if( pEntry ){
  173231. pEntry->pTerm = (char*)&pEntry[1];
  173232. pEntry->nTerm = nTerm;
  173233. pEntry->iIdx = iIdx;
  173234. memcpy(pEntry->pTerm, pTerm, nTerm);
  173235. pEntry->pNext = p->apHash[hash];
  173236. p->apHash[hash] = pEntry;
  173237. }
  173238. }
  173239. }
  173240. return rc;
  173241. }
  173242. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  173243. if( p ){
  173244. u32 i;
  173245. for(i=0; i<ArraySize(p->apHash); i++){
  173246. Fts5TermsetEntry *pEntry = p->apHash[i];
  173247. while( pEntry ){
  173248. Fts5TermsetEntry *pDel = pEntry;
  173249. pEntry = pEntry->pNext;
  173250. sqlite3_free(pDel);
  173251. }
  173252. }
  173253. sqlite3_free(p);
  173254. }
  173255. }
  173256. /*
  173257. ** 2014 Jun 09
  173258. **
  173259. ** The author disclaims copyright to this source code. In place of
  173260. ** a legal notice, here is a blessing:
  173261. **
  173262. ** May you do good and not evil.
  173263. ** May you find forgiveness for yourself and forgive others.
  173264. ** May you share freely, never taking more than you give.
  173265. **
  173266. ******************************************************************************
  173267. **
  173268. ** This is an SQLite module implementing full-text search.
  173269. */
  173270. /* #include "fts5Int.h" */
  173271. #define FTS5_DEFAULT_PAGE_SIZE 4050
  173272. #define FTS5_DEFAULT_AUTOMERGE 4
  173273. #define FTS5_DEFAULT_USERMERGE 4
  173274. #define FTS5_DEFAULT_CRISISMERGE 16
  173275. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  173276. /* Maximum allowed page size */
  173277. #define FTS5_MAX_PAGE_SIZE (128*1024)
  173278. static int fts5_iswhitespace(char x){
  173279. return (x==' ');
  173280. }
  173281. static int fts5_isopenquote(char x){
  173282. return (x=='"' || x=='\'' || x=='[' || x=='`');
  173283. }
  173284. /*
  173285. ** Argument pIn points to a character that is part of a nul-terminated
  173286. ** string. Return a pointer to the first character following *pIn in
  173287. ** the string that is not a white-space character.
  173288. */
  173289. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  173290. const char *p = pIn;
  173291. if( p ){
  173292. while( fts5_iswhitespace(*p) ){ p++; }
  173293. }
  173294. return p;
  173295. }
  173296. /*
  173297. ** Argument pIn points to a character that is part of a nul-terminated
  173298. ** string. Return a pointer to the first character following *pIn in
  173299. ** the string that is not a "bareword" character.
  173300. */
  173301. static const char *fts5ConfigSkipBareword(const char *pIn){
  173302. const char *p = pIn;
  173303. while ( sqlite3Fts5IsBareword(*p) ) p++;
  173304. if( p==pIn ) p = 0;
  173305. return p;
  173306. }
  173307. static int fts5_isdigit(char a){
  173308. return (a>='0' && a<='9');
  173309. }
  173310. static const char *fts5ConfigSkipLiteral(const char *pIn){
  173311. const char *p = pIn;
  173312. switch( *p ){
  173313. case 'n': case 'N':
  173314. if( sqlite3_strnicmp("null", p, 4)==0 ){
  173315. p = &p[4];
  173316. }else{
  173317. p = 0;
  173318. }
  173319. break;
  173320. case 'x': case 'X':
  173321. p++;
  173322. if( *p=='\'' ){
  173323. p++;
  173324. while( (*p>='a' && *p<='f')
  173325. || (*p>='A' && *p<='F')
  173326. || (*p>='0' && *p<='9')
  173327. ){
  173328. p++;
  173329. }
  173330. if( *p=='\'' && 0==((p-pIn)%2) ){
  173331. p++;
  173332. }else{
  173333. p = 0;
  173334. }
  173335. }else{
  173336. p = 0;
  173337. }
  173338. break;
  173339. case '\'':
  173340. p++;
  173341. while( p ){
  173342. if( *p=='\'' ){
  173343. p++;
  173344. if( *p!='\'' ) break;
  173345. }
  173346. p++;
  173347. if( *p==0 ) p = 0;
  173348. }
  173349. break;
  173350. default:
  173351. /* maybe a number */
  173352. if( *p=='+' || *p=='-' ) p++;
  173353. while( fts5_isdigit(*p) ) p++;
  173354. /* At this point, if the literal was an integer, the parse is
  173355. ** finished. Or, if it is a floating point value, it may continue
  173356. ** with either a decimal point or an 'E' character. */
  173357. if( *p=='.' && fts5_isdigit(p[1]) ){
  173358. p += 2;
  173359. while( fts5_isdigit(*p) ) p++;
  173360. }
  173361. if( p==pIn ) p = 0;
  173362. break;
  173363. }
  173364. return p;
  173365. }
  173366. /*
  173367. ** The first character of the string pointed to by argument z is guaranteed
  173368. ** to be an open-quote character (see function fts5_isopenquote()).
  173369. **
  173370. ** This function searches for the corresponding close-quote character within
  173371. ** the string and, if found, dequotes the string in place and adds a new
  173372. ** nul-terminator byte.
  173373. **
  173374. ** If the close-quote is found, the value returned is the byte offset of
  173375. ** the character immediately following it. Or, if the close-quote is not
  173376. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  173377. ** undefined state.
  173378. */
  173379. static int fts5Dequote(char *z){
  173380. char q;
  173381. int iIn = 1;
  173382. int iOut = 0;
  173383. q = z[0];
  173384. /* Set stack variable q to the close-quote character */
  173385. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  173386. if( q=='[' ) q = ']';
  173387. while( ALWAYS(z[iIn]) ){
  173388. if( z[iIn]==q ){
  173389. if( z[iIn+1]!=q ){
  173390. /* Character iIn was the close quote. */
  173391. iIn++;
  173392. break;
  173393. }else{
  173394. /* Character iIn and iIn+1 form an escaped quote character. Skip
  173395. ** the input cursor past both and copy a single quote character
  173396. ** to the output buffer. */
  173397. iIn += 2;
  173398. z[iOut++] = q;
  173399. }
  173400. }else{
  173401. z[iOut++] = z[iIn++];
  173402. }
  173403. }
  173404. z[iOut] = '\0';
  173405. return iIn;
  173406. }
  173407. /*
  173408. ** Convert an SQL-style quoted string into a normal string by removing
  173409. ** the quote characters. The conversion is done in-place. If the
  173410. ** input does not begin with a quote character, then this routine
  173411. ** is a no-op.
  173412. **
  173413. ** Examples:
  173414. **
  173415. ** "abc" becomes abc
  173416. ** 'xyz' becomes xyz
  173417. ** [pqr] becomes pqr
  173418. ** `mno` becomes mno
  173419. */
  173420. static void sqlite3Fts5Dequote(char *z){
  173421. char quote; /* Quote character (if any ) */
  173422. assert( 0==fts5_iswhitespace(z[0]) );
  173423. quote = z[0];
  173424. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  173425. fts5Dequote(z);
  173426. }
  173427. }
  173428. struct Fts5Enum {
  173429. const char *zName;
  173430. int eVal;
  173431. };
  173432. typedef struct Fts5Enum Fts5Enum;
  173433. static int fts5ConfigSetEnum(
  173434. const Fts5Enum *aEnum,
  173435. const char *zEnum,
  173436. int *peVal
  173437. ){
  173438. int nEnum = (int)strlen(zEnum);
  173439. int i;
  173440. int iVal = -1;
  173441. for(i=0; aEnum[i].zName; i++){
  173442. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  173443. if( iVal>=0 ) return SQLITE_ERROR;
  173444. iVal = aEnum[i].eVal;
  173445. }
  173446. }
  173447. *peVal = iVal;
  173448. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  173449. }
  173450. /*
  173451. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  173452. ** configuration object pConfig as appropriate.
  173453. **
  173454. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  173455. ** an error occurs, an SQLite error code is returned and an error message
  173456. ** may be left in *pzErr. It is the responsibility of the caller to
  173457. ** eventually free any such error message using sqlite3_free().
  173458. */
  173459. static int fts5ConfigParseSpecial(
  173460. Fts5Global *pGlobal,
  173461. Fts5Config *pConfig, /* Configuration object to update */
  173462. const char *zCmd, /* Special command to parse */
  173463. const char *zArg, /* Argument to parse */
  173464. char **pzErr /* OUT: Error message */
  173465. ){
  173466. int rc = SQLITE_OK;
  173467. int nCmd = (int)strlen(zCmd);
  173468. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  173469. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  173470. const char *p;
  173471. int bFirst = 1;
  173472. if( pConfig->aPrefix==0 ){
  173473. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  173474. if( rc ) return rc;
  173475. }
  173476. p = zArg;
  173477. while( 1 ){
  173478. int nPre = 0;
  173479. while( p[0]==' ' ) p++;
  173480. if( bFirst==0 && p[0]==',' ){
  173481. p++;
  173482. while( p[0]==' ' ) p++;
  173483. }else if( p[0]=='\0' ){
  173484. break;
  173485. }
  173486. if( p[0]<'0' || p[0]>'9' ){
  173487. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  173488. rc = SQLITE_ERROR;
  173489. break;
  173490. }
  173491. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  173492. *pzErr = sqlite3_mprintf(
  173493. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  173494. );
  173495. rc = SQLITE_ERROR;
  173496. break;
  173497. }
  173498. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  173499. nPre = nPre*10 + (p[0] - '0');
  173500. p++;
  173501. }
  173502. if( nPre<=0 || nPre>=1000 ){
  173503. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  173504. rc = SQLITE_ERROR;
  173505. break;
  173506. }
  173507. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  173508. pConfig->nPrefix++;
  173509. bFirst = 0;
  173510. }
  173511. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  173512. return rc;
  173513. }
  173514. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  173515. const char *p = (const char*)zArg;
  173516. int nArg = (int)strlen(zArg) + 1;
  173517. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  173518. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  173519. char *pSpace = pDel;
  173520. if( azArg && pSpace ){
  173521. if( pConfig->pTok ){
  173522. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  173523. rc = SQLITE_ERROR;
  173524. }else{
  173525. for(nArg=0; p && *p; nArg++){
  173526. const char *p2 = fts5ConfigSkipWhitespace(p);
  173527. if( *p2=='\'' ){
  173528. p = fts5ConfigSkipLiteral(p2);
  173529. }else{
  173530. p = fts5ConfigSkipBareword(p2);
  173531. }
  173532. if( p ){
  173533. memcpy(pSpace, p2, p-p2);
  173534. azArg[nArg] = pSpace;
  173535. sqlite3Fts5Dequote(pSpace);
  173536. pSpace += (p - p2) + 1;
  173537. p = fts5ConfigSkipWhitespace(p);
  173538. }
  173539. }
  173540. if( p==0 ){
  173541. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  173542. rc = SQLITE_ERROR;
  173543. }else{
  173544. rc = sqlite3Fts5GetTokenizer(pGlobal,
  173545. (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
  173546. pzErr
  173547. );
  173548. }
  173549. }
  173550. }
  173551. sqlite3_free(azArg);
  173552. sqlite3_free(pDel);
  173553. return rc;
  173554. }
  173555. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  173556. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  173557. *pzErr = sqlite3_mprintf("multiple content=... directives");
  173558. rc = SQLITE_ERROR;
  173559. }else{
  173560. if( zArg[0] ){
  173561. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  173562. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  173563. }else{
  173564. pConfig->eContent = FTS5_CONTENT_NONE;
  173565. }
  173566. }
  173567. return rc;
  173568. }
  173569. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  173570. if( pConfig->zContentRowid ){
  173571. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  173572. rc = SQLITE_ERROR;
  173573. }else{
  173574. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  173575. }
  173576. return rc;
  173577. }
  173578. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  173579. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  173580. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  173581. rc = SQLITE_ERROR;
  173582. }else{
  173583. pConfig->bColumnsize = (zArg[0]=='1');
  173584. }
  173585. return rc;
  173586. }
  173587. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  173588. const Fts5Enum aDetail[] = {
  173589. { "none", FTS5_DETAIL_NONE },
  173590. { "full", FTS5_DETAIL_FULL },
  173591. { "columns", FTS5_DETAIL_COLUMNS },
  173592. { 0, 0 }
  173593. };
  173594. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  173595. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  173596. }
  173597. return rc;
  173598. }
  173599. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  173600. return SQLITE_ERROR;
  173601. }
  173602. /*
  173603. ** Allocate an instance of the default tokenizer ("simple") at
  173604. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  173605. ** code if an error occurs.
  173606. */
  173607. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  173608. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  173609. return sqlite3Fts5GetTokenizer(
  173610. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  173611. );
  173612. }
  173613. /*
  173614. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  173615. ** Return a pointer to the character immediately following the last in
  173616. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  173617. ** to find close-quote character).
  173618. **
  173619. ** Before returning, set pzOut to point to a new buffer containing a
  173620. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  173621. ** quoted, *pbQuoted is also set to 1 before returning.
  173622. **
  173623. ** If *pRc is other than SQLITE_OK when this function is called, it is
  173624. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  173625. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  173626. ** set if a parse error (failed to find close quote) occurs.
  173627. */
  173628. static const char *fts5ConfigGobbleWord(
  173629. int *pRc, /* IN/OUT: Error code */
  173630. const char *zIn, /* Buffer to gobble string/bareword from */
  173631. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  173632. int *pbQuoted /* OUT: Set to true if dequoting required */
  173633. ){
  173634. const char *zRet = 0;
  173635. int nIn = (int)strlen(zIn);
  173636. char *zOut = sqlite3_malloc(nIn+1);
  173637. assert( *pRc==SQLITE_OK );
  173638. *pbQuoted = 0;
  173639. *pzOut = 0;
  173640. if( zOut==0 ){
  173641. *pRc = SQLITE_NOMEM;
  173642. }else{
  173643. memcpy(zOut, zIn, nIn+1);
  173644. if( fts5_isopenquote(zOut[0]) ){
  173645. int ii = fts5Dequote(zOut);
  173646. zRet = &zIn[ii];
  173647. *pbQuoted = 1;
  173648. }else{
  173649. zRet = fts5ConfigSkipBareword(zIn);
  173650. if( zRet ){
  173651. zOut[zRet-zIn] = '\0';
  173652. }
  173653. }
  173654. }
  173655. if( zRet==0 ){
  173656. sqlite3_free(zOut);
  173657. }else{
  173658. *pzOut = zOut;
  173659. }
  173660. return zRet;
  173661. }
  173662. static int fts5ConfigParseColumn(
  173663. Fts5Config *p,
  173664. char *zCol,
  173665. char *zArg,
  173666. char **pzErr
  173667. ){
  173668. int rc = SQLITE_OK;
  173669. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  173670. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  173671. ){
  173672. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  173673. rc = SQLITE_ERROR;
  173674. }else if( zArg ){
  173675. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  173676. p->abUnindexed[p->nCol] = 1;
  173677. }else{
  173678. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  173679. rc = SQLITE_ERROR;
  173680. }
  173681. }
  173682. p->azCol[p->nCol++] = zCol;
  173683. return rc;
  173684. }
  173685. /*
  173686. ** Populate the Fts5Config.zContentExprlist string.
  173687. */
  173688. static int fts5ConfigMakeExprlist(Fts5Config *p){
  173689. int i;
  173690. int rc = SQLITE_OK;
  173691. Fts5Buffer buf = {0, 0, 0};
  173692. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  173693. if( p->eContent!=FTS5_CONTENT_NONE ){
  173694. for(i=0; i<p->nCol; i++){
  173695. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  173696. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  173697. }else{
  173698. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  173699. }
  173700. }
  173701. }
  173702. assert( p->zContentExprlist==0 );
  173703. p->zContentExprlist = (char*)buf.p;
  173704. return rc;
  173705. }
  173706. /*
  173707. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  173708. ** or xConnect method of the virtual table. This function attempts to
  173709. ** allocate an instance of Fts5Config containing the results of parsing
  173710. ** those arguments.
  173711. **
  173712. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  173713. ** new Fts5Config object. If an error occurs, an SQLite error code is
  173714. ** returned, *ppOut is set to NULL and an error message may be left in
  173715. ** *pzErr. It is the responsibility of the caller to eventually free any
  173716. ** such error message using sqlite3_free().
  173717. */
  173718. static int sqlite3Fts5ConfigParse(
  173719. Fts5Global *pGlobal,
  173720. sqlite3 *db,
  173721. int nArg, /* Number of arguments */
  173722. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  173723. Fts5Config **ppOut, /* OUT: Results of parse */
  173724. char **pzErr /* OUT: Error message */
  173725. ){
  173726. int rc = SQLITE_OK; /* Return code */
  173727. Fts5Config *pRet; /* New object to return */
  173728. int i;
  173729. int nByte;
  173730. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  173731. if( pRet==0 ) return SQLITE_NOMEM;
  173732. memset(pRet, 0, sizeof(Fts5Config));
  173733. pRet->db = db;
  173734. pRet->iCookie = -1;
  173735. nByte = nArg * (sizeof(char*) + sizeof(u8));
  173736. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  173737. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  173738. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  173739. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  173740. pRet->bColumnsize = 1;
  173741. pRet->eDetail = FTS5_DETAIL_FULL;
  173742. #ifdef SQLITE_DEBUG
  173743. pRet->bPrefixIndex = 1;
  173744. #endif
  173745. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  173746. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  173747. rc = SQLITE_ERROR;
  173748. }
  173749. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  173750. const char *zOrig = azArg[i];
  173751. const char *z;
  173752. char *zOne = 0;
  173753. char *zTwo = 0;
  173754. int bOption = 0;
  173755. int bMustBeCol = 0;
  173756. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  173757. z = fts5ConfigSkipWhitespace(z);
  173758. if( z && *z=='=' ){
  173759. bOption = 1;
  173760. z++;
  173761. if( bMustBeCol ) z = 0;
  173762. }
  173763. z = fts5ConfigSkipWhitespace(z);
  173764. if( z && z[0] ){
  173765. int bDummy;
  173766. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  173767. if( z && z[0] ) z = 0;
  173768. }
  173769. if( rc==SQLITE_OK ){
  173770. if( z==0 ){
  173771. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  173772. rc = SQLITE_ERROR;
  173773. }else{
  173774. if( bOption ){
  173775. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  173776. }else{
  173777. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  173778. zOne = 0;
  173779. }
  173780. }
  173781. }
  173782. sqlite3_free(zOne);
  173783. sqlite3_free(zTwo);
  173784. }
  173785. /* If a tokenizer= option was successfully parsed, the tokenizer has
  173786. ** already been allocated. Otherwise, allocate an instance of the default
  173787. ** tokenizer (unicode61) now. */
  173788. if( rc==SQLITE_OK && pRet->pTok==0 ){
  173789. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  173790. }
  173791. /* If no zContent option was specified, fill in the default values. */
  173792. if( rc==SQLITE_OK && pRet->zContent==0 ){
  173793. const char *zTail = 0;
  173794. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  173795. || pRet->eContent==FTS5_CONTENT_NONE
  173796. );
  173797. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  173798. zTail = "content";
  173799. }else if( pRet->bColumnsize ){
  173800. zTail = "docsize";
  173801. }
  173802. if( zTail ){
  173803. pRet->zContent = sqlite3Fts5Mprintf(
  173804. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  173805. );
  173806. }
  173807. }
  173808. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  173809. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  173810. }
  173811. /* Formulate the zContentExprlist text */
  173812. if( rc==SQLITE_OK ){
  173813. rc = fts5ConfigMakeExprlist(pRet);
  173814. }
  173815. if( rc!=SQLITE_OK ){
  173816. sqlite3Fts5ConfigFree(pRet);
  173817. *ppOut = 0;
  173818. }
  173819. return rc;
  173820. }
  173821. /*
  173822. ** Free the configuration object passed as the only argument.
  173823. */
  173824. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  173825. if( pConfig ){
  173826. int i;
  173827. if( pConfig->pTok ){
  173828. pConfig->pTokApi->xDelete(pConfig->pTok);
  173829. }
  173830. sqlite3_free(pConfig->zDb);
  173831. sqlite3_free(pConfig->zName);
  173832. for(i=0; i<pConfig->nCol; i++){
  173833. sqlite3_free(pConfig->azCol[i]);
  173834. }
  173835. sqlite3_free(pConfig->azCol);
  173836. sqlite3_free(pConfig->aPrefix);
  173837. sqlite3_free(pConfig->zRank);
  173838. sqlite3_free(pConfig->zRankArgs);
  173839. sqlite3_free(pConfig->zContent);
  173840. sqlite3_free(pConfig->zContentRowid);
  173841. sqlite3_free(pConfig->zContentExprlist);
  173842. sqlite3_free(pConfig);
  173843. }
  173844. }
  173845. /*
  173846. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  173847. ** object passed as the only argument. Return SQLITE_OK if successful, or
  173848. ** an SQLite error code if an error occurs.
  173849. */
  173850. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  173851. int i;
  173852. int rc = SQLITE_OK;
  173853. char *zSql;
  173854. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  173855. for(i=0; zSql && i<pConfig->nCol; i++){
  173856. const char *zSep = (i==0?"":", ");
  173857. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  173858. }
  173859. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  173860. zSql, pConfig->zName, FTS5_RANK_NAME
  173861. );
  173862. assert( zSql || rc==SQLITE_NOMEM );
  173863. if( zSql ){
  173864. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  173865. sqlite3_free(zSql);
  173866. }
  173867. return rc;
  173868. }
  173869. /*
  173870. ** Tokenize the text passed via the second and third arguments.
  173871. **
  173872. ** The callback is invoked once for each token in the input text. The
  173873. ** arguments passed to it are, in order:
  173874. **
  173875. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  173876. ** const char *pToken // Pointer to buffer containing token
  173877. ** int nToken // Size of token in bytes
  173878. ** int iStart // Byte offset of start of token within input text
  173879. ** int iEnd // Byte offset of end of token within input text
  173880. ** int iPos // Position of token in input (first token is 0)
  173881. **
  173882. ** If the callback returns a non-zero value the tokenization is abandoned
  173883. ** and no further callbacks are issued.
  173884. **
  173885. ** This function returns SQLITE_OK if successful or an SQLite error code
  173886. ** if an error occurs. If the tokenization was abandoned early because
  173887. ** the callback returned SQLITE_DONE, this is not an error and this function
  173888. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  173889. ** because the callback returned another non-zero value, it is assumed
  173890. ** to be an SQLite error code and returned to the caller.
  173891. */
  173892. static int sqlite3Fts5Tokenize(
  173893. Fts5Config *pConfig, /* FTS5 Configuration object */
  173894. int flags, /* FTS5_TOKENIZE_* flags */
  173895. const char *pText, int nText, /* Text to tokenize */
  173896. void *pCtx, /* Context passed to xToken() */
  173897. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  173898. ){
  173899. if( pText==0 ) return SQLITE_OK;
  173900. return pConfig->pTokApi->xTokenize(
  173901. pConfig->pTok, pCtx, flags, pText, nText, xToken
  173902. );
  173903. }
  173904. /*
  173905. ** Argument pIn points to the first character in what is expected to be
  173906. ** a comma-separated list of SQL literals followed by a ')' character.
  173907. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  173908. ** NULL to indicate a parse error.
  173909. */
  173910. static const char *fts5ConfigSkipArgs(const char *pIn){
  173911. const char *p = pIn;
  173912. while( 1 ){
  173913. p = fts5ConfigSkipWhitespace(p);
  173914. p = fts5ConfigSkipLiteral(p);
  173915. p = fts5ConfigSkipWhitespace(p);
  173916. if( p==0 || *p==')' ) break;
  173917. if( *p!=',' ){
  173918. p = 0;
  173919. break;
  173920. }
  173921. p++;
  173922. }
  173923. return p;
  173924. }
  173925. /*
  173926. ** Parameter zIn contains a rank() function specification. The format of
  173927. ** this is:
  173928. **
  173929. ** + Bareword (function name)
  173930. ** + Open parenthesis - "("
  173931. ** + Zero or more SQL literals in a comma separated list
  173932. ** + Close parenthesis - ")"
  173933. */
  173934. static int sqlite3Fts5ConfigParseRank(
  173935. const char *zIn, /* Input string */
  173936. char **pzRank, /* OUT: Rank function name */
  173937. char **pzRankArgs /* OUT: Rank function arguments */
  173938. ){
  173939. const char *p = zIn;
  173940. const char *pRank;
  173941. char *zRank = 0;
  173942. char *zRankArgs = 0;
  173943. int rc = SQLITE_OK;
  173944. *pzRank = 0;
  173945. *pzRankArgs = 0;
  173946. if( p==0 ){
  173947. rc = SQLITE_ERROR;
  173948. }else{
  173949. p = fts5ConfigSkipWhitespace(p);
  173950. pRank = p;
  173951. p = fts5ConfigSkipBareword(p);
  173952. if( p ){
  173953. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  173954. if( zRank ) memcpy(zRank, pRank, p-pRank);
  173955. }else{
  173956. rc = SQLITE_ERROR;
  173957. }
  173958. if( rc==SQLITE_OK ){
  173959. p = fts5ConfigSkipWhitespace(p);
  173960. if( *p!='(' ) rc = SQLITE_ERROR;
  173961. p++;
  173962. }
  173963. if( rc==SQLITE_OK ){
  173964. const char *pArgs;
  173965. p = fts5ConfigSkipWhitespace(p);
  173966. pArgs = p;
  173967. if( *p!=')' ){
  173968. p = fts5ConfigSkipArgs(p);
  173969. if( p==0 ){
  173970. rc = SQLITE_ERROR;
  173971. }else{
  173972. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  173973. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  173974. }
  173975. }
  173976. }
  173977. }
  173978. if( rc!=SQLITE_OK ){
  173979. sqlite3_free(zRank);
  173980. assert( zRankArgs==0 );
  173981. }else{
  173982. *pzRank = zRank;
  173983. *pzRankArgs = zRankArgs;
  173984. }
  173985. return rc;
  173986. }
  173987. static int sqlite3Fts5ConfigSetValue(
  173988. Fts5Config *pConfig,
  173989. const char *zKey,
  173990. sqlite3_value *pVal,
  173991. int *pbBadkey
  173992. ){
  173993. int rc = SQLITE_OK;
  173994. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  173995. int pgsz = 0;
  173996. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  173997. pgsz = sqlite3_value_int(pVal);
  173998. }
  173999. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  174000. *pbBadkey = 1;
  174001. }else{
  174002. pConfig->pgsz = pgsz;
  174003. }
  174004. }
  174005. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  174006. int nHashSize = -1;
  174007. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  174008. nHashSize = sqlite3_value_int(pVal);
  174009. }
  174010. if( nHashSize<=0 ){
  174011. *pbBadkey = 1;
  174012. }else{
  174013. pConfig->nHashSize = nHashSize;
  174014. }
  174015. }
  174016. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  174017. int nAutomerge = -1;
  174018. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  174019. nAutomerge = sqlite3_value_int(pVal);
  174020. }
  174021. if( nAutomerge<0 || nAutomerge>64 ){
  174022. *pbBadkey = 1;
  174023. }else{
  174024. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  174025. pConfig->nAutomerge = nAutomerge;
  174026. }
  174027. }
  174028. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  174029. int nUsermerge = -1;
  174030. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  174031. nUsermerge = sqlite3_value_int(pVal);
  174032. }
  174033. if( nUsermerge<2 || nUsermerge>16 ){
  174034. *pbBadkey = 1;
  174035. }else{
  174036. pConfig->nUsermerge = nUsermerge;
  174037. }
  174038. }
  174039. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  174040. int nCrisisMerge = -1;
  174041. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  174042. nCrisisMerge = sqlite3_value_int(pVal);
  174043. }
  174044. if( nCrisisMerge<0 ){
  174045. *pbBadkey = 1;
  174046. }else{
  174047. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  174048. pConfig->nCrisisMerge = nCrisisMerge;
  174049. }
  174050. }
  174051. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  174052. const char *zIn = (const char*)sqlite3_value_text(pVal);
  174053. char *zRank;
  174054. char *zRankArgs;
  174055. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  174056. if( rc==SQLITE_OK ){
  174057. sqlite3_free(pConfig->zRank);
  174058. sqlite3_free(pConfig->zRankArgs);
  174059. pConfig->zRank = zRank;
  174060. pConfig->zRankArgs = zRankArgs;
  174061. }else if( rc==SQLITE_ERROR ){
  174062. rc = SQLITE_OK;
  174063. *pbBadkey = 1;
  174064. }
  174065. }else{
  174066. *pbBadkey = 1;
  174067. }
  174068. return rc;
  174069. }
  174070. /*
  174071. ** Load the contents of the %_config table into memory.
  174072. */
  174073. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  174074. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  174075. char *zSql;
  174076. sqlite3_stmt *p = 0;
  174077. int rc = SQLITE_OK;
  174078. int iVersion = 0;
  174079. /* Set default values */
  174080. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  174081. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  174082. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  174083. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  174084. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  174085. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  174086. if( zSql ){
  174087. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  174088. sqlite3_free(zSql);
  174089. }
  174090. assert( rc==SQLITE_OK || p==0 );
  174091. if( rc==SQLITE_OK ){
  174092. while( SQLITE_ROW==sqlite3_step(p) ){
  174093. const char *zK = (const char*)sqlite3_column_text(p, 0);
  174094. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  174095. if( 0==sqlite3_stricmp(zK, "version") ){
  174096. iVersion = sqlite3_value_int(pVal);
  174097. }else{
  174098. int bDummy = 0;
  174099. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  174100. }
  174101. }
  174102. rc = sqlite3_finalize(p);
  174103. }
  174104. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  174105. rc = SQLITE_ERROR;
  174106. if( pConfig->pzErrmsg ){
  174107. assert( 0==*pConfig->pzErrmsg );
  174108. *pConfig->pzErrmsg = sqlite3_mprintf(
  174109. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  174110. iVersion, FTS5_CURRENT_VERSION
  174111. );
  174112. }
  174113. }
  174114. if( rc==SQLITE_OK ){
  174115. pConfig->iCookie = iCookie;
  174116. }
  174117. return rc;
  174118. }
  174119. /*
  174120. ** 2014 May 31
  174121. **
  174122. ** The author disclaims copyright to this source code. In place of
  174123. ** a legal notice, here is a blessing:
  174124. **
  174125. ** May you do good and not evil.
  174126. ** May you find forgiveness for yourself and forgive others.
  174127. ** May you share freely, never taking more than you give.
  174128. **
  174129. ******************************************************************************
  174130. **
  174131. */
  174132. /* #include "fts5Int.h" */
  174133. /* #include "fts5parse.h" */
  174134. /*
  174135. ** All token types in the generated fts5parse.h file are greater than 0.
  174136. */
  174137. #define FTS5_EOF 0
  174138. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  174139. typedef struct Fts5ExprTerm Fts5ExprTerm;
  174140. /*
  174141. ** Functions generated by lemon from fts5parse.y.
  174142. */
  174143. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  174144. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  174145. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  174146. #ifndef NDEBUG
  174147. /* #include <stdio.h> */
  174148. static void sqlite3Fts5ParserTrace(FILE*, char*);
  174149. #endif
  174150. struct Fts5Expr {
  174151. Fts5Index *pIndex;
  174152. Fts5Config *pConfig;
  174153. Fts5ExprNode *pRoot;
  174154. int bDesc; /* Iterate in descending rowid order */
  174155. int nPhrase; /* Number of phrases in expression */
  174156. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  174157. };
  174158. /*
  174159. ** eType:
  174160. ** Expression node type. Always one of:
  174161. **
  174162. ** FTS5_AND (nChild, apChild valid)
  174163. ** FTS5_OR (nChild, apChild valid)
  174164. ** FTS5_NOT (nChild, apChild valid)
  174165. ** FTS5_STRING (pNear valid)
  174166. ** FTS5_TERM (pNear valid)
  174167. */
  174168. struct Fts5ExprNode {
  174169. int eType; /* Node type */
  174170. int bEof; /* True at EOF */
  174171. int bNomatch; /* True if entry is not a match */
  174172. /* Next method for this node. */
  174173. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  174174. i64 iRowid; /* Current rowid */
  174175. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  174176. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  174177. ** AND or OR nodes, it contains 2 or more entries. */
  174178. int nChild; /* Number of child nodes */
  174179. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  174180. };
  174181. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  174182. /*
  174183. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  174184. ** used as if it has the same signature as the xNext() methods themselves.
  174185. */
  174186. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  174187. /*
  174188. ** An instance of the following structure represents a single search term
  174189. ** or term prefix.
  174190. */
  174191. struct Fts5ExprTerm {
  174192. int bPrefix; /* True for a prefix term */
  174193. char *zTerm; /* nul-terminated term */
  174194. Fts5IndexIter *pIter; /* Iterator for this term */
  174195. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  174196. };
  174197. /*
  174198. ** A phrase. One or more terms that must appear in a contiguous sequence
  174199. ** within a document for it to match.
  174200. */
  174201. struct Fts5ExprPhrase {
  174202. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  174203. Fts5Buffer poslist; /* Current position list */
  174204. int nTerm; /* Number of entries in aTerm[] */
  174205. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  174206. };
  174207. /*
  174208. ** One or more phrases that must appear within a certain token distance of
  174209. ** each other within each matching document.
  174210. */
  174211. struct Fts5ExprNearset {
  174212. int nNear; /* NEAR parameter */
  174213. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  174214. int nPhrase; /* Number of entries in aPhrase[] array */
  174215. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  174216. };
  174217. /*
  174218. ** Parse context.
  174219. */
  174220. struct Fts5Parse {
  174221. Fts5Config *pConfig;
  174222. char *zErr;
  174223. int rc;
  174224. int nPhrase; /* Size of apPhrase array */
  174225. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  174226. Fts5ExprNode *pExpr; /* Result of a successful parse */
  174227. };
  174228. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  174229. va_list ap;
  174230. va_start(ap, zFmt);
  174231. if( pParse->rc==SQLITE_OK ){
  174232. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  174233. pParse->rc = SQLITE_ERROR;
  174234. }
  174235. va_end(ap);
  174236. }
  174237. static int fts5ExprIsspace(char t){
  174238. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  174239. }
  174240. /*
  174241. ** Read the first token from the nul-terminated string at *pz.
  174242. */
  174243. static int fts5ExprGetToken(
  174244. Fts5Parse *pParse,
  174245. const char **pz, /* IN/OUT: Pointer into buffer */
  174246. Fts5Token *pToken
  174247. ){
  174248. const char *z = *pz;
  174249. int tok;
  174250. /* Skip past any whitespace */
  174251. while( fts5ExprIsspace(*z) ) z++;
  174252. pToken->p = z;
  174253. pToken->n = 1;
  174254. switch( *z ){
  174255. case '(': tok = FTS5_LP; break;
  174256. case ')': tok = FTS5_RP; break;
  174257. case '{': tok = FTS5_LCP; break;
  174258. case '}': tok = FTS5_RCP; break;
  174259. case ':': tok = FTS5_COLON; break;
  174260. case ',': tok = FTS5_COMMA; break;
  174261. case '+': tok = FTS5_PLUS; break;
  174262. case '*': tok = FTS5_STAR; break;
  174263. case '-': tok = FTS5_MINUS; break;
  174264. case '\0': tok = FTS5_EOF; break;
  174265. case '"': {
  174266. const char *z2;
  174267. tok = FTS5_STRING;
  174268. for(z2=&z[1]; 1; z2++){
  174269. if( z2[0]=='"' ){
  174270. z2++;
  174271. if( z2[0]!='"' ) break;
  174272. }
  174273. if( z2[0]=='\0' ){
  174274. sqlite3Fts5ParseError(pParse, "unterminated string");
  174275. return FTS5_EOF;
  174276. }
  174277. }
  174278. pToken->n = (z2 - z);
  174279. break;
  174280. }
  174281. default: {
  174282. const char *z2;
  174283. if( sqlite3Fts5IsBareword(z[0])==0 ){
  174284. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  174285. return FTS5_EOF;
  174286. }
  174287. tok = FTS5_STRING;
  174288. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  174289. pToken->n = (z2 - z);
  174290. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  174291. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  174292. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  174293. break;
  174294. }
  174295. }
  174296. *pz = &pToken->p[pToken->n];
  174297. return tok;
  174298. }
  174299. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
  174300. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  174301. static int sqlite3Fts5ExprNew(
  174302. Fts5Config *pConfig, /* FTS5 Configuration */
  174303. int iCol,
  174304. const char *zExpr, /* Expression text */
  174305. Fts5Expr **ppNew,
  174306. char **pzErr
  174307. ){
  174308. Fts5Parse sParse;
  174309. Fts5Token token;
  174310. const char *z = zExpr;
  174311. int t; /* Next token type */
  174312. void *pEngine;
  174313. Fts5Expr *pNew;
  174314. *ppNew = 0;
  174315. *pzErr = 0;
  174316. memset(&sParse, 0, sizeof(sParse));
  174317. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  174318. if( pEngine==0 ){ return SQLITE_NOMEM; }
  174319. sParse.pConfig = pConfig;
  174320. do {
  174321. t = fts5ExprGetToken(&sParse, &z, &token);
  174322. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  174323. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  174324. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  174325. /* If the LHS of the MATCH expression was a user column, apply the
  174326. ** implicit column-filter. */
  174327. if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
  174328. int n = sizeof(Fts5Colset);
  174329. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
  174330. if( pColset ){
  174331. pColset->nCol = 1;
  174332. pColset->aiCol[0] = iCol;
  174333. sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
  174334. }
  174335. }
  174336. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  174337. if( sParse.rc==SQLITE_OK ){
  174338. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  174339. if( pNew==0 ){
  174340. sParse.rc = SQLITE_NOMEM;
  174341. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  174342. }else{
  174343. if( !sParse.pExpr ){
  174344. const int nByte = sizeof(Fts5ExprNode);
  174345. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  174346. if( pNew->pRoot ){
  174347. pNew->pRoot->bEof = 1;
  174348. }
  174349. }else{
  174350. pNew->pRoot = sParse.pExpr;
  174351. }
  174352. pNew->pIndex = 0;
  174353. pNew->pConfig = pConfig;
  174354. pNew->apExprPhrase = sParse.apPhrase;
  174355. pNew->nPhrase = sParse.nPhrase;
  174356. sParse.apPhrase = 0;
  174357. }
  174358. }else{
  174359. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  174360. }
  174361. sqlite3_free(sParse.apPhrase);
  174362. *pzErr = sParse.zErr;
  174363. return sParse.rc;
  174364. }
  174365. /*
  174366. ** Free the expression node object passed as the only argument.
  174367. */
  174368. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  174369. if( p ){
  174370. int i;
  174371. for(i=0; i<p->nChild; i++){
  174372. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  174373. }
  174374. sqlite3Fts5ParseNearsetFree(p->pNear);
  174375. sqlite3_free(p);
  174376. }
  174377. }
  174378. /*
  174379. ** Free the expression object passed as the only argument.
  174380. */
  174381. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  174382. if( p ){
  174383. sqlite3Fts5ParseNodeFree(p->pRoot);
  174384. sqlite3_free(p->apExprPhrase);
  174385. sqlite3_free(p);
  174386. }
  174387. }
  174388. /*
  174389. ** Argument pTerm must be a synonym iterator. Return the current rowid
  174390. ** that it points to.
  174391. */
  174392. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  174393. i64 iRet = 0;
  174394. int bRetValid = 0;
  174395. Fts5ExprTerm *p;
  174396. assert( pTerm->pSynonym );
  174397. assert( bDesc==0 || bDesc==1 );
  174398. for(p=pTerm; p; p=p->pSynonym){
  174399. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  174400. i64 iRowid = p->pIter->iRowid;
  174401. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  174402. iRet = iRowid;
  174403. bRetValid = 1;
  174404. }
  174405. }
  174406. }
  174407. if( pbEof && bRetValid==0 ) *pbEof = 1;
  174408. return iRet;
  174409. }
  174410. /*
  174411. ** Argument pTerm must be a synonym iterator.
  174412. */
  174413. static int fts5ExprSynonymList(
  174414. Fts5ExprTerm *pTerm,
  174415. i64 iRowid,
  174416. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  174417. u8 **pa, int *pn
  174418. ){
  174419. Fts5PoslistReader aStatic[4];
  174420. Fts5PoslistReader *aIter = aStatic;
  174421. int nIter = 0;
  174422. int nAlloc = 4;
  174423. int rc = SQLITE_OK;
  174424. Fts5ExprTerm *p;
  174425. assert( pTerm->pSynonym );
  174426. for(p=pTerm; p; p=p->pSynonym){
  174427. Fts5IndexIter *pIter = p->pIter;
  174428. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  174429. if( pIter->nData==0 ) continue;
  174430. if( nIter==nAlloc ){
  174431. int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  174432. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  174433. if( aNew==0 ){
  174434. rc = SQLITE_NOMEM;
  174435. goto synonym_poslist_out;
  174436. }
  174437. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  174438. nAlloc = nAlloc*2;
  174439. if( aIter!=aStatic ) sqlite3_free(aIter);
  174440. aIter = aNew;
  174441. }
  174442. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  174443. assert( aIter[nIter].bEof==0 );
  174444. nIter++;
  174445. }
  174446. }
  174447. if( nIter==1 ){
  174448. *pa = (u8*)aIter[0].a;
  174449. *pn = aIter[0].n;
  174450. }else{
  174451. Fts5PoslistWriter writer = {0};
  174452. i64 iPrev = -1;
  174453. fts5BufferZero(pBuf);
  174454. while( 1 ){
  174455. int i;
  174456. i64 iMin = FTS5_LARGEST_INT64;
  174457. for(i=0; i<nIter; i++){
  174458. if( aIter[i].bEof==0 ){
  174459. if( aIter[i].iPos==iPrev ){
  174460. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  174461. }
  174462. if( aIter[i].iPos<iMin ){
  174463. iMin = aIter[i].iPos;
  174464. }
  174465. }
  174466. }
  174467. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  174468. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  174469. iPrev = iMin;
  174470. }
  174471. if( rc==SQLITE_OK ){
  174472. *pa = pBuf->p;
  174473. *pn = pBuf->n;
  174474. }
  174475. }
  174476. synonym_poslist_out:
  174477. if( aIter!=aStatic ) sqlite3_free(aIter);
  174478. return rc;
  174479. }
  174480. /*
  174481. ** All individual term iterators in pPhrase are guaranteed to be valid and
  174482. ** pointing to the same rowid when this function is called. This function
  174483. ** checks if the current rowid really is a match, and if so populates
  174484. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  174485. ** is set to true if this is really a match, or false otherwise.
  174486. **
  174487. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  174488. ** otherwise. It is not considered an error code if the current rowid is
  174489. ** not a match.
  174490. */
  174491. static int fts5ExprPhraseIsMatch(
  174492. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  174493. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  174494. int *pbMatch /* OUT: Set to true if really a match */
  174495. ){
  174496. Fts5PoslistWriter writer = {0};
  174497. Fts5PoslistReader aStatic[4];
  174498. Fts5PoslistReader *aIter = aStatic;
  174499. int i;
  174500. int rc = SQLITE_OK;
  174501. fts5BufferZero(&pPhrase->poslist);
  174502. /* If the aStatic[] array is not large enough, allocate a large array
  174503. ** using sqlite3_malloc(). This approach could be improved upon. */
  174504. if( pPhrase->nTerm>ArraySize(aStatic) ){
  174505. int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  174506. aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  174507. if( !aIter ) return SQLITE_NOMEM;
  174508. }
  174509. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  174510. /* Initialize a term iterator for each term in the phrase */
  174511. for(i=0; i<pPhrase->nTerm; i++){
  174512. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  174513. int n = 0;
  174514. int bFlag = 0;
  174515. u8 *a = 0;
  174516. if( pTerm->pSynonym ){
  174517. Fts5Buffer buf = {0, 0, 0};
  174518. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  174519. if( rc ){
  174520. sqlite3_free(a);
  174521. goto ismatch_out;
  174522. }
  174523. if( a==buf.p ) bFlag = 1;
  174524. }else{
  174525. a = (u8*)pTerm->pIter->pData;
  174526. n = pTerm->pIter->nData;
  174527. }
  174528. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  174529. aIter[i].bFlag = (u8)bFlag;
  174530. if( aIter[i].bEof ) goto ismatch_out;
  174531. }
  174532. while( 1 ){
  174533. int bMatch;
  174534. i64 iPos = aIter[0].iPos;
  174535. do {
  174536. bMatch = 1;
  174537. for(i=0; i<pPhrase->nTerm; i++){
  174538. Fts5PoslistReader *pPos = &aIter[i];
  174539. i64 iAdj = iPos + i;
  174540. if( pPos->iPos!=iAdj ){
  174541. bMatch = 0;
  174542. while( pPos->iPos<iAdj ){
  174543. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  174544. }
  174545. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  174546. }
  174547. }
  174548. }while( bMatch==0 );
  174549. /* Append position iPos to the output */
  174550. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  174551. if( rc!=SQLITE_OK ) goto ismatch_out;
  174552. for(i=0; i<pPhrase->nTerm; i++){
  174553. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  174554. }
  174555. }
  174556. ismatch_out:
  174557. *pbMatch = (pPhrase->poslist.n>0);
  174558. for(i=0; i<pPhrase->nTerm; i++){
  174559. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  174560. }
  174561. if( aIter!=aStatic ) sqlite3_free(aIter);
  174562. return rc;
  174563. }
  174564. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  174565. struct Fts5LookaheadReader {
  174566. const u8 *a; /* Buffer containing position list */
  174567. int n; /* Size of buffer a[] in bytes */
  174568. int i; /* Current offset in position list */
  174569. i64 iPos; /* Current position */
  174570. i64 iLookahead; /* Next position */
  174571. };
  174572. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  174573. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  174574. p->iPos = p->iLookahead;
  174575. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  174576. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  174577. }
  174578. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  174579. }
  174580. static int fts5LookaheadReaderInit(
  174581. const u8 *a, int n, /* Buffer to read position list from */
  174582. Fts5LookaheadReader *p /* Iterator object to initialize */
  174583. ){
  174584. memset(p, 0, sizeof(Fts5LookaheadReader));
  174585. p->a = a;
  174586. p->n = n;
  174587. fts5LookaheadReaderNext(p);
  174588. return fts5LookaheadReaderNext(p);
  174589. }
  174590. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  174591. struct Fts5NearTrimmer {
  174592. Fts5LookaheadReader reader; /* Input iterator */
  174593. Fts5PoslistWriter writer; /* Writer context */
  174594. Fts5Buffer *pOut; /* Output poslist */
  174595. };
  174596. /*
  174597. ** The near-set object passed as the first argument contains more than
  174598. ** one phrase. All phrases currently point to the same row. The
  174599. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  174600. ** tests if the current row contains instances of each phrase sufficiently
  174601. ** close together to meet the NEAR constraint. Non-zero is returned if it
  174602. ** does, or zero otherwise.
  174603. **
  174604. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  174605. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  174606. ** occurs within this function (*pRc) is set accordingly before returning.
  174607. ** The return value is undefined in both these cases.
  174608. **
  174609. ** If no error occurs and non-zero (a match) is returned, the position-list
  174610. ** of each phrase object is edited to contain only those entries that
  174611. ** meet the constraint before returning.
  174612. */
  174613. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  174614. Fts5NearTrimmer aStatic[4];
  174615. Fts5NearTrimmer *a = aStatic;
  174616. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  174617. int i;
  174618. int rc = *pRc;
  174619. int bMatch;
  174620. assert( pNear->nPhrase>1 );
  174621. /* If the aStatic[] array is not large enough, allocate a large array
  174622. ** using sqlite3_malloc(). This approach could be improved upon. */
  174623. if( pNear->nPhrase>ArraySize(aStatic) ){
  174624. int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  174625. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  174626. }else{
  174627. memset(aStatic, 0, sizeof(aStatic));
  174628. }
  174629. if( rc!=SQLITE_OK ){
  174630. *pRc = rc;
  174631. return 0;
  174632. }
  174633. /* Initialize a lookahead iterator for each phrase. After passing the
  174634. ** buffer and buffer size to the lookaside-reader init function, zero
  174635. ** the phrase poslist buffer. The new poslist for the phrase (containing
  174636. ** the same entries as the original with some entries removed on account
  174637. ** of the NEAR constraint) is written over the original even as it is
  174638. ** being read. This is safe as the entries for the new poslist are a
  174639. ** subset of the old, so it is not possible for data yet to be read to
  174640. ** be overwritten. */
  174641. for(i=0; i<pNear->nPhrase; i++){
  174642. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  174643. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  174644. pPoslist->n = 0;
  174645. a[i].pOut = pPoslist;
  174646. }
  174647. while( 1 ){
  174648. int iAdv;
  174649. i64 iMin;
  174650. i64 iMax;
  174651. /* This block advances the phrase iterators until they point to a set of
  174652. ** entries that together comprise a match. */
  174653. iMax = a[0].reader.iPos;
  174654. do {
  174655. bMatch = 1;
  174656. for(i=0; i<pNear->nPhrase; i++){
  174657. Fts5LookaheadReader *pPos = &a[i].reader;
  174658. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  174659. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  174660. bMatch = 0;
  174661. while( pPos->iPos<iMin ){
  174662. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  174663. }
  174664. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  174665. }
  174666. }
  174667. }while( bMatch==0 );
  174668. /* Add an entry to each output position list */
  174669. for(i=0; i<pNear->nPhrase; i++){
  174670. i64 iPos = a[i].reader.iPos;
  174671. Fts5PoslistWriter *pWriter = &a[i].writer;
  174672. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  174673. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  174674. }
  174675. }
  174676. iAdv = 0;
  174677. iMin = a[0].reader.iLookahead;
  174678. for(i=0; i<pNear->nPhrase; i++){
  174679. if( a[i].reader.iLookahead < iMin ){
  174680. iMin = a[i].reader.iLookahead;
  174681. iAdv = i;
  174682. }
  174683. }
  174684. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  174685. }
  174686. ismatch_out: {
  174687. int bRet = a[0].pOut->n>0;
  174688. *pRc = rc;
  174689. if( a!=aStatic ) sqlite3_free(a);
  174690. return bRet;
  174691. }
  174692. }
  174693. /*
  174694. ** Advance iterator pIter until it points to a value equal to or laster
  174695. ** than the initial value of *piLast. If this means the iterator points
  174696. ** to a value laster than *piLast, update *piLast to the new lastest value.
  174697. **
  174698. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  174699. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  174700. ** are set, return a non-zero value. Otherwise, return zero.
  174701. */
  174702. static int fts5ExprAdvanceto(
  174703. Fts5IndexIter *pIter, /* Iterator to advance */
  174704. int bDesc, /* True if iterator is "rowid DESC" */
  174705. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  174706. int *pRc, /* OUT: Error code */
  174707. int *pbEof /* OUT: Set to true if EOF */
  174708. ){
  174709. i64 iLast = *piLast;
  174710. i64 iRowid;
  174711. iRowid = pIter->iRowid;
  174712. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  174713. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  174714. if( rc || sqlite3Fts5IterEof(pIter) ){
  174715. *pRc = rc;
  174716. *pbEof = 1;
  174717. return 1;
  174718. }
  174719. iRowid = pIter->iRowid;
  174720. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  174721. }
  174722. *piLast = iRowid;
  174723. return 0;
  174724. }
  174725. static int fts5ExprSynonymAdvanceto(
  174726. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  174727. int bDesc, /* True if iterator is "rowid DESC" */
  174728. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  174729. int *pRc /* OUT: Error code */
  174730. ){
  174731. int rc = SQLITE_OK;
  174732. i64 iLast = *piLast;
  174733. Fts5ExprTerm *p;
  174734. int bEof = 0;
  174735. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  174736. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  174737. i64 iRowid = p->pIter->iRowid;
  174738. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  174739. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  174740. }
  174741. }
  174742. }
  174743. if( rc!=SQLITE_OK ){
  174744. *pRc = rc;
  174745. bEof = 1;
  174746. }else{
  174747. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  174748. }
  174749. return bEof;
  174750. }
  174751. static int fts5ExprNearTest(
  174752. int *pRc,
  174753. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  174754. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  174755. ){
  174756. Fts5ExprNearset *pNear = pNode->pNear;
  174757. int rc = *pRc;
  174758. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  174759. Fts5ExprTerm *pTerm;
  174760. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  174761. pPhrase->poslist.n = 0;
  174762. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  174763. Fts5IndexIter *pIter = pTerm->pIter;
  174764. if( sqlite3Fts5IterEof(pIter)==0 ){
  174765. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  174766. pPhrase->poslist.n = 1;
  174767. }
  174768. }
  174769. }
  174770. return pPhrase->poslist.n;
  174771. }else{
  174772. int i;
  174773. /* Check that each phrase in the nearset matches the current row.
  174774. ** Populate the pPhrase->poslist buffers at the same time. If any
  174775. ** phrase is not a match, break out of the loop early. */
  174776. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  174777. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  174778. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
  174779. int bMatch = 0;
  174780. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  174781. if( bMatch==0 ) break;
  174782. }else{
  174783. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  174784. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  174785. }
  174786. }
  174787. *pRc = rc;
  174788. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  174789. return 1;
  174790. }
  174791. return 0;
  174792. }
  174793. }
  174794. /*
  174795. ** Initialize all term iterators in the pNear object. If any term is found
  174796. ** to match no documents at all, return immediately without initializing any
  174797. ** further iterators.
  174798. **
  174799. ** If an error occurs, return an SQLite error code. Otherwise, return
  174800. ** SQLITE_OK. It is not considered an error if some term matches zero
  174801. ** documents.
  174802. */
  174803. static int fts5ExprNearInitAll(
  174804. Fts5Expr *pExpr,
  174805. Fts5ExprNode *pNode
  174806. ){
  174807. Fts5ExprNearset *pNear = pNode->pNear;
  174808. int i;
  174809. assert( pNode->bNomatch==0 );
  174810. for(i=0; i<pNear->nPhrase; i++){
  174811. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  174812. if( pPhrase->nTerm==0 ){
  174813. pNode->bEof = 1;
  174814. return SQLITE_OK;
  174815. }else{
  174816. int j;
  174817. for(j=0; j<pPhrase->nTerm; j++){
  174818. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  174819. Fts5ExprTerm *p;
  174820. int bHit = 0;
  174821. for(p=pTerm; p; p=p->pSynonym){
  174822. int rc;
  174823. if( p->pIter ){
  174824. sqlite3Fts5IterClose(p->pIter);
  174825. p->pIter = 0;
  174826. }
  174827. rc = sqlite3Fts5IndexQuery(
  174828. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  174829. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  174830. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  174831. pNear->pColset,
  174832. &p->pIter
  174833. );
  174834. assert( (rc==SQLITE_OK)==(p->pIter!=0) );
  174835. if( rc!=SQLITE_OK ) return rc;
  174836. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  174837. bHit = 1;
  174838. }
  174839. }
  174840. if( bHit==0 ){
  174841. pNode->bEof = 1;
  174842. return SQLITE_OK;
  174843. }
  174844. }
  174845. }
  174846. }
  174847. pNode->bEof = 0;
  174848. return SQLITE_OK;
  174849. }
  174850. /*
  174851. ** If pExpr is an ASC iterator, this function returns a value with the
  174852. ** same sign as:
  174853. **
  174854. ** (iLhs - iRhs)
  174855. **
  174856. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  174857. **
  174858. ** (iRhs - iLhs)
  174859. */
  174860. static int fts5RowidCmp(
  174861. Fts5Expr *pExpr,
  174862. i64 iLhs,
  174863. i64 iRhs
  174864. ){
  174865. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  174866. if( pExpr->bDesc==0 ){
  174867. if( iLhs<iRhs ) return -1;
  174868. return (iLhs > iRhs);
  174869. }else{
  174870. if( iLhs>iRhs ) return -1;
  174871. return (iLhs < iRhs);
  174872. }
  174873. }
  174874. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  174875. int i;
  174876. pNode->bEof = 1;
  174877. pNode->bNomatch = 0;
  174878. for(i=0; i<pNode->nChild; i++){
  174879. fts5ExprSetEof(pNode->apChild[i]);
  174880. }
  174881. }
  174882. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  174883. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  174884. Fts5ExprNearset *pNear = pNode->pNear;
  174885. int i;
  174886. for(i=0; i<pNear->nPhrase; i++){
  174887. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  174888. pPhrase->poslist.n = 0;
  174889. }
  174890. }else{
  174891. int i;
  174892. for(i=0; i<pNode->nChild; i++){
  174893. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  174894. }
  174895. }
  174896. }
  174897. /*
  174898. ** Compare the values currently indicated by the two nodes as follows:
  174899. **
  174900. ** res = (*p1) - (*p2)
  174901. **
  174902. ** Nodes that point to values that come later in the iteration order are
  174903. ** considered to be larger. Nodes at EOF are the largest of all.
  174904. **
  174905. ** This means that if the iteration order is ASC, then numerically larger
  174906. ** rowids are considered larger. Or if it is the default DESC, numerically
  174907. ** smaller rowids are larger.
  174908. */
  174909. static int fts5NodeCompare(
  174910. Fts5Expr *pExpr,
  174911. Fts5ExprNode *p1,
  174912. Fts5ExprNode *p2
  174913. ){
  174914. if( p2->bEof ) return -1;
  174915. if( p1->bEof ) return +1;
  174916. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  174917. }
  174918. /*
  174919. ** All individual term iterators in pNear are guaranteed to be valid when
  174920. ** this function is called. This function checks if all term iterators
  174921. ** point to the same rowid, and if not, advances them until they do.
  174922. ** If an EOF is reached before this happens, *pbEof is set to true before
  174923. ** returning.
  174924. **
  174925. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  174926. ** otherwise. It is not considered an error code if an iterator reaches
  174927. ** EOF.
  174928. */
  174929. static int fts5ExprNodeTest_STRING(
  174930. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  174931. Fts5ExprNode *pNode
  174932. ){
  174933. Fts5ExprNearset *pNear = pNode->pNear;
  174934. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  174935. int rc = SQLITE_OK;
  174936. i64 iLast; /* Lastest rowid any iterator points to */
  174937. int i, j; /* Phrase and token index, respectively */
  174938. int bMatch; /* True if all terms are at the same rowid */
  174939. const int bDesc = pExpr->bDesc;
  174940. /* Check that this node should not be FTS5_TERM */
  174941. assert( pNear->nPhrase>1
  174942. || pNear->apPhrase[0]->nTerm>1
  174943. || pNear->apPhrase[0]->aTerm[0].pSynonym
  174944. );
  174945. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  174946. ** iterator skips through rowids in the default ascending order, this means
  174947. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  174948. ** means the minimum rowid. */
  174949. if( pLeft->aTerm[0].pSynonym ){
  174950. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  174951. }else{
  174952. iLast = pLeft->aTerm[0].pIter->iRowid;
  174953. }
  174954. do {
  174955. bMatch = 1;
  174956. for(i=0; i<pNear->nPhrase; i++){
  174957. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  174958. for(j=0; j<pPhrase->nTerm; j++){
  174959. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  174960. if( pTerm->pSynonym ){
  174961. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  174962. if( iRowid==iLast ) continue;
  174963. bMatch = 0;
  174964. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  174965. pNode->bNomatch = 0;
  174966. pNode->bEof = 1;
  174967. return rc;
  174968. }
  174969. }else{
  174970. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  174971. if( pIter->iRowid==iLast || pIter->bEof ) continue;
  174972. bMatch = 0;
  174973. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  174974. return rc;
  174975. }
  174976. }
  174977. }
  174978. }
  174979. }while( bMatch==0 );
  174980. pNode->iRowid = iLast;
  174981. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  174982. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  174983. return rc;
  174984. }
  174985. /*
  174986. ** Advance the first term iterator in the first phrase of pNear. Set output
  174987. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  174988. **
  174989. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  174990. ** occurs.
  174991. */
  174992. static int fts5ExprNodeNext_STRING(
  174993. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  174994. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  174995. int bFromValid,
  174996. i64 iFrom
  174997. ){
  174998. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  174999. int rc = SQLITE_OK;
  175000. pNode->bNomatch = 0;
  175001. if( pTerm->pSynonym ){
  175002. int bEof = 1;
  175003. Fts5ExprTerm *p;
  175004. /* Find the firstest rowid any synonym points to. */
  175005. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  175006. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  175007. ** is valid - each iterator that points to a rowid before iFrom. */
  175008. for(p=pTerm; p; p=p->pSynonym){
  175009. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  175010. i64 ii = p->pIter->iRowid;
  175011. if( ii==iRowid
  175012. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  175013. ){
  175014. if( bFromValid ){
  175015. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  175016. }else{
  175017. rc = sqlite3Fts5IterNext(p->pIter);
  175018. }
  175019. if( rc!=SQLITE_OK ) break;
  175020. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  175021. bEof = 0;
  175022. }
  175023. }else{
  175024. bEof = 0;
  175025. }
  175026. }
  175027. }
  175028. /* Set the EOF flag if either all synonym iterators are at EOF or an
  175029. ** error has occurred. */
  175030. pNode->bEof = (rc || bEof);
  175031. }else{
  175032. Fts5IndexIter *pIter = pTerm->pIter;
  175033. assert( Fts5NodeIsString(pNode) );
  175034. if( bFromValid ){
  175035. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  175036. }else{
  175037. rc = sqlite3Fts5IterNext(pIter);
  175038. }
  175039. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  175040. }
  175041. if( pNode->bEof==0 ){
  175042. assert( rc==SQLITE_OK );
  175043. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  175044. }
  175045. return rc;
  175046. }
  175047. static int fts5ExprNodeTest_TERM(
  175048. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  175049. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  175050. ){
  175051. /* As this "NEAR" object is actually a single phrase that consists
  175052. ** of a single term only, grab pointers into the poslist managed by the
  175053. ** fts5_index.c iterator object. This is much faster than synthesizing
  175054. ** a new poslist the way we have to for more complicated phrase or NEAR
  175055. ** expressions. */
  175056. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  175057. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  175058. assert( pNode->eType==FTS5_TERM );
  175059. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  175060. assert( pPhrase->aTerm[0].pSynonym==0 );
  175061. pPhrase->poslist.n = pIter->nData;
  175062. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  175063. pPhrase->poslist.p = (u8*)pIter->pData;
  175064. }
  175065. pNode->iRowid = pIter->iRowid;
  175066. pNode->bNomatch = (pPhrase->poslist.n==0);
  175067. return SQLITE_OK;
  175068. }
  175069. /*
  175070. ** xNext() method for a node of type FTS5_TERM.
  175071. */
  175072. static int fts5ExprNodeNext_TERM(
  175073. Fts5Expr *pExpr,
  175074. Fts5ExprNode *pNode,
  175075. int bFromValid,
  175076. i64 iFrom
  175077. ){
  175078. int rc;
  175079. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  175080. assert( pNode->bEof==0 );
  175081. if( bFromValid ){
  175082. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  175083. }else{
  175084. rc = sqlite3Fts5IterNext(pIter);
  175085. }
  175086. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  175087. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  175088. }else{
  175089. pNode->bEof = 1;
  175090. pNode->bNomatch = 0;
  175091. }
  175092. return rc;
  175093. }
  175094. static void fts5ExprNodeTest_OR(
  175095. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  175096. Fts5ExprNode *pNode /* Expression node to test */
  175097. ){
  175098. Fts5ExprNode *pNext = pNode->apChild[0];
  175099. int i;
  175100. for(i=1; i<pNode->nChild; i++){
  175101. Fts5ExprNode *pChild = pNode->apChild[i];
  175102. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  175103. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  175104. pNext = pChild;
  175105. }
  175106. }
  175107. pNode->iRowid = pNext->iRowid;
  175108. pNode->bEof = pNext->bEof;
  175109. pNode->bNomatch = pNext->bNomatch;
  175110. }
  175111. static int fts5ExprNodeNext_OR(
  175112. Fts5Expr *pExpr,
  175113. Fts5ExprNode *pNode,
  175114. int bFromValid,
  175115. i64 iFrom
  175116. ){
  175117. int i;
  175118. i64 iLast = pNode->iRowid;
  175119. for(i=0; i<pNode->nChild; i++){
  175120. Fts5ExprNode *p1 = pNode->apChild[i];
  175121. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  175122. if( p1->bEof==0 ){
  175123. if( (p1->iRowid==iLast)
  175124. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  175125. ){
  175126. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  175127. if( rc!=SQLITE_OK ){
  175128. pNode->bNomatch = 0;
  175129. return rc;
  175130. }
  175131. }
  175132. }
  175133. }
  175134. fts5ExprNodeTest_OR(pExpr, pNode);
  175135. return SQLITE_OK;
  175136. }
  175137. /*
  175138. ** Argument pNode is an FTS5_AND node.
  175139. */
  175140. static int fts5ExprNodeTest_AND(
  175141. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  175142. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  175143. ){
  175144. int iChild;
  175145. i64 iLast = pAnd->iRowid;
  175146. int rc = SQLITE_OK;
  175147. int bMatch;
  175148. assert( pAnd->bEof==0 );
  175149. do {
  175150. pAnd->bNomatch = 0;
  175151. bMatch = 1;
  175152. for(iChild=0; iChild<pAnd->nChild; iChild++){
  175153. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  175154. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  175155. if( cmp>0 ){
  175156. /* Advance pChild until it points to iLast or laster */
  175157. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  175158. if( rc!=SQLITE_OK ){
  175159. pAnd->bNomatch = 0;
  175160. return rc;
  175161. }
  175162. }
  175163. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  175164. ** the child node is guaranteed to have advanced at least as far as
  175165. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  175166. ** new lastest rowid seen so far. */
  175167. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  175168. if( pChild->bEof ){
  175169. fts5ExprSetEof(pAnd);
  175170. bMatch = 1;
  175171. break;
  175172. }else if( iLast!=pChild->iRowid ){
  175173. bMatch = 0;
  175174. iLast = pChild->iRowid;
  175175. }
  175176. if( pChild->bNomatch ){
  175177. pAnd->bNomatch = 1;
  175178. }
  175179. }
  175180. }while( bMatch==0 );
  175181. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  175182. fts5ExprNodeZeroPoslist(pAnd);
  175183. }
  175184. pAnd->iRowid = iLast;
  175185. return SQLITE_OK;
  175186. }
  175187. static int fts5ExprNodeNext_AND(
  175188. Fts5Expr *pExpr,
  175189. Fts5ExprNode *pNode,
  175190. int bFromValid,
  175191. i64 iFrom
  175192. ){
  175193. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  175194. if( rc==SQLITE_OK ){
  175195. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  175196. }else{
  175197. pNode->bNomatch = 0;
  175198. }
  175199. return rc;
  175200. }
  175201. static int fts5ExprNodeTest_NOT(
  175202. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  175203. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  175204. ){
  175205. int rc = SQLITE_OK;
  175206. Fts5ExprNode *p1 = pNode->apChild[0];
  175207. Fts5ExprNode *p2 = pNode->apChild[1];
  175208. assert( pNode->nChild==2 );
  175209. while( rc==SQLITE_OK && p1->bEof==0 ){
  175210. int cmp = fts5NodeCompare(pExpr, p1, p2);
  175211. if( cmp>0 ){
  175212. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  175213. cmp = fts5NodeCompare(pExpr, p1, p2);
  175214. }
  175215. assert( rc!=SQLITE_OK || cmp<=0 );
  175216. if( cmp || p2->bNomatch ) break;
  175217. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  175218. }
  175219. pNode->bEof = p1->bEof;
  175220. pNode->bNomatch = p1->bNomatch;
  175221. pNode->iRowid = p1->iRowid;
  175222. if( p1->bEof ){
  175223. fts5ExprNodeZeroPoslist(p2);
  175224. }
  175225. return rc;
  175226. }
  175227. static int fts5ExprNodeNext_NOT(
  175228. Fts5Expr *pExpr,
  175229. Fts5ExprNode *pNode,
  175230. int bFromValid,
  175231. i64 iFrom
  175232. ){
  175233. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  175234. if( rc==SQLITE_OK ){
  175235. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  175236. }
  175237. if( rc!=SQLITE_OK ){
  175238. pNode->bNomatch = 0;
  175239. }
  175240. return rc;
  175241. }
  175242. /*
  175243. ** If pNode currently points to a match, this function returns SQLITE_OK
  175244. ** without modifying it. Otherwise, pNode is advanced until it does point
  175245. ** to a match or EOF is reached.
  175246. */
  175247. static int fts5ExprNodeTest(
  175248. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  175249. Fts5ExprNode *pNode /* Expression node to test */
  175250. ){
  175251. int rc = SQLITE_OK;
  175252. if( pNode->bEof==0 ){
  175253. switch( pNode->eType ){
  175254. case FTS5_STRING: {
  175255. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  175256. break;
  175257. }
  175258. case FTS5_TERM: {
  175259. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  175260. break;
  175261. }
  175262. case FTS5_AND: {
  175263. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  175264. break;
  175265. }
  175266. case FTS5_OR: {
  175267. fts5ExprNodeTest_OR(pExpr, pNode);
  175268. break;
  175269. }
  175270. default: assert( pNode->eType==FTS5_NOT ); {
  175271. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  175272. break;
  175273. }
  175274. }
  175275. }
  175276. return rc;
  175277. }
  175278. /*
  175279. ** Set node pNode, which is part of expression pExpr, to point to the first
  175280. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  175281. **
  175282. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  175283. ** It is not an error if there are no matches.
  175284. */
  175285. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  175286. int rc = SQLITE_OK;
  175287. pNode->bEof = 0;
  175288. pNode->bNomatch = 0;
  175289. if( Fts5NodeIsString(pNode) ){
  175290. /* Initialize all term iterators in the NEAR object. */
  175291. rc = fts5ExprNearInitAll(pExpr, pNode);
  175292. }else if( pNode->xNext==0 ){
  175293. pNode->bEof = 1;
  175294. }else{
  175295. int i;
  175296. int nEof = 0;
  175297. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  175298. Fts5ExprNode *pChild = pNode->apChild[i];
  175299. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  175300. assert( pChild->bEof==0 || pChild->bEof==1 );
  175301. nEof += pChild->bEof;
  175302. }
  175303. pNode->iRowid = pNode->apChild[0]->iRowid;
  175304. switch( pNode->eType ){
  175305. case FTS5_AND:
  175306. if( nEof>0 ) fts5ExprSetEof(pNode);
  175307. break;
  175308. case FTS5_OR:
  175309. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  175310. break;
  175311. default:
  175312. assert( pNode->eType==FTS5_NOT );
  175313. pNode->bEof = pNode->apChild[0]->bEof;
  175314. break;
  175315. }
  175316. }
  175317. if( rc==SQLITE_OK ){
  175318. rc = fts5ExprNodeTest(pExpr, pNode);
  175319. }
  175320. return rc;
  175321. }
  175322. /*
  175323. ** Begin iterating through the set of documents in index pIdx matched by
  175324. ** the MATCH expression passed as the first argument. If the "bDesc"
  175325. ** parameter is passed a non-zero value, iteration is in descending rowid
  175326. ** order. Or, if it is zero, in ascending order.
  175327. **
  175328. ** If iterating in ascending rowid order (bDesc==0), the first document
  175329. ** visited is that with the smallest rowid that is larger than or equal
  175330. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  175331. ** then the first document visited must have a rowid smaller than or
  175332. ** equal to iFirst.
  175333. **
  175334. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  175335. ** is not considered an error if the query does not match any documents.
  175336. */
  175337. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  175338. Fts5ExprNode *pRoot = p->pRoot;
  175339. int rc; /* Return code */
  175340. p->pIndex = pIdx;
  175341. p->bDesc = bDesc;
  175342. rc = fts5ExprNodeFirst(p, pRoot);
  175343. /* If not at EOF but the current rowid occurs earlier than iFirst in
  175344. ** the iteration order, move to document iFirst or later. */
  175345. if( rc==SQLITE_OK
  175346. && 0==pRoot->bEof
  175347. && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
  175348. ){
  175349. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  175350. }
  175351. /* If the iterator is not at a real match, skip forward until it is. */
  175352. while( pRoot->bNomatch ){
  175353. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  175354. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  175355. }
  175356. return rc;
  175357. }
  175358. /*
  175359. ** Move to the next document
  175360. **
  175361. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  175362. ** is not considered an error if the query does not match any documents.
  175363. */
  175364. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  175365. int rc;
  175366. Fts5ExprNode *pRoot = p->pRoot;
  175367. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  175368. do {
  175369. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  175370. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  175371. }while( pRoot->bNomatch );
  175372. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  175373. pRoot->bEof = 1;
  175374. }
  175375. return rc;
  175376. }
  175377. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  175378. return p->pRoot->bEof;
  175379. }
  175380. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  175381. return p->pRoot->iRowid;
  175382. }
  175383. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  175384. int rc = SQLITE_OK;
  175385. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  175386. return rc;
  175387. }
  175388. /*
  175389. ** Free the phrase object passed as the only argument.
  175390. */
  175391. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  175392. if( pPhrase ){
  175393. int i;
  175394. for(i=0; i<pPhrase->nTerm; i++){
  175395. Fts5ExprTerm *pSyn;
  175396. Fts5ExprTerm *pNext;
  175397. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  175398. sqlite3_free(pTerm->zTerm);
  175399. sqlite3Fts5IterClose(pTerm->pIter);
  175400. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  175401. pNext = pSyn->pSynonym;
  175402. sqlite3Fts5IterClose(pSyn->pIter);
  175403. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  175404. sqlite3_free(pSyn);
  175405. }
  175406. }
  175407. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  175408. sqlite3_free(pPhrase);
  175409. }
  175410. }
  175411. /*
  175412. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  175413. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  175414. ** appended to it and the results returned.
  175415. **
  175416. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  175417. ** NULL returned.
  175418. */
  175419. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  175420. Fts5Parse *pParse, /* Parse context */
  175421. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  175422. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  175423. ){
  175424. const int SZALLOC = 8;
  175425. Fts5ExprNearset *pRet = 0;
  175426. if( pParse->rc==SQLITE_OK ){
  175427. if( pPhrase==0 ){
  175428. return pNear;
  175429. }
  175430. if( pNear==0 ){
  175431. int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  175432. pRet = sqlite3_malloc(nByte);
  175433. if( pRet==0 ){
  175434. pParse->rc = SQLITE_NOMEM;
  175435. }else{
  175436. memset(pRet, 0, nByte);
  175437. }
  175438. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  175439. int nNew = pNear->nPhrase + SZALLOC;
  175440. int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  175441. pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
  175442. if( pRet==0 ){
  175443. pParse->rc = SQLITE_NOMEM;
  175444. }
  175445. }else{
  175446. pRet = pNear;
  175447. }
  175448. }
  175449. if( pRet==0 ){
  175450. assert( pParse->rc!=SQLITE_OK );
  175451. sqlite3Fts5ParseNearsetFree(pNear);
  175452. sqlite3Fts5ParsePhraseFree(pPhrase);
  175453. }else{
  175454. if( pRet->nPhrase>0 ){
  175455. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  175456. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  175457. if( pPhrase->nTerm==0 ){
  175458. fts5ExprPhraseFree(pPhrase);
  175459. pRet->nPhrase--;
  175460. pParse->nPhrase--;
  175461. pPhrase = pLast;
  175462. }else if( pLast->nTerm==0 ){
  175463. fts5ExprPhraseFree(pLast);
  175464. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  175465. pParse->nPhrase--;
  175466. pRet->nPhrase--;
  175467. }
  175468. }
  175469. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  175470. }
  175471. return pRet;
  175472. }
  175473. typedef struct TokenCtx TokenCtx;
  175474. struct TokenCtx {
  175475. Fts5ExprPhrase *pPhrase;
  175476. int rc;
  175477. };
  175478. /*
  175479. ** Callback for tokenizing terms used by ParseTerm().
  175480. */
  175481. static int fts5ParseTokenize(
  175482. void *pContext, /* Pointer to Fts5InsertCtx object */
  175483. int tflags, /* Mask of FTS5_TOKEN_* flags */
  175484. const char *pToken, /* Buffer containing token */
  175485. int nToken, /* Size of token in bytes */
  175486. int iUnused1, /* Start offset of token */
  175487. int iUnused2 /* End offset of token */
  175488. ){
  175489. int rc = SQLITE_OK;
  175490. const int SZALLOC = 8;
  175491. TokenCtx *pCtx = (TokenCtx*)pContext;
  175492. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  175493. UNUSED_PARAM2(iUnused1, iUnused2);
  175494. /* If an error has already occurred, this is a no-op */
  175495. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  175496. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  175497. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  175498. Fts5ExprTerm *pSyn;
  175499. int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  175500. pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
  175501. if( pSyn==0 ){
  175502. rc = SQLITE_NOMEM;
  175503. }else{
  175504. memset(pSyn, 0, nByte);
  175505. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  175506. memcpy(pSyn->zTerm, pToken, nToken);
  175507. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  175508. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  175509. }
  175510. }else{
  175511. Fts5ExprTerm *pTerm;
  175512. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  175513. Fts5ExprPhrase *pNew;
  175514. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  175515. pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
  175516. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  175517. );
  175518. if( pNew==0 ){
  175519. rc = SQLITE_NOMEM;
  175520. }else{
  175521. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  175522. pCtx->pPhrase = pPhrase = pNew;
  175523. pNew->nTerm = nNew - SZALLOC;
  175524. }
  175525. }
  175526. if( rc==SQLITE_OK ){
  175527. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  175528. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  175529. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  175530. }
  175531. }
  175532. pCtx->rc = rc;
  175533. return rc;
  175534. }
  175535. /*
  175536. ** Free the phrase object passed as the only argument.
  175537. */
  175538. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  175539. fts5ExprPhraseFree(pPhrase);
  175540. }
  175541. /*
  175542. ** Free the phrase object passed as the second argument.
  175543. */
  175544. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  175545. if( pNear ){
  175546. int i;
  175547. for(i=0; i<pNear->nPhrase; i++){
  175548. fts5ExprPhraseFree(pNear->apPhrase[i]);
  175549. }
  175550. sqlite3_free(pNear->pColset);
  175551. sqlite3_free(pNear);
  175552. }
  175553. }
  175554. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  175555. assert( pParse->pExpr==0 );
  175556. pParse->pExpr = p;
  175557. }
  175558. /*
  175559. ** This function is called by the parser to process a string token. The
  175560. ** string may or may not be quoted. In any case it is tokenized and a
  175561. ** phrase object consisting of all tokens returned.
  175562. */
  175563. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  175564. Fts5Parse *pParse, /* Parse context */
  175565. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  175566. Fts5Token *pToken, /* String to tokenize */
  175567. int bPrefix /* True if there is a trailing "*" */
  175568. ){
  175569. Fts5Config *pConfig = pParse->pConfig;
  175570. TokenCtx sCtx; /* Context object passed to callback */
  175571. int rc; /* Tokenize return code */
  175572. char *z = 0;
  175573. memset(&sCtx, 0, sizeof(TokenCtx));
  175574. sCtx.pPhrase = pAppend;
  175575. rc = fts5ParseStringFromToken(pToken, &z);
  175576. if( rc==SQLITE_OK ){
  175577. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
  175578. int n;
  175579. sqlite3Fts5Dequote(z);
  175580. n = (int)strlen(z);
  175581. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  175582. }
  175583. sqlite3_free(z);
  175584. if( rc || (rc = sCtx.rc) ){
  175585. pParse->rc = rc;
  175586. fts5ExprPhraseFree(sCtx.pPhrase);
  175587. sCtx.pPhrase = 0;
  175588. }else{
  175589. if( pAppend==0 ){
  175590. if( (pParse->nPhrase % 8)==0 ){
  175591. int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  175592. Fts5ExprPhrase **apNew;
  175593. apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
  175594. if( apNew==0 ){
  175595. pParse->rc = SQLITE_NOMEM;
  175596. fts5ExprPhraseFree(sCtx.pPhrase);
  175597. return 0;
  175598. }
  175599. pParse->apPhrase = apNew;
  175600. }
  175601. pParse->nPhrase++;
  175602. }
  175603. if( sCtx.pPhrase==0 ){
  175604. /* This happens when parsing a token or quoted phrase that contains
  175605. ** no token characters at all. (e.g ... MATCH '""'). */
  175606. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  175607. }else if( sCtx.pPhrase->nTerm ){
  175608. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
  175609. }
  175610. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  175611. }
  175612. return sCtx.pPhrase;
  175613. }
  175614. /*
  175615. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  175616. ** expression passed as the second argument.
  175617. */
  175618. static int sqlite3Fts5ExprClonePhrase(
  175619. Fts5Expr *pExpr,
  175620. int iPhrase,
  175621. Fts5Expr **ppNew
  175622. ){
  175623. int rc = SQLITE_OK; /* Return code */
  175624. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  175625. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  175626. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  175627. pOrig = pExpr->apExprPhrase[iPhrase];
  175628. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  175629. if( rc==SQLITE_OK ){
  175630. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  175631. sizeof(Fts5ExprPhrase*));
  175632. }
  175633. if( rc==SQLITE_OK ){
  175634. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  175635. sizeof(Fts5ExprNode));
  175636. }
  175637. if( rc==SQLITE_OK ){
  175638. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  175639. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  175640. }
  175641. if( rc==SQLITE_OK ){
  175642. Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  175643. if( pColsetOrig ){
  175644. int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  175645. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  175646. if( pColset ){
  175647. memcpy(pColset, pColsetOrig, nByte);
  175648. }
  175649. pNew->pRoot->pNear->pColset = pColset;
  175650. }
  175651. }
  175652. if( pOrig->nTerm ){
  175653. int i; /* Used to iterate through phrase terms */
  175654. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  175655. int tflags = 0;
  175656. Fts5ExprTerm *p;
  175657. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  175658. const char *zTerm = p->zTerm;
  175659. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  175660. 0, 0);
  175661. tflags = FTS5_TOKEN_COLOCATED;
  175662. }
  175663. if( rc==SQLITE_OK ){
  175664. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  175665. }
  175666. }
  175667. }else{
  175668. /* This happens when parsing a token or quoted phrase that contains
  175669. ** no token characters at all. (e.g ... MATCH '""'). */
  175670. sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
  175671. }
  175672. if( rc==SQLITE_OK ){
  175673. /* All the allocations succeeded. Put the expression object together. */
  175674. pNew->pIndex = pExpr->pIndex;
  175675. pNew->pConfig = pExpr->pConfig;
  175676. pNew->nPhrase = 1;
  175677. pNew->apExprPhrase[0] = sCtx.pPhrase;
  175678. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  175679. pNew->pRoot->pNear->nPhrase = 1;
  175680. sCtx.pPhrase->pNode = pNew->pRoot;
  175681. if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
  175682. pNew->pRoot->eType = FTS5_TERM;
  175683. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  175684. }else{
  175685. pNew->pRoot->eType = FTS5_STRING;
  175686. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  175687. }
  175688. }else{
  175689. sqlite3Fts5ExprFree(pNew);
  175690. fts5ExprPhraseFree(sCtx.pPhrase);
  175691. pNew = 0;
  175692. }
  175693. *ppNew = pNew;
  175694. return rc;
  175695. }
  175696. /*
  175697. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  175698. ** is expected. If token pTok does not contain "NEAR", store an error
  175699. ** in the pParse object.
  175700. */
  175701. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  175702. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  175703. sqlite3Fts5ParseError(
  175704. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  175705. );
  175706. }
  175707. }
  175708. static void sqlite3Fts5ParseSetDistance(
  175709. Fts5Parse *pParse,
  175710. Fts5ExprNearset *pNear,
  175711. Fts5Token *p
  175712. ){
  175713. if( pNear ){
  175714. int nNear = 0;
  175715. int i;
  175716. if( p->n ){
  175717. for(i=0; i<p->n; i++){
  175718. char c = (char)p->p[i];
  175719. if( c<'0' || c>'9' ){
  175720. sqlite3Fts5ParseError(
  175721. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  175722. );
  175723. return;
  175724. }
  175725. nNear = nNear * 10 + (p->p[i] - '0');
  175726. }
  175727. }else{
  175728. nNear = FTS5_DEFAULT_NEARDIST;
  175729. }
  175730. pNear->nNear = nNear;
  175731. }
  175732. }
  175733. /*
  175734. ** The second argument passed to this function may be NULL, or it may be
  175735. ** an existing Fts5Colset object. This function returns a pointer to
  175736. ** a new colset object containing the contents of (p) with new value column
  175737. ** number iCol appended.
  175738. **
  175739. ** If an OOM error occurs, store an error code in pParse and return NULL.
  175740. ** The old colset object (if any) is not freed in this case.
  175741. */
  175742. static Fts5Colset *fts5ParseColset(
  175743. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  175744. Fts5Colset *p, /* Existing colset object */
  175745. int iCol /* New column to add to colset object */
  175746. ){
  175747. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  175748. Fts5Colset *pNew; /* New colset object to return */
  175749. assert( pParse->rc==SQLITE_OK );
  175750. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  175751. pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  175752. if( pNew==0 ){
  175753. pParse->rc = SQLITE_NOMEM;
  175754. }else{
  175755. int *aiCol = pNew->aiCol;
  175756. int i, j;
  175757. for(i=0; i<nCol; i++){
  175758. if( aiCol[i]==iCol ) return pNew;
  175759. if( aiCol[i]>iCol ) break;
  175760. }
  175761. for(j=nCol; j>i; j--){
  175762. aiCol[j] = aiCol[j-1];
  175763. }
  175764. aiCol[i] = iCol;
  175765. pNew->nCol = nCol+1;
  175766. #ifndef NDEBUG
  175767. /* Check that the array is in order and contains no duplicate entries. */
  175768. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  175769. #endif
  175770. }
  175771. return pNew;
  175772. }
  175773. /*
  175774. ** Allocate and return an Fts5Colset object specifying the inverse of
  175775. ** the colset passed as the second argument. Free the colset passed
  175776. ** as the second argument before returning.
  175777. */
  175778. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
  175779. Fts5Colset *pRet;
  175780. int nCol = pParse->pConfig->nCol;
  175781. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
  175782. sizeof(Fts5Colset) + sizeof(int)*nCol
  175783. );
  175784. if( pRet ){
  175785. int i;
  175786. int iOld = 0;
  175787. for(i=0; i<nCol; i++){
  175788. if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
  175789. pRet->aiCol[pRet->nCol++] = i;
  175790. }else{
  175791. iOld++;
  175792. }
  175793. }
  175794. }
  175795. sqlite3_free(p);
  175796. return pRet;
  175797. }
  175798. static Fts5Colset *sqlite3Fts5ParseColset(
  175799. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  175800. Fts5Colset *pColset, /* Existing colset object */
  175801. Fts5Token *p
  175802. ){
  175803. Fts5Colset *pRet = 0;
  175804. int iCol;
  175805. char *z; /* Dequoted copy of token p */
  175806. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  175807. if( pParse->rc==SQLITE_OK ){
  175808. Fts5Config *pConfig = pParse->pConfig;
  175809. sqlite3Fts5Dequote(z);
  175810. for(iCol=0; iCol<pConfig->nCol; iCol++){
  175811. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  175812. }
  175813. if( iCol==pConfig->nCol ){
  175814. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  175815. }else{
  175816. pRet = fts5ParseColset(pParse, pColset, iCol);
  175817. }
  175818. sqlite3_free(z);
  175819. }
  175820. if( pRet==0 ){
  175821. assert( pParse->rc!=SQLITE_OK );
  175822. sqlite3_free(pColset);
  175823. }
  175824. return pRet;
  175825. }
  175826. /*
  175827. ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
  175828. ** SQLITE_OK when this function is called, NULL is returned.
  175829. **
  175830. ** Otherwise, a copy of (*pOrig) is made into memory obtained from
  175831. ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
  175832. ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
  175833. */
  175834. static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
  175835. Fts5Colset *pRet;
  175836. if( pOrig ){
  175837. int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
  175838. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
  175839. if( pRet ){
  175840. memcpy(pRet, pOrig, nByte);
  175841. }
  175842. }else{
  175843. pRet = 0;
  175844. }
  175845. return pRet;
  175846. }
  175847. /*
  175848. ** Remove from colset pColset any columns that are not also in colset pMerge.
  175849. */
  175850. static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
  175851. int iIn = 0; /* Next input in pColset */
  175852. int iMerge = 0; /* Next input in pMerge */
  175853. int iOut = 0; /* Next output slot in pColset */
  175854. while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
  175855. int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
  175856. if( iDiff==0 ){
  175857. pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
  175858. iMerge++;
  175859. iIn++;
  175860. }else if( iDiff>0 ){
  175861. iMerge++;
  175862. }else{
  175863. iIn++;
  175864. }
  175865. }
  175866. pColset->nCol = iOut;
  175867. }
  175868. /*
  175869. ** Recursively apply colset pColset to expression node pNode and all of
  175870. ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
  175871. ** of pColset. This function may use the spare copy and set (*ppFree) to
  175872. ** zero, or it may create copies of pColset using fts5CloneColset().
  175873. */
  175874. static void fts5ParseSetColset(
  175875. Fts5Parse *pParse,
  175876. Fts5ExprNode *pNode,
  175877. Fts5Colset *pColset,
  175878. Fts5Colset **ppFree
  175879. ){
  175880. if( pParse->rc==SQLITE_OK ){
  175881. assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
  175882. || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
  175883. || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
  175884. );
  175885. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  175886. Fts5ExprNearset *pNear = pNode->pNear;
  175887. if( pNear->pColset ){
  175888. fts5MergeColset(pNear->pColset, pColset);
  175889. if( pNear->pColset->nCol==0 ){
  175890. pNode->eType = FTS5_EOF;
  175891. pNode->xNext = 0;
  175892. }
  175893. }else if( *ppFree ){
  175894. pNear->pColset = pColset;
  175895. *ppFree = 0;
  175896. }else{
  175897. pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
  175898. }
  175899. }else{
  175900. int i;
  175901. assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
  175902. for(i=0; i<pNode->nChild; i++){
  175903. fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
  175904. }
  175905. }
  175906. }
  175907. }
  175908. /*
  175909. ** Apply colset pColset to expression node pExpr and all of its descendents.
  175910. */
  175911. static void sqlite3Fts5ParseSetColset(
  175912. Fts5Parse *pParse,
  175913. Fts5ExprNode *pExpr,
  175914. Fts5Colset *pColset
  175915. ){
  175916. Fts5Colset *pFree = pColset;
  175917. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  175918. pParse->rc = SQLITE_ERROR;
  175919. pParse->zErr = sqlite3_mprintf(
  175920. "fts5: column queries are not supported (detail=none)"
  175921. );
  175922. }else{
  175923. fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
  175924. }
  175925. sqlite3_free(pFree);
  175926. }
  175927. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  175928. switch( pNode->eType ){
  175929. case FTS5_STRING: {
  175930. Fts5ExprNearset *pNear = pNode->pNear;
  175931. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  175932. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  175933. ){
  175934. pNode->eType = FTS5_TERM;
  175935. pNode->xNext = fts5ExprNodeNext_TERM;
  175936. }else{
  175937. pNode->xNext = fts5ExprNodeNext_STRING;
  175938. }
  175939. break;
  175940. };
  175941. case FTS5_OR: {
  175942. pNode->xNext = fts5ExprNodeNext_OR;
  175943. break;
  175944. };
  175945. case FTS5_AND: {
  175946. pNode->xNext = fts5ExprNodeNext_AND;
  175947. break;
  175948. };
  175949. default: assert( pNode->eType==FTS5_NOT ); {
  175950. pNode->xNext = fts5ExprNodeNext_NOT;
  175951. break;
  175952. };
  175953. }
  175954. }
  175955. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  175956. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  175957. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  175958. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  175959. p->nChild += pSub->nChild;
  175960. sqlite3_free(pSub);
  175961. }else{
  175962. p->apChild[p->nChild++] = pSub;
  175963. }
  175964. }
  175965. /*
  175966. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  175967. ** OOM error), leave an error code in pParse and return NULL.
  175968. */
  175969. static Fts5ExprNode *sqlite3Fts5ParseNode(
  175970. Fts5Parse *pParse, /* Parse context */
  175971. int eType, /* FTS5_STRING, AND, OR or NOT */
  175972. Fts5ExprNode *pLeft, /* Left hand child expression */
  175973. Fts5ExprNode *pRight, /* Right hand child expression */
  175974. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  175975. ){
  175976. Fts5ExprNode *pRet = 0;
  175977. if( pParse->rc==SQLITE_OK ){
  175978. int nChild = 0; /* Number of children of returned node */
  175979. int nByte; /* Bytes of space to allocate for this node */
  175980. assert( (eType!=FTS5_STRING && !pNear)
  175981. || (eType==FTS5_STRING && !pLeft && !pRight)
  175982. );
  175983. if( eType==FTS5_STRING && pNear==0 ) return 0;
  175984. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  175985. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  175986. if( eType==FTS5_NOT ){
  175987. nChild = 2;
  175988. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  175989. nChild = 2;
  175990. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  175991. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  175992. }
  175993. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  175994. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  175995. if( pRet ){
  175996. pRet->eType = eType;
  175997. pRet->pNear = pNear;
  175998. fts5ExprAssignXNext(pRet);
  175999. if( eType==FTS5_STRING ){
  176000. int iPhrase;
  176001. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  176002. pNear->apPhrase[iPhrase]->pNode = pRet;
  176003. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  176004. pRet->xNext = 0;
  176005. pRet->eType = FTS5_EOF;
  176006. }
  176007. }
  176008. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
  176009. && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
  176010. ){
  176011. assert( pParse->rc==SQLITE_OK );
  176012. pParse->rc = SQLITE_ERROR;
  176013. assert( pParse->zErr==0 );
  176014. pParse->zErr = sqlite3_mprintf(
  176015. "fts5: %s queries are not supported (detail!=full)",
  176016. pNear->nPhrase==1 ? "phrase": "NEAR"
  176017. );
  176018. sqlite3_free(pRet);
  176019. pRet = 0;
  176020. }
  176021. }else{
  176022. fts5ExprAddChildren(pRet, pLeft);
  176023. fts5ExprAddChildren(pRet, pRight);
  176024. }
  176025. }
  176026. }
  176027. if( pRet==0 ){
  176028. assert( pParse->rc!=SQLITE_OK );
  176029. sqlite3Fts5ParseNodeFree(pLeft);
  176030. sqlite3Fts5ParseNodeFree(pRight);
  176031. sqlite3Fts5ParseNearsetFree(pNear);
  176032. }
  176033. return pRet;
  176034. }
  176035. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  176036. Fts5Parse *pParse, /* Parse context */
  176037. Fts5ExprNode *pLeft, /* Left hand child expression */
  176038. Fts5ExprNode *pRight /* Right hand child expression */
  176039. ){
  176040. Fts5ExprNode *pRet = 0;
  176041. Fts5ExprNode *pPrev;
  176042. if( pParse->rc ){
  176043. sqlite3Fts5ParseNodeFree(pLeft);
  176044. sqlite3Fts5ParseNodeFree(pRight);
  176045. }else{
  176046. assert( pLeft->eType==FTS5_STRING
  176047. || pLeft->eType==FTS5_TERM
  176048. || pLeft->eType==FTS5_EOF
  176049. || pLeft->eType==FTS5_AND
  176050. );
  176051. assert( pRight->eType==FTS5_STRING
  176052. || pRight->eType==FTS5_TERM
  176053. || pRight->eType==FTS5_EOF
  176054. );
  176055. if( pLeft->eType==FTS5_AND ){
  176056. pPrev = pLeft->apChild[pLeft->nChild-1];
  176057. }else{
  176058. pPrev = pLeft;
  176059. }
  176060. assert( pPrev->eType==FTS5_STRING
  176061. || pPrev->eType==FTS5_TERM
  176062. || pPrev->eType==FTS5_EOF
  176063. );
  176064. if( pRight->eType==FTS5_EOF ){
  176065. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  176066. sqlite3Fts5ParseNodeFree(pRight);
  176067. pRet = pLeft;
  176068. pParse->nPhrase--;
  176069. }
  176070. else if( pPrev->eType==FTS5_EOF ){
  176071. Fts5ExprPhrase **ap;
  176072. if( pPrev==pLeft ){
  176073. pRet = pRight;
  176074. }else{
  176075. pLeft->apChild[pLeft->nChild-1] = pRight;
  176076. pRet = pLeft;
  176077. }
  176078. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  176079. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  176080. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  176081. pParse->nPhrase--;
  176082. sqlite3Fts5ParseNodeFree(pPrev);
  176083. }
  176084. else{
  176085. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  176086. }
  176087. }
  176088. return pRet;
  176089. }
  176090. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  176091. int nByte = 0;
  176092. Fts5ExprTerm *p;
  176093. char *zQuoted;
  176094. /* Determine the maximum amount of space required. */
  176095. for(p=pTerm; p; p=p->pSynonym){
  176096. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  176097. }
  176098. zQuoted = sqlite3_malloc(nByte);
  176099. if( zQuoted ){
  176100. int i = 0;
  176101. for(p=pTerm; p; p=p->pSynonym){
  176102. char *zIn = p->zTerm;
  176103. zQuoted[i++] = '"';
  176104. while( *zIn ){
  176105. if( *zIn=='"' ) zQuoted[i++] = '"';
  176106. zQuoted[i++] = *zIn++;
  176107. }
  176108. zQuoted[i++] = '"';
  176109. if( p->pSynonym ) zQuoted[i++] = '|';
  176110. }
  176111. if( pTerm->bPrefix ){
  176112. zQuoted[i++] = ' ';
  176113. zQuoted[i++] = '*';
  176114. }
  176115. zQuoted[i++] = '\0';
  176116. }
  176117. return zQuoted;
  176118. }
  176119. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  176120. char *zNew;
  176121. va_list ap;
  176122. va_start(ap, zFmt);
  176123. zNew = sqlite3_vmprintf(zFmt, ap);
  176124. va_end(ap);
  176125. if( zApp && zNew ){
  176126. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  176127. sqlite3_free(zNew);
  176128. zNew = zNew2;
  176129. }
  176130. sqlite3_free(zApp);
  176131. return zNew;
  176132. }
  176133. /*
  176134. ** Compose a tcl-readable representation of expression pExpr. Return a
  176135. ** pointer to a buffer containing that representation. It is the
  176136. ** responsibility of the caller to at some point free the buffer using
  176137. ** sqlite3_free().
  176138. */
  176139. static char *fts5ExprPrintTcl(
  176140. Fts5Config *pConfig,
  176141. const char *zNearsetCmd,
  176142. Fts5ExprNode *pExpr
  176143. ){
  176144. char *zRet = 0;
  176145. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  176146. Fts5ExprNearset *pNear = pExpr->pNear;
  176147. int i;
  176148. int iTerm;
  176149. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  176150. if( zRet==0 ) return 0;
  176151. if( pNear->pColset ){
  176152. int *aiCol = pNear->pColset->aiCol;
  176153. int nCol = pNear->pColset->nCol;
  176154. if( nCol==1 ){
  176155. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  176156. }else{
  176157. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  176158. for(i=1; i<pNear->pColset->nCol; i++){
  176159. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  176160. }
  176161. zRet = fts5PrintfAppend(zRet, "} ");
  176162. }
  176163. if( zRet==0 ) return 0;
  176164. }
  176165. if( pNear->nPhrase>1 ){
  176166. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  176167. if( zRet==0 ) return 0;
  176168. }
  176169. zRet = fts5PrintfAppend(zRet, "--");
  176170. if( zRet==0 ) return 0;
  176171. for(i=0; i<pNear->nPhrase; i++){
  176172. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  176173. zRet = fts5PrintfAppend(zRet, " {");
  176174. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  176175. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  176176. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  176177. if( pPhrase->aTerm[iTerm].bPrefix ){
  176178. zRet = fts5PrintfAppend(zRet, "*");
  176179. }
  176180. }
  176181. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  176182. if( zRet==0 ) return 0;
  176183. }
  176184. }else{
  176185. char const *zOp = 0;
  176186. int i;
  176187. switch( pExpr->eType ){
  176188. case FTS5_AND: zOp = "AND"; break;
  176189. case FTS5_NOT: zOp = "NOT"; break;
  176190. default:
  176191. assert( pExpr->eType==FTS5_OR );
  176192. zOp = "OR";
  176193. break;
  176194. }
  176195. zRet = sqlite3_mprintf("%s", zOp);
  176196. for(i=0; zRet && i<pExpr->nChild; i++){
  176197. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  176198. if( !z ){
  176199. sqlite3_free(zRet);
  176200. zRet = 0;
  176201. }else{
  176202. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  176203. }
  176204. }
  176205. }
  176206. return zRet;
  176207. }
  176208. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  176209. char *zRet = 0;
  176210. if( pExpr->eType==0 ){
  176211. return sqlite3_mprintf("\"\"");
  176212. }else
  176213. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  176214. Fts5ExprNearset *pNear = pExpr->pNear;
  176215. int i;
  176216. int iTerm;
  176217. if( pNear->pColset ){
  176218. int iCol = pNear->pColset->aiCol[0];
  176219. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  176220. if( zRet==0 ) return 0;
  176221. }
  176222. if( pNear->nPhrase>1 ){
  176223. zRet = fts5PrintfAppend(zRet, "NEAR(");
  176224. if( zRet==0 ) return 0;
  176225. }
  176226. for(i=0; i<pNear->nPhrase; i++){
  176227. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  176228. if( i!=0 ){
  176229. zRet = fts5PrintfAppend(zRet, " ");
  176230. if( zRet==0 ) return 0;
  176231. }
  176232. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  176233. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  176234. if( zTerm ){
  176235. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  176236. sqlite3_free(zTerm);
  176237. }
  176238. if( zTerm==0 || zRet==0 ){
  176239. sqlite3_free(zRet);
  176240. return 0;
  176241. }
  176242. }
  176243. }
  176244. if( pNear->nPhrase>1 ){
  176245. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  176246. if( zRet==0 ) return 0;
  176247. }
  176248. }else{
  176249. char const *zOp = 0;
  176250. int i;
  176251. switch( pExpr->eType ){
  176252. case FTS5_AND: zOp = " AND "; break;
  176253. case FTS5_NOT: zOp = " NOT "; break;
  176254. default:
  176255. assert( pExpr->eType==FTS5_OR );
  176256. zOp = " OR ";
  176257. break;
  176258. }
  176259. for(i=0; i<pExpr->nChild; i++){
  176260. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  176261. if( z==0 ){
  176262. sqlite3_free(zRet);
  176263. zRet = 0;
  176264. }else{
  176265. int e = pExpr->apChild[i]->eType;
  176266. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  176267. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  176268. (i==0 ? "" : zOp),
  176269. (b?"(":""), z, (b?")":"")
  176270. );
  176271. }
  176272. if( zRet==0 ) break;
  176273. }
  176274. }
  176275. return zRet;
  176276. }
  176277. /*
  176278. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  176279. ** and fts5_expr_tcl() (bTcl!=0).
  176280. */
  176281. static void fts5ExprFunction(
  176282. sqlite3_context *pCtx, /* Function call context */
  176283. int nArg, /* Number of args */
  176284. sqlite3_value **apVal, /* Function arguments */
  176285. int bTcl
  176286. ){
  176287. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  176288. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  176289. const char *zExpr = 0;
  176290. char *zErr = 0;
  176291. Fts5Expr *pExpr = 0;
  176292. int rc;
  176293. int i;
  176294. const char **azConfig; /* Array of arguments for Fts5Config */
  176295. const char *zNearsetCmd = "nearset";
  176296. int nConfig; /* Size of azConfig[] */
  176297. Fts5Config *pConfig = 0;
  176298. int iArg = 1;
  176299. if( nArg<1 ){
  176300. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  176301. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  176302. );
  176303. sqlite3_result_error(pCtx, zErr, -1);
  176304. sqlite3_free(zErr);
  176305. return;
  176306. }
  176307. if( bTcl && nArg>1 ){
  176308. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  176309. iArg = 2;
  176310. }
  176311. nConfig = 3 + (nArg-iArg);
  176312. azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
  176313. if( azConfig==0 ){
  176314. sqlite3_result_error_nomem(pCtx);
  176315. return;
  176316. }
  176317. azConfig[0] = 0;
  176318. azConfig[1] = "main";
  176319. azConfig[2] = "tbl";
  176320. for(i=3; iArg<nArg; iArg++){
  176321. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  176322. }
  176323. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  176324. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  176325. if( rc==SQLITE_OK ){
  176326. rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
  176327. }
  176328. if( rc==SQLITE_OK ){
  176329. char *zText;
  176330. if( pExpr->pRoot->xNext==0 ){
  176331. zText = sqlite3_mprintf("");
  176332. }else if( bTcl ){
  176333. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  176334. }else{
  176335. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  176336. }
  176337. if( zText==0 ){
  176338. rc = SQLITE_NOMEM;
  176339. }else{
  176340. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  176341. sqlite3_free(zText);
  176342. }
  176343. }
  176344. if( rc!=SQLITE_OK ){
  176345. if( zErr ){
  176346. sqlite3_result_error(pCtx, zErr, -1);
  176347. sqlite3_free(zErr);
  176348. }else{
  176349. sqlite3_result_error_code(pCtx, rc);
  176350. }
  176351. }
  176352. sqlite3_free((void *)azConfig);
  176353. sqlite3Fts5ConfigFree(pConfig);
  176354. sqlite3Fts5ExprFree(pExpr);
  176355. }
  176356. static void fts5ExprFunctionHr(
  176357. sqlite3_context *pCtx, /* Function call context */
  176358. int nArg, /* Number of args */
  176359. sqlite3_value **apVal /* Function arguments */
  176360. ){
  176361. fts5ExprFunction(pCtx, nArg, apVal, 0);
  176362. }
  176363. static void fts5ExprFunctionTcl(
  176364. sqlite3_context *pCtx, /* Function call context */
  176365. int nArg, /* Number of args */
  176366. sqlite3_value **apVal /* Function arguments */
  176367. ){
  176368. fts5ExprFunction(pCtx, nArg, apVal, 1);
  176369. }
  176370. /*
  176371. ** The implementation of an SQLite user-defined-function that accepts a
  176372. ** single integer as an argument. If the integer is an alpha-numeric
  176373. ** unicode code point, 1 is returned. Otherwise 0.
  176374. */
  176375. static void fts5ExprIsAlnum(
  176376. sqlite3_context *pCtx, /* Function call context */
  176377. int nArg, /* Number of args */
  176378. sqlite3_value **apVal /* Function arguments */
  176379. ){
  176380. int iCode;
  176381. if( nArg!=1 ){
  176382. sqlite3_result_error(pCtx,
  176383. "wrong number of arguments to function fts5_isalnum", -1
  176384. );
  176385. return;
  176386. }
  176387. iCode = sqlite3_value_int(apVal[0]);
  176388. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
  176389. }
  176390. static void fts5ExprFold(
  176391. sqlite3_context *pCtx, /* Function call context */
  176392. int nArg, /* Number of args */
  176393. sqlite3_value **apVal /* Function arguments */
  176394. ){
  176395. if( nArg!=1 && nArg!=2 ){
  176396. sqlite3_result_error(pCtx,
  176397. "wrong number of arguments to function fts5_fold", -1
  176398. );
  176399. }else{
  176400. int iCode;
  176401. int bRemoveDiacritics = 0;
  176402. iCode = sqlite3_value_int(apVal[0]);
  176403. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  176404. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  176405. }
  176406. }
  176407. /*
  176408. ** This is called during initialization to register the fts5_expr() scalar
  176409. ** UDF with the SQLite handle passed as the only argument.
  176410. */
  176411. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  176412. struct Fts5ExprFunc {
  176413. const char *z;
  176414. void (*x)(sqlite3_context*,int,sqlite3_value**);
  176415. } aFunc[] = {
  176416. { "fts5_expr", fts5ExprFunctionHr },
  176417. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  176418. { "fts5_isalnum", fts5ExprIsAlnum },
  176419. { "fts5_fold", fts5ExprFold },
  176420. };
  176421. int i;
  176422. int rc = SQLITE_OK;
  176423. void *pCtx = (void*)pGlobal;
  176424. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  176425. struct Fts5ExprFunc *p = &aFunc[i];
  176426. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  176427. }
  176428. /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
  176429. #ifndef NDEBUG
  176430. (void)sqlite3Fts5ParserTrace;
  176431. #endif
  176432. return rc;
  176433. }
  176434. /*
  176435. ** Return the number of phrases in expression pExpr.
  176436. */
  176437. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  176438. return (pExpr ? pExpr->nPhrase : 0);
  176439. }
  176440. /*
  176441. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  176442. */
  176443. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  176444. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  176445. return pExpr->apExprPhrase[iPhrase]->nTerm;
  176446. }
  176447. /*
  176448. ** This function is used to access the current position list for phrase
  176449. ** iPhrase.
  176450. */
  176451. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  176452. int nRet;
  176453. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  176454. Fts5ExprNode *pNode = pPhrase->pNode;
  176455. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  176456. *pa = pPhrase->poslist.p;
  176457. nRet = pPhrase->poslist.n;
  176458. }else{
  176459. *pa = 0;
  176460. nRet = 0;
  176461. }
  176462. return nRet;
  176463. }
  176464. struct Fts5PoslistPopulator {
  176465. Fts5PoslistWriter writer;
  176466. int bOk; /* True if ok to populate */
  176467. int bMiss;
  176468. };
  176469. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  176470. Fts5PoslistPopulator *pRet;
  176471. pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  176472. if( pRet ){
  176473. int i;
  176474. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  176475. for(i=0; i<pExpr->nPhrase; i++){
  176476. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  176477. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  176478. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  176479. if( bLive &&
  176480. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  176481. ){
  176482. pRet[i].bMiss = 1;
  176483. }else{
  176484. pBuf->n = 0;
  176485. }
  176486. }
  176487. }
  176488. return pRet;
  176489. }
  176490. struct Fts5ExprCtx {
  176491. Fts5Expr *pExpr;
  176492. Fts5PoslistPopulator *aPopulator;
  176493. i64 iOff;
  176494. };
  176495. typedef struct Fts5ExprCtx Fts5ExprCtx;
  176496. /*
  176497. ** TODO: Make this more efficient!
  176498. */
  176499. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  176500. int i;
  176501. for(i=0; i<pColset->nCol; i++){
  176502. if( pColset->aiCol[i]==iCol ) return 1;
  176503. }
  176504. return 0;
  176505. }
  176506. static int fts5ExprPopulatePoslistsCb(
  176507. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  176508. int tflags, /* Mask of FTS5_TOKEN_* flags */
  176509. const char *pToken, /* Pointer to buffer containing token */
  176510. int nToken, /* Size of token in bytes */
  176511. int iUnused1, /* Byte offset of token within input text */
  176512. int iUnused2 /* Byte offset of end of token within input text */
  176513. ){
  176514. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  176515. Fts5Expr *pExpr = p->pExpr;
  176516. int i;
  176517. UNUSED_PARAM2(iUnused1, iUnused2);
  176518. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  176519. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  176520. for(i=0; i<pExpr->nPhrase; i++){
  176521. Fts5ExprTerm *pTerm;
  176522. if( p->aPopulator[i].bOk==0 ) continue;
  176523. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  176524. int nTerm = (int)strlen(pTerm->zTerm);
  176525. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  176526. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  176527. ){
  176528. int rc = sqlite3Fts5PoslistWriterAppend(
  176529. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  176530. );
  176531. if( rc ) return rc;
  176532. break;
  176533. }
  176534. }
  176535. }
  176536. return SQLITE_OK;
  176537. }
  176538. static int sqlite3Fts5ExprPopulatePoslists(
  176539. Fts5Config *pConfig,
  176540. Fts5Expr *pExpr,
  176541. Fts5PoslistPopulator *aPopulator,
  176542. int iCol,
  176543. const char *z, int n
  176544. ){
  176545. int i;
  176546. Fts5ExprCtx sCtx;
  176547. sCtx.pExpr = pExpr;
  176548. sCtx.aPopulator = aPopulator;
  176549. sCtx.iOff = (((i64)iCol) << 32) - 1;
  176550. for(i=0; i<pExpr->nPhrase; i++){
  176551. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  176552. Fts5Colset *pColset = pNode->pNear->pColset;
  176553. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  176554. || aPopulator[i].bMiss
  176555. ){
  176556. aPopulator[i].bOk = 0;
  176557. }else{
  176558. aPopulator[i].bOk = 1;
  176559. }
  176560. }
  176561. return sqlite3Fts5Tokenize(pConfig,
  176562. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  176563. );
  176564. }
  176565. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  176566. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  176567. pNode->pNear->apPhrase[0]->poslist.n = 0;
  176568. }else{
  176569. int i;
  176570. for(i=0; i<pNode->nChild; i++){
  176571. fts5ExprClearPoslists(pNode->apChild[i]);
  176572. }
  176573. }
  176574. }
  176575. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  176576. pNode->iRowid = iRowid;
  176577. pNode->bEof = 0;
  176578. switch( pNode->eType ){
  176579. case FTS5_TERM:
  176580. case FTS5_STRING:
  176581. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  176582. case FTS5_AND: {
  176583. int i;
  176584. for(i=0; i<pNode->nChild; i++){
  176585. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  176586. fts5ExprClearPoslists(pNode);
  176587. return 0;
  176588. }
  176589. }
  176590. break;
  176591. }
  176592. case FTS5_OR: {
  176593. int i;
  176594. int bRet = 0;
  176595. for(i=0; i<pNode->nChild; i++){
  176596. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  176597. bRet = 1;
  176598. }
  176599. }
  176600. return bRet;
  176601. }
  176602. default: {
  176603. assert( pNode->eType==FTS5_NOT );
  176604. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  176605. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  176606. ){
  176607. fts5ExprClearPoslists(pNode);
  176608. return 0;
  176609. }
  176610. break;
  176611. }
  176612. }
  176613. return 1;
  176614. }
  176615. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  176616. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  176617. }
  176618. /*
  176619. ** This function is only called for detail=columns tables.
  176620. */
  176621. static int sqlite3Fts5ExprPhraseCollist(
  176622. Fts5Expr *pExpr,
  176623. int iPhrase,
  176624. const u8 **ppCollist,
  176625. int *pnCollist
  176626. ){
  176627. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  176628. Fts5ExprNode *pNode = pPhrase->pNode;
  176629. int rc = SQLITE_OK;
  176630. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  176631. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  176632. if( pNode->bEof==0
  176633. && pNode->iRowid==pExpr->pRoot->iRowid
  176634. && pPhrase->poslist.n>0
  176635. ){
  176636. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  176637. if( pTerm->pSynonym ){
  176638. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  176639. rc = fts5ExprSynonymList(
  176640. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  176641. );
  176642. }else{
  176643. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  176644. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  176645. }
  176646. }else{
  176647. *ppCollist = 0;
  176648. *pnCollist = 0;
  176649. }
  176650. return rc;
  176651. }
  176652. /*
  176653. ** 2014 August 11
  176654. **
  176655. ** The author disclaims copyright to this source code. In place of
  176656. ** a legal notice, here is a blessing:
  176657. **
  176658. ** May you do good and not evil.
  176659. ** May you find forgiveness for yourself and forgive others.
  176660. ** May you share freely, never taking more than you give.
  176661. **
  176662. ******************************************************************************
  176663. **
  176664. */
  176665. /* #include "fts5Int.h" */
  176666. typedef struct Fts5HashEntry Fts5HashEntry;
  176667. /*
  176668. ** This file contains the implementation of an in-memory hash table used
  176669. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  176670. ** segment.
  176671. */
  176672. struct Fts5Hash {
  176673. int eDetail; /* Copy of Fts5Config.eDetail */
  176674. int *pnByte; /* Pointer to bytes counter */
  176675. int nEntry; /* Number of entries currently in hash */
  176676. int nSlot; /* Size of aSlot[] array */
  176677. Fts5HashEntry *pScan; /* Current ordered scan item */
  176678. Fts5HashEntry **aSlot; /* Array of hash slots */
  176679. };
  176680. /*
  176681. ** Each entry in the hash table is represented by an object of the
  176682. ** following type. Each object, its key (a nul-terminated string) and
  176683. ** its current data are stored in a single memory allocation. The
  176684. ** key immediately follows the object in memory. The position list
  176685. ** data immediately follows the key data in memory.
  176686. **
  176687. ** The data that follows the key is in a similar, but not identical format
  176688. ** to the doclist data stored in the database. It is:
  176689. **
  176690. ** * Rowid, as a varint
  176691. ** * Position list, without 0x00 terminator.
  176692. ** * Size of previous position list and rowid, as a 4 byte
  176693. ** big-endian integer.
  176694. **
  176695. ** iRowidOff:
  176696. ** Offset of last rowid written to data area. Relative to first byte of
  176697. ** structure.
  176698. **
  176699. ** nData:
  176700. ** Bytes of data written since iRowidOff.
  176701. */
  176702. struct Fts5HashEntry {
  176703. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  176704. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  176705. int nAlloc; /* Total size of allocation */
  176706. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  176707. int nData; /* Total bytes of data (incl. structure) */
  176708. int nKey; /* Length of key in bytes */
  176709. u8 bDel; /* Set delete-flag @ iSzPoslist */
  176710. u8 bContent; /* Set content-flag (detail=none mode) */
  176711. i16 iCol; /* Column of last value written */
  176712. int iPos; /* Position of last value written */
  176713. i64 iRowid; /* Rowid of last value written */
  176714. };
  176715. /*
  176716. ** Eqivalent to:
  176717. **
  176718. ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
  176719. */
  176720. #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
  176721. /*
  176722. ** Allocate a new hash table.
  176723. */
  176724. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  176725. int rc = SQLITE_OK;
  176726. Fts5Hash *pNew;
  176727. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  176728. if( pNew==0 ){
  176729. rc = SQLITE_NOMEM;
  176730. }else{
  176731. int nByte;
  176732. memset(pNew, 0, sizeof(Fts5Hash));
  176733. pNew->pnByte = pnByte;
  176734. pNew->eDetail = pConfig->eDetail;
  176735. pNew->nSlot = 1024;
  176736. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  176737. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
  176738. if( pNew->aSlot==0 ){
  176739. sqlite3_free(pNew);
  176740. *ppNew = 0;
  176741. rc = SQLITE_NOMEM;
  176742. }else{
  176743. memset(pNew->aSlot, 0, nByte);
  176744. }
  176745. }
  176746. return rc;
  176747. }
  176748. /*
  176749. ** Free a hash table object.
  176750. */
  176751. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  176752. if( pHash ){
  176753. sqlite3Fts5HashClear(pHash);
  176754. sqlite3_free(pHash->aSlot);
  176755. sqlite3_free(pHash);
  176756. }
  176757. }
  176758. /*
  176759. ** Empty (but do not delete) a hash table.
  176760. */
  176761. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  176762. int i;
  176763. for(i=0; i<pHash->nSlot; i++){
  176764. Fts5HashEntry *pNext;
  176765. Fts5HashEntry *pSlot;
  176766. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  176767. pNext = pSlot->pHashNext;
  176768. sqlite3_free(pSlot);
  176769. }
  176770. }
  176771. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  176772. pHash->nEntry = 0;
  176773. }
  176774. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  176775. int i;
  176776. unsigned int h = 13;
  176777. for(i=n-1; i>=0; i--){
  176778. h = (h << 3) ^ h ^ p[i];
  176779. }
  176780. return (h % nSlot);
  176781. }
  176782. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  176783. int i;
  176784. unsigned int h = 13;
  176785. for(i=n-1; i>=0; i--){
  176786. h = (h << 3) ^ h ^ p[i];
  176787. }
  176788. h = (h << 3) ^ h ^ b;
  176789. return (h % nSlot);
  176790. }
  176791. /*
  176792. ** Resize the hash table by doubling the number of slots.
  176793. */
  176794. static int fts5HashResize(Fts5Hash *pHash){
  176795. int nNew = pHash->nSlot*2;
  176796. int i;
  176797. Fts5HashEntry **apNew;
  176798. Fts5HashEntry **apOld = pHash->aSlot;
  176799. apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
  176800. if( !apNew ) return SQLITE_NOMEM;
  176801. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  176802. for(i=0; i<pHash->nSlot; i++){
  176803. while( apOld[i] ){
  176804. int iHash;
  176805. Fts5HashEntry *p = apOld[i];
  176806. apOld[i] = p->pHashNext;
  176807. iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p), strlen(fts5EntryKey(p)));
  176808. p->pHashNext = apNew[iHash];
  176809. apNew[iHash] = p;
  176810. }
  176811. }
  176812. sqlite3_free(apOld);
  176813. pHash->nSlot = nNew;
  176814. pHash->aSlot = apNew;
  176815. return SQLITE_OK;
  176816. }
  176817. static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
  176818. if( p->iSzPoslist ){
  176819. u8 *pPtr = (u8*)p;
  176820. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  176821. assert( p->nData==p->iSzPoslist );
  176822. if( p->bDel ){
  176823. pPtr[p->nData++] = 0x00;
  176824. if( p->bContent ){
  176825. pPtr[p->nData++] = 0x00;
  176826. }
  176827. }
  176828. }else{
  176829. int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
  176830. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  176831. assert( p->bDel==0 || p->bDel==1 );
  176832. if( nPos<=127 ){
  176833. pPtr[p->iSzPoslist] = (u8)nPos;
  176834. }else{
  176835. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  176836. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  176837. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  176838. p->nData += (nByte-1);
  176839. }
  176840. }
  176841. p->iSzPoslist = 0;
  176842. p->bDel = 0;
  176843. p->bContent = 0;
  176844. }
  176845. }
  176846. /*
  176847. ** Add an entry to the in-memory hash table. The key is the concatenation
  176848. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  176849. **
  176850. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  176851. **
  176852. ** Or, if iCol is negative, then the value is a delete marker.
  176853. */
  176854. static int sqlite3Fts5HashWrite(
  176855. Fts5Hash *pHash,
  176856. i64 iRowid, /* Rowid for this entry */
  176857. int iCol, /* Column token appears in (-ve -> delete) */
  176858. int iPos, /* Position of token within column */
  176859. char bByte, /* First byte of token */
  176860. const char *pToken, int nToken /* Token to add or remove to or from index */
  176861. ){
  176862. unsigned int iHash;
  176863. Fts5HashEntry *p;
  176864. u8 *pPtr;
  176865. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  176866. int bNew; /* If non-delete entry should be written */
  176867. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  176868. /* Attempt to locate an existing hash entry */
  176869. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  176870. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  176871. char *zKey = fts5EntryKey(p);
  176872. if( zKey[0]==bByte
  176873. && p->nKey==nToken
  176874. && memcmp(&zKey[1], pToken, nToken)==0
  176875. ){
  176876. break;
  176877. }
  176878. }
  176879. /* If an existing hash entry cannot be found, create a new one. */
  176880. if( p==0 ){
  176881. /* Figure out how much space to allocate */
  176882. char *zKey;
  176883. int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
  176884. if( nByte<128 ) nByte = 128;
  176885. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  176886. if( (pHash->nEntry*2)>=pHash->nSlot ){
  176887. int rc = fts5HashResize(pHash);
  176888. if( rc!=SQLITE_OK ) return rc;
  176889. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  176890. }
  176891. /* Allocate new Fts5HashEntry and add it to the hash table. */
  176892. p = (Fts5HashEntry*)sqlite3_malloc(nByte);
  176893. if( !p ) return SQLITE_NOMEM;
  176894. memset(p, 0, sizeof(Fts5HashEntry));
  176895. p->nAlloc = nByte;
  176896. zKey = fts5EntryKey(p);
  176897. zKey[0] = bByte;
  176898. memcpy(&zKey[1], pToken, nToken);
  176899. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
  176900. p->nKey = nToken;
  176901. zKey[nToken+1] = '\0';
  176902. p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
  176903. p->pHashNext = pHash->aSlot[iHash];
  176904. pHash->aSlot[iHash] = p;
  176905. pHash->nEntry++;
  176906. /* Add the first rowid field to the hash-entry */
  176907. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  176908. p->iRowid = iRowid;
  176909. p->iSzPoslist = p->nData;
  176910. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  176911. p->nData += 1;
  176912. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  176913. }
  176914. nIncr += p->nData;
  176915. }else{
  176916. /* Appending to an existing hash-entry. Check that there is enough
  176917. ** space to append the largest possible new entry. Worst case scenario
  176918. ** is:
  176919. **
  176920. ** + 9 bytes for a new rowid,
  176921. ** + 4 byte reserved for the "poslist size" varint.
  176922. ** + 1 byte for a "new column" byte,
  176923. ** + 3 bytes for a new column number (16-bit max) as a varint,
  176924. ** + 5 bytes for the new position offset (32-bit max).
  176925. */
  176926. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  176927. int nNew = p->nAlloc * 2;
  176928. Fts5HashEntry *pNew;
  176929. Fts5HashEntry **pp;
  176930. pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
  176931. if( pNew==0 ) return SQLITE_NOMEM;
  176932. pNew->nAlloc = nNew;
  176933. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  176934. *pp = pNew;
  176935. p = pNew;
  176936. }
  176937. nIncr -= p->nData;
  176938. }
  176939. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  176940. pPtr = (u8*)p;
  176941. /* If this is a new rowid, append the 4-byte size field for the previous
  176942. ** entry, and the new rowid for this entry. */
  176943. if( iRowid!=p->iRowid ){
  176944. fts5HashAddPoslistSize(pHash, p);
  176945. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  176946. p->iRowid = iRowid;
  176947. bNew = 1;
  176948. p->iSzPoslist = p->nData;
  176949. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  176950. p->nData += 1;
  176951. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  176952. p->iPos = 0;
  176953. }
  176954. }
  176955. if( iCol>=0 ){
  176956. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  176957. p->bContent = 1;
  176958. }else{
  176959. /* Append a new column value, if necessary */
  176960. assert( iCol>=p->iCol );
  176961. if( iCol!=p->iCol ){
  176962. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  176963. pPtr[p->nData++] = 0x01;
  176964. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  176965. p->iCol = (i16)iCol;
  176966. p->iPos = 0;
  176967. }else{
  176968. bNew = 1;
  176969. p->iCol = (i16)(iPos = iCol);
  176970. }
  176971. }
  176972. /* Append the new position offset, if necessary */
  176973. if( bNew ){
  176974. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  176975. p->iPos = iPos;
  176976. }
  176977. }
  176978. }else{
  176979. /* This is a delete. Set the delete flag. */
  176980. p->bDel = 1;
  176981. }
  176982. nIncr += p->nData;
  176983. *pHash->pnByte += nIncr;
  176984. return SQLITE_OK;
  176985. }
  176986. /*
  176987. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  176988. ** each sorted in key order. This function merges the two lists into a
  176989. ** single list and returns a pointer to its first element.
  176990. */
  176991. static Fts5HashEntry *fts5HashEntryMerge(
  176992. Fts5HashEntry *pLeft,
  176993. Fts5HashEntry *pRight
  176994. ){
  176995. Fts5HashEntry *p1 = pLeft;
  176996. Fts5HashEntry *p2 = pRight;
  176997. Fts5HashEntry *pRet = 0;
  176998. Fts5HashEntry **ppOut = &pRet;
  176999. while( p1 || p2 ){
  177000. if( p1==0 ){
  177001. *ppOut = p2;
  177002. p2 = 0;
  177003. }else if( p2==0 ){
  177004. *ppOut = p1;
  177005. p1 = 0;
  177006. }else{
  177007. int i = 0;
  177008. char *zKey1 = fts5EntryKey(p1);
  177009. char *zKey2 = fts5EntryKey(p2);
  177010. while( zKey1[i]==zKey2[i] ) i++;
  177011. if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
  177012. /* p2 is smaller */
  177013. *ppOut = p2;
  177014. ppOut = &p2->pScanNext;
  177015. p2 = p2->pScanNext;
  177016. }else{
  177017. /* p1 is smaller */
  177018. *ppOut = p1;
  177019. ppOut = &p1->pScanNext;
  177020. p1 = p1->pScanNext;
  177021. }
  177022. *ppOut = 0;
  177023. }
  177024. }
  177025. return pRet;
  177026. }
  177027. /*
  177028. ** Extract all tokens from hash table iHash and link them into a list
  177029. ** in sorted order. The hash table is cleared before returning. It is
  177030. ** the responsibility of the caller to free the elements of the returned
  177031. ** list.
  177032. */
  177033. static int fts5HashEntrySort(
  177034. Fts5Hash *pHash,
  177035. const char *pTerm, int nTerm, /* Query prefix, if any */
  177036. Fts5HashEntry **ppSorted
  177037. ){
  177038. const int nMergeSlot = 32;
  177039. Fts5HashEntry **ap;
  177040. Fts5HashEntry *pList;
  177041. int iSlot;
  177042. int i;
  177043. *ppSorted = 0;
  177044. ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  177045. if( !ap ) return SQLITE_NOMEM;
  177046. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  177047. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  177048. Fts5HashEntry *pIter;
  177049. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  177050. if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
  177051. Fts5HashEntry *pEntry = pIter;
  177052. pEntry->pScanNext = 0;
  177053. for(i=0; ap[i]; i++){
  177054. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  177055. ap[i] = 0;
  177056. }
  177057. ap[i] = pEntry;
  177058. }
  177059. }
  177060. }
  177061. pList = 0;
  177062. for(i=0; i<nMergeSlot; i++){
  177063. pList = fts5HashEntryMerge(pList, ap[i]);
  177064. }
  177065. pHash->nEntry = 0;
  177066. sqlite3_free(ap);
  177067. *ppSorted = pList;
  177068. return SQLITE_OK;
  177069. }
  177070. /*
  177071. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  177072. */
  177073. static int sqlite3Fts5HashQuery(
  177074. Fts5Hash *pHash, /* Hash table to query */
  177075. const char *pTerm, int nTerm, /* Query term */
  177076. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  177077. int *pnDoclist /* OUT: Size of doclist in bytes */
  177078. ){
  177079. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  177080. char *zKey;
  177081. Fts5HashEntry *p;
  177082. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  177083. zKey = fts5EntryKey(p);
  177084. if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
  177085. }
  177086. if( p ){
  177087. fts5HashAddPoslistSize(pHash, p);
  177088. *ppDoclist = (const u8*)&zKey[nTerm+1];
  177089. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  177090. }else{
  177091. *ppDoclist = 0;
  177092. *pnDoclist = 0;
  177093. }
  177094. return SQLITE_OK;
  177095. }
  177096. static int sqlite3Fts5HashScanInit(
  177097. Fts5Hash *p, /* Hash table to query */
  177098. const char *pTerm, int nTerm /* Query prefix */
  177099. ){
  177100. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  177101. }
  177102. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  177103. assert( !sqlite3Fts5HashScanEof(p) );
  177104. p->pScan = p->pScan->pScanNext;
  177105. }
  177106. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  177107. return (p->pScan==0);
  177108. }
  177109. static void sqlite3Fts5HashScanEntry(
  177110. Fts5Hash *pHash,
  177111. const char **pzTerm, /* OUT: term (nul-terminated) */
  177112. const u8 **ppDoclist, /* OUT: pointer to doclist */
  177113. int *pnDoclist /* OUT: size of doclist in bytes */
  177114. ){
  177115. Fts5HashEntry *p;
  177116. if( (p = pHash->pScan) ){
  177117. char *zKey = fts5EntryKey(p);
  177118. int nTerm = (int)strlen(zKey);
  177119. fts5HashAddPoslistSize(pHash, p);
  177120. *pzTerm = zKey;
  177121. *ppDoclist = (const u8*)&zKey[nTerm+1];
  177122. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  177123. }else{
  177124. *pzTerm = 0;
  177125. *ppDoclist = 0;
  177126. *pnDoclist = 0;
  177127. }
  177128. }
  177129. /*
  177130. ** 2014 May 31
  177131. **
  177132. ** The author disclaims copyright to this source code. In place of
  177133. ** a legal notice, here is a blessing:
  177134. **
  177135. ** May you do good and not evil.
  177136. ** May you find forgiveness for yourself and forgive others.
  177137. ** May you share freely, never taking more than you give.
  177138. **
  177139. ******************************************************************************
  177140. **
  177141. ** Low level access to the FTS index stored in the database file. The
  177142. ** routines in this file file implement all read and write access to the
  177143. ** %_data table. Other parts of the system access this functionality via
  177144. ** the interface defined in fts5Int.h.
  177145. */
  177146. /* #include "fts5Int.h" */
  177147. /*
  177148. ** Overview:
  177149. **
  177150. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  177151. ** As well as the main term index, there may be up to 31 prefix indexes.
  177152. ** The format is similar to FTS3/4, except that:
  177153. **
  177154. ** * all segment b-tree leaf data is stored in fixed size page records
  177155. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  177156. ** taken to ensure it is possible to iterate in either direction through
  177157. ** the entries in a doclist, or to seek to a specific entry within a
  177158. ** doclist, without loading it into memory.
  177159. **
  177160. ** * large doclists that span many pages have associated "doclist index"
  177161. ** records that contain a copy of the first rowid on each page spanned by
  177162. ** the doclist. This is used to speed up seek operations, and merges of
  177163. ** large doclists with very small doclists.
  177164. **
  177165. ** * extra fields in the "structure record" record the state of ongoing
  177166. ** incremental merge operations.
  177167. **
  177168. */
  177169. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  177170. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  177171. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  177172. #define FTS5_MAIN_PREFIX '0'
  177173. #if FTS5_MAX_PREFIX_INDEXES > 31
  177174. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  177175. #endif
  177176. /*
  177177. ** Details:
  177178. **
  177179. ** The %_data table managed by this module,
  177180. **
  177181. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  177182. **
  177183. ** , contains the following 5 types of records. See the comments surrounding
  177184. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  177185. ** assigned to each fo them.
  177186. **
  177187. ** 1. Structure Records:
  177188. **
  177189. ** The set of segments that make up an index - the index structure - are
  177190. ** recorded in a single record within the %_data table. The record consists
  177191. ** of a single 32-bit configuration cookie value followed by a list of
  177192. ** SQLite varints. If the FTS table features more than one index (because
  177193. ** there are one or more prefix indexes), it is guaranteed that all share
  177194. ** the same cookie value.
  177195. **
  177196. ** Immediately following the configuration cookie, the record begins with
  177197. ** three varints:
  177198. **
  177199. ** + number of levels,
  177200. ** + total number of segments on all levels,
  177201. ** + value of write counter.
  177202. **
  177203. ** Then, for each level from 0 to nMax:
  177204. **
  177205. ** + number of input segments in ongoing merge.
  177206. ** + total number of segments in level.
  177207. ** + for each segment from oldest to newest:
  177208. ** + segment id (always > 0)
  177209. ** + first leaf page number (often 1, always greater than 0)
  177210. ** + final leaf page number
  177211. **
  177212. ** 2. The Averages Record:
  177213. **
  177214. ** A single record within the %_data table. The data is a list of varints.
  177215. ** The first value is the number of rows in the index. Then, for each column
  177216. ** from left to right, the total number of tokens in the column for all
  177217. ** rows of the table.
  177218. **
  177219. ** 3. Segment leaves:
  177220. **
  177221. ** TERM/DOCLIST FORMAT:
  177222. **
  177223. ** Most of each segment leaf is taken up by term/doclist data. The
  177224. ** general format of term/doclist, starting with the first term
  177225. ** on the leaf page, is:
  177226. **
  177227. ** varint : size of first term
  177228. ** blob: first term data
  177229. ** doclist: first doclist
  177230. ** zero-or-more {
  177231. ** varint: number of bytes in common with previous term
  177232. ** varint: number of bytes of new term data (nNew)
  177233. ** blob: nNew bytes of new term data
  177234. ** doclist: next doclist
  177235. ** }
  177236. **
  177237. ** doclist format:
  177238. **
  177239. ** varint: first rowid
  177240. ** poslist: first poslist
  177241. ** zero-or-more {
  177242. ** varint: rowid delta (always > 0)
  177243. ** poslist: next poslist
  177244. ** }
  177245. **
  177246. ** poslist format:
  177247. **
  177248. ** varint: size of poslist in bytes multiplied by 2, not including
  177249. ** this field. Plus 1 if this entry carries the "delete" flag.
  177250. ** collist: collist for column 0
  177251. ** zero-or-more {
  177252. ** 0x01 byte
  177253. ** varint: column number (I)
  177254. ** collist: collist for column I
  177255. ** }
  177256. **
  177257. ** collist format:
  177258. **
  177259. ** varint: first offset + 2
  177260. ** zero-or-more {
  177261. ** varint: offset delta + 2
  177262. ** }
  177263. **
  177264. ** PAGE FORMAT
  177265. **
  177266. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  177267. ** unsigned integer fields in big-endian format. They are:
  177268. **
  177269. ** * The byte offset of the first rowid on the page, if it exists
  177270. ** and occurs before the first term (otherwise 0).
  177271. **
  177272. ** * The byte offset of the start of the page footer. If the page
  177273. ** footer is 0 bytes in size, then this field is the same as the
  177274. ** size of the leaf page in bytes.
  177275. **
  177276. ** The page footer consists of a single varint for each term located
  177277. ** on the page. Each varint is the byte offset of the current term
  177278. ** within the page, delta-compressed against the previous value. In
  177279. ** other words, the first varint in the footer is the byte offset of
  177280. ** the first term, the second is the byte offset of the second less that
  177281. ** of the first, and so on.
  177282. **
  177283. ** The term/doclist format described above is accurate if the entire
  177284. ** term/doclist data fits on a single leaf page. If this is not the case,
  177285. ** the format is changed in two ways:
  177286. **
  177287. ** + if the first rowid on a page occurs before the first term, it
  177288. ** is stored as a literal value:
  177289. **
  177290. ** varint: first rowid
  177291. **
  177292. ** + the first term on each page is stored in the same way as the
  177293. ** very first term of the segment:
  177294. **
  177295. ** varint : size of first term
  177296. ** blob: first term data
  177297. **
  177298. ** 5. Segment doclist indexes:
  177299. **
  177300. ** Doclist indexes are themselves b-trees, however they usually consist of
  177301. ** a single leaf record only. The format of each doclist index leaf page
  177302. ** is:
  177303. **
  177304. ** * Flags byte. Bits are:
  177305. ** 0x01: Clear if leaf is also the root page, otherwise set.
  177306. **
  177307. ** * Page number of fts index leaf page. As a varint.
  177308. **
  177309. ** * First rowid on page indicated by previous field. As a varint.
  177310. **
  177311. ** * A list of varints, one for each subsequent termless page. A
  177312. ** positive delta if the termless page contains at least one rowid,
  177313. ** or an 0x00 byte otherwise.
  177314. **
  177315. ** Internal doclist index nodes are:
  177316. **
  177317. ** * Flags byte. Bits are:
  177318. ** 0x01: Clear for root page, otherwise set.
  177319. **
  177320. ** * Page number of first child page. As a varint.
  177321. **
  177322. ** * Copy of first rowid on page indicated by previous field. As a varint.
  177323. **
  177324. ** * A list of delta-encoded varints - the first rowid on each subsequent
  177325. ** child page.
  177326. **
  177327. */
  177328. /*
  177329. ** Rowids for the averages and structure records in the %_data table.
  177330. */
  177331. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  177332. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  177333. /*
  177334. ** Macros determining the rowids used by segment leaves and dlidx leaves
  177335. ** and nodes. All nodes and leaves are stored in the %_data table with large
  177336. ** positive rowids.
  177337. **
  177338. ** Each segment has a unique non-zero 16-bit id.
  177339. **
  177340. ** The rowid for each segment leaf is found by passing the segment id and
  177341. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  177342. ** sequentially starting from 1.
  177343. */
  177344. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  177345. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  177346. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  177347. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  177348. #define fts5_dri(segid, dlidx, height, pgno) ( \
  177349. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  177350. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  177351. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  177352. ((i64)(pgno)) \
  177353. )
  177354. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  177355. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  177356. /*
  177357. ** Maximum segments permitted in a single index
  177358. */
  177359. #define FTS5_MAX_SEGMENT 2000
  177360. #ifdef SQLITE_DEBUG
  177361. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  177362. #endif
  177363. /*
  177364. ** Each time a blob is read from the %_data table, it is padded with this
  177365. ** many zero bytes. This makes it easier to decode the various record formats
  177366. ** without overreading if the records are corrupt.
  177367. */
  177368. #define FTS5_DATA_ZERO_PADDING 8
  177369. #define FTS5_DATA_PADDING 20
  177370. typedef struct Fts5Data Fts5Data;
  177371. typedef struct Fts5DlidxIter Fts5DlidxIter;
  177372. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  177373. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  177374. typedef struct Fts5Iter Fts5Iter;
  177375. typedef struct Fts5PageWriter Fts5PageWriter;
  177376. typedef struct Fts5SegIter Fts5SegIter;
  177377. typedef struct Fts5DoclistIter Fts5DoclistIter;
  177378. typedef struct Fts5SegWriter Fts5SegWriter;
  177379. typedef struct Fts5Structure Fts5Structure;
  177380. typedef struct Fts5StructureLevel Fts5StructureLevel;
  177381. typedef struct Fts5StructureSegment Fts5StructureSegment;
  177382. struct Fts5Data {
  177383. u8 *p; /* Pointer to buffer containing record */
  177384. int nn; /* Size of record in bytes */
  177385. int szLeaf; /* Size of leaf without page-index */
  177386. };
  177387. /*
  177388. ** One object per %_data table.
  177389. */
  177390. struct Fts5Index {
  177391. Fts5Config *pConfig; /* Virtual table configuration */
  177392. char *zDataTbl; /* Name of %_data table */
  177393. int nWorkUnit; /* Leaf pages in a "unit" of work */
  177394. /*
  177395. ** Variables related to the accumulation of tokens and doclists within the
  177396. ** in-memory hash tables before they are flushed to disk.
  177397. */
  177398. Fts5Hash *pHash; /* Hash table for in-memory data */
  177399. int nPendingData; /* Current bytes of pending data */
  177400. i64 iWriteRowid; /* Rowid for current doc being written */
  177401. int bDelete; /* Current write is a delete */
  177402. /* Error state. */
  177403. int rc; /* Current error code */
  177404. /* State used by the fts5DataXXX() functions. */
  177405. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  177406. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  177407. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  177408. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  177409. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  177410. sqlite3_stmt *pIdxSelect;
  177411. int nRead; /* Total number of blocks read */
  177412. sqlite3_stmt *pDataVersion;
  177413. i64 iStructVersion; /* data_version when pStruct read */
  177414. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  177415. };
  177416. struct Fts5DoclistIter {
  177417. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  177418. /* Output variables. aPoslist==0 at EOF */
  177419. i64 iRowid;
  177420. u8 *aPoslist;
  177421. int nPoslist;
  177422. int nSize;
  177423. };
  177424. /*
  177425. ** The contents of the "structure" record for each index are represented
  177426. ** using an Fts5Structure record in memory. Which uses instances of the
  177427. ** other Fts5StructureXXX types as components.
  177428. */
  177429. struct Fts5StructureSegment {
  177430. int iSegid; /* Segment id */
  177431. int pgnoFirst; /* First leaf page number in segment */
  177432. int pgnoLast; /* Last leaf page number in segment */
  177433. };
  177434. struct Fts5StructureLevel {
  177435. int nMerge; /* Number of segments in incr-merge */
  177436. int nSeg; /* Total number of segments on level */
  177437. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  177438. };
  177439. struct Fts5Structure {
  177440. int nRef; /* Object reference count */
  177441. u64 nWriteCounter; /* Total leaves written to level 0 */
  177442. int nSegment; /* Total segments in this structure */
  177443. int nLevel; /* Number of levels in this index */
  177444. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  177445. };
  177446. /*
  177447. ** An object of type Fts5SegWriter is used to write to segments.
  177448. */
  177449. struct Fts5PageWriter {
  177450. int pgno; /* Page number for this page */
  177451. int iPrevPgidx; /* Previous value written into pgidx */
  177452. Fts5Buffer buf; /* Buffer containing leaf data */
  177453. Fts5Buffer pgidx; /* Buffer containing page-index */
  177454. Fts5Buffer term; /* Buffer containing previous term on page */
  177455. };
  177456. struct Fts5DlidxWriter {
  177457. int pgno; /* Page number for this page */
  177458. int bPrevValid; /* True if iPrev is valid */
  177459. i64 iPrev; /* Previous rowid value written to page */
  177460. Fts5Buffer buf; /* Buffer containing page data */
  177461. };
  177462. struct Fts5SegWriter {
  177463. int iSegid; /* Segid to write to */
  177464. Fts5PageWriter writer; /* PageWriter object */
  177465. i64 iPrevRowid; /* Previous rowid written to current leaf */
  177466. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  177467. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  177468. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  177469. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  177470. int nLeafWritten; /* Number of leaf pages written */
  177471. int nEmpty; /* Number of contiguous term-less nodes */
  177472. int nDlidx; /* Allocated size of aDlidx[] array */
  177473. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  177474. /* Values to insert into the %_idx table */
  177475. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  177476. int iBtPage; /* Page number corresponding to btterm */
  177477. };
  177478. typedef struct Fts5CResult Fts5CResult;
  177479. struct Fts5CResult {
  177480. u16 iFirst; /* aSeg[] index of firstest iterator */
  177481. u8 bTermEq; /* True if the terms are equal */
  177482. };
  177483. /*
  177484. ** Object for iterating through a single segment, visiting each term/rowid
  177485. ** pair in the segment.
  177486. **
  177487. ** pSeg:
  177488. ** The segment to iterate through.
  177489. **
  177490. ** iLeafPgno:
  177491. ** Current leaf page number within segment.
  177492. **
  177493. ** iLeafOffset:
  177494. ** Byte offset within the current leaf that is the first byte of the
  177495. ** position list data (one byte passed the position-list size field).
  177496. ** rowid field of the current entry. Usually this is the size field of the
  177497. ** position list data. The exception is if the rowid for the current entry
  177498. ** is the last thing on the leaf page.
  177499. **
  177500. ** pLeaf:
  177501. ** Buffer containing current leaf page data. Set to NULL at EOF.
  177502. **
  177503. ** iTermLeafPgno, iTermLeafOffset:
  177504. ** Leaf page number containing the last term read from the segment. And
  177505. ** the offset immediately following the term data.
  177506. **
  177507. ** flags:
  177508. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  177509. **
  177510. ** FTS5_SEGITER_ONETERM:
  177511. ** If set, set the iterator to point to EOF after the current doclist
  177512. ** has been exhausted. Do not proceed to the next term in the segment.
  177513. **
  177514. ** FTS5_SEGITER_REVERSE:
  177515. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  177516. ** it is set, iterate through rowid in descending order instead of the
  177517. ** default ascending order.
  177518. **
  177519. ** iRowidOffset/nRowidOffset/aRowidOffset:
  177520. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  177521. **
  177522. ** For each rowid on the page corresponding to the current term, the
  177523. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  177524. ** start of the "position-list-size" field within the page.
  177525. **
  177526. ** iTermIdx:
  177527. ** Index of current term on iTermLeafPgno.
  177528. */
  177529. struct Fts5SegIter {
  177530. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  177531. int flags; /* Mask of configuration flags */
  177532. int iLeafPgno; /* Current leaf page number */
  177533. Fts5Data *pLeaf; /* Current leaf data */
  177534. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  177535. int iLeafOffset; /* Byte offset within current leaf */
  177536. /* Next method */
  177537. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  177538. /* The page and offset from which the current term was read. The offset
  177539. ** is the offset of the first rowid in the current doclist. */
  177540. int iTermLeafPgno;
  177541. int iTermLeafOffset;
  177542. int iPgidxOff; /* Next offset in pgidx */
  177543. int iEndofDoclist;
  177544. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  177545. int iRowidOffset; /* Current entry in aRowidOffset[] */
  177546. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  177547. int *aRowidOffset; /* Array of offset to rowid fields */
  177548. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  177549. /* Variables populated based on current entry. */
  177550. Fts5Buffer term; /* Current term */
  177551. i64 iRowid; /* Current rowid */
  177552. int nPos; /* Number of bytes in current position list */
  177553. u8 bDel; /* True if the delete flag is set */
  177554. };
  177555. /*
  177556. ** Argument is a pointer to an Fts5Data structure that contains a
  177557. ** leaf page.
  177558. */
  177559. #define ASSERT_SZLEAF_OK(x) assert( \
  177560. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  177561. )
  177562. #define FTS5_SEGITER_ONETERM 0x01
  177563. #define FTS5_SEGITER_REVERSE 0x02
  177564. /*
  177565. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  177566. ** page. This macro evaluates to true if the leaf contains no terms, or
  177567. ** false if it contains at least one term.
  177568. */
  177569. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  177570. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  177571. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  177572. /*
  177573. ** Object for iterating through the merged results of one or more segments,
  177574. ** visiting each term/rowid pair in the merged data.
  177575. **
  177576. ** nSeg is always a power of two greater than or equal to the number of
  177577. ** segments that this object is merging data from. Both the aSeg[] and
  177578. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  177579. ** with zeroed objects - these are handled as if they were iterators opened
  177580. ** on empty segments.
  177581. **
  177582. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  177583. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  177584. ** comparison in this context is the index of the iterator that currently
  177585. ** points to the smaller term/rowid combination. Iterators at EOF are
  177586. ** considered to be greater than all other iterators.
  177587. **
  177588. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  177589. ** the smallest key overall. aFirst[0] is unused.
  177590. **
  177591. ** poslist:
  177592. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  177593. ** There is no way to tell if this is populated or not.
  177594. */
  177595. struct Fts5Iter {
  177596. Fts5IndexIter base; /* Base class containing output vars */
  177597. Fts5Index *pIndex; /* Index that owns this iterator */
  177598. Fts5Structure *pStruct; /* Database structure for this iterator */
  177599. Fts5Buffer poslist; /* Buffer containing current poslist */
  177600. Fts5Colset *pColset; /* Restrict matches to these columns */
  177601. /* Invoked to set output variables. */
  177602. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  177603. int nSeg; /* Size of aSeg[] array */
  177604. int bRev; /* True to iterate in reverse order */
  177605. u8 bSkipEmpty; /* True to skip deleted entries */
  177606. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  177607. Fts5CResult *aFirst; /* Current merge state (see above) */
  177608. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  177609. };
  177610. /*
  177611. ** An instance of the following type is used to iterate through the contents
  177612. ** of a doclist-index record.
  177613. **
  177614. ** pData:
  177615. ** Record containing the doclist-index data.
  177616. **
  177617. ** bEof:
  177618. ** Set to true once iterator has reached EOF.
  177619. **
  177620. ** iOff:
  177621. ** Set to the current offset within record pData.
  177622. */
  177623. struct Fts5DlidxLvl {
  177624. Fts5Data *pData; /* Data for current page of this level */
  177625. int iOff; /* Current offset into pData */
  177626. int bEof; /* At EOF already */
  177627. int iFirstOff; /* Used by reverse iterators */
  177628. /* Output variables */
  177629. int iLeafPgno; /* Page number of current leaf page */
  177630. i64 iRowid; /* First rowid on leaf iLeafPgno */
  177631. };
  177632. struct Fts5DlidxIter {
  177633. int nLvl;
  177634. int iSegid;
  177635. Fts5DlidxLvl aLvl[1];
  177636. };
  177637. static void fts5PutU16(u8 *aOut, u16 iVal){
  177638. aOut[0] = (iVal>>8);
  177639. aOut[1] = (iVal&0xFF);
  177640. }
  177641. static u16 fts5GetU16(const u8 *aIn){
  177642. return ((u16)aIn[0] << 8) + aIn[1];
  177643. }
  177644. /*
  177645. ** Allocate and return a buffer at least nByte bytes in size.
  177646. **
  177647. ** If an OOM error is encountered, return NULL and set the error code in
  177648. ** the Fts5Index handle passed as the first argument.
  177649. */
  177650. static void *fts5IdxMalloc(Fts5Index *p, int nByte){
  177651. return sqlite3Fts5MallocZero(&p->rc, nByte);
  177652. }
  177653. /*
  177654. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  177655. **
  177656. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  177657. ** +ve if pRight is smaller than pLeft. In other words:
  177658. **
  177659. ** res = *pLeft - *pRight
  177660. */
  177661. #ifdef SQLITE_DEBUG
  177662. static int fts5BufferCompareBlob(
  177663. Fts5Buffer *pLeft, /* Left hand side of comparison */
  177664. const u8 *pRight, int nRight /* Right hand side of comparison */
  177665. ){
  177666. int nCmp = MIN(pLeft->n, nRight);
  177667. int res = memcmp(pLeft->p, pRight, nCmp);
  177668. return (res==0 ? (pLeft->n - nRight) : res);
  177669. }
  177670. #endif
  177671. /*
  177672. ** Compare the contents of the two buffers using memcmp(). If one buffer
  177673. ** is a prefix of the other, it is considered the lesser.
  177674. **
  177675. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  177676. ** +ve if pRight is smaller than pLeft. In other words:
  177677. **
  177678. ** res = *pLeft - *pRight
  177679. */
  177680. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  177681. int nCmp = MIN(pLeft->n, pRight->n);
  177682. int res = memcmp(pLeft->p, pRight->p, nCmp);
  177683. return (res==0 ? (pLeft->n - pRight->n) : res);
  177684. }
  177685. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  177686. int ret;
  177687. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  177688. return ret;
  177689. }
  177690. /*
  177691. ** Close the read-only blob handle, if it is open.
  177692. */
  177693. static void fts5CloseReader(Fts5Index *p){
  177694. if( p->pReader ){
  177695. sqlite3_blob *pReader = p->pReader;
  177696. p->pReader = 0;
  177697. sqlite3_blob_close(pReader);
  177698. }
  177699. }
  177700. /*
  177701. ** Retrieve a record from the %_data table.
  177702. **
  177703. ** If an error occurs, NULL is returned and an error left in the
  177704. ** Fts5Index object.
  177705. */
  177706. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  177707. Fts5Data *pRet = 0;
  177708. if( p->rc==SQLITE_OK ){
  177709. int rc = SQLITE_OK;
  177710. if( p->pReader ){
  177711. /* This call may return SQLITE_ABORT if there has been a savepoint
  177712. ** rollback since it was last used. In this case a new blob handle
  177713. ** is required. */
  177714. sqlite3_blob *pBlob = p->pReader;
  177715. p->pReader = 0;
  177716. rc = sqlite3_blob_reopen(pBlob, iRowid);
  177717. assert( p->pReader==0 );
  177718. p->pReader = pBlob;
  177719. if( rc!=SQLITE_OK ){
  177720. fts5CloseReader(p);
  177721. }
  177722. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  177723. }
  177724. /* If the blob handle is not open at this point, open it and seek
  177725. ** to the requested entry. */
  177726. if( p->pReader==0 && rc==SQLITE_OK ){
  177727. Fts5Config *pConfig = p->pConfig;
  177728. rc = sqlite3_blob_open(pConfig->db,
  177729. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  177730. );
  177731. }
  177732. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  177733. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  177734. ** All the reasons those functions might return SQLITE_ERROR - missing
  177735. ** table, missing row, non-blob/text in block column - indicate
  177736. ** backing store corruption. */
  177737. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  177738. if( rc==SQLITE_OK ){
  177739. u8 *aOut = 0; /* Read blob data into this buffer */
  177740. int nByte = sqlite3_blob_bytes(p->pReader);
  177741. int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  177742. pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
  177743. if( pRet ){
  177744. pRet->nn = nByte;
  177745. aOut = pRet->p = (u8*)&pRet[1];
  177746. }else{
  177747. rc = SQLITE_NOMEM;
  177748. }
  177749. if( rc==SQLITE_OK ){
  177750. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  177751. }
  177752. if( rc!=SQLITE_OK ){
  177753. sqlite3_free(pRet);
  177754. pRet = 0;
  177755. }else{
  177756. /* TODO1: Fix this */
  177757. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  177758. }
  177759. }
  177760. p->rc = rc;
  177761. p->nRead++;
  177762. }
  177763. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  177764. return pRet;
  177765. }
  177766. /*
  177767. ** Release a reference to data record returned by an earlier call to
  177768. ** fts5DataRead().
  177769. */
  177770. static void fts5DataRelease(Fts5Data *pData){
  177771. sqlite3_free(pData);
  177772. }
  177773. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  177774. Fts5Data *pRet = fts5DataRead(p, iRowid);
  177775. if( pRet ){
  177776. if( pRet->szLeaf>pRet->nn ){
  177777. p->rc = FTS5_CORRUPT;
  177778. fts5DataRelease(pRet);
  177779. pRet = 0;
  177780. }
  177781. }
  177782. return pRet;
  177783. }
  177784. static int fts5IndexPrepareStmt(
  177785. Fts5Index *p,
  177786. sqlite3_stmt **ppStmt,
  177787. char *zSql
  177788. ){
  177789. if( p->rc==SQLITE_OK ){
  177790. if( zSql ){
  177791. p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
  177792. }else{
  177793. p->rc = SQLITE_NOMEM;
  177794. }
  177795. }
  177796. sqlite3_free(zSql);
  177797. return p->rc;
  177798. }
  177799. /*
  177800. ** INSERT OR REPLACE a record into the %_data table.
  177801. */
  177802. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  177803. if( p->rc!=SQLITE_OK ) return;
  177804. if( p->pWriter==0 ){
  177805. Fts5Config *pConfig = p->pConfig;
  177806. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  177807. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  177808. pConfig->zDb, pConfig->zName
  177809. ));
  177810. if( p->rc ) return;
  177811. }
  177812. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  177813. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  177814. sqlite3_step(p->pWriter);
  177815. p->rc = sqlite3_reset(p->pWriter);
  177816. }
  177817. /*
  177818. ** Execute the following SQL:
  177819. **
  177820. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  177821. */
  177822. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  177823. if( p->rc!=SQLITE_OK ) return;
  177824. if( p->pDeleter==0 ){
  177825. int rc;
  177826. Fts5Config *pConfig = p->pConfig;
  177827. char *zSql = sqlite3_mprintf(
  177828. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  177829. pConfig->zDb, pConfig->zName
  177830. );
  177831. if( zSql==0 ){
  177832. rc = SQLITE_NOMEM;
  177833. }else{
  177834. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
  177835. sqlite3_free(zSql);
  177836. }
  177837. if( rc!=SQLITE_OK ){
  177838. p->rc = rc;
  177839. return;
  177840. }
  177841. }
  177842. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  177843. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  177844. sqlite3_step(p->pDeleter);
  177845. p->rc = sqlite3_reset(p->pDeleter);
  177846. }
  177847. /*
  177848. ** Remove all records associated with segment iSegid.
  177849. */
  177850. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  177851. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  177852. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  177853. fts5DataDelete(p, iFirst, iLast);
  177854. if( p->pIdxDeleter==0 ){
  177855. Fts5Config *pConfig = p->pConfig;
  177856. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  177857. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  177858. pConfig->zDb, pConfig->zName
  177859. ));
  177860. }
  177861. if( p->rc==SQLITE_OK ){
  177862. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  177863. sqlite3_step(p->pIdxDeleter);
  177864. p->rc = sqlite3_reset(p->pIdxDeleter);
  177865. }
  177866. }
  177867. /*
  177868. ** Release a reference to an Fts5Structure object returned by an earlier
  177869. ** call to fts5StructureRead() or fts5StructureDecode().
  177870. */
  177871. static void fts5StructureRelease(Fts5Structure *pStruct){
  177872. if( pStruct && 0>=(--pStruct->nRef) ){
  177873. int i;
  177874. assert( pStruct->nRef==0 );
  177875. for(i=0; i<pStruct->nLevel; i++){
  177876. sqlite3_free(pStruct->aLevel[i].aSeg);
  177877. }
  177878. sqlite3_free(pStruct);
  177879. }
  177880. }
  177881. static void fts5StructureRef(Fts5Structure *pStruct){
  177882. pStruct->nRef++;
  177883. }
  177884. /*
  177885. ** Deserialize and return the structure record currently stored in serialized
  177886. ** form within buffer pData/nData.
  177887. **
  177888. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  177889. ** are over-allocated by one slot. This allows the structure contents
  177890. ** to be more easily edited.
  177891. **
  177892. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  177893. ** returned. Otherwise, *ppOut is set to point to the new object and
  177894. ** SQLITE_OK returned.
  177895. */
  177896. static int fts5StructureDecode(
  177897. const u8 *pData, /* Buffer containing serialized structure */
  177898. int nData, /* Size of buffer pData in bytes */
  177899. int *piCookie, /* Configuration cookie value */
  177900. Fts5Structure **ppOut /* OUT: Deserialized object */
  177901. ){
  177902. int rc = SQLITE_OK;
  177903. int i = 0;
  177904. int iLvl;
  177905. int nLevel = 0;
  177906. int nSegment = 0;
  177907. int nByte; /* Bytes of space to allocate at pRet */
  177908. Fts5Structure *pRet = 0; /* Structure object to return */
  177909. /* Grab the cookie value */
  177910. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  177911. i = 4;
  177912. /* Read the total number of levels and segments from the start of the
  177913. ** structure record. */
  177914. i += fts5GetVarint32(&pData[i], nLevel);
  177915. i += fts5GetVarint32(&pData[i], nSegment);
  177916. nByte = (
  177917. sizeof(Fts5Structure) + /* Main structure */
  177918. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  177919. );
  177920. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  177921. if( pRet ){
  177922. pRet->nRef = 1;
  177923. pRet->nLevel = nLevel;
  177924. pRet->nSegment = nSegment;
  177925. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  177926. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  177927. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  177928. int nTotal = 0;
  177929. int iSeg;
  177930. if( i>=nData ){
  177931. rc = FTS5_CORRUPT;
  177932. }else{
  177933. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  177934. i += fts5GetVarint32(&pData[i], nTotal);
  177935. assert( nTotal>=pLvl->nMerge );
  177936. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  177937. nTotal * sizeof(Fts5StructureSegment)
  177938. );
  177939. }
  177940. if( rc==SQLITE_OK ){
  177941. pLvl->nSeg = nTotal;
  177942. for(iSeg=0; iSeg<nTotal; iSeg++){
  177943. if( i>=nData ){
  177944. rc = FTS5_CORRUPT;
  177945. break;
  177946. }
  177947. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
  177948. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
  177949. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
  177950. }
  177951. }
  177952. }
  177953. if( rc!=SQLITE_OK ){
  177954. fts5StructureRelease(pRet);
  177955. pRet = 0;
  177956. }
  177957. }
  177958. *ppOut = pRet;
  177959. return rc;
  177960. }
  177961. /*
  177962. **
  177963. */
  177964. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  177965. if( *pRc==SQLITE_OK ){
  177966. Fts5Structure *pStruct = *ppStruct;
  177967. int nLevel = pStruct->nLevel;
  177968. int nByte = (
  177969. sizeof(Fts5Structure) + /* Main structure */
  177970. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  177971. );
  177972. pStruct = sqlite3_realloc(pStruct, nByte);
  177973. if( pStruct ){
  177974. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  177975. pStruct->nLevel++;
  177976. *ppStruct = pStruct;
  177977. }else{
  177978. *pRc = SQLITE_NOMEM;
  177979. }
  177980. }
  177981. }
  177982. /*
  177983. ** Extend level iLvl so that there is room for at least nExtra more
  177984. ** segments.
  177985. */
  177986. static void fts5StructureExtendLevel(
  177987. int *pRc,
  177988. Fts5Structure *pStruct,
  177989. int iLvl,
  177990. int nExtra,
  177991. int bInsert
  177992. ){
  177993. if( *pRc==SQLITE_OK ){
  177994. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  177995. Fts5StructureSegment *aNew;
  177996. int nByte;
  177997. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  177998. aNew = sqlite3_realloc(pLvl->aSeg, nByte);
  177999. if( aNew ){
  178000. if( bInsert==0 ){
  178001. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  178002. }else{
  178003. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  178004. memmove(&aNew[nExtra], aNew, nMove);
  178005. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  178006. }
  178007. pLvl->aSeg = aNew;
  178008. }else{
  178009. *pRc = SQLITE_NOMEM;
  178010. }
  178011. }
  178012. }
  178013. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  178014. Fts5Structure *pRet = 0;
  178015. Fts5Config *pConfig = p->pConfig;
  178016. int iCookie; /* Configuration cookie */
  178017. Fts5Data *pData;
  178018. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  178019. if( p->rc==SQLITE_OK ){
  178020. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  178021. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  178022. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  178023. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  178024. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  178025. }
  178026. fts5DataRelease(pData);
  178027. if( p->rc!=SQLITE_OK ){
  178028. fts5StructureRelease(pRet);
  178029. pRet = 0;
  178030. }
  178031. }
  178032. return pRet;
  178033. }
  178034. static i64 fts5IndexDataVersion(Fts5Index *p){
  178035. i64 iVersion = 0;
  178036. if( p->rc==SQLITE_OK ){
  178037. if( p->pDataVersion==0 ){
  178038. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  178039. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  178040. );
  178041. if( p->rc ) return 0;
  178042. }
  178043. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  178044. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  178045. }
  178046. p->rc = sqlite3_reset(p->pDataVersion);
  178047. }
  178048. return iVersion;
  178049. }
  178050. /*
  178051. ** Read, deserialize and return the structure record.
  178052. **
  178053. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  178054. ** are over-allocated as described for function fts5StructureDecode()
  178055. ** above.
  178056. **
  178057. ** If an error occurs, NULL is returned and an error code left in the
  178058. ** Fts5Index handle. If an error has already occurred when this function
  178059. ** is called, it is a no-op.
  178060. */
  178061. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  178062. if( p->pStruct==0 ){
  178063. p->iStructVersion = fts5IndexDataVersion(p);
  178064. if( p->rc==SQLITE_OK ){
  178065. p->pStruct = fts5StructureReadUncached(p);
  178066. }
  178067. }
  178068. #if 0
  178069. else{
  178070. Fts5Structure *pTest = fts5StructureReadUncached(p);
  178071. if( pTest ){
  178072. int i, j;
  178073. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  178074. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  178075. for(i=0; i<pTest->nLevel; i++){
  178076. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  178077. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  178078. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  178079. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  178080. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  178081. assert_nc( p1->iSegid==p2->iSegid );
  178082. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  178083. assert_nc( p1->pgnoLast==p2->pgnoLast );
  178084. }
  178085. }
  178086. fts5StructureRelease(pTest);
  178087. }
  178088. }
  178089. #endif
  178090. if( p->rc!=SQLITE_OK ) return 0;
  178091. assert( p->iStructVersion!=0 );
  178092. assert( p->pStruct!=0 );
  178093. fts5StructureRef(p->pStruct);
  178094. return p->pStruct;
  178095. }
  178096. static void fts5StructureInvalidate(Fts5Index *p){
  178097. if( p->pStruct ){
  178098. fts5StructureRelease(p->pStruct);
  178099. p->pStruct = 0;
  178100. }
  178101. }
  178102. /*
  178103. ** Return the total number of segments in index structure pStruct. This
  178104. ** function is only ever used as part of assert() conditions.
  178105. */
  178106. #ifdef SQLITE_DEBUG
  178107. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  178108. int nSegment = 0; /* Total number of segments */
  178109. if( pStruct ){
  178110. int iLvl; /* Used to iterate through levels */
  178111. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  178112. nSegment += pStruct->aLevel[iLvl].nSeg;
  178113. }
  178114. }
  178115. return nSegment;
  178116. }
  178117. #endif
  178118. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  178119. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  178120. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  178121. (pBuf)->n += nBlob; \
  178122. }
  178123. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  178124. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  178125. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  178126. }
  178127. /*
  178128. ** Serialize and store the "structure" record.
  178129. **
  178130. ** If an error occurs, leave an error code in the Fts5Index object. If an
  178131. ** error has already occurred, this function is a no-op.
  178132. */
  178133. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  178134. if( p->rc==SQLITE_OK ){
  178135. Fts5Buffer buf; /* Buffer to serialize record into */
  178136. int iLvl; /* Used to iterate through levels */
  178137. int iCookie; /* Cookie value to store */
  178138. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  178139. memset(&buf, 0, sizeof(Fts5Buffer));
  178140. /* Append the current configuration cookie */
  178141. iCookie = p->pConfig->iCookie;
  178142. if( iCookie<0 ) iCookie = 0;
  178143. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  178144. sqlite3Fts5Put32(buf.p, iCookie);
  178145. buf.n = 4;
  178146. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  178147. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  178148. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  178149. }
  178150. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  178151. int iSeg; /* Used to iterate through segments */
  178152. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  178153. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  178154. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  178155. assert( pLvl->nMerge<=pLvl->nSeg );
  178156. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  178157. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  178158. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  178159. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  178160. }
  178161. }
  178162. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  178163. fts5BufferFree(&buf);
  178164. }
  178165. }
  178166. #if 0
  178167. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  178168. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  178169. int rc = SQLITE_OK;
  178170. Fts5Buffer buf;
  178171. memset(&buf, 0, sizeof(buf));
  178172. fts5DebugStructure(&rc, &buf, pStruct);
  178173. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  178174. fflush(stdout);
  178175. fts5BufferFree(&buf);
  178176. }
  178177. #else
  178178. # define fts5PrintStructure(x,y)
  178179. #endif
  178180. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  178181. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  178182. }
  178183. /*
  178184. ** Return a copy of index structure pStruct. Except, promote as many
  178185. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  178186. ** returned.
  178187. */
  178188. static void fts5StructurePromoteTo(
  178189. Fts5Index *p,
  178190. int iPromote,
  178191. int szPromote,
  178192. Fts5Structure *pStruct
  178193. ){
  178194. int il, is;
  178195. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  178196. if( pOut->nMerge==0 ){
  178197. for(il=iPromote+1; il<pStruct->nLevel; il++){
  178198. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  178199. if( pLvl->nMerge ) return;
  178200. for(is=pLvl->nSeg-1; is>=0; is--){
  178201. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  178202. if( sz>szPromote ) return;
  178203. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  178204. if( p->rc ) return;
  178205. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  178206. pOut->nSeg++;
  178207. pLvl->nSeg--;
  178208. }
  178209. }
  178210. }
  178211. }
  178212. /*
  178213. ** A new segment has just been written to level iLvl of index structure
  178214. ** pStruct. This function determines if any segments should be promoted
  178215. ** as a result. Segments are promoted in two scenarios:
  178216. **
  178217. ** a) If the segment just written is smaller than one or more segments
  178218. ** within the previous populated level, it is promoted to the previous
  178219. ** populated level.
  178220. **
  178221. ** b) If the segment just written is larger than the newest segment on
  178222. ** the next populated level, then that segment, and any other adjacent
  178223. ** segments that are also smaller than the one just written, are
  178224. ** promoted.
  178225. **
  178226. ** If one or more segments are promoted, the structure object is updated
  178227. ** to reflect this.
  178228. */
  178229. static void fts5StructurePromote(
  178230. Fts5Index *p, /* FTS5 backend object */
  178231. int iLvl, /* Index level just updated */
  178232. Fts5Structure *pStruct /* Index structure */
  178233. ){
  178234. if( p->rc==SQLITE_OK ){
  178235. int iTst;
  178236. int iPromote = -1;
  178237. int szPromote = 0; /* Promote anything this size or smaller */
  178238. Fts5StructureSegment *pSeg; /* Segment just written */
  178239. int szSeg; /* Size of segment just written */
  178240. int nSeg = pStruct->aLevel[iLvl].nSeg;
  178241. if( nSeg==0 ) return;
  178242. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  178243. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  178244. /* Check for condition (a) */
  178245. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  178246. if( iTst>=0 ){
  178247. int i;
  178248. int szMax = 0;
  178249. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  178250. assert( pTst->nMerge==0 );
  178251. for(i=0; i<pTst->nSeg; i++){
  178252. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  178253. if( sz>szMax ) szMax = sz;
  178254. }
  178255. if( szMax>=szSeg ){
  178256. /* Condition (a) is true. Promote the newest segment on level
  178257. ** iLvl to level iTst. */
  178258. iPromote = iTst;
  178259. szPromote = szMax;
  178260. }
  178261. }
  178262. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  178263. ** is a no-op if it is not. */
  178264. if( iPromote<0 ){
  178265. iPromote = iLvl;
  178266. szPromote = szSeg;
  178267. }
  178268. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  178269. }
  178270. }
  178271. /*
  178272. ** Advance the iterator passed as the only argument. If the end of the
  178273. ** doclist-index page is reached, return non-zero.
  178274. */
  178275. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  178276. Fts5Data *pData = pLvl->pData;
  178277. if( pLvl->iOff==0 ){
  178278. assert( pLvl->bEof==0 );
  178279. pLvl->iOff = 1;
  178280. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  178281. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  178282. pLvl->iFirstOff = pLvl->iOff;
  178283. }else{
  178284. int iOff;
  178285. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  178286. if( pData->p[iOff] ) break;
  178287. }
  178288. if( iOff<pData->nn ){
  178289. i64 iVal;
  178290. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  178291. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  178292. pLvl->iRowid += iVal;
  178293. pLvl->iOff = iOff;
  178294. }else{
  178295. pLvl->bEof = 1;
  178296. }
  178297. }
  178298. return pLvl->bEof;
  178299. }
  178300. /*
  178301. ** Advance the iterator passed as the only argument.
  178302. */
  178303. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  178304. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  178305. assert( iLvl<pIter->nLvl );
  178306. if( fts5DlidxLvlNext(pLvl) ){
  178307. if( (iLvl+1) < pIter->nLvl ){
  178308. fts5DlidxIterNextR(p, pIter, iLvl+1);
  178309. if( pLvl[1].bEof==0 ){
  178310. fts5DataRelease(pLvl->pData);
  178311. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  178312. pLvl->pData = fts5DataRead(p,
  178313. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  178314. );
  178315. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  178316. }
  178317. }
  178318. }
  178319. return pIter->aLvl[0].bEof;
  178320. }
  178321. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  178322. return fts5DlidxIterNextR(p, pIter, 0);
  178323. }
  178324. /*
  178325. ** The iterator passed as the first argument has the following fields set
  178326. ** as follows. This function sets up the rest of the iterator so that it
  178327. ** points to the first rowid in the doclist-index.
  178328. **
  178329. ** pData:
  178330. ** pointer to doclist-index record,
  178331. **
  178332. ** When this function is called pIter->iLeafPgno is the page number the
  178333. ** doclist is associated with (the one featuring the term).
  178334. */
  178335. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  178336. int i;
  178337. for(i=0; i<pIter->nLvl; i++){
  178338. fts5DlidxLvlNext(&pIter->aLvl[i]);
  178339. }
  178340. return pIter->aLvl[0].bEof;
  178341. }
  178342. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  178343. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  178344. }
  178345. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  178346. int i;
  178347. /* Advance each level to the last entry on the last page */
  178348. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  178349. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  178350. while( fts5DlidxLvlNext(pLvl)==0 );
  178351. pLvl->bEof = 0;
  178352. if( i>0 ){
  178353. Fts5DlidxLvl *pChild = &pLvl[-1];
  178354. fts5DataRelease(pChild->pData);
  178355. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  178356. pChild->pData = fts5DataRead(p,
  178357. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  178358. );
  178359. }
  178360. }
  178361. }
  178362. /*
  178363. ** Move the iterator passed as the only argument to the previous entry.
  178364. */
  178365. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  178366. int iOff = pLvl->iOff;
  178367. assert( pLvl->bEof==0 );
  178368. if( iOff<=pLvl->iFirstOff ){
  178369. pLvl->bEof = 1;
  178370. }else{
  178371. u8 *a = pLvl->pData->p;
  178372. i64 iVal;
  178373. int iLimit;
  178374. int ii;
  178375. int nZero = 0;
  178376. /* Currently iOff points to the first byte of a varint. This block
  178377. ** decrements iOff until it points to the first byte of the previous
  178378. ** varint. Taking care not to read any memory locations that occur
  178379. ** before the buffer in memory. */
  178380. iLimit = (iOff>9 ? iOff-9 : 0);
  178381. for(iOff--; iOff>iLimit; iOff--){
  178382. if( (a[iOff-1] & 0x80)==0 ) break;
  178383. }
  178384. fts5GetVarint(&a[iOff], (u64*)&iVal);
  178385. pLvl->iRowid -= iVal;
  178386. pLvl->iLeafPgno--;
  178387. /* Skip backwards past any 0x00 varints. */
  178388. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  178389. nZero++;
  178390. }
  178391. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  178392. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  178393. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  178394. ** bytes before a[ii]. */
  178395. int bZero = 0; /* True if last 0x00 counts */
  178396. if( (ii-8)>=pLvl->iFirstOff ){
  178397. int j;
  178398. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  178399. bZero = (j>8);
  178400. }
  178401. if( bZero==0 ) nZero--;
  178402. }
  178403. pLvl->iLeafPgno -= nZero;
  178404. pLvl->iOff = iOff - nZero;
  178405. }
  178406. return pLvl->bEof;
  178407. }
  178408. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  178409. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  178410. assert( iLvl<pIter->nLvl );
  178411. if( fts5DlidxLvlPrev(pLvl) ){
  178412. if( (iLvl+1) < pIter->nLvl ){
  178413. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  178414. if( pLvl[1].bEof==0 ){
  178415. fts5DataRelease(pLvl->pData);
  178416. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  178417. pLvl->pData = fts5DataRead(p,
  178418. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  178419. );
  178420. if( pLvl->pData ){
  178421. while( fts5DlidxLvlNext(pLvl)==0 );
  178422. pLvl->bEof = 0;
  178423. }
  178424. }
  178425. }
  178426. }
  178427. return pIter->aLvl[0].bEof;
  178428. }
  178429. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  178430. return fts5DlidxIterPrevR(p, pIter, 0);
  178431. }
  178432. /*
  178433. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  178434. */
  178435. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  178436. if( pIter ){
  178437. int i;
  178438. for(i=0; i<pIter->nLvl; i++){
  178439. fts5DataRelease(pIter->aLvl[i].pData);
  178440. }
  178441. sqlite3_free(pIter);
  178442. }
  178443. }
  178444. static Fts5DlidxIter *fts5DlidxIterInit(
  178445. Fts5Index *p, /* Fts5 Backend to iterate within */
  178446. int bRev, /* True for ORDER BY ASC */
  178447. int iSegid, /* Segment id */
  178448. int iLeafPg /* Leaf page number to load dlidx for */
  178449. ){
  178450. Fts5DlidxIter *pIter = 0;
  178451. int i;
  178452. int bDone = 0;
  178453. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  178454. int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  178455. Fts5DlidxIter *pNew;
  178456. pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
  178457. if( pNew==0 ){
  178458. p->rc = SQLITE_NOMEM;
  178459. }else{
  178460. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  178461. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  178462. pIter = pNew;
  178463. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  178464. pLvl->pData = fts5DataRead(p, iRowid);
  178465. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  178466. bDone = 1;
  178467. }
  178468. pIter->nLvl = i+1;
  178469. }
  178470. }
  178471. if( p->rc==SQLITE_OK ){
  178472. pIter->iSegid = iSegid;
  178473. if( bRev==0 ){
  178474. fts5DlidxIterFirst(pIter);
  178475. }else{
  178476. fts5DlidxIterLast(p, pIter);
  178477. }
  178478. }
  178479. if( p->rc!=SQLITE_OK ){
  178480. fts5DlidxIterFree(pIter);
  178481. pIter = 0;
  178482. }
  178483. return pIter;
  178484. }
  178485. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  178486. return pIter->aLvl[0].iRowid;
  178487. }
  178488. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  178489. return pIter->aLvl[0].iLeafPgno;
  178490. }
  178491. /*
  178492. ** Load the next leaf page into the segment iterator.
  178493. */
  178494. static void fts5SegIterNextPage(
  178495. Fts5Index *p, /* FTS5 backend object */
  178496. Fts5SegIter *pIter /* Iterator to advance to next page */
  178497. ){
  178498. Fts5Data *pLeaf;
  178499. Fts5StructureSegment *pSeg = pIter->pSeg;
  178500. fts5DataRelease(pIter->pLeaf);
  178501. pIter->iLeafPgno++;
  178502. if( pIter->pNextLeaf ){
  178503. pIter->pLeaf = pIter->pNextLeaf;
  178504. pIter->pNextLeaf = 0;
  178505. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  178506. pIter->pLeaf = fts5LeafRead(p,
  178507. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  178508. );
  178509. }else{
  178510. pIter->pLeaf = 0;
  178511. }
  178512. pLeaf = pIter->pLeaf;
  178513. if( pLeaf ){
  178514. pIter->iPgidxOff = pLeaf->szLeaf;
  178515. if( fts5LeafIsTermless(pLeaf) ){
  178516. pIter->iEndofDoclist = pLeaf->nn+1;
  178517. }else{
  178518. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  178519. pIter->iEndofDoclist
  178520. );
  178521. }
  178522. }
  178523. }
  178524. /*
  178525. ** Argument p points to a buffer containing a varint to be interpreted as a
  178526. ** position list size field. Read the varint and return the number of bytes
  178527. ** read. Before returning, set *pnSz to the number of bytes in the position
  178528. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  178529. */
  178530. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  178531. int nSz;
  178532. int n = 0;
  178533. fts5FastGetVarint32(p, n, nSz);
  178534. assert_nc( nSz>=0 );
  178535. *pnSz = nSz/2;
  178536. *pbDel = nSz & 0x0001;
  178537. return n;
  178538. }
  178539. /*
  178540. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  178541. ** position-list size field. Read the value of the field and store it
  178542. ** in the following variables:
  178543. **
  178544. ** Fts5SegIter.nPos
  178545. ** Fts5SegIter.bDel
  178546. **
  178547. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  178548. ** position list content (if any).
  178549. */
  178550. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  178551. if( p->rc==SQLITE_OK ){
  178552. int iOff = pIter->iLeafOffset; /* Offset to read at */
  178553. ASSERT_SZLEAF_OK(pIter->pLeaf);
  178554. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  178555. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  178556. pIter->bDel = 0;
  178557. pIter->nPos = 1;
  178558. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  178559. pIter->bDel = 1;
  178560. iOff++;
  178561. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  178562. pIter->nPos = 1;
  178563. iOff++;
  178564. }else{
  178565. pIter->nPos = 0;
  178566. }
  178567. }
  178568. }else{
  178569. int nSz;
  178570. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  178571. pIter->bDel = (nSz & 0x0001);
  178572. pIter->nPos = nSz>>1;
  178573. assert_nc( pIter->nPos>=0 );
  178574. }
  178575. pIter->iLeafOffset = iOff;
  178576. }
  178577. }
  178578. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  178579. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  178580. int iOff = pIter->iLeafOffset;
  178581. ASSERT_SZLEAF_OK(pIter->pLeaf);
  178582. if( iOff>=pIter->pLeaf->szLeaf ){
  178583. fts5SegIterNextPage(p, pIter);
  178584. if( pIter->pLeaf==0 ){
  178585. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  178586. return;
  178587. }
  178588. iOff = 4;
  178589. a = pIter->pLeaf->p;
  178590. }
  178591. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  178592. pIter->iLeafOffset = iOff;
  178593. }
  178594. /*
  178595. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  178596. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  178597. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  178598. ** the first term in the segment).
  178599. **
  178600. ** This function populates:
  178601. **
  178602. ** Fts5SegIter.term
  178603. ** Fts5SegIter.rowid
  178604. **
  178605. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  178606. ** the first position list. The position list belonging to document
  178607. ** (Fts5SegIter.iRowid).
  178608. */
  178609. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  178610. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  178611. int iOff = pIter->iLeafOffset; /* Offset to read at */
  178612. int nNew; /* Bytes of new data */
  178613. iOff += fts5GetVarint32(&a[iOff], nNew);
  178614. if( iOff+nNew>pIter->pLeaf->nn ){
  178615. p->rc = FTS5_CORRUPT;
  178616. return;
  178617. }
  178618. pIter->term.n = nKeep;
  178619. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  178620. iOff += nNew;
  178621. pIter->iTermLeafOffset = iOff;
  178622. pIter->iTermLeafPgno = pIter->iLeafPgno;
  178623. pIter->iLeafOffset = iOff;
  178624. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  178625. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  178626. }else{
  178627. int nExtra;
  178628. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  178629. pIter->iEndofDoclist += nExtra;
  178630. }
  178631. fts5SegIterLoadRowid(p, pIter);
  178632. }
  178633. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  178634. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  178635. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  178636. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  178637. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  178638. pIter->xNext = fts5SegIterNext_Reverse;
  178639. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  178640. pIter->xNext = fts5SegIterNext_None;
  178641. }else{
  178642. pIter->xNext = fts5SegIterNext;
  178643. }
  178644. }
  178645. /*
  178646. ** Initialize the iterator object pIter to iterate through the entries in
  178647. ** segment pSeg. The iterator is left pointing to the first entry when
  178648. ** this function returns.
  178649. **
  178650. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  178651. ** an error has already occurred when this function is called, it is a no-op.
  178652. */
  178653. static void fts5SegIterInit(
  178654. Fts5Index *p, /* FTS index object */
  178655. Fts5StructureSegment *pSeg, /* Description of segment */
  178656. Fts5SegIter *pIter /* Object to populate */
  178657. ){
  178658. if( pSeg->pgnoFirst==0 ){
  178659. /* This happens if the segment is being used as an input to an incremental
  178660. ** merge and all data has already been "trimmed". See function
  178661. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  178662. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  178663. ** at EOF already. */
  178664. assert( pIter->pLeaf==0 );
  178665. return;
  178666. }
  178667. if( p->rc==SQLITE_OK ){
  178668. memset(pIter, 0, sizeof(*pIter));
  178669. fts5SegIterSetNext(p, pIter);
  178670. pIter->pSeg = pSeg;
  178671. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  178672. fts5SegIterNextPage(p, pIter);
  178673. }
  178674. if( p->rc==SQLITE_OK ){
  178675. pIter->iLeafOffset = 4;
  178676. assert_nc( pIter->pLeaf->nn>4 );
  178677. assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  178678. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  178679. fts5SegIterLoadTerm(p, pIter, 0);
  178680. fts5SegIterLoadNPos(p, pIter);
  178681. }
  178682. }
  178683. /*
  178684. ** This function is only ever called on iterators created by calls to
  178685. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  178686. **
  178687. ** The iterator is in an unusual state when this function is called: the
  178688. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  178689. ** the position-list size field for the first relevant rowid on the page.
  178690. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  178691. **
  178692. ** This function advances the iterator so that it points to the last
  178693. ** relevant rowid on the page and, if necessary, initializes the
  178694. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  178695. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  178696. ** byte of the position list content associated with said rowid.
  178697. */
  178698. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  178699. int eDetail = p->pConfig->eDetail;
  178700. int n = pIter->pLeaf->szLeaf;
  178701. int i = pIter->iLeafOffset;
  178702. u8 *a = pIter->pLeaf->p;
  178703. int iRowidOffset = 0;
  178704. if( n>pIter->iEndofDoclist ){
  178705. n = pIter->iEndofDoclist;
  178706. }
  178707. ASSERT_SZLEAF_OK(pIter->pLeaf);
  178708. while( 1 ){
  178709. i64 iDelta = 0;
  178710. if( eDetail==FTS5_DETAIL_NONE ){
  178711. /* todo */
  178712. if( i<n && a[i]==0 ){
  178713. i++;
  178714. if( i<n && a[i]==0 ) i++;
  178715. }
  178716. }else{
  178717. int nPos;
  178718. int bDummy;
  178719. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  178720. i += nPos;
  178721. }
  178722. if( i>=n ) break;
  178723. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  178724. pIter->iRowid += iDelta;
  178725. /* If necessary, grow the pIter->aRowidOffset[] array. */
  178726. if( iRowidOffset>=pIter->nRowidOffset ){
  178727. int nNew = pIter->nRowidOffset + 8;
  178728. int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
  178729. if( aNew==0 ){
  178730. p->rc = SQLITE_NOMEM;
  178731. break;
  178732. }
  178733. pIter->aRowidOffset = aNew;
  178734. pIter->nRowidOffset = nNew;
  178735. }
  178736. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  178737. pIter->iLeafOffset = i;
  178738. }
  178739. pIter->iRowidOffset = iRowidOffset;
  178740. fts5SegIterLoadNPos(p, pIter);
  178741. }
  178742. /*
  178743. **
  178744. */
  178745. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  178746. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  178747. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  178748. fts5DataRelease(pIter->pLeaf);
  178749. pIter->pLeaf = 0;
  178750. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  178751. Fts5Data *pNew;
  178752. pIter->iLeafPgno--;
  178753. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  178754. pIter->pSeg->iSegid, pIter->iLeafPgno
  178755. ));
  178756. if( pNew ){
  178757. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  178758. ** thing on the page - i.e. the first rowid is on the following page.
  178759. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  178760. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  178761. assert( pIter->pLeaf==0 );
  178762. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  178763. pIter->pLeaf = pNew;
  178764. pIter->iLeafOffset = pIter->iTermLeafOffset;
  178765. }
  178766. }else{
  178767. int iRowidOff;
  178768. iRowidOff = fts5LeafFirstRowidOff(pNew);
  178769. if( iRowidOff ){
  178770. pIter->pLeaf = pNew;
  178771. pIter->iLeafOffset = iRowidOff;
  178772. }
  178773. }
  178774. if( pIter->pLeaf ){
  178775. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  178776. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  178777. break;
  178778. }else{
  178779. fts5DataRelease(pNew);
  178780. }
  178781. }
  178782. }
  178783. if( pIter->pLeaf ){
  178784. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  178785. fts5SegIterReverseInitPage(p, pIter);
  178786. }
  178787. }
  178788. /*
  178789. ** Return true if the iterator passed as the second argument currently
  178790. ** points to a delete marker. A delete marker is an entry with a 0 byte
  178791. ** position-list.
  178792. */
  178793. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  178794. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  178795. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  178796. }
  178797. /*
  178798. ** Advance iterator pIter to the next entry.
  178799. **
  178800. ** This version of fts5SegIterNext() is only used by reverse iterators.
  178801. */
  178802. static void fts5SegIterNext_Reverse(
  178803. Fts5Index *p, /* FTS5 backend object */
  178804. Fts5SegIter *pIter, /* Iterator to advance */
  178805. int *pbUnused /* Unused */
  178806. ){
  178807. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  178808. assert( pIter->pNextLeaf==0 );
  178809. UNUSED_PARAM(pbUnused);
  178810. if( pIter->iRowidOffset>0 ){
  178811. u8 *a = pIter->pLeaf->p;
  178812. int iOff;
  178813. i64 iDelta;
  178814. pIter->iRowidOffset--;
  178815. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  178816. fts5SegIterLoadNPos(p, pIter);
  178817. iOff = pIter->iLeafOffset;
  178818. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  178819. iOff += pIter->nPos;
  178820. }
  178821. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  178822. pIter->iRowid -= iDelta;
  178823. }else{
  178824. fts5SegIterReverseNewPage(p, pIter);
  178825. }
  178826. }
  178827. /*
  178828. ** Advance iterator pIter to the next entry.
  178829. **
  178830. ** This version of fts5SegIterNext() is only used if detail=none and the
  178831. ** iterator is not a reverse direction iterator.
  178832. */
  178833. static void fts5SegIterNext_None(
  178834. Fts5Index *p, /* FTS5 backend object */
  178835. Fts5SegIter *pIter, /* Iterator to advance */
  178836. int *pbNewTerm /* OUT: Set for new term */
  178837. ){
  178838. int iOff;
  178839. assert( p->rc==SQLITE_OK );
  178840. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  178841. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  178842. ASSERT_SZLEAF_OK(pIter->pLeaf);
  178843. iOff = pIter->iLeafOffset;
  178844. /* Next entry is on the next page */
  178845. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  178846. fts5SegIterNextPage(p, pIter);
  178847. if( p->rc || pIter->pLeaf==0 ) return;
  178848. pIter->iRowid = 0;
  178849. iOff = 4;
  178850. }
  178851. if( iOff<pIter->iEndofDoclist ){
  178852. /* Next entry is on the current page */
  178853. i64 iDelta;
  178854. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  178855. pIter->iLeafOffset = iOff;
  178856. pIter->iRowid += iDelta;
  178857. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  178858. if( pIter->pSeg ){
  178859. int nKeep = 0;
  178860. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  178861. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  178862. }
  178863. pIter->iLeafOffset = iOff;
  178864. fts5SegIterLoadTerm(p, pIter, nKeep);
  178865. }else{
  178866. const u8 *pList = 0;
  178867. const char *zTerm = 0;
  178868. int nList;
  178869. sqlite3Fts5HashScanNext(p->pHash);
  178870. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  178871. if( pList==0 ) goto next_none_eof;
  178872. pIter->pLeaf->p = (u8*)pList;
  178873. pIter->pLeaf->nn = nList;
  178874. pIter->pLeaf->szLeaf = nList;
  178875. pIter->iEndofDoclist = nList;
  178876. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  178877. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  178878. }
  178879. if( pbNewTerm ) *pbNewTerm = 1;
  178880. }else{
  178881. goto next_none_eof;
  178882. }
  178883. fts5SegIterLoadNPos(p, pIter);
  178884. return;
  178885. next_none_eof:
  178886. fts5DataRelease(pIter->pLeaf);
  178887. pIter->pLeaf = 0;
  178888. }
  178889. /*
  178890. ** Advance iterator pIter to the next entry.
  178891. **
  178892. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  178893. ** is not considered an error if the iterator reaches EOF. If an error has
  178894. ** already occurred when this function is called, it is a no-op.
  178895. */
  178896. static void fts5SegIterNext(
  178897. Fts5Index *p, /* FTS5 backend object */
  178898. Fts5SegIter *pIter, /* Iterator to advance */
  178899. int *pbNewTerm /* OUT: Set for new term */
  178900. ){
  178901. Fts5Data *pLeaf = pIter->pLeaf;
  178902. int iOff;
  178903. int bNewTerm = 0;
  178904. int nKeep = 0;
  178905. u8 *a;
  178906. int n;
  178907. assert( pbNewTerm==0 || *pbNewTerm==0 );
  178908. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  178909. /* Search for the end of the position list within the current page. */
  178910. a = pLeaf->p;
  178911. n = pLeaf->szLeaf;
  178912. ASSERT_SZLEAF_OK(pLeaf);
  178913. iOff = pIter->iLeafOffset + pIter->nPos;
  178914. if( iOff<n ){
  178915. /* The next entry is on the current page. */
  178916. assert_nc( iOff<=pIter->iEndofDoclist );
  178917. if( iOff>=pIter->iEndofDoclist ){
  178918. bNewTerm = 1;
  178919. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  178920. iOff += fts5GetVarint32(&a[iOff], nKeep);
  178921. }
  178922. }else{
  178923. u64 iDelta;
  178924. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  178925. pIter->iRowid += iDelta;
  178926. assert_nc( iDelta>0 );
  178927. }
  178928. pIter->iLeafOffset = iOff;
  178929. }else if( pIter->pSeg==0 ){
  178930. const u8 *pList = 0;
  178931. const char *zTerm = 0;
  178932. int nList = 0;
  178933. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  178934. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  178935. sqlite3Fts5HashScanNext(p->pHash);
  178936. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  178937. }
  178938. if( pList==0 ){
  178939. fts5DataRelease(pIter->pLeaf);
  178940. pIter->pLeaf = 0;
  178941. }else{
  178942. pIter->pLeaf->p = (u8*)pList;
  178943. pIter->pLeaf->nn = nList;
  178944. pIter->pLeaf->szLeaf = nList;
  178945. pIter->iEndofDoclist = nList+1;
  178946. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  178947. (u8*)zTerm);
  178948. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  178949. *pbNewTerm = 1;
  178950. }
  178951. }else{
  178952. iOff = 0;
  178953. /* Next entry is not on the current page */
  178954. while( iOff==0 ){
  178955. fts5SegIterNextPage(p, pIter);
  178956. pLeaf = pIter->pLeaf;
  178957. if( pLeaf==0 ) break;
  178958. ASSERT_SZLEAF_OK(pLeaf);
  178959. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  178960. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  178961. pIter->iLeafOffset = iOff;
  178962. if( pLeaf->nn>pLeaf->szLeaf ){
  178963. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  178964. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  178965. );
  178966. }
  178967. }
  178968. else if( pLeaf->nn>pLeaf->szLeaf ){
  178969. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  178970. &pLeaf->p[pLeaf->szLeaf], iOff
  178971. );
  178972. pIter->iLeafOffset = iOff;
  178973. pIter->iEndofDoclist = iOff;
  178974. bNewTerm = 1;
  178975. }
  178976. assert_nc( iOff<pLeaf->szLeaf );
  178977. if( iOff>pLeaf->szLeaf ){
  178978. p->rc = FTS5_CORRUPT;
  178979. return;
  178980. }
  178981. }
  178982. }
  178983. /* Check if the iterator is now at EOF. If so, return early. */
  178984. if( pIter->pLeaf ){
  178985. if( bNewTerm ){
  178986. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  178987. fts5DataRelease(pIter->pLeaf);
  178988. pIter->pLeaf = 0;
  178989. }else{
  178990. fts5SegIterLoadTerm(p, pIter, nKeep);
  178991. fts5SegIterLoadNPos(p, pIter);
  178992. if( pbNewTerm ) *pbNewTerm = 1;
  178993. }
  178994. }else{
  178995. /* The following could be done by calling fts5SegIterLoadNPos(). But
  178996. ** this block is particularly performance critical, so equivalent
  178997. ** code is inlined.
  178998. **
  178999. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  179000. ** detail=none mode. Not ideal.
  179001. */
  179002. int nSz;
  179003. assert( p->rc==SQLITE_OK );
  179004. assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
  179005. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  179006. pIter->bDel = (nSz & 0x0001);
  179007. pIter->nPos = nSz>>1;
  179008. assert_nc( pIter->nPos>=0 );
  179009. }
  179010. }
  179011. }
  179012. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  179013. #define fts5IndexSkipVarint(a, iOff) { \
  179014. int iEnd = iOff+9; \
  179015. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  179016. }
  179017. /*
  179018. ** Iterator pIter currently points to the first rowid in a doclist. This
  179019. ** function sets the iterator up so that iterates in reverse order through
  179020. ** the doclist.
  179021. */
  179022. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  179023. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  179024. Fts5Data *pLast = 0;
  179025. int pgnoLast = 0;
  179026. if( pDlidx ){
  179027. int iSegid = pIter->pSeg->iSegid;
  179028. pgnoLast = fts5DlidxIterPgno(pDlidx);
  179029. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  179030. }else{
  179031. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  179032. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  179033. ** position-list content for the current rowid. Back it up so that it
  179034. ** points to the start of the position-list size field. */
  179035. int iPoslist;
  179036. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  179037. iPoslist = pIter->iTermLeafOffset;
  179038. }else{
  179039. iPoslist = 4;
  179040. }
  179041. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  179042. pIter->iLeafOffset = iPoslist;
  179043. /* If this condition is true then the largest rowid for the current
  179044. ** term may not be stored on the current page. So search forward to
  179045. ** see where said rowid really is. */
  179046. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  179047. int pgno;
  179048. Fts5StructureSegment *pSeg = pIter->pSeg;
  179049. /* The last rowid in the doclist may not be on the current page. Search
  179050. ** forward to find the page containing the last rowid. */
  179051. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  179052. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  179053. Fts5Data *pNew = fts5DataRead(p, iAbs);
  179054. if( pNew ){
  179055. int iRowid, bTermless;
  179056. iRowid = fts5LeafFirstRowidOff(pNew);
  179057. bTermless = fts5LeafIsTermless(pNew);
  179058. if( iRowid ){
  179059. SWAPVAL(Fts5Data*, pNew, pLast);
  179060. pgnoLast = pgno;
  179061. }
  179062. fts5DataRelease(pNew);
  179063. if( bTermless==0 ) break;
  179064. }
  179065. }
  179066. }
  179067. }
  179068. /* If pLast is NULL at this point, then the last rowid for this doclist
  179069. ** lies on the page currently indicated by the iterator. In this case
  179070. ** pIter->iLeafOffset is already set to point to the position-list size
  179071. ** field associated with the first relevant rowid on the page.
  179072. **
  179073. ** Or, if pLast is non-NULL, then it is the page that contains the last
  179074. ** rowid. In this case configure the iterator so that it points to the
  179075. ** first rowid on this page.
  179076. */
  179077. if( pLast ){
  179078. int iOff;
  179079. fts5DataRelease(pIter->pLeaf);
  179080. pIter->pLeaf = pLast;
  179081. pIter->iLeafPgno = pgnoLast;
  179082. iOff = fts5LeafFirstRowidOff(pLast);
  179083. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  179084. pIter->iLeafOffset = iOff;
  179085. if( fts5LeafIsTermless(pLast) ){
  179086. pIter->iEndofDoclist = pLast->nn+1;
  179087. }else{
  179088. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  179089. }
  179090. }
  179091. fts5SegIterReverseInitPage(p, pIter);
  179092. }
  179093. /*
  179094. ** Iterator pIter currently points to the first rowid of a doclist.
  179095. ** There is a doclist-index associated with the final term on the current
  179096. ** page. If the current term is the last term on the page, load the
  179097. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  179098. */
  179099. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  179100. int iSeg = pIter->pSeg->iSegid;
  179101. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  179102. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  179103. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  179104. assert( pIter->pDlidx==0 );
  179105. /* Check if the current doclist ends on this page. If it does, return
  179106. ** early without loading the doclist-index (as it belongs to a different
  179107. ** term. */
  179108. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  179109. && pIter->iEndofDoclist<pLeaf->szLeaf
  179110. ){
  179111. return;
  179112. }
  179113. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  179114. }
  179115. /*
  179116. ** The iterator object passed as the second argument currently contains
  179117. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  179118. ** function searches the leaf page for a term matching (pTerm/nTerm).
  179119. **
  179120. ** If the specified term is found on the page, then the iterator is left
  179121. ** pointing to it. If argument bGe is zero and the term is not found,
  179122. ** the iterator is left pointing at EOF.
  179123. **
  179124. ** If bGe is non-zero and the specified term is not found, then the
  179125. ** iterator is left pointing to the smallest term in the segment that
  179126. ** is larger than the specified term, even if this term is not on the
  179127. ** current page.
  179128. */
  179129. static void fts5LeafSeek(
  179130. Fts5Index *p, /* Leave any error code here */
  179131. int bGe, /* True for a >= search */
  179132. Fts5SegIter *pIter, /* Iterator to seek */
  179133. const u8 *pTerm, int nTerm /* Term to search for */
  179134. ){
  179135. int iOff;
  179136. const u8 *a = pIter->pLeaf->p;
  179137. int szLeaf = pIter->pLeaf->szLeaf;
  179138. int n = pIter->pLeaf->nn;
  179139. int nMatch = 0;
  179140. int nKeep = 0;
  179141. int nNew = 0;
  179142. int iTermOff;
  179143. int iPgidx; /* Current offset in pgidx */
  179144. int bEndOfPage = 0;
  179145. assert( p->rc==SQLITE_OK );
  179146. iPgidx = szLeaf;
  179147. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  179148. iOff = iTermOff;
  179149. if( iOff>n ){
  179150. p->rc = FTS5_CORRUPT;
  179151. return;
  179152. }
  179153. while( 1 ){
  179154. /* Figure out how many new bytes are in this term */
  179155. fts5FastGetVarint32(a, iOff, nNew);
  179156. if( nKeep<nMatch ){
  179157. goto search_failed;
  179158. }
  179159. assert( nKeep>=nMatch );
  179160. if( nKeep==nMatch ){
  179161. int nCmp;
  179162. int i;
  179163. nCmp = MIN(nNew, nTerm-nMatch);
  179164. for(i=0; i<nCmp; i++){
  179165. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  179166. }
  179167. nMatch += i;
  179168. if( nTerm==nMatch ){
  179169. if( i==nNew ){
  179170. goto search_success;
  179171. }else{
  179172. goto search_failed;
  179173. }
  179174. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  179175. goto search_failed;
  179176. }
  179177. }
  179178. if( iPgidx>=n ){
  179179. bEndOfPage = 1;
  179180. break;
  179181. }
  179182. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  179183. iTermOff += nKeep;
  179184. iOff = iTermOff;
  179185. if( iOff>=n ){
  179186. p->rc = FTS5_CORRUPT;
  179187. return;
  179188. }
  179189. /* Read the nKeep field of the next term. */
  179190. fts5FastGetVarint32(a, iOff, nKeep);
  179191. }
  179192. search_failed:
  179193. if( bGe==0 ){
  179194. fts5DataRelease(pIter->pLeaf);
  179195. pIter->pLeaf = 0;
  179196. return;
  179197. }else if( bEndOfPage ){
  179198. do {
  179199. fts5SegIterNextPage(p, pIter);
  179200. if( pIter->pLeaf==0 ) return;
  179201. a = pIter->pLeaf->p;
  179202. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  179203. iPgidx = pIter->pLeaf->szLeaf;
  179204. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  179205. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  179206. p->rc = FTS5_CORRUPT;
  179207. }else{
  179208. nKeep = 0;
  179209. iTermOff = iOff;
  179210. n = pIter->pLeaf->nn;
  179211. iOff += fts5GetVarint32(&a[iOff], nNew);
  179212. break;
  179213. }
  179214. }
  179215. }while( 1 );
  179216. }
  179217. search_success:
  179218. pIter->iLeafOffset = iOff + nNew;
  179219. pIter->iTermLeafOffset = pIter->iLeafOffset;
  179220. pIter->iTermLeafPgno = pIter->iLeafPgno;
  179221. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  179222. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  179223. if( iPgidx>=n ){
  179224. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  179225. }else{
  179226. int nExtra;
  179227. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  179228. pIter->iEndofDoclist = iTermOff + nExtra;
  179229. }
  179230. pIter->iPgidxOff = iPgidx;
  179231. fts5SegIterLoadRowid(p, pIter);
  179232. fts5SegIterLoadNPos(p, pIter);
  179233. }
  179234. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  179235. if( p->pIdxSelect==0 ){
  179236. Fts5Config *pConfig = p->pConfig;
  179237. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  179238. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  179239. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  179240. pConfig->zDb, pConfig->zName
  179241. ));
  179242. }
  179243. return p->pIdxSelect;
  179244. }
  179245. /*
  179246. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  179247. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  179248. **
  179249. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  179250. ** an error has already occurred when this function is called, it is a no-op.
  179251. */
  179252. static void fts5SegIterSeekInit(
  179253. Fts5Index *p, /* FTS5 backend */
  179254. const u8 *pTerm, int nTerm, /* Term to seek to */
  179255. int flags, /* Mask of FTS5INDEX_XXX flags */
  179256. Fts5StructureSegment *pSeg, /* Description of segment */
  179257. Fts5SegIter *pIter /* Object to populate */
  179258. ){
  179259. int iPg = 1;
  179260. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  179261. int bDlidx = 0; /* True if there is a doclist-index */
  179262. sqlite3_stmt *pIdxSelect = 0;
  179263. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  179264. assert( pTerm && nTerm );
  179265. memset(pIter, 0, sizeof(*pIter));
  179266. pIter->pSeg = pSeg;
  179267. /* This block sets stack variable iPg to the leaf page number that may
  179268. ** contain term (pTerm/nTerm), if it is present in the segment. */
  179269. pIdxSelect = fts5IdxSelectStmt(p);
  179270. if( p->rc ) return;
  179271. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  179272. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  179273. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  179274. i64 val = sqlite3_column_int(pIdxSelect, 0);
  179275. iPg = (int)(val>>1);
  179276. bDlidx = (val & 0x0001);
  179277. }
  179278. p->rc = sqlite3_reset(pIdxSelect);
  179279. if( iPg<pSeg->pgnoFirst ){
  179280. iPg = pSeg->pgnoFirst;
  179281. bDlidx = 0;
  179282. }
  179283. pIter->iLeafPgno = iPg - 1;
  179284. fts5SegIterNextPage(p, pIter);
  179285. if( pIter->pLeaf ){
  179286. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  179287. }
  179288. if( p->rc==SQLITE_OK && bGe==0 ){
  179289. pIter->flags |= FTS5_SEGITER_ONETERM;
  179290. if( pIter->pLeaf ){
  179291. if( flags & FTS5INDEX_QUERY_DESC ){
  179292. pIter->flags |= FTS5_SEGITER_REVERSE;
  179293. }
  179294. if( bDlidx ){
  179295. fts5SegIterLoadDlidx(p, pIter);
  179296. }
  179297. if( flags & FTS5INDEX_QUERY_DESC ){
  179298. fts5SegIterReverse(p, pIter);
  179299. }
  179300. }
  179301. }
  179302. fts5SegIterSetNext(p, pIter);
  179303. /* Either:
  179304. **
  179305. ** 1) an error has occurred, or
  179306. ** 2) the iterator points to EOF, or
  179307. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  179308. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  179309. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  179310. */
  179311. assert( p->rc!=SQLITE_OK /* 1 */
  179312. || pIter->pLeaf==0 /* 2 */
  179313. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  179314. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  179315. );
  179316. }
  179317. /*
  179318. ** Initialize the object pIter to point to term pTerm/nTerm within the
  179319. ** in-memory hash table. If there is no such term in the hash-table, the
  179320. ** iterator is set to EOF.
  179321. **
  179322. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  179323. ** an error has already occurred when this function is called, it is a no-op.
  179324. */
  179325. static void fts5SegIterHashInit(
  179326. Fts5Index *p, /* FTS5 backend */
  179327. const u8 *pTerm, int nTerm, /* Term to seek to */
  179328. int flags, /* Mask of FTS5INDEX_XXX flags */
  179329. Fts5SegIter *pIter /* Object to populate */
  179330. ){
  179331. const u8 *pList = 0;
  179332. int nList = 0;
  179333. const u8 *z = 0;
  179334. int n = 0;
  179335. assert( p->pHash );
  179336. assert( p->rc==SQLITE_OK );
  179337. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  179338. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  179339. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  179340. n = (z ? (int)strlen((const char*)z) : 0);
  179341. }else{
  179342. pIter->flags |= FTS5_SEGITER_ONETERM;
  179343. sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
  179344. z = pTerm;
  179345. n = nTerm;
  179346. }
  179347. if( pList ){
  179348. Fts5Data *pLeaf;
  179349. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  179350. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  179351. if( pLeaf==0 ) return;
  179352. pLeaf->p = (u8*)pList;
  179353. pLeaf->nn = pLeaf->szLeaf = nList;
  179354. pIter->pLeaf = pLeaf;
  179355. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  179356. pIter->iEndofDoclist = pLeaf->nn;
  179357. if( flags & FTS5INDEX_QUERY_DESC ){
  179358. pIter->flags |= FTS5_SEGITER_REVERSE;
  179359. fts5SegIterReverseInitPage(p, pIter);
  179360. }else{
  179361. fts5SegIterLoadNPos(p, pIter);
  179362. }
  179363. }
  179364. fts5SegIterSetNext(p, pIter);
  179365. }
  179366. /*
  179367. ** Zero the iterator passed as the only argument.
  179368. */
  179369. static void fts5SegIterClear(Fts5SegIter *pIter){
  179370. fts5BufferFree(&pIter->term);
  179371. fts5DataRelease(pIter->pLeaf);
  179372. fts5DataRelease(pIter->pNextLeaf);
  179373. fts5DlidxIterFree(pIter->pDlidx);
  179374. sqlite3_free(pIter->aRowidOffset);
  179375. memset(pIter, 0, sizeof(Fts5SegIter));
  179376. }
  179377. #ifdef SQLITE_DEBUG
  179378. /*
  179379. ** This function is used as part of the big assert() procedure implemented by
  179380. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  179381. ** in *pRes is the correct result of comparing the current positions of the
  179382. ** two iterators.
  179383. */
  179384. static void fts5AssertComparisonResult(
  179385. Fts5Iter *pIter,
  179386. Fts5SegIter *p1,
  179387. Fts5SegIter *p2,
  179388. Fts5CResult *pRes
  179389. ){
  179390. int i1 = p1 - pIter->aSeg;
  179391. int i2 = p2 - pIter->aSeg;
  179392. if( p1->pLeaf || p2->pLeaf ){
  179393. if( p1->pLeaf==0 ){
  179394. assert( pRes->iFirst==i2 );
  179395. }else if( p2->pLeaf==0 ){
  179396. assert( pRes->iFirst==i1 );
  179397. }else{
  179398. int nMin = MIN(p1->term.n, p2->term.n);
  179399. int res = memcmp(p1->term.p, p2->term.p, nMin);
  179400. if( res==0 ) res = p1->term.n - p2->term.n;
  179401. if( res==0 ){
  179402. assert( pRes->bTermEq==1 );
  179403. assert( p1->iRowid!=p2->iRowid );
  179404. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  179405. }else{
  179406. assert( pRes->bTermEq==0 );
  179407. }
  179408. if( res<0 ){
  179409. assert( pRes->iFirst==i1 );
  179410. }else{
  179411. assert( pRes->iFirst==i2 );
  179412. }
  179413. }
  179414. }
  179415. }
  179416. /*
  179417. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  179418. ** is compiled. In that case, this function is essentially an assert()
  179419. ** statement used to verify that the contents of the pIter->aFirst[] array
  179420. ** are correct.
  179421. */
  179422. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  179423. if( p->rc==SQLITE_OK ){
  179424. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  179425. int i;
  179426. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  179427. /* Check that pIter->iSwitchRowid is set correctly. */
  179428. for(i=0; i<pIter->nSeg; i++){
  179429. Fts5SegIter *p1 = &pIter->aSeg[i];
  179430. assert( p1==pFirst
  179431. || p1->pLeaf==0
  179432. || fts5BufferCompare(&pFirst->term, &p1->term)
  179433. || p1->iRowid==pIter->iSwitchRowid
  179434. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  179435. );
  179436. }
  179437. for(i=0; i<pIter->nSeg; i+=2){
  179438. Fts5SegIter *p1 = &pIter->aSeg[i];
  179439. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  179440. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  179441. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  179442. }
  179443. for(i=1; i<(pIter->nSeg / 2); i+=2){
  179444. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  179445. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  179446. Fts5CResult *pRes = &pIter->aFirst[i];
  179447. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  179448. }
  179449. }
  179450. }
  179451. #else
  179452. # define fts5AssertMultiIterSetup(x,y)
  179453. #endif
  179454. /*
  179455. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  179456. **
  179457. ** If the returned value is non-zero, then it is the index of an entry
  179458. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  179459. ** to a key that is a duplicate of another, higher priority,
  179460. ** segment-iterator in the pSeg->aSeg[] array.
  179461. */
  179462. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  179463. int i1; /* Index of left-hand Fts5SegIter */
  179464. int i2; /* Index of right-hand Fts5SegIter */
  179465. int iRes;
  179466. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  179467. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  179468. Fts5CResult *pRes = &pIter->aFirst[iOut];
  179469. assert( iOut<pIter->nSeg && iOut>0 );
  179470. assert( pIter->bRev==0 || pIter->bRev==1 );
  179471. if( iOut>=(pIter->nSeg/2) ){
  179472. i1 = (iOut - pIter->nSeg/2) * 2;
  179473. i2 = i1 + 1;
  179474. }else{
  179475. i1 = pIter->aFirst[iOut*2].iFirst;
  179476. i2 = pIter->aFirst[iOut*2+1].iFirst;
  179477. }
  179478. p1 = &pIter->aSeg[i1];
  179479. p2 = &pIter->aSeg[i2];
  179480. pRes->bTermEq = 0;
  179481. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  179482. iRes = i2;
  179483. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  179484. iRes = i1;
  179485. }else{
  179486. int res = fts5BufferCompare(&p1->term, &p2->term);
  179487. if( res==0 ){
  179488. assert( i2>i1 );
  179489. assert( i2!=0 );
  179490. pRes->bTermEq = 1;
  179491. if( p1->iRowid==p2->iRowid ){
  179492. p1->bDel = p2->bDel;
  179493. return i2;
  179494. }
  179495. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  179496. }
  179497. assert( res!=0 );
  179498. if( res<0 ){
  179499. iRes = i1;
  179500. }else{
  179501. iRes = i2;
  179502. }
  179503. }
  179504. pRes->iFirst = (u16)iRes;
  179505. return 0;
  179506. }
  179507. /*
  179508. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  179509. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  179510. */
  179511. static void fts5SegIterGotoPage(
  179512. Fts5Index *p, /* FTS5 backend object */
  179513. Fts5SegIter *pIter, /* Iterator to advance */
  179514. int iLeafPgno
  179515. ){
  179516. assert( iLeafPgno>pIter->iLeafPgno );
  179517. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  179518. p->rc = FTS5_CORRUPT;
  179519. }else{
  179520. fts5DataRelease(pIter->pNextLeaf);
  179521. pIter->pNextLeaf = 0;
  179522. pIter->iLeafPgno = iLeafPgno-1;
  179523. fts5SegIterNextPage(p, pIter);
  179524. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  179525. if( p->rc==SQLITE_OK ){
  179526. int iOff;
  179527. u8 *a = pIter->pLeaf->p;
  179528. int n = pIter->pLeaf->szLeaf;
  179529. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  179530. if( iOff<4 || iOff>=n ){
  179531. p->rc = FTS5_CORRUPT;
  179532. }else{
  179533. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  179534. pIter->iLeafOffset = iOff;
  179535. fts5SegIterLoadNPos(p, pIter);
  179536. }
  179537. }
  179538. }
  179539. }
  179540. /*
  179541. ** Advance the iterator passed as the second argument until it is at or
  179542. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  179543. ** always advanced at least once.
  179544. */
  179545. static void fts5SegIterNextFrom(
  179546. Fts5Index *p, /* FTS5 backend object */
  179547. Fts5SegIter *pIter, /* Iterator to advance */
  179548. i64 iMatch /* Advance iterator at least this far */
  179549. ){
  179550. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  179551. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  179552. int iLeafPgno = pIter->iLeafPgno;
  179553. int bMove = 1;
  179554. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  179555. assert( pIter->pDlidx );
  179556. assert( pIter->pLeaf );
  179557. if( bRev==0 ){
  179558. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  179559. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  179560. fts5DlidxIterNext(p, pDlidx);
  179561. }
  179562. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  179563. if( iLeafPgno>pIter->iLeafPgno ){
  179564. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  179565. bMove = 0;
  179566. }
  179567. }else{
  179568. assert( pIter->pNextLeaf==0 );
  179569. assert( iMatch<pIter->iRowid );
  179570. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  179571. fts5DlidxIterPrev(p, pDlidx);
  179572. }
  179573. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  179574. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  179575. if( iLeafPgno<pIter->iLeafPgno ){
  179576. pIter->iLeafPgno = iLeafPgno+1;
  179577. fts5SegIterReverseNewPage(p, pIter);
  179578. bMove = 0;
  179579. }
  179580. }
  179581. do{
  179582. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  179583. if( pIter->pLeaf==0 ) break;
  179584. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  179585. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  179586. bMove = 1;
  179587. }while( p->rc==SQLITE_OK );
  179588. }
  179589. /*
  179590. ** Free the iterator object passed as the second argument.
  179591. */
  179592. static void fts5MultiIterFree(Fts5Iter *pIter){
  179593. if( pIter ){
  179594. int i;
  179595. for(i=0; i<pIter->nSeg; i++){
  179596. fts5SegIterClear(&pIter->aSeg[i]);
  179597. }
  179598. fts5StructureRelease(pIter->pStruct);
  179599. fts5BufferFree(&pIter->poslist);
  179600. sqlite3_free(pIter);
  179601. }
  179602. }
  179603. static void fts5MultiIterAdvanced(
  179604. Fts5Index *p, /* FTS5 backend to iterate within */
  179605. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  179606. int iChanged, /* Index of sub-iterator just advanced */
  179607. int iMinset /* Minimum entry in aFirst[] to set */
  179608. ){
  179609. int i;
  179610. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  179611. int iEq;
  179612. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  179613. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  179614. assert( p->rc==SQLITE_OK );
  179615. pSeg->xNext(p, pSeg, 0);
  179616. i = pIter->nSeg + iEq;
  179617. }
  179618. }
  179619. }
  179620. /*
  179621. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  179622. ** points to the same term though - just a different rowid. This function
  179623. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  179624. ** If it does so successfully, 0 is returned. Otherwise 1.
  179625. **
  179626. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  179627. ** on the iterator instead. That function does the same as this one, except
  179628. ** that it deals with more complicated cases as well.
  179629. */
  179630. static int fts5MultiIterAdvanceRowid(
  179631. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  179632. int iChanged, /* Index of sub-iterator just advanced */
  179633. Fts5SegIter **ppFirst
  179634. ){
  179635. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  179636. if( pNew->iRowid==pIter->iSwitchRowid
  179637. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  179638. ){
  179639. int i;
  179640. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  179641. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  179642. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  179643. Fts5CResult *pRes = &pIter->aFirst[i];
  179644. assert( pNew->pLeaf );
  179645. assert( pRes->bTermEq==0 || pOther->pLeaf );
  179646. if( pRes->bTermEq ){
  179647. if( pNew->iRowid==pOther->iRowid ){
  179648. return 1;
  179649. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  179650. pIter->iSwitchRowid = pOther->iRowid;
  179651. pNew = pOther;
  179652. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  179653. pIter->iSwitchRowid = pOther->iRowid;
  179654. }
  179655. }
  179656. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  179657. if( i==1 ) break;
  179658. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  179659. }
  179660. }
  179661. *ppFirst = pNew;
  179662. return 0;
  179663. }
  179664. /*
  179665. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  179666. */
  179667. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  179668. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  179669. pIter->base.bEof = pSeg->pLeaf==0;
  179670. pIter->iSwitchRowid = pSeg->iRowid;
  179671. }
  179672. /*
  179673. ** Move the iterator to the next entry.
  179674. **
  179675. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  179676. ** considered an error if the iterator reaches EOF, or if it is already at
  179677. ** EOF when this function is called.
  179678. */
  179679. static void fts5MultiIterNext(
  179680. Fts5Index *p,
  179681. Fts5Iter *pIter,
  179682. int bFrom, /* True if argument iFrom is valid */
  179683. i64 iFrom /* Advance at least as far as this */
  179684. ){
  179685. int bUseFrom = bFrom;
  179686. assert( pIter->base.bEof==0 );
  179687. while( p->rc==SQLITE_OK ){
  179688. int iFirst = pIter->aFirst[1].iFirst;
  179689. int bNewTerm = 0;
  179690. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  179691. assert( p->rc==SQLITE_OK );
  179692. if( bUseFrom && pSeg->pDlidx ){
  179693. fts5SegIterNextFrom(p, pSeg, iFrom);
  179694. }else{
  179695. pSeg->xNext(p, pSeg, &bNewTerm);
  179696. }
  179697. if( pSeg->pLeaf==0 || bNewTerm
  179698. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  179699. ){
  179700. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  179701. fts5MultiIterSetEof(pIter);
  179702. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  179703. if( pSeg->pLeaf==0 ) return;
  179704. }
  179705. fts5AssertMultiIterSetup(p, pIter);
  179706. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  179707. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  179708. pIter->xSetOutputs(pIter, pSeg);
  179709. return;
  179710. }
  179711. bUseFrom = 0;
  179712. }
  179713. }
  179714. static void fts5MultiIterNext2(
  179715. Fts5Index *p,
  179716. Fts5Iter *pIter,
  179717. int *pbNewTerm /* OUT: True if *might* be new term */
  179718. ){
  179719. assert( pIter->bSkipEmpty );
  179720. if( p->rc==SQLITE_OK ){
  179721. *pbNewTerm = 0;
  179722. do{
  179723. int iFirst = pIter->aFirst[1].iFirst;
  179724. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  179725. int bNewTerm = 0;
  179726. assert( p->rc==SQLITE_OK );
  179727. pSeg->xNext(p, pSeg, &bNewTerm);
  179728. if( pSeg->pLeaf==0 || bNewTerm
  179729. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  179730. ){
  179731. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  179732. fts5MultiIterSetEof(pIter);
  179733. *pbNewTerm = 1;
  179734. }
  179735. fts5AssertMultiIterSetup(p, pIter);
  179736. }while( fts5MultiIterIsEmpty(p, pIter) );
  179737. }
  179738. }
  179739. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  179740. UNUSED_PARAM2(pUnused1, pUnused2);
  179741. }
  179742. static Fts5Iter *fts5MultiIterAlloc(
  179743. Fts5Index *p, /* FTS5 backend to iterate within */
  179744. int nSeg
  179745. ){
  179746. Fts5Iter *pNew;
  179747. int nSlot; /* Power of two >= nSeg */
  179748. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  179749. pNew = fts5IdxMalloc(p,
  179750. sizeof(Fts5Iter) + /* pNew */
  179751. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  179752. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  179753. );
  179754. if( pNew ){
  179755. pNew->nSeg = nSlot;
  179756. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  179757. pNew->pIndex = p;
  179758. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  179759. }
  179760. return pNew;
  179761. }
  179762. static void fts5PoslistCallback(
  179763. Fts5Index *pUnused,
  179764. void *pContext,
  179765. const u8 *pChunk, int nChunk
  179766. ){
  179767. UNUSED_PARAM(pUnused);
  179768. assert_nc( nChunk>=0 );
  179769. if( nChunk>0 ){
  179770. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  179771. }
  179772. }
  179773. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  179774. struct PoslistCallbackCtx {
  179775. Fts5Buffer *pBuf; /* Append to this buffer */
  179776. Fts5Colset *pColset; /* Restrict matches to this column */
  179777. int eState; /* See above */
  179778. };
  179779. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  179780. struct PoslistOffsetsCtx {
  179781. Fts5Buffer *pBuf; /* Append to this buffer */
  179782. Fts5Colset *pColset; /* Restrict matches to this column */
  179783. int iRead;
  179784. int iWrite;
  179785. };
  179786. /*
  179787. ** TODO: Make this more efficient!
  179788. */
  179789. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  179790. int i;
  179791. for(i=0; i<pColset->nCol; i++){
  179792. if( pColset->aiCol[i]==iCol ) return 1;
  179793. }
  179794. return 0;
  179795. }
  179796. static void fts5PoslistOffsetsCallback(
  179797. Fts5Index *pUnused,
  179798. void *pContext,
  179799. const u8 *pChunk, int nChunk
  179800. ){
  179801. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  179802. UNUSED_PARAM(pUnused);
  179803. assert_nc( nChunk>=0 );
  179804. if( nChunk>0 ){
  179805. int i = 0;
  179806. while( i<nChunk ){
  179807. int iVal;
  179808. i += fts5GetVarint32(&pChunk[i], iVal);
  179809. iVal += pCtx->iRead - 2;
  179810. pCtx->iRead = iVal;
  179811. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  179812. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  179813. pCtx->iWrite = iVal;
  179814. }
  179815. }
  179816. }
  179817. }
  179818. static void fts5PoslistFilterCallback(
  179819. Fts5Index *pUnused,
  179820. void *pContext,
  179821. const u8 *pChunk, int nChunk
  179822. ){
  179823. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  179824. UNUSED_PARAM(pUnused);
  179825. assert_nc( nChunk>=0 );
  179826. if( nChunk>0 ){
  179827. /* Search through to find the first varint with value 1. This is the
  179828. ** start of the next columns hits. */
  179829. int i = 0;
  179830. int iStart = 0;
  179831. if( pCtx->eState==2 ){
  179832. int iCol;
  179833. fts5FastGetVarint32(pChunk, i, iCol);
  179834. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  179835. pCtx->eState = 1;
  179836. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  179837. }else{
  179838. pCtx->eState = 0;
  179839. }
  179840. }
  179841. do {
  179842. while( i<nChunk && pChunk[i]!=0x01 ){
  179843. while( pChunk[i] & 0x80 ) i++;
  179844. i++;
  179845. }
  179846. if( pCtx->eState ){
  179847. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  179848. }
  179849. if( i<nChunk ){
  179850. int iCol;
  179851. iStart = i;
  179852. i++;
  179853. if( i>=nChunk ){
  179854. pCtx->eState = 2;
  179855. }else{
  179856. fts5FastGetVarint32(pChunk, i, iCol);
  179857. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  179858. if( pCtx->eState ){
  179859. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  179860. iStart = i;
  179861. }
  179862. }
  179863. }
  179864. }while( i<nChunk );
  179865. }
  179866. }
  179867. static void fts5ChunkIterate(
  179868. Fts5Index *p, /* Index object */
  179869. Fts5SegIter *pSeg, /* Poslist of this iterator */
  179870. void *pCtx, /* Context pointer for xChunk callback */
  179871. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  179872. ){
  179873. int nRem = pSeg->nPos; /* Number of bytes still to come */
  179874. Fts5Data *pData = 0;
  179875. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  179876. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  179877. int pgno = pSeg->iLeafPgno;
  179878. int pgnoSave = 0;
  179879. /* This function does notmwork with detail=none databases. */
  179880. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  179881. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  179882. pgnoSave = pgno+1;
  179883. }
  179884. while( 1 ){
  179885. xChunk(p, pCtx, pChunk, nChunk);
  179886. nRem -= nChunk;
  179887. fts5DataRelease(pData);
  179888. if( nRem<=0 ){
  179889. break;
  179890. }else{
  179891. pgno++;
  179892. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  179893. if( pData==0 ) break;
  179894. pChunk = &pData->p[4];
  179895. nChunk = MIN(nRem, pData->szLeaf - 4);
  179896. if( pgno==pgnoSave ){
  179897. assert( pSeg->pNextLeaf==0 );
  179898. pSeg->pNextLeaf = pData;
  179899. pData = 0;
  179900. }
  179901. }
  179902. }
  179903. }
  179904. /*
  179905. ** Iterator pIter currently points to a valid entry (not EOF). This
  179906. ** function appends the position list data for the current entry to
  179907. ** buffer pBuf. It does not make a copy of the position-list size
  179908. ** field.
  179909. */
  179910. static void fts5SegiterPoslist(
  179911. Fts5Index *p,
  179912. Fts5SegIter *pSeg,
  179913. Fts5Colset *pColset,
  179914. Fts5Buffer *pBuf
  179915. ){
  179916. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
  179917. if( pColset==0 ){
  179918. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  179919. }else{
  179920. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  179921. PoslistCallbackCtx sCtx;
  179922. sCtx.pBuf = pBuf;
  179923. sCtx.pColset = pColset;
  179924. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  179925. assert( sCtx.eState==0 || sCtx.eState==1 );
  179926. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  179927. }else{
  179928. PoslistOffsetsCtx sCtx;
  179929. memset(&sCtx, 0, sizeof(sCtx));
  179930. sCtx.pBuf = pBuf;
  179931. sCtx.pColset = pColset;
  179932. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  179933. }
  179934. }
  179935. }
  179936. }
  179937. /*
  179938. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  179939. ** the position list contains entries for column iCol, then (*pa) is set
  179940. ** to point to the sub-position-list for that column and the number of
  179941. ** bytes in it returned. Or, if the argument position list does not
  179942. ** contain any entries for column iCol, return 0.
  179943. */
  179944. static int fts5IndexExtractCol(
  179945. const u8 **pa, /* IN/OUT: Pointer to poslist */
  179946. int n, /* IN: Size of poslist in bytes */
  179947. int iCol /* Column to extract from poslist */
  179948. ){
  179949. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  179950. const u8 *p = *pa;
  179951. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  179952. while( iCol>iCurrent ){
  179953. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  179954. ** not part of a varint. Note that it is not possible for a negative
  179955. ** or extremely large varint to occur within an uncorrupted position
  179956. ** list. So the last byte of each varint may be assumed to have a clear
  179957. ** 0x80 bit. */
  179958. while( *p!=0x01 ){
  179959. while( *p++ & 0x80 );
  179960. if( p>=pEnd ) return 0;
  179961. }
  179962. *pa = p++;
  179963. iCurrent = *p++;
  179964. if( iCurrent & 0x80 ){
  179965. p--;
  179966. p += fts5GetVarint32(p, iCurrent);
  179967. }
  179968. }
  179969. if( iCol!=iCurrent ) return 0;
  179970. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  179971. ** not part of a varint */
  179972. while( p<pEnd && *p!=0x01 ){
  179973. while( *p++ & 0x80 );
  179974. }
  179975. return p - (*pa);
  179976. }
  179977. static void fts5IndexExtractColset(
  179978. int *pRc,
  179979. Fts5Colset *pColset, /* Colset to filter on */
  179980. const u8 *pPos, int nPos, /* Position list */
  179981. Fts5Buffer *pBuf /* Output buffer */
  179982. ){
  179983. if( *pRc==SQLITE_OK ){
  179984. int i;
  179985. fts5BufferZero(pBuf);
  179986. for(i=0; i<pColset->nCol; i++){
  179987. const u8 *pSub = pPos;
  179988. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  179989. if( nSub ){
  179990. fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
  179991. }
  179992. }
  179993. }
  179994. }
  179995. /*
  179996. ** xSetOutputs callback used by detail=none tables.
  179997. */
  179998. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  179999. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  180000. pIter->base.iRowid = pSeg->iRowid;
  180001. pIter->base.nData = pSeg->nPos;
  180002. }
  180003. /*
  180004. ** xSetOutputs callback used by detail=full and detail=col tables when no
  180005. ** column filters are specified.
  180006. */
  180007. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180008. pIter->base.iRowid = pSeg->iRowid;
  180009. pIter->base.nData = pSeg->nPos;
  180010. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  180011. assert( pIter->pColset==0 );
  180012. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  180013. /* All data is stored on the current page. Populate the output
  180014. ** variables to point into the body of the page object. */
  180015. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  180016. }else{
  180017. /* The data is distributed over two or more pages. Copy it into the
  180018. ** Fts5Iter.poslist buffer and then set the output pointer to point
  180019. ** to this buffer. */
  180020. fts5BufferZero(&pIter->poslist);
  180021. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  180022. pIter->base.pData = pIter->poslist.p;
  180023. }
  180024. }
  180025. /*
  180026. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  180027. ** against no columns at all).
  180028. */
  180029. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180030. UNUSED_PARAM(pSeg);
  180031. pIter->base.nData = 0;
  180032. }
  180033. /*
  180034. ** xSetOutputs callback used by detail=col when there is a column filter
  180035. ** and there are 100 or more columns. Also called as a fallback from
  180036. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  180037. */
  180038. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180039. fts5BufferZero(&pIter->poslist);
  180040. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  180041. pIter->base.iRowid = pSeg->iRowid;
  180042. pIter->base.pData = pIter->poslist.p;
  180043. pIter->base.nData = pIter->poslist.n;
  180044. }
  180045. /*
  180046. ** xSetOutputs callback used when:
  180047. **
  180048. ** * detail=col,
  180049. ** * there is a column filter, and
  180050. ** * the table contains 100 or fewer columns.
  180051. **
  180052. ** The last point is to ensure all column numbers are stored as
  180053. ** single-byte varints.
  180054. */
  180055. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180056. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  180057. assert( pIter->pColset );
  180058. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  180059. fts5IterSetOutputs_Col(pIter, pSeg);
  180060. }else{
  180061. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  180062. u8 *pEnd = (u8*)&a[pSeg->nPos];
  180063. int iPrev = 0;
  180064. int *aiCol = pIter->pColset->aiCol;
  180065. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  180066. u8 *aOut = pIter->poslist.p;
  180067. int iPrevOut = 0;
  180068. pIter->base.iRowid = pSeg->iRowid;
  180069. while( a<pEnd ){
  180070. iPrev += (int)a++[0] - 2;
  180071. while( *aiCol<iPrev ){
  180072. aiCol++;
  180073. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  180074. }
  180075. if( *aiCol==iPrev ){
  180076. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  180077. iPrevOut = iPrev;
  180078. }
  180079. }
  180080. setoutputs_col_out:
  180081. pIter->base.pData = pIter->poslist.p;
  180082. pIter->base.nData = aOut - pIter->poslist.p;
  180083. }
  180084. }
  180085. /*
  180086. ** xSetOutputs callback used by detail=full when there is a column filter.
  180087. */
  180088. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180089. Fts5Colset *pColset = pIter->pColset;
  180090. pIter->base.iRowid = pSeg->iRowid;
  180091. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  180092. assert( pColset );
  180093. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  180094. /* All data is stored on the current page. Populate the output
  180095. ** variables to point into the body of the page object. */
  180096. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  180097. if( pColset->nCol==1 ){
  180098. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  180099. pIter->base.pData = a;
  180100. }else{
  180101. int *pRc = &pIter->pIndex->rc;
  180102. fts5BufferZero(&pIter->poslist);
  180103. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
  180104. pIter->base.pData = pIter->poslist.p;
  180105. pIter->base.nData = pIter->poslist.n;
  180106. }
  180107. }else{
  180108. /* The data is distributed over two or more pages. Copy it into the
  180109. ** Fts5Iter.poslist buffer and then set the output pointer to point
  180110. ** to this buffer. */
  180111. fts5BufferZero(&pIter->poslist);
  180112. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  180113. pIter->base.pData = pIter->poslist.p;
  180114. pIter->base.nData = pIter->poslist.n;
  180115. }
  180116. }
  180117. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  180118. if( *pRc==SQLITE_OK ){
  180119. Fts5Config *pConfig = pIter->pIndex->pConfig;
  180120. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  180121. pIter->xSetOutputs = fts5IterSetOutputs_None;
  180122. }
  180123. else if( pIter->pColset==0 ){
  180124. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  180125. }
  180126. else if( pIter->pColset->nCol==0 ){
  180127. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  180128. }
  180129. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  180130. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  180131. }
  180132. else{
  180133. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  180134. if( pConfig->nCol<=100 ){
  180135. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  180136. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  180137. }else{
  180138. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  180139. }
  180140. }
  180141. }
  180142. }
  180143. /*
  180144. ** Allocate a new Fts5Iter object.
  180145. **
  180146. ** The new object will be used to iterate through data in structure pStruct.
  180147. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  180148. ** is zero or greater, data from the first nSegment segments on level iLevel
  180149. ** is merged.
  180150. **
  180151. ** The iterator initially points to the first term/rowid entry in the
  180152. ** iterated data.
  180153. */
  180154. static void fts5MultiIterNew(
  180155. Fts5Index *p, /* FTS5 backend to iterate within */
  180156. Fts5Structure *pStruct, /* Structure of specific index */
  180157. int flags, /* FTS5INDEX_QUERY_XXX flags */
  180158. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  180159. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  180160. int iLevel, /* Level to iterate (-1 for all) */
  180161. int nSegment, /* Number of segments to merge (iLevel>=0) */
  180162. Fts5Iter **ppOut /* New object */
  180163. ){
  180164. int nSeg = 0; /* Number of segment-iters in use */
  180165. int iIter = 0; /* */
  180166. int iSeg; /* Used to iterate through segments */
  180167. Fts5StructureLevel *pLvl;
  180168. Fts5Iter *pNew;
  180169. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  180170. /* Allocate space for the new multi-seg-iterator. */
  180171. if( p->rc==SQLITE_OK ){
  180172. if( iLevel<0 ){
  180173. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  180174. nSeg = pStruct->nSegment;
  180175. nSeg += (p->pHash ? 1 : 0);
  180176. }else{
  180177. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  180178. }
  180179. }
  180180. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  180181. if( pNew==0 ) return;
  180182. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  180183. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  180184. pNew->pStruct = pStruct;
  180185. pNew->pColset = pColset;
  180186. fts5StructureRef(pStruct);
  180187. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  180188. fts5IterSetOutputCb(&p->rc, pNew);
  180189. }
  180190. /* Initialize each of the component segment iterators. */
  180191. if( p->rc==SQLITE_OK ){
  180192. if( iLevel<0 ){
  180193. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  180194. if( p->pHash ){
  180195. /* Add a segment iterator for the current contents of the hash table. */
  180196. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  180197. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  180198. }
  180199. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  180200. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  180201. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  180202. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  180203. if( pTerm==0 ){
  180204. fts5SegIterInit(p, pSeg, pIter);
  180205. }else{
  180206. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  180207. }
  180208. }
  180209. }
  180210. }else{
  180211. pLvl = &pStruct->aLevel[iLevel];
  180212. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  180213. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  180214. }
  180215. }
  180216. assert( iIter==nSeg );
  180217. }
  180218. /* If the above was successful, each component iterators now points
  180219. ** to the first entry in its segment. In this case initialize the
  180220. ** aFirst[] array. Or, if an error has occurred, free the iterator
  180221. ** object and set the output variable to NULL. */
  180222. if( p->rc==SQLITE_OK ){
  180223. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  180224. int iEq;
  180225. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  180226. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  180227. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  180228. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  180229. }
  180230. }
  180231. fts5MultiIterSetEof(pNew);
  180232. fts5AssertMultiIterSetup(p, pNew);
  180233. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  180234. fts5MultiIterNext(p, pNew, 0, 0);
  180235. }else if( pNew->base.bEof==0 ){
  180236. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  180237. pNew->xSetOutputs(pNew, pSeg);
  180238. }
  180239. }else{
  180240. fts5MultiIterFree(pNew);
  180241. *ppOut = 0;
  180242. }
  180243. }
  180244. /*
  180245. ** Create an Fts5Iter that iterates through the doclist provided
  180246. ** as the second argument.
  180247. */
  180248. static void fts5MultiIterNew2(
  180249. Fts5Index *p, /* FTS5 backend to iterate within */
  180250. Fts5Data *pData, /* Doclist to iterate through */
  180251. int bDesc, /* True for descending rowid order */
  180252. Fts5Iter **ppOut /* New object */
  180253. ){
  180254. Fts5Iter *pNew;
  180255. pNew = fts5MultiIterAlloc(p, 2);
  180256. if( pNew ){
  180257. Fts5SegIter *pIter = &pNew->aSeg[1];
  180258. pIter->flags = FTS5_SEGITER_ONETERM;
  180259. if( pData->szLeaf>0 ){
  180260. pIter->pLeaf = pData;
  180261. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  180262. pIter->iEndofDoclist = pData->nn;
  180263. pNew->aFirst[1].iFirst = 1;
  180264. if( bDesc ){
  180265. pNew->bRev = 1;
  180266. pIter->flags |= FTS5_SEGITER_REVERSE;
  180267. fts5SegIterReverseInitPage(p, pIter);
  180268. }else{
  180269. fts5SegIterLoadNPos(p, pIter);
  180270. }
  180271. pData = 0;
  180272. }else{
  180273. pNew->base.bEof = 1;
  180274. }
  180275. fts5SegIterSetNext(p, pIter);
  180276. *ppOut = pNew;
  180277. }
  180278. fts5DataRelease(pData);
  180279. }
  180280. /*
  180281. ** Return true if the iterator is at EOF or if an error has occurred.
  180282. ** False otherwise.
  180283. */
  180284. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  180285. assert( p->rc
  180286. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  180287. );
  180288. return (p->rc || pIter->base.bEof);
  180289. }
  180290. /*
  180291. ** Return the rowid of the entry that the iterator currently points
  180292. ** to. If the iterator points to EOF when this function is called the
  180293. ** results are undefined.
  180294. */
  180295. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  180296. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  180297. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  180298. }
  180299. /*
  180300. ** Move the iterator to the next entry at or following iMatch.
  180301. */
  180302. static void fts5MultiIterNextFrom(
  180303. Fts5Index *p,
  180304. Fts5Iter *pIter,
  180305. i64 iMatch
  180306. ){
  180307. while( 1 ){
  180308. i64 iRowid;
  180309. fts5MultiIterNext(p, pIter, 1, iMatch);
  180310. if( fts5MultiIterEof(p, pIter) ) break;
  180311. iRowid = fts5MultiIterRowid(pIter);
  180312. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  180313. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  180314. }
  180315. }
  180316. /*
  180317. ** Return a pointer to a buffer containing the term associated with the
  180318. ** entry that the iterator currently points to.
  180319. */
  180320. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  180321. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  180322. *pn = p->term.n;
  180323. return p->term.p;
  180324. }
  180325. /*
  180326. ** Allocate a new segment-id for the structure pStruct. The new segment
  180327. ** id must be between 1 and 65335 inclusive, and must not be used by
  180328. ** any currently existing segment. If a free segment id cannot be found,
  180329. ** SQLITE_FULL is returned.
  180330. **
  180331. ** If an error has already occurred, this function is a no-op. 0 is
  180332. ** returned in this case.
  180333. */
  180334. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  180335. int iSegid = 0;
  180336. if( p->rc==SQLITE_OK ){
  180337. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  180338. p->rc = SQLITE_FULL;
  180339. }else{
  180340. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  180341. ** array is 63 elements, or 252 bytes, in size. */
  180342. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  180343. int iLvl, iSeg;
  180344. int i;
  180345. u32 mask;
  180346. memset(aUsed, 0, sizeof(aUsed));
  180347. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  180348. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  180349. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  180350. if( iId<=FTS5_MAX_SEGMENT ){
  180351. aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
  180352. }
  180353. }
  180354. }
  180355. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  180356. mask = aUsed[i];
  180357. for(iSegid=0; mask & (1 << iSegid); iSegid++);
  180358. iSegid += 1 + i*32;
  180359. #ifdef SQLITE_DEBUG
  180360. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  180361. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  180362. assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  180363. }
  180364. }
  180365. assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  180366. {
  180367. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  180368. if( p->rc==SQLITE_OK ){
  180369. u8 aBlob[2] = {0xff, 0xff};
  180370. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  180371. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  180372. assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  180373. p->rc = sqlite3_reset(pIdxSelect);
  180374. }
  180375. }
  180376. #endif
  180377. }
  180378. }
  180379. return iSegid;
  180380. }
  180381. /*
  180382. ** Discard all data currently cached in the hash-tables.
  180383. */
  180384. static void fts5IndexDiscardData(Fts5Index *p){
  180385. assert( p->pHash || p->nPendingData==0 );
  180386. if( p->pHash ){
  180387. sqlite3Fts5HashClear(p->pHash);
  180388. p->nPendingData = 0;
  180389. }
  180390. }
  180391. /*
  180392. ** Return the size of the prefix, in bytes, that buffer
  180393. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  180394. **
  180395. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  180396. ** than buffer (pOld/nOld).
  180397. */
  180398. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  180399. int i;
  180400. for(i=0; i<nOld; i++){
  180401. if( pOld[i]!=pNew[i] ) break;
  180402. }
  180403. return i;
  180404. }
  180405. static void fts5WriteDlidxClear(
  180406. Fts5Index *p,
  180407. Fts5SegWriter *pWriter,
  180408. int bFlush /* If true, write dlidx to disk */
  180409. ){
  180410. int i;
  180411. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  180412. for(i=0; i<pWriter->nDlidx; i++){
  180413. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  180414. if( pDlidx->buf.n==0 ) break;
  180415. if( bFlush ){
  180416. assert( pDlidx->pgno!=0 );
  180417. fts5DataWrite(p,
  180418. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  180419. pDlidx->buf.p, pDlidx->buf.n
  180420. );
  180421. }
  180422. sqlite3Fts5BufferZero(&pDlidx->buf);
  180423. pDlidx->bPrevValid = 0;
  180424. }
  180425. }
  180426. /*
  180427. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  180428. ** Any new array elements are zeroed before returning.
  180429. */
  180430. static int fts5WriteDlidxGrow(
  180431. Fts5Index *p,
  180432. Fts5SegWriter *pWriter,
  180433. int nLvl
  180434. ){
  180435. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  180436. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
  180437. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  180438. );
  180439. if( aDlidx==0 ){
  180440. p->rc = SQLITE_NOMEM;
  180441. }else{
  180442. int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  180443. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  180444. pWriter->aDlidx = aDlidx;
  180445. pWriter->nDlidx = nLvl;
  180446. }
  180447. }
  180448. return p->rc;
  180449. }
  180450. /*
  180451. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  180452. ** enough, flush it to disk and return 1. Otherwise discard it and return
  180453. ** zero.
  180454. */
  180455. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  180456. int bFlag = 0;
  180457. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  180458. ** to the database, also write the doclist-index to disk. */
  180459. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  180460. bFlag = 1;
  180461. }
  180462. fts5WriteDlidxClear(p, pWriter, bFlag);
  180463. pWriter->nEmpty = 0;
  180464. return bFlag;
  180465. }
  180466. /*
  180467. ** This function is called whenever processing of the doclist for the
  180468. ** last term on leaf page (pWriter->iBtPage) is completed.
  180469. **
  180470. ** The doclist-index for that term is currently stored in-memory within the
  180471. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  180472. ** writes it out to disk. Or, if it is too small to bother with, discards
  180473. ** it.
  180474. **
  180475. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  180476. */
  180477. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  180478. int bFlag;
  180479. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  180480. if( pWriter->iBtPage==0 ) return;
  180481. bFlag = fts5WriteFlushDlidx(p, pWriter);
  180482. if( p->rc==SQLITE_OK ){
  180483. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  180484. /* The following was already done in fts5WriteInit(): */
  180485. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  180486. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  180487. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  180488. sqlite3_step(p->pIdxWriter);
  180489. p->rc = sqlite3_reset(p->pIdxWriter);
  180490. }
  180491. pWriter->iBtPage = 0;
  180492. }
  180493. /*
  180494. ** This is called once for each leaf page except the first that contains
  180495. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  180496. ** is larger than all terms written to earlier leaves, and equal to or
  180497. ** smaller than the first term on the new leaf.
  180498. **
  180499. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  180500. ** has already occurred when this function is called, it is a no-op.
  180501. */
  180502. static void fts5WriteBtreeTerm(
  180503. Fts5Index *p, /* FTS5 backend object */
  180504. Fts5SegWriter *pWriter, /* Writer object */
  180505. int nTerm, const u8 *pTerm /* First term on new page */
  180506. ){
  180507. fts5WriteFlushBtree(p, pWriter);
  180508. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  180509. pWriter->iBtPage = pWriter->writer.pgno;
  180510. }
  180511. /*
  180512. ** This function is called when flushing a leaf page that contains no
  180513. ** terms at all to disk.
  180514. */
  180515. static void fts5WriteBtreeNoTerm(
  180516. Fts5Index *p, /* FTS5 backend object */
  180517. Fts5SegWriter *pWriter /* Writer object */
  180518. ){
  180519. /* If there were no rowids on the leaf page either and the doclist-index
  180520. ** has already been started, append an 0x00 byte to it. */
  180521. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  180522. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  180523. assert( pDlidx->bPrevValid );
  180524. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  180525. }
  180526. /* Increment the "number of sequential leaves without a term" counter. */
  180527. pWriter->nEmpty++;
  180528. }
  180529. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  180530. i64 iRowid;
  180531. int iOff;
  180532. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  180533. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  180534. return iRowid;
  180535. }
  180536. /*
  180537. ** Rowid iRowid has just been appended to the current leaf page. It is the
  180538. ** first on the page. This function appends an appropriate entry to the current
  180539. ** doclist-index.
  180540. */
  180541. static void fts5WriteDlidxAppend(
  180542. Fts5Index *p,
  180543. Fts5SegWriter *pWriter,
  180544. i64 iRowid
  180545. ){
  180546. int i;
  180547. int bDone = 0;
  180548. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  180549. i64 iVal;
  180550. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  180551. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  180552. /* The current doclist-index page is full. Write it to disk and push
  180553. ** a copy of iRowid (which will become the first rowid on the next
  180554. ** doclist-index leaf page) up into the next level of the b-tree
  180555. ** hierarchy. If the node being flushed is currently the root node,
  180556. ** also push its first rowid upwards. */
  180557. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  180558. fts5DataWrite(p,
  180559. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  180560. pDlidx->buf.p, pDlidx->buf.n
  180561. );
  180562. fts5WriteDlidxGrow(p, pWriter, i+2);
  180563. pDlidx = &pWriter->aDlidx[i];
  180564. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  180565. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  180566. /* This was the root node. Push its first rowid up to the new root. */
  180567. pDlidx[1].pgno = pDlidx->pgno;
  180568. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  180569. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  180570. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  180571. pDlidx[1].bPrevValid = 1;
  180572. pDlidx[1].iPrev = iFirst;
  180573. }
  180574. sqlite3Fts5BufferZero(&pDlidx->buf);
  180575. pDlidx->bPrevValid = 0;
  180576. pDlidx->pgno++;
  180577. }else{
  180578. bDone = 1;
  180579. }
  180580. if( pDlidx->bPrevValid ){
  180581. iVal = iRowid - pDlidx->iPrev;
  180582. }else{
  180583. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  180584. assert( pDlidx->buf.n==0 );
  180585. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  180586. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  180587. iVal = iRowid;
  180588. }
  180589. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  180590. pDlidx->bPrevValid = 1;
  180591. pDlidx->iPrev = iRowid;
  180592. }
  180593. }
  180594. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  180595. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  180596. Fts5PageWriter *pPage = &pWriter->writer;
  180597. i64 iRowid;
  180598. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  180599. /* Set the szLeaf header field. */
  180600. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  180601. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  180602. if( pWriter->bFirstTermInPage ){
  180603. /* No term was written to this page. */
  180604. assert( pPage->pgidx.n==0 );
  180605. fts5WriteBtreeNoTerm(p, pWriter);
  180606. }else{
  180607. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  180608. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  180609. }
  180610. /* Write the page out to disk */
  180611. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  180612. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  180613. /* Initialize the next page. */
  180614. fts5BufferZero(&pPage->buf);
  180615. fts5BufferZero(&pPage->pgidx);
  180616. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  180617. pPage->iPrevPgidx = 0;
  180618. pPage->pgno++;
  180619. /* Increase the leaves written counter */
  180620. pWriter->nLeafWritten++;
  180621. /* The new leaf holds no terms or rowids */
  180622. pWriter->bFirstTermInPage = 1;
  180623. pWriter->bFirstRowidInPage = 1;
  180624. }
  180625. /*
  180626. ** Append term pTerm/nTerm to the segment being written by the writer passed
  180627. ** as the second argument.
  180628. **
  180629. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  180630. ** already occurred, this function is a no-op.
  180631. */
  180632. static void fts5WriteAppendTerm(
  180633. Fts5Index *p,
  180634. Fts5SegWriter *pWriter,
  180635. int nTerm, const u8 *pTerm
  180636. ){
  180637. int nPrefix; /* Bytes of prefix compression for term */
  180638. Fts5PageWriter *pPage = &pWriter->writer;
  180639. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  180640. assert( p->rc==SQLITE_OK );
  180641. assert( pPage->buf.n>=4 );
  180642. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  180643. /* If the current leaf page is full, flush it to disk. */
  180644. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  180645. if( pPage->buf.n>4 ){
  180646. fts5WriteFlushLeaf(p, pWriter);
  180647. }
  180648. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  180649. }
  180650. /* TODO1: Updating pgidx here. */
  180651. pPgidx->n += sqlite3Fts5PutVarint(
  180652. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  180653. );
  180654. pPage->iPrevPgidx = pPage->buf.n;
  180655. #if 0
  180656. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  180657. pPgidx->n += 2;
  180658. #endif
  180659. if( pWriter->bFirstTermInPage ){
  180660. nPrefix = 0;
  180661. if( pPage->pgno!=1 ){
  180662. /* This is the first term on a leaf that is not the leftmost leaf in
  180663. ** the segment b-tree. In this case it is necessary to add a term to
  180664. ** the b-tree hierarchy that is (a) larger than the largest term
  180665. ** already written to the segment and (b) smaller than or equal to
  180666. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  180667. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  180668. ** previous term.
  180669. **
  180670. ** Usually, the previous term is available in pPage->term. The exception
  180671. ** is if this is the first term written in an incremental-merge step.
  180672. ** In this case the previous term is not available, so just write a
  180673. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  180674. ** inefficient, but still correct. */
  180675. int n = nTerm;
  180676. if( pPage->term.n ){
  180677. n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  180678. }
  180679. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  180680. pPage = &pWriter->writer;
  180681. }
  180682. }else{
  180683. nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  180684. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  180685. }
  180686. /* Append the number of bytes of new data, then the term data itself
  180687. ** to the page. */
  180688. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  180689. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  180690. /* Update the Fts5PageWriter.term field. */
  180691. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  180692. pWriter->bFirstTermInPage = 0;
  180693. pWriter->bFirstRowidInPage = 0;
  180694. pWriter->bFirstRowidInDoclist = 1;
  180695. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  180696. pWriter->aDlidx[0].pgno = pPage->pgno;
  180697. }
  180698. /*
  180699. ** Append a rowid and position-list size field to the writers output.
  180700. */
  180701. static void fts5WriteAppendRowid(
  180702. Fts5Index *p,
  180703. Fts5SegWriter *pWriter,
  180704. i64 iRowid
  180705. ){
  180706. if( p->rc==SQLITE_OK ){
  180707. Fts5PageWriter *pPage = &pWriter->writer;
  180708. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  180709. fts5WriteFlushLeaf(p, pWriter);
  180710. }
  180711. /* If this is to be the first rowid written to the page, set the
  180712. ** rowid-pointer in the page-header. Also append a value to the dlidx
  180713. ** buffer, in case a doclist-index is required. */
  180714. if( pWriter->bFirstRowidInPage ){
  180715. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  180716. fts5WriteDlidxAppend(p, pWriter, iRowid);
  180717. }
  180718. /* Write the rowid. */
  180719. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  180720. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  180721. }else{
  180722. assert( p->rc || iRowid>pWriter->iPrevRowid );
  180723. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  180724. }
  180725. pWriter->iPrevRowid = iRowid;
  180726. pWriter->bFirstRowidInDoclist = 0;
  180727. pWriter->bFirstRowidInPage = 0;
  180728. }
  180729. }
  180730. static void fts5WriteAppendPoslistData(
  180731. Fts5Index *p,
  180732. Fts5SegWriter *pWriter,
  180733. const u8 *aData,
  180734. int nData
  180735. ){
  180736. Fts5PageWriter *pPage = &pWriter->writer;
  180737. const u8 *a = aData;
  180738. int n = nData;
  180739. assert( p->pConfig->pgsz>0 );
  180740. while( p->rc==SQLITE_OK
  180741. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  180742. ){
  180743. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  180744. int nCopy = 0;
  180745. while( nCopy<nReq ){
  180746. i64 dummy;
  180747. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  180748. }
  180749. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  180750. a += nCopy;
  180751. n -= nCopy;
  180752. fts5WriteFlushLeaf(p, pWriter);
  180753. }
  180754. if( n>0 ){
  180755. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  180756. }
  180757. }
  180758. /*
  180759. ** Flush any data cached by the writer object to the database. Free any
  180760. ** allocations associated with the writer.
  180761. */
  180762. static void fts5WriteFinish(
  180763. Fts5Index *p,
  180764. Fts5SegWriter *pWriter, /* Writer object */
  180765. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  180766. ){
  180767. int i;
  180768. Fts5PageWriter *pLeaf = &pWriter->writer;
  180769. if( p->rc==SQLITE_OK ){
  180770. assert( pLeaf->pgno>=1 );
  180771. if( pLeaf->buf.n>4 ){
  180772. fts5WriteFlushLeaf(p, pWriter);
  180773. }
  180774. *pnLeaf = pLeaf->pgno-1;
  180775. if( pLeaf->pgno>1 ){
  180776. fts5WriteFlushBtree(p, pWriter);
  180777. }
  180778. }
  180779. fts5BufferFree(&pLeaf->term);
  180780. fts5BufferFree(&pLeaf->buf);
  180781. fts5BufferFree(&pLeaf->pgidx);
  180782. fts5BufferFree(&pWriter->btterm);
  180783. for(i=0; i<pWriter->nDlidx; i++){
  180784. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  180785. }
  180786. sqlite3_free(pWriter->aDlidx);
  180787. }
  180788. static void fts5WriteInit(
  180789. Fts5Index *p,
  180790. Fts5SegWriter *pWriter,
  180791. int iSegid
  180792. ){
  180793. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  180794. memset(pWriter, 0, sizeof(Fts5SegWriter));
  180795. pWriter->iSegid = iSegid;
  180796. fts5WriteDlidxGrow(p, pWriter, 1);
  180797. pWriter->writer.pgno = 1;
  180798. pWriter->bFirstTermInPage = 1;
  180799. pWriter->iBtPage = 1;
  180800. assert( pWriter->writer.buf.n==0 );
  180801. assert( pWriter->writer.pgidx.n==0 );
  180802. /* Grow the two buffers to pgsz + padding bytes in size. */
  180803. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  180804. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  180805. if( p->pIdxWriter==0 ){
  180806. Fts5Config *pConfig = p->pConfig;
  180807. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  180808. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  180809. pConfig->zDb, pConfig->zName
  180810. ));
  180811. }
  180812. if( p->rc==SQLITE_OK ){
  180813. /* Initialize the 4-byte leaf-page header to 0x00. */
  180814. memset(pWriter->writer.buf.p, 0, 4);
  180815. pWriter->writer.buf.n = 4;
  180816. /* Bind the current output segment id to the index-writer. This is an
  180817. ** optimization over binding the same value over and over as rows are
  180818. ** inserted into %_idx by the current writer. */
  180819. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  180820. }
  180821. }
  180822. /*
  180823. ** Iterator pIter was used to iterate through the input segments of on an
  180824. ** incremental merge operation. This function is called if the incremental
  180825. ** merge step has finished but the input has not been completely exhausted.
  180826. */
  180827. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  180828. int i;
  180829. Fts5Buffer buf;
  180830. memset(&buf, 0, sizeof(Fts5Buffer));
  180831. for(i=0; i<pIter->nSeg; i++){
  180832. Fts5SegIter *pSeg = &pIter->aSeg[i];
  180833. if( pSeg->pSeg==0 ){
  180834. /* no-op */
  180835. }else if( pSeg->pLeaf==0 ){
  180836. /* All keys from this input segment have been transfered to the output.
  180837. ** Set both the first and last page-numbers to 0 to indicate that the
  180838. ** segment is now empty. */
  180839. pSeg->pSeg->pgnoLast = 0;
  180840. pSeg->pSeg->pgnoFirst = 0;
  180841. }else{
  180842. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  180843. i64 iLeafRowid;
  180844. Fts5Data *pData;
  180845. int iId = pSeg->pSeg->iSegid;
  180846. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  180847. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  180848. pData = fts5DataRead(p, iLeafRowid);
  180849. if( pData ){
  180850. fts5BufferZero(&buf);
  180851. fts5BufferGrow(&p->rc, &buf, pData->nn);
  180852. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  180853. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  180854. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  180855. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
  180856. if( p->rc==SQLITE_OK ){
  180857. /* Set the szLeaf field */
  180858. fts5PutU16(&buf.p[2], (u16)buf.n);
  180859. }
  180860. /* Set up the new page-index array */
  180861. fts5BufferAppendVarint(&p->rc, &buf, 4);
  180862. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  180863. && pSeg->iEndofDoclist<pData->szLeaf
  180864. ){
  180865. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  180866. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  180867. fts5BufferAppendBlob(&p->rc, &buf,
  180868. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  180869. );
  180870. }
  180871. fts5DataRelease(pData);
  180872. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  180873. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  180874. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  180875. }
  180876. }
  180877. }
  180878. fts5BufferFree(&buf);
  180879. }
  180880. static void fts5MergeChunkCallback(
  180881. Fts5Index *p,
  180882. void *pCtx,
  180883. const u8 *pChunk, int nChunk
  180884. ){
  180885. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  180886. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  180887. }
  180888. /*
  180889. **
  180890. */
  180891. static void fts5IndexMergeLevel(
  180892. Fts5Index *p, /* FTS5 backend object */
  180893. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  180894. int iLvl, /* Level to read input from */
  180895. int *pnRem /* Write up to this many output leaves */
  180896. ){
  180897. Fts5Structure *pStruct = *ppStruct;
  180898. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  180899. Fts5StructureLevel *pLvlOut;
  180900. Fts5Iter *pIter = 0; /* Iterator to read input data */
  180901. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  180902. int nInput; /* Number of input segments */
  180903. Fts5SegWriter writer; /* Writer object */
  180904. Fts5StructureSegment *pSeg; /* Output segment */
  180905. Fts5Buffer term;
  180906. int bOldest; /* True if the output segment is the oldest */
  180907. int eDetail = p->pConfig->eDetail;
  180908. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  180909. int bTermWritten = 0; /* True if current term already output */
  180910. assert( iLvl<pStruct->nLevel );
  180911. assert( pLvl->nMerge<=pLvl->nSeg );
  180912. memset(&writer, 0, sizeof(Fts5SegWriter));
  180913. memset(&term, 0, sizeof(Fts5Buffer));
  180914. if( pLvl->nMerge ){
  180915. pLvlOut = &pStruct->aLevel[iLvl+1];
  180916. assert( pLvlOut->nSeg>0 );
  180917. nInput = pLvl->nMerge;
  180918. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  180919. fts5WriteInit(p, &writer, pSeg->iSegid);
  180920. writer.writer.pgno = pSeg->pgnoLast+1;
  180921. writer.iBtPage = 0;
  180922. }else{
  180923. int iSegid = fts5AllocateSegid(p, pStruct);
  180924. /* Extend the Fts5Structure object as required to ensure the output
  180925. ** segment exists. */
  180926. if( iLvl==pStruct->nLevel-1 ){
  180927. fts5StructureAddLevel(&p->rc, ppStruct);
  180928. pStruct = *ppStruct;
  180929. }
  180930. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  180931. if( p->rc ) return;
  180932. pLvl = &pStruct->aLevel[iLvl];
  180933. pLvlOut = &pStruct->aLevel[iLvl+1];
  180934. fts5WriteInit(p, &writer, iSegid);
  180935. /* Add the new segment to the output level */
  180936. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  180937. pLvlOut->nSeg++;
  180938. pSeg->pgnoFirst = 1;
  180939. pSeg->iSegid = iSegid;
  180940. pStruct->nSegment++;
  180941. /* Read input from all segments in the input level */
  180942. nInput = pLvl->nSeg;
  180943. }
  180944. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  180945. assert( iLvl>=0 );
  180946. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  180947. fts5MultiIterEof(p, pIter)==0;
  180948. fts5MultiIterNext(p, pIter, 0, 0)
  180949. ){
  180950. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  180951. int nPos; /* position-list size field value */
  180952. int nTerm;
  180953. const u8 *pTerm;
  180954. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  180955. if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
  180956. if( pnRem && writer.nLeafWritten>nRem ){
  180957. break;
  180958. }
  180959. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  180960. bTermWritten =0;
  180961. }
  180962. /* Check for key annihilation. */
  180963. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  180964. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  180965. /* This is a new term. Append a term to the output segment. */
  180966. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  180967. bTermWritten = 1;
  180968. }
  180969. /* Append the rowid to the output */
  180970. /* WRITEPOSLISTSIZE */
  180971. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  180972. if( eDetail==FTS5_DETAIL_NONE ){
  180973. if( pSegIter->bDel ){
  180974. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  180975. if( pSegIter->nPos>0 ){
  180976. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  180977. }
  180978. }
  180979. }else{
  180980. /* Append the position-list data to the output */
  180981. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  180982. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  180983. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  180984. }
  180985. }
  180986. /* Flush the last leaf page to disk. Set the output segment b-tree height
  180987. ** and last leaf page number at the same time. */
  180988. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  180989. if( fts5MultiIterEof(p, pIter) ){
  180990. int i;
  180991. /* Remove the redundant segments from the %_data table */
  180992. for(i=0; i<nInput; i++){
  180993. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  180994. }
  180995. /* Remove the redundant segments from the input level */
  180996. if( pLvl->nSeg!=nInput ){
  180997. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  180998. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  180999. }
  181000. pStruct->nSegment -= nInput;
  181001. pLvl->nSeg -= nInput;
  181002. pLvl->nMerge = 0;
  181003. if( pSeg->pgnoLast==0 ){
  181004. pLvlOut->nSeg--;
  181005. pStruct->nSegment--;
  181006. }
  181007. }else{
  181008. assert( pSeg->pgnoLast>0 );
  181009. fts5TrimSegments(p, pIter);
  181010. pLvl->nMerge = nInput;
  181011. }
  181012. fts5MultiIterFree(pIter);
  181013. fts5BufferFree(&term);
  181014. if( pnRem ) *pnRem -= writer.nLeafWritten;
  181015. }
  181016. /*
  181017. ** Do up to nPg pages of automerge work on the index.
  181018. **
  181019. ** Return true if any changes were actually made, or false otherwise.
  181020. */
  181021. static int fts5IndexMerge(
  181022. Fts5Index *p, /* FTS5 backend object */
  181023. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  181024. int nPg, /* Pages of work to do */
  181025. int nMin /* Minimum number of segments to merge */
  181026. ){
  181027. int nRem = nPg;
  181028. int bRet = 0;
  181029. Fts5Structure *pStruct = *ppStruct;
  181030. while( nRem>0 && p->rc==SQLITE_OK ){
  181031. int iLvl; /* To iterate through levels */
  181032. int iBestLvl = 0; /* Level offering the most input segments */
  181033. int nBest = 0; /* Number of input segments on best level */
  181034. /* Set iBestLvl to the level to read input segments from. */
  181035. assert( pStruct->nLevel>0 );
  181036. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  181037. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  181038. if( pLvl->nMerge ){
  181039. if( pLvl->nMerge>nBest ){
  181040. iBestLvl = iLvl;
  181041. nBest = pLvl->nMerge;
  181042. }
  181043. break;
  181044. }
  181045. if( pLvl->nSeg>nBest ){
  181046. nBest = pLvl->nSeg;
  181047. iBestLvl = iLvl;
  181048. }
  181049. }
  181050. /* If nBest is still 0, then the index must be empty. */
  181051. #ifdef SQLITE_DEBUG
  181052. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  181053. assert( pStruct->aLevel[iLvl].nSeg==0 );
  181054. }
  181055. #endif
  181056. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  181057. break;
  181058. }
  181059. bRet = 1;
  181060. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  181061. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  181062. fts5StructurePromote(p, iBestLvl+1, pStruct);
  181063. }
  181064. }
  181065. *ppStruct = pStruct;
  181066. return bRet;
  181067. }
  181068. /*
  181069. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  181070. ** segment. This function updates the write-counter accordingly and, if
  181071. ** necessary, performs incremental merge work.
  181072. **
  181073. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  181074. ** already occurred, this function is a no-op.
  181075. */
  181076. static void fts5IndexAutomerge(
  181077. Fts5Index *p, /* FTS5 backend object */
  181078. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  181079. int nLeaf /* Number of output leaves just written */
  181080. ){
  181081. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  181082. Fts5Structure *pStruct = *ppStruct;
  181083. u64 nWrite; /* Initial value of write-counter */
  181084. int nWork; /* Number of work-quanta to perform */
  181085. int nRem; /* Number of leaf pages left to write */
  181086. /* Update the write-counter. While doing so, set nWork. */
  181087. nWrite = pStruct->nWriteCounter;
  181088. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  181089. pStruct->nWriteCounter += nLeaf;
  181090. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  181091. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  181092. }
  181093. }
  181094. static void fts5IndexCrisismerge(
  181095. Fts5Index *p, /* FTS5 backend object */
  181096. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  181097. ){
  181098. const int nCrisis = p->pConfig->nCrisisMerge;
  181099. Fts5Structure *pStruct = *ppStruct;
  181100. int iLvl = 0;
  181101. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  181102. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  181103. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  181104. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  181105. fts5StructurePromote(p, iLvl+1, pStruct);
  181106. iLvl++;
  181107. }
  181108. *ppStruct = pStruct;
  181109. }
  181110. static int fts5IndexReturn(Fts5Index *p){
  181111. int rc = p->rc;
  181112. p->rc = SQLITE_OK;
  181113. return rc;
  181114. }
  181115. typedef struct Fts5FlushCtx Fts5FlushCtx;
  181116. struct Fts5FlushCtx {
  181117. Fts5Index *pIdx;
  181118. Fts5SegWriter writer;
  181119. };
  181120. /*
  181121. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  181122. ** in a 32-bit integer. Return the size of the largest prefix of this
  181123. ** list nMax bytes or less in size.
  181124. */
  181125. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  181126. int ret;
  181127. u32 dummy;
  181128. ret = fts5GetVarint32(aBuf, dummy);
  181129. if( ret<nMax ){
  181130. while( 1 ){
  181131. int i = fts5GetVarint32(&aBuf[ret], dummy);
  181132. if( (ret + i) > nMax ) break;
  181133. ret += i;
  181134. }
  181135. }
  181136. return ret;
  181137. }
  181138. /*
  181139. ** Flush the contents of in-memory hash table iHash to a new level-0
  181140. ** segment on disk. Also update the corresponding structure record.
  181141. **
  181142. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  181143. ** already occurred, this function is a no-op.
  181144. */
  181145. static void fts5FlushOneHash(Fts5Index *p){
  181146. Fts5Hash *pHash = p->pHash;
  181147. Fts5Structure *pStruct;
  181148. int iSegid;
  181149. int pgnoLast = 0; /* Last leaf page number in segment */
  181150. /* Obtain a reference to the index structure and allocate a new segment-id
  181151. ** for the new level-0 segment. */
  181152. pStruct = fts5StructureRead(p);
  181153. iSegid = fts5AllocateSegid(p, pStruct);
  181154. fts5StructureInvalidate(p);
  181155. if( iSegid ){
  181156. const int pgsz = p->pConfig->pgsz;
  181157. int eDetail = p->pConfig->eDetail;
  181158. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  181159. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  181160. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  181161. Fts5SegWriter writer;
  181162. fts5WriteInit(p, &writer, iSegid);
  181163. pBuf = &writer.writer.buf;
  181164. pPgidx = &writer.writer.pgidx;
  181165. /* fts5WriteInit() should have initialized the buffers to (most likely)
  181166. ** the maximum space required. */
  181167. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  181168. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  181169. /* Begin scanning through hash table entries. This loop runs once for each
  181170. ** term/doclist currently stored within the hash table. */
  181171. if( p->rc==SQLITE_OK ){
  181172. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  181173. }
  181174. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  181175. const char *zTerm; /* Buffer containing term */
  181176. const u8 *pDoclist; /* Pointer to doclist for this term */
  181177. int nDoclist; /* Size of doclist in bytes */
  181178. /* Write the term for this entry to disk. */
  181179. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  181180. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  181181. assert( writer.bFirstRowidInPage==0 );
  181182. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  181183. /* The entire doclist will fit on the current leaf. */
  181184. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  181185. }else{
  181186. i64 iRowid = 0;
  181187. i64 iDelta = 0;
  181188. int iOff = 0;
  181189. /* The entire doclist will not fit on this leaf. The following
  181190. ** loop iterates through the poslists that make up the current
  181191. ** doclist. */
  181192. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  181193. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  181194. iRowid += iDelta;
  181195. if( writer.bFirstRowidInPage ){
  181196. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  181197. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  181198. writer.bFirstRowidInPage = 0;
  181199. fts5WriteDlidxAppend(p, &writer, iRowid);
  181200. }else{
  181201. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  181202. }
  181203. assert( pBuf->n<=pBuf->nSpace );
  181204. if( eDetail==FTS5_DETAIL_NONE ){
  181205. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  181206. pBuf->p[pBuf->n++] = 0;
  181207. iOff++;
  181208. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  181209. pBuf->p[pBuf->n++] = 0;
  181210. iOff++;
  181211. }
  181212. }
  181213. if( (pBuf->n + pPgidx->n)>=pgsz ){
  181214. fts5WriteFlushLeaf(p, &writer);
  181215. }
  181216. }else{
  181217. int bDummy;
  181218. int nPos;
  181219. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  181220. nCopy += nPos;
  181221. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  181222. /* The entire poslist will fit on the current leaf. So copy
  181223. ** it in one go. */
  181224. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  181225. }else{
  181226. /* The entire poslist will not fit on this leaf. So it needs
  181227. ** to be broken into sections. The only qualification being
  181228. ** that each varint must be stored contiguously. */
  181229. const u8 *pPoslist = &pDoclist[iOff];
  181230. int iPos = 0;
  181231. while( p->rc==SQLITE_OK ){
  181232. int nSpace = pgsz - pBuf->n - pPgidx->n;
  181233. int n = 0;
  181234. if( (nCopy - iPos)<=nSpace ){
  181235. n = nCopy - iPos;
  181236. }else{
  181237. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  181238. }
  181239. assert( n>0 );
  181240. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  181241. iPos += n;
  181242. if( (pBuf->n + pPgidx->n)>=pgsz ){
  181243. fts5WriteFlushLeaf(p, &writer);
  181244. }
  181245. if( iPos>=nCopy ) break;
  181246. }
  181247. }
  181248. iOff += nCopy;
  181249. }
  181250. }
  181251. }
  181252. /* TODO2: Doclist terminator written here. */
  181253. /* pBuf->p[pBuf->n++] = '\0'; */
  181254. assert( pBuf->n<=pBuf->nSpace );
  181255. sqlite3Fts5HashScanNext(pHash);
  181256. }
  181257. sqlite3Fts5HashClear(pHash);
  181258. fts5WriteFinish(p, &writer, &pgnoLast);
  181259. /* Update the Fts5Structure. It is written back to the database by the
  181260. ** fts5StructureRelease() call below. */
  181261. if( pStruct->nLevel==0 ){
  181262. fts5StructureAddLevel(&p->rc, &pStruct);
  181263. }
  181264. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  181265. if( p->rc==SQLITE_OK ){
  181266. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  181267. pSeg->iSegid = iSegid;
  181268. pSeg->pgnoFirst = 1;
  181269. pSeg->pgnoLast = pgnoLast;
  181270. pStruct->nSegment++;
  181271. }
  181272. fts5StructurePromote(p, 0, pStruct);
  181273. }
  181274. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  181275. fts5IndexCrisismerge(p, &pStruct);
  181276. fts5StructureWrite(p, pStruct);
  181277. fts5StructureRelease(pStruct);
  181278. }
  181279. /*
  181280. ** Flush any data stored in the in-memory hash tables to the database.
  181281. */
  181282. static void fts5IndexFlush(Fts5Index *p){
  181283. /* Unless it is empty, flush the hash table to disk */
  181284. if( p->nPendingData ){
  181285. assert( p->pHash );
  181286. p->nPendingData = 0;
  181287. fts5FlushOneHash(p);
  181288. }
  181289. }
  181290. static Fts5Structure *fts5IndexOptimizeStruct(
  181291. Fts5Index *p,
  181292. Fts5Structure *pStruct
  181293. ){
  181294. Fts5Structure *pNew = 0;
  181295. int nByte = sizeof(Fts5Structure);
  181296. int nSeg = pStruct->nSegment;
  181297. int i;
  181298. /* Figure out if this structure requires optimization. A structure does
  181299. ** not require optimization if either:
  181300. **
  181301. ** + it consists of fewer than two segments, or
  181302. ** + all segments are on the same level, or
  181303. ** + all segments except one are currently inputs to a merge operation.
  181304. **
  181305. ** In the first case, return NULL. In the second, increment the ref-count
  181306. ** on *pStruct and return a copy of the pointer to it.
  181307. */
  181308. if( nSeg<2 ) return 0;
  181309. for(i=0; i<pStruct->nLevel; i++){
  181310. int nThis = pStruct->aLevel[i].nSeg;
  181311. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  181312. fts5StructureRef(pStruct);
  181313. return pStruct;
  181314. }
  181315. assert( pStruct->aLevel[i].nMerge<=nThis );
  181316. }
  181317. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  181318. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  181319. if( pNew ){
  181320. Fts5StructureLevel *pLvl;
  181321. nByte = nSeg * sizeof(Fts5StructureSegment);
  181322. pNew->nLevel = pStruct->nLevel+1;
  181323. pNew->nRef = 1;
  181324. pNew->nWriteCounter = pStruct->nWriteCounter;
  181325. pLvl = &pNew->aLevel[pStruct->nLevel];
  181326. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  181327. if( pLvl->aSeg ){
  181328. int iLvl, iSeg;
  181329. int iSegOut = 0;
  181330. /* Iterate through all segments, from oldest to newest. Add them to
  181331. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  181332. ** segment in the data structure. */
  181333. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  181334. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  181335. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  181336. iSegOut++;
  181337. }
  181338. }
  181339. pNew->nSegment = pLvl->nSeg = nSeg;
  181340. }else{
  181341. sqlite3_free(pNew);
  181342. pNew = 0;
  181343. }
  181344. }
  181345. return pNew;
  181346. }
  181347. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  181348. Fts5Structure *pStruct;
  181349. Fts5Structure *pNew = 0;
  181350. assert( p->rc==SQLITE_OK );
  181351. fts5IndexFlush(p);
  181352. pStruct = fts5StructureRead(p);
  181353. fts5StructureInvalidate(p);
  181354. if( pStruct ){
  181355. pNew = fts5IndexOptimizeStruct(p, pStruct);
  181356. }
  181357. fts5StructureRelease(pStruct);
  181358. assert( pNew==0 || pNew->nSegment>0 );
  181359. if( pNew ){
  181360. int iLvl;
  181361. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  181362. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  181363. int nRem = FTS5_OPT_WORK_UNIT;
  181364. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  181365. }
  181366. fts5StructureWrite(p, pNew);
  181367. fts5StructureRelease(pNew);
  181368. }
  181369. return fts5IndexReturn(p);
  181370. }
  181371. /*
  181372. ** This is called to implement the special "VALUES('merge', $nMerge)"
  181373. ** INSERT command.
  181374. */
  181375. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  181376. Fts5Structure *pStruct = fts5StructureRead(p);
  181377. if( pStruct ){
  181378. int nMin = p->pConfig->nUsermerge;
  181379. fts5StructureInvalidate(p);
  181380. if( nMerge<0 ){
  181381. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  181382. fts5StructureRelease(pStruct);
  181383. pStruct = pNew;
  181384. nMin = 2;
  181385. nMerge = nMerge*-1;
  181386. }
  181387. if( pStruct && pStruct->nLevel ){
  181388. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  181389. fts5StructureWrite(p, pStruct);
  181390. }
  181391. }
  181392. fts5StructureRelease(pStruct);
  181393. }
  181394. return fts5IndexReturn(p);
  181395. }
  181396. static void fts5AppendRowid(
  181397. Fts5Index *p,
  181398. i64 iDelta,
  181399. Fts5Iter *pUnused,
  181400. Fts5Buffer *pBuf
  181401. ){
  181402. UNUSED_PARAM(pUnused);
  181403. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  181404. }
  181405. static void fts5AppendPoslist(
  181406. Fts5Index *p,
  181407. i64 iDelta,
  181408. Fts5Iter *pMulti,
  181409. Fts5Buffer *pBuf
  181410. ){
  181411. int nData = pMulti->base.nData;
  181412. assert( nData>0 );
  181413. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
  181414. fts5BufferSafeAppendVarint(pBuf, iDelta);
  181415. fts5BufferSafeAppendVarint(pBuf, nData*2);
  181416. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  181417. }
  181418. }
  181419. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  181420. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  181421. assert( pIter->aPoslist );
  181422. if( p>=pIter->aEof ){
  181423. pIter->aPoslist = 0;
  181424. }else{
  181425. i64 iDelta;
  181426. p += fts5GetVarint(p, (u64*)&iDelta);
  181427. pIter->iRowid += iDelta;
  181428. /* Read position list size */
  181429. if( p[0] & 0x80 ){
  181430. int nPos;
  181431. pIter->nSize = fts5GetVarint32(p, nPos);
  181432. pIter->nPoslist = (nPos>>1);
  181433. }else{
  181434. pIter->nPoslist = ((int)(p[0])) >> 1;
  181435. pIter->nSize = 1;
  181436. }
  181437. pIter->aPoslist = p;
  181438. }
  181439. }
  181440. static void fts5DoclistIterInit(
  181441. Fts5Buffer *pBuf,
  181442. Fts5DoclistIter *pIter
  181443. ){
  181444. memset(pIter, 0, sizeof(*pIter));
  181445. pIter->aPoslist = pBuf->p;
  181446. pIter->aEof = &pBuf->p[pBuf->n];
  181447. fts5DoclistIterNext(pIter);
  181448. }
  181449. #if 0
  181450. /*
  181451. ** Append a doclist to buffer pBuf.
  181452. **
  181453. ** This function assumes that space within the buffer has already been
  181454. ** allocated.
  181455. */
  181456. static void fts5MergeAppendDocid(
  181457. Fts5Buffer *pBuf, /* Buffer to write to */
  181458. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  181459. i64 iRowid /* Rowid to append */
  181460. ){
  181461. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  181462. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  181463. *piLastRowid = iRowid;
  181464. }
  181465. #endif
  181466. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  181467. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  181468. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  181469. (iLastRowid) = (iRowid); \
  181470. }
  181471. /*
  181472. ** Swap the contents of buffer *p1 with that of *p2.
  181473. */
  181474. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  181475. Fts5Buffer tmp = *p1;
  181476. *p1 = *p2;
  181477. *p2 = tmp;
  181478. }
  181479. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  181480. int i = *piOff;
  181481. if( i>=pBuf->n ){
  181482. *piOff = -1;
  181483. }else{
  181484. u64 iVal;
  181485. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  181486. *piRowid += iVal;
  181487. }
  181488. }
  181489. /*
  181490. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  181491. ** In this case the buffers consist of a delta-encoded list of rowids only.
  181492. */
  181493. static void fts5MergeRowidLists(
  181494. Fts5Index *p, /* FTS5 backend object */
  181495. Fts5Buffer *p1, /* First list to merge */
  181496. Fts5Buffer *p2 /* Second list to merge */
  181497. ){
  181498. int i1 = 0;
  181499. int i2 = 0;
  181500. i64 iRowid1 = 0;
  181501. i64 iRowid2 = 0;
  181502. i64 iOut = 0;
  181503. Fts5Buffer out;
  181504. memset(&out, 0, sizeof(out));
  181505. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  181506. if( p->rc ) return;
  181507. fts5NextRowid(p1, &i1, &iRowid1);
  181508. fts5NextRowid(p2, &i2, &iRowid2);
  181509. while( i1>=0 || i2>=0 ){
  181510. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  181511. assert( iOut==0 || iRowid1>iOut );
  181512. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  181513. iOut = iRowid1;
  181514. fts5NextRowid(p1, &i1, &iRowid1);
  181515. }else{
  181516. assert( iOut==0 || iRowid2>iOut );
  181517. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  181518. iOut = iRowid2;
  181519. if( i1>=0 && iRowid1==iRowid2 ){
  181520. fts5NextRowid(p1, &i1, &iRowid1);
  181521. }
  181522. fts5NextRowid(p2, &i2, &iRowid2);
  181523. }
  181524. }
  181525. fts5BufferSwap(&out, p1);
  181526. fts5BufferFree(&out);
  181527. }
  181528. /*
  181529. ** Buffers p1 and p2 contain doclists. This function merges the content
  181530. ** of the two doclists together and sets buffer p1 to the result before
  181531. ** returning.
  181532. **
  181533. ** If an error occurs, an error code is left in p->rc. If an error has
  181534. ** already occurred, this function is a no-op.
  181535. */
  181536. static void fts5MergePrefixLists(
  181537. Fts5Index *p, /* FTS5 backend object */
  181538. Fts5Buffer *p1, /* First list to merge */
  181539. Fts5Buffer *p2 /* Second list to merge */
  181540. ){
  181541. if( p2->n ){
  181542. i64 iLastRowid = 0;
  181543. Fts5DoclistIter i1;
  181544. Fts5DoclistIter i2;
  181545. Fts5Buffer out = {0, 0, 0};
  181546. Fts5Buffer tmp = {0, 0, 0};
  181547. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
  181548. fts5DoclistIterInit(p1, &i1);
  181549. fts5DoclistIterInit(p2, &i2);
  181550. while( 1 ){
  181551. if( i1.iRowid<i2.iRowid ){
  181552. /* Copy entry from i1 */
  181553. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  181554. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  181555. fts5DoclistIterNext(&i1);
  181556. if( i1.aPoslist==0 ) break;
  181557. }
  181558. else if( i2.iRowid!=i1.iRowid ){
  181559. /* Copy entry from i2 */
  181560. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  181561. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  181562. fts5DoclistIterNext(&i2);
  181563. if( i2.aPoslist==0 ) break;
  181564. }
  181565. else{
  181566. /* Merge the two position lists. */
  181567. i64 iPos1 = 0;
  181568. i64 iPos2 = 0;
  181569. int iOff1 = 0;
  181570. int iOff2 = 0;
  181571. u8 *a1 = &i1.aPoslist[i1.nSize];
  181572. u8 *a2 = &i2.aPoslist[i2.nSize];
  181573. i64 iPrev = 0;
  181574. Fts5PoslistWriter writer;
  181575. memset(&writer, 0, sizeof(writer));
  181576. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  181577. fts5BufferZero(&tmp);
  181578. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
  181579. if( p->rc ) break;
  181580. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  181581. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  181582. assert( iPos1>=0 && iPos2>=0 );
  181583. if( iPos1<iPos2 ){
  181584. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  181585. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  181586. }else{
  181587. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  181588. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  181589. }
  181590. if( iPos1>=0 && iPos2>=0 ){
  181591. while( 1 ){
  181592. if( iPos1<iPos2 ){
  181593. if( iPos1!=iPrev ){
  181594. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  181595. }
  181596. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  181597. if( iPos1<0 ) break;
  181598. }else{
  181599. assert( iPos2!=iPrev );
  181600. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  181601. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  181602. if( iPos2<0 ) break;
  181603. }
  181604. }
  181605. }
  181606. if( iPos1>=0 ){
  181607. if( iPos1!=iPrev ){
  181608. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  181609. }
  181610. fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
  181611. }else{
  181612. assert( iPos2>=0 && iPos2!=iPrev );
  181613. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  181614. fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
  181615. }
  181616. /* WRITEPOSLISTSIZE */
  181617. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  181618. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  181619. fts5DoclistIterNext(&i1);
  181620. fts5DoclistIterNext(&i2);
  181621. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  181622. }
  181623. }
  181624. if( i1.aPoslist ){
  181625. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  181626. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  181627. }
  181628. else if( i2.aPoslist ){
  181629. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  181630. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  181631. }
  181632. fts5BufferSet(&p->rc, p1, out.n, out.p);
  181633. fts5BufferFree(&tmp);
  181634. fts5BufferFree(&out);
  181635. }
  181636. }
  181637. static void fts5SetupPrefixIter(
  181638. Fts5Index *p, /* Index to read from */
  181639. int bDesc, /* True for "ORDER BY rowid DESC" */
  181640. const u8 *pToken, /* Buffer containing prefix to match */
  181641. int nToken, /* Size of buffer pToken in bytes */
  181642. Fts5Colset *pColset, /* Restrict matches to these columns */
  181643. Fts5Iter **ppIter /* OUT: New iterator */
  181644. ){
  181645. Fts5Structure *pStruct;
  181646. Fts5Buffer *aBuf;
  181647. const int nBuf = 32;
  181648. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  181649. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  181650. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  181651. xMerge = fts5MergeRowidLists;
  181652. xAppend = fts5AppendRowid;
  181653. }else{
  181654. xMerge = fts5MergePrefixLists;
  181655. xAppend = fts5AppendPoslist;
  181656. }
  181657. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  181658. pStruct = fts5StructureRead(p);
  181659. if( aBuf && pStruct ){
  181660. const int flags = FTS5INDEX_QUERY_SCAN
  181661. | FTS5INDEX_QUERY_SKIPEMPTY
  181662. | FTS5INDEX_QUERY_NOOUTPUT;
  181663. int i;
  181664. i64 iLastRowid = 0;
  181665. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  181666. Fts5Data *pData;
  181667. Fts5Buffer doclist;
  181668. int bNewTerm = 1;
  181669. memset(&doclist, 0, sizeof(doclist));
  181670. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  181671. fts5IterSetOutputCb(&p->rc, p1);
  181672. for( /* no-op */ ;
  181673. fts5MultiIterEof(p, p1)==0;
  181674. fts5MultiIterNext2(p, p1, &bNewTerm)
  181675. ){
  181676. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  181677. int nTerm = pSeg->term.n;
  181678. const u8 *pTerm = pSeg->term.p;
  181679. p1->xSetOutputs(p1, pSeg);
  181680. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  181681. if( bNewTerm ){
  181682. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  181683. }
  181684. if( p1->base.nData==0 ) continue;
  181685. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  181686. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  181687. assert( i<nBuf );
  181688. if( aBuf[i].n==0 ){
  181689. fts5BufferSwap(&doclist, &aBuf[i]);
  181690. fts5BufferZero(&doclist);
  181691. }else{
  181692. xMerge(p, &doclist, &aBuf[i]);
  181693. fts5BufferZero(&aBuf[i]);
  181694. }
  181695. }
  181696. iLastRowid = 0;
  181697. }
  181698. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  181699. iLastRowid = p1->base.iRowid;
  181700. }
  181701. for(i=0; i<nBuf; i++){
  181702. if( p->rc==SQLITE_OK ){
  181703. xMerge(p, &doclist, &aBuf[i]);
  181704. }
  181705. fts5BufferFree(&aBuf[i]);
  181706. }
  181707. fts5MultiIterFree(p1);
  181708. pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
  181709. if( pData ){
  181710. pData->p = (u8*)&pData[1];
  181711. pData->nn = pData->szLeaf = doclist.n;
  181712. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  181713. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  181714. }
  181715. fts5BufferFree(&doclist);
  181716. }
  181717. fts5StructureRelease(pStruct);
  181718. sqlite3_free(aBuf);
  181719. }
  181720. /*
  181721. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  181722. ** to the document with rowid iRowid.
  181723. */
  181724. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  181725. assert( p->rc==SQLITE_OK );
  181726. /* Allocate the hash table if it has not already been allocated */
  181727. if( p->pHash==0 ){
  181728. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  181729. }
  181730. /* Flush the hash table to disk if required */
  181731. if( iRowid<p->iWriteRowid
  181732. || (iRowid==p->iWriteRowid && p->bDelete==0)
  181733. || (p->nPendingData > p->pConfig->nHashSize)
  181734. ){
  181735. fts5IndexFlush(p);
  181736. }
  181737. p->iWriteRowid = iRowid;
  181738. p->bDelete = bDelete;
  181739. return fts5IndexReturn(p);
  181740. }
  181741. /*
  181742. ** Commit data to disk.
  181743. */
  181744. static int sqlite3Fts5IndexSync(Fts5Index *p){
  181745. assert( p->rc==SQLITE_OK );
  181746. fts5IndexFlush(p);
  181747. fts5CloseReader(p);
  181748. return fts5IndexReturn(p);
  181749. }
  181750. /*
  181751. ** Discard any data stored in the in-memory hash tables. Do not write it
  181752. ** to the database. Additionally, assume that the contents of the %_data
  181753. ** table may have changed on disk. So any in-memory caches of %_data
  181754. ** records must be invalidated.
  181755. */
  181756. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  181757. fts5CloseReader(p);
  181758. fts5IndexDiscardData(p);
  181759. fts5StructureInvalidate(p);
  181760. /* assert( p->rc==SQLITE_OK ); */
  181761. return SQLITE_OK;
  181762. }
  181763. /*
  181764. ** The %_data table is completely empty when this function is called. This
  181765. ** function populates it with the initial structure objects for each index,
  181766. ** and the initial version of the "averages" record (a zero-byte blob).
  181767. */
  181768. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  181769. Fts5Structure s;
  181770. fts5StructureInvalidate(p);
  181771. memset(&s, 0, sizeof(Fts5Structure));
  181772. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  181773. fts5StructureWrite(p, &s);
  181774. return fts5IndexReturn(p);
  181775. }
  181776. /*
  181777. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  181778. ** and initialize the underlying %_data table.
  181779. **
  181780. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  181781. ** Otherwise, set *pp to NULL and return an SQLite error code.
  181782. */
  181783. static int sqlite3Fts5IndexOpen(
  181784. Fts5Config *pConfig,
  181785. int bCreate,
  181786. Fts5Index **pp,
  181787. char **pzErr
  181788. ){
  181789. int rc = SQLITE_OK;
  181790. Fts5Index *p; /* New object */
  181791. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  181792. if( rc==SQLITE_OK ){
  181793. p->pConfig = pConfig;
  181794. p->nWorkUnit = FTS5_WORK_UNIT;
  181795. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  181796. if( p->zDataTbl && bCreate ){
  181797. rc = sqlite3Fts5CreateTable(
  181798. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  181799. );
  181800. if( rc==SQLITE_OK ){
  181801. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  181802. "segid, term, pgno, PRIMARY KEY(segid, term)",
  181803. 1, pzErr
  181804. );
  181805. }
  181806. if( rc==SQLITE_OK ){
  181807. rc = sqlite3Fts5IndexReinit(p);
  181808. }
  181809. }
  181810. }
  181811. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  181812. if( rc ){
  181813. sqlite3Fts5IndexClose(p);
  181814. *pp = 0;
  181815. }
  181816. return rc;
  181817. }
  181818. /*
  181819. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  181820. */
  181821. static int sqlite3Fts5IndexClose(Fts5Index *p){
  181822. int rc = SQLITE_OK;
  181823. if( p ){
  181824. assert( p->pReader==0 );
  181825. fts5StructureInvalidate(p);
  181826. sqlite3_finalize(p->pWriter);
  181827. sqlite3_finalize(p->pDeleter);
  181828. sqlite3_finalize(p->pIdxWriter);
  181829. sqlite3_finalize(p->pIdxDeleter);
  181830. sqlite3_finalize(p->pIdxSelect);
  181831. sqlite3_finalize(p->pDataVersion);
  181832. sqlite3Fts5HashFree(p->pHash);
  181833. sqlite3_free(p->zDataTbl);
  181834. sqlite3_free(p);
  181835. }
  181836. return rc;
  181837. }
  181838. /*
  181839. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  181840. ** size. Return the number of bytes in the nChar character prefix of the
  181841. ** buffer, or 0 if there are less than nChar characters in total.
  181842. */
  181843. static int sqlite3Fts5IndexCharlenToBytelen(
  181844. const char *p,
  181845. int nByte,
  181846. int nChar
  181847. ){
  181848. int n = 0;
  181849. int i;
  181850. for(i=0; i<nChar; i++){
  181851. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  181852. if( (unsigned char)p[n++]>=0xc0 ){
  181853. while( (p[n] & 0xc0)==0x80 ) n++;
  181854. }
  181855. }
  181856. return n;
  181857. }
  181858. /*
  181859. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  181860. ** unicode characters in the string.
  181861. */
  181862. static int fts5IndexCharlen(const char *pIn, int nIn){
  181863. int nChar = 0;
  181864. int i = 0;
  181865. while( i<nIn ){
  181866. if( (unsigned char)pIn[i++]>=0xc0 ){
  181867. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  181868. }
  181869. nChar++;
  181870. }
  181871. return nChar;
  181872. }
  181873. /*
  181874. ** Insert or remove data to or from the index. Each time a document is
  181875. ** added to or removed from the index, this function is called one or more
  181876. ** times.
  181877. **
  181878. ** For an insert, it must be called once for each token in the new document.
  181879. ** If the operation is a delete, it must be called (at least) once for each
  181880. ** unique token in the document with an iCol value less than zero. The iPos
  181881. ** argument is ignored for a delete.
  181882. */
  181883. static int sqlite3Fts5IndexWrite(
  181884. Fts5Index *p, /* Index to write to */
  181885. int iCol, /* Column token appears in (-ve -> delete) */
  181886. int iPos, /* Position of token within column */
  181887. const char *pToken, int nToken /* Token to add or remove to or from index */
  181888. ){
  181889. int i; /* Used to iterate through indexes */
  181890. int rc = SQLITE_OK; /* Return code */
  181891. Fts5Config *pConfig = p->pConfig;
  181892. assert( p->rc==SQLITE_OK );
  181893. assert( (iCol<0)==p->bDelete );
  181894. /* Add the entry to the main terms index. */
  181895. rc = sqlite3Fts5HashWrite(
  181896. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  181897. );
  181898. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  181899. const int nChar = pConfig->aPrefix[i];
  181900. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  181901. if( nByte ){
  181902. rc = sqlite3Fts5HashWrite(p->pHash,
  181903. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  181904. nByte
  181905. );
  181906. }
  181907. }
  181908. return rc;
  181909. }
  181910. /*
  181911. ** Open a new iterator to iterate though all rowid that match the
  181912. ** specified token or token prefix.
  181913. */
  181914. static int sqlite3Fts5IndexQuery(
  181915. Fts5Index *p, /* FTS index to query */
  181916. const char *pToken, int nToken, /* Token (or prefix) to query for */
  181917. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  181918. Fts5Colset *pColset, /* Match these columns only */
  181919. Fts5IndexIter **ppIter /* OUT: New iterator object */
  181920. ){
  181921. Fts5Config *pConfig = p->pConfig;
  181922. Fts5Iter *pRet = 0;
  181923. Fts5Buffer buf = {0, 0, 0};
  181924. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  181925. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  181926. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  181927. int iIdx = 0; /* Index to search */
  181928. if( nToken ) memcpy(&buf.p[1], pToken, nToken);
  181929. /* Figure out which index to search and set iIdx accordingly. If this
  181930. ** is a prefix query for which there is no prefix index, set iIdx to
  181931. ** greater than pConfig->nPrefix to indicate that the query will be
  181932. ** satisfied by scanning multiple terms in the main index.
  181933. **
  181934. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  181935. ** prefix-query. Instead of using a prefix-index (if one exists),
  181936. ** evaluate the prefix query using the main FTS index. This is used
  181937. ** for internal sanity checking by the integrity-check in debug
  181938. ** mode only. */
  181939. #ifdef SQLITE_DEBUG
  181940. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  181941. assert( flags & FTS5INDEX_QUERY_PREFIX );
  181942. iIdx = 1+pConfig->nPrefix;
  181943. }else
  181944. #endif
  181945. if( flags & FTS5INDEX_QUERY_PREFIX ){
  181946. int nChar = fts5IndexCharlen(pToken, nToken);
  181947. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  181948. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  181949. }
  181950. }
  181951. if( iIdx<=pConfig->nPrefix ){
  181952. /* Straight index lookup */
  181953. Fts5Structure *pStruct = fts5StructureRead(p);
  181954. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  181955. if( pStruct ){
  181956. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  181957. pColset, buf.p, nToken+1, -1, 0, &pRet
  181958. );
  181959. fts5StructureRelease(pStruct);
  181960. }
  181961. }else{
  181962. /* Scan multiple terms in the main index */
  181963. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  181964. buf.p[0] = FTS5_MAIN_PREFIX;
  181965. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  181966. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  181967. fts5IterSetOutputCb(&p->rc, pRet);
  181968. if( p->rc==SQLITE_OK ){
  181969. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  181970. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  181971. }
  181972. }
  181973. if( p->rc ){
  181974. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  181975. pRet = 0;
  181976. fts5CloseReader(p);
  181977. }
  181978. *ppIter = &pRet->base;
  181979. sqlite3Fts5BufferFree(&buf);
  181980. }
  181981. return fts5IndexReturn(p);
  181982. }
  181983. /*
  181984. ** Return true if the iterator passed as the only argument is at EOF.
  181985. */
  181986. /*
  181987. ** Move to the next matching rowid.
  181988. */
  181989. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  181990. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  181991. assert( pIter->pIndex->rc==SQLITE_OK );
  181992. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  181993. return fts5IndexReturn(pIter->pIndex);
  181994. }
  181995. /*
  181996. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  181997. */
  181998. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  181999. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  182000. Fts5Index *p = pIter->pIndex;
  182001. assert( pIter->pIndex->rc==SQLITE_OK );
  182002. fts5MultiIterNext(p, pIter, 0, 0);
  182003. if( p->rc==SQLITE_OK ){
  182004. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  182005. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  182006. fts5DataRelease(pSeg->pLeaf);
  182007. pSeg->pLeaf = 0;
  182008. pIter->base.bEof = 1;
  182009. }
  182010. }
  182011. return fts5IndexReturn(pIter->pIndex);
  182012. }
  182013. /*
  182014. ** Move to the next matching rowid that occurs at or after iMatch. The
  182015. ** definition of "at or after" depends on whether this iterator iterates
  182016. ** in ascending or descending rowid order.
  182017. */
  182018. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  182019. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  182020. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  182021. return fts5IndexReturn(pIter->pIndex);
  182022. }
  182023. /*
  182024. ** Return the current term.
  182025. */
  182026. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  182027. int n;
  182028. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  182029. *pn = n-1;
  182030. return &z[1];
  182031. }
  182032. /*
  182033. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  182034. */
  182035. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  182036. if( pIndexIter ){
  182037. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  182038. Fts5Index *pIndex = pIter->pIndex;
  182039. fts5MultiIterFree(pIter);
  182040. fts5CloseReader(pIndex);
  182041. }
  182042. }
  182043. /*
  182044. ** Read and decode the "averages" record from the database.
  182045. **
  182046. ** Parameter anSize must point to an array of size nCol, where nCol is
  182047. ** the number of user defined columns in the FTS table.
  182048. */
  182049. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  182050. int nCol = p->pConfig->nCol;
  182051. Fts5Data *pData;
  182052. *pnRow = 0;
  182053. memset(anSize, 0, sizeof(i64) * nCol);
  182054. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  182055. if( p->rc==SQLITE_OK && pData->nn ){
  182056. int i = 0;
  182057. int iCol;
  182058. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  182059. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  182060. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  182061. }
  182062. }
  182063. fts5DataRelease(pData);
  182064. return fts5IndexReturn(p);
  182065. }
  182066. /*
  182067. ** Replace the current "averages" record with the contents of the buffer
  182068. ** supplied as the second argument.
  182069. */
  182070. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  182071. assert( p->rc==SQLITE_OK );
  182072. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  182073. return fts5IndexReturn(p);
  182074. }
  182075. /*
  182076. ** Return the total number of blocks this module has read from the %_data
  182077. ** table since it was created.
  182078. */
  182079. static int sqlite3Fts5IndexReads(Fts5Index *p){
  182080. return p->nRead;
  182081. }
  182082. /*
  182083. ** Set the 32-bit cookie value stored at the start of all structure
  182084. ** records to the value passed as the second argument.
  182085. **
  182086. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  182087. ** occurs.
  182088. */
  182089. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  182090. int rc; /* Return code */
  182091. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  182092. u8 aCookie[4]; /* Binary representation of iNew */
  182093. sqlite3_blob *pBlob = 0;
  182094. assert( p->rc==SQLITE_OK );
  182095. sqlite3Fts5Put32(aCookie, iNew);
  182096. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  182097. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  182098. );
  182099. if( rc==SQLITE_OK ){
  182100. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  182101. rc = sqlite3_blob_close(pBlob);
  182102. }
  182103. return rc;
  182104. }
  182105. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  182106. Fts5Structure *pStruct;
  182107. pStruct = fts5StructureRead(p);
  182108. fts5StructureRelease(pStruct);
  182109. return fts5IndexReturn(p);
  182110. }
  182111. /*************************************************************************
  182112. **************************************************************************
  182113. ** Below this point is the implementation of the integrity-check
  182114. ** functionality.
  182115. */
  182116. /*
  182117. ** Return a simple checksum value based on the arguments.
  182118. */
  182119. static u64 sqlite3Fts5IndexEntryCksum(
  182120. i64 iRowid,
  182121. int iCol,
  182122. int iPos,
  182123. int iIdx,
  182124. const char *pTerm,
  182125. int nTerm
  182126. ){
  182127. int i;
  182128. u64 ret = iRowid;
  182129. ret += (ret<<3) + iCol;
  182130. ret += (ret<<3) + iPos;
  182131. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  182132. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  182133. return ret;
  182134. }
  182135. #ifdef SQLITE_DEBUG
  182136. /*
  182137. ** This function is purely an internal test. It does not contribute to
  182138. ** FTS functionality, or even the integrity-check, in any way.
  182139. **
  182140. ** Instead, it tests that the same set of pgno/rowid combinations are
  182141. ** visited regardless of whether the doclist-index identified by parameters
  182142. ** iSegid/iLeaf is iterated in forwards or reverse order.
  182143. */
  182144. static void fts5TestDlidxReverse(
  182145. Fts5Index *p,
  182146. int iSegid, /* Segment id to load from */
  182147. int iLeaf /* Load doclist-index for this leaf */
  182148. ){
  182149. Fts5DlidxIter *pDlidx = 0;
  182150. u64 cksum1 = 13;
  182151. u64 cksum2 = 13;
  182152. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  182153. fts5DlidxIterEof(p, pDlidx)==0;
  182154. fts5DlidxIterNext(p, pDlidx)
  182155. ){
  182156. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  182157. int pgno = fts5DlidxIterPgno(pDlidx);
  182158. assert( pgno>iLeaf );
  182159. cksum1 += iRowid + ((i64)pgno<<32);
  182160. }
  182161. fts5DlidxIterFree(pDlidx);
  182162. pDlidx = 0;
  182163. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  182164. fts5DlidxIterEof(p, pDlidx)==0;
  182165. fts5DlidxIterPrev(p, pDlidx)
  182166. ){
  182167. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  182168. int pgno = fts5DlidxIterPgno(pDlidx);
  182169. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  182170. cksum2 += iRowid + ((i64)pgno<<32);
  182171. }
  182172. fts5DlidxIterFree(pDlidx);
  182173. pDlidx = 0;
  182174. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  182175. }
  182176. static int fts5QueryCksum(
  182177. Fts5Index *p, /* Fts5 index object */
  182178. int iIdx,
  182179. const char *z, /* Index key to query for */
  182180. int n, /* Size of index key in bytes */
  182181. int flags, /* Flags for Fts5IndexQuery */
  182182. u64 *pCksum /* IN/OUT: Checksum value */
  182183. ){
  182184. int eDetail = p->pConfig->eDetail;
  182185. u64 cksum = *pCksum;
  182186. Fts5IndexIter *pIter = 0;
  182187. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  182188. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  182189. i64 rowid = pIter->iRowid;
  182190. if( eDetail==FTS5_DETAIL_NONE ){
  182191. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  182192. }else{
  182193. Fts5PoslistReader sReader;
  182194. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  182195. sReader.bEof==0;
  182196. sqlite3Fts5PoslistReaderNext(&sReader)
  182197. ){
  182198. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  182199. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  182200. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  182201. }
  182202. }
  182203. if( rc==SQLITE_OK ){
  182204. rc = sqlite3Fts5IterNext(pIter);
  182205. }
  182206. }
  182207. sqlite3Fts5IterClose(pIter);
  182208. *pCksum = cksum;
  182209. return rc;
  182210. }
  182211. /*
  182212. ** This function is also purely an internal test. It does not contribute to
  182213. ** FTS functionality, or even the integrity-check, in any way.
  182214. */
  182215. static void fts5TestTerm(
  182216. Fts5Index *p,
  182217. Fts5Buffer *pPrev, /* Previous term */
  182218. const char *z, int n, /* Possibly new term to test */
  182219. u64 expected,
  182220. u64 *pCksum
  182221. ){
  182222. int rc = p->rc;
  182223. if( pPrev->n==0 ){
  182224. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  182225. }else
  182226. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  182227. u64 cksum3 = *pCksum;
  182228. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  182229. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  182230. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  182231. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  182232. u64 ck1 = 0;
  182233. u64 ck2 = 0;
  182234. /* Check that the results returned for ASC and DESC queries are
  182235. ** the same. If not, call this corruption. */
  182236. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  182237. if( rc==SQLITE_OK ){
  182238. int f = flags|FTS5INDEX_QUERY_DESC;
  182239. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  182240. }
  182241. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  182242. /* If this is a prefix query, check that the results returned if the
  182243. ** the index is disabled are the same. In both ASC and DESC order.
  182244. **
  182245. ** This check may only be performed if the hash table is empty. This
  182246. ** is because the hash table only supports a single scan query at
  182247. ** a time, and the multi-iter loop from which this function is called
  182248. ** is already performing such a scan. */
  182249. if( p->nPendingData==0 ){
  182250. if( iIdx>0 && rc==SQLITE_OK ){
  182251. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  182252. ck2 = 0;
  182253. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  182254. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  182255. }
  182256. if( iIdx>0 && rc==SQLITE_OK ){
  182257. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  182258. ck2 = 0;
  182259. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  182260. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  182261. }
  182262. }
  182263. cksum3 ^= ck1;
  182264. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  182265. if( rc==SQLITE_OK && cksum3!=expected ){
  182266. rc = FTS5_CORRUPT;
  182267. }
  182268. *pCksum = cksum3;
  182269. }
  182270. p->rc = rc;
  182271. }
  182272. #else
  182273. # define fts5TestDlidxReverse(x,y,z)
  182274. # define fts5TestTerm(u,v,w,x,y,z)
  182275. #endif
  182276. /*
  182277. ** Check that:
  182278. **
  182279. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  182280. ** contain zero terms.
  182281. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  182282. ** contain zero rowids.
  182283. */
  182284. static void fts5IndexIntegrityCheckEmpty(
  182285. Fts5Index *p,
  182286. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  182287. int iFirst,
  182288. int iNoRowid,
  182289. int iLast
  182290. ){
  182291. int i;
  182292. /* Now check that the iter.nEmpty leaves following the current leaf
  182293. ** (a) exist and (b) contain no terms. */
  182294. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  182295. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  182296. if( pLeaf ){
  182297. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  182298. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  182299. }
  182300. fts5DataRelease(pLeaf);
  182301. }
  182302. }
  182303. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  182304. int iTermOff = 0;
  182305. int ii;
  182306. Fts5Buffer buf1 = {0,0,0};
  182307. Fts5Buffer buf2 = {0,0,0};
  182308. ii = pLeaf->szLeaf;
  182309. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  182310. int res;
  182311. int iOff;
  182312. int nIncr;
  182313. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  182314. iTermOff += nIncr;
  182315. iOff = iTermOff;
  182316. if( iOff>=pLeaf->szLeaf ){
  182317. p->rc = FTS5_CORRUPT;
  182318. }else if( iTermOff==nIncr ){
  182319. int nByte;
  182320. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  182321. if( (iOff+nByte)>pLeaf->szLeaf ){
  182322. p->rc = FTS5_CORRUPT;
  182323. }else{
  182324. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  182325. }
  182326. }else{
  182327. int nKeep, nByte;
  182328. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  182329. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  182330. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  182331. p->rc = FTS5_CORRUPT;
  182332. }else{
  182333. buf1.n = nKeep;
  182334. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  182335. }
  182336. if( p->rc==SQLITE_OK ){
  182337. res = fts5BufferCompare(&buf1, &buf2);
  182338. if( res<=0 ) p->rc = FTS5_CORRUPT;
  182339. }
  182340. }
  182341. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  182342. }
  182343. fts5BufferFree(&buf1);
  182344. fts5BufferFree(&buf2);
  182345. }
  182346. static void fts5IndexIntegrityCheckSegment(
  182347. Fts5Index *p, /* FTS5 backend object */
  182348. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  182349. ){
  182350. Fts5Config *pConfig = p->pConfig;
  182351. sqlite3_stmt *pStmt = 0;
  182352. int rc2;
  182353. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  182354. int iDlidxPrevLeaf = pSeg->pgnoLast;
  182355. if( pSeg->pgnoFirst==0 ) return;
  182356. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  182357. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  182358. pConfig->zDb, pConfig->zName, pSeg->iSegid
  182359. ));
  182360. /* Iterate through the b-tree hierarchy. */
  182361. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  182362. i64 iRow; /* Rowid for this leaf */
  182363. Fts5Data *pLeaf; /* Data for this leaf */
  182364. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  182365. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  182366. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  182367. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  182368. /* If the leaf in question has already been trimmed from the segment,
  182369. ** ignore this b-tree entry. Otherwise, load it into memory. */
  182370. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  182371. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  182372. pLeaf = fts5LeafRead(p, iRow);
  182373. if( pLeaf==0 ) break;
  182374. /* Check that the leaf contains at least one term, and that it is equal
  182375. ** to or larger than the split-key in zIdxTerm. Also check that if there
  182376. ** is also a rowid pointer within the leaf page header, it points to a
  182377. ** location before the term. */
  182378. if( pLeaf->nn<=pLeaf->szLeaf ){
  182379. p->rc = FTS5_CORRUPT;
  182380. }else{
  182381. int iOff; /* Offset of first term on leaf */
  182382. int iRowidOff; /* Offset of first rowid on leaf */
  182383. int nTerm; /* Size of term on leaf in bytes */
  182384. int res; /* Comparison of term and split-key */
  182385. iOff = fts5LeafFirstTermOff(pLeaf);
  182386. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  182387. if( iRowidOff>=iOff ){
  182388. p->rc = FTS5_CORRUPT;
  182389. }else{
  182390. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  182391. res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  182392. if( res==0 ) res = nTerm - nIdxTerm;
  182393. if( res<0 ) p->rc = FTS5_CORRUPT;
  182394. }
  182395. fts5IntegrityCheckPgidx(p, pLeaf);
  182396. }
  182397. fts5DataRelease(pLeaf);
  182398. if( p->rc ) break;
  182399. /* Now check that the iter.nEmpty leaves following the current leaf
  182400. ** (a) exist and (b) contain no terms. */
  182401. fts5IndexIntegrityCheckEmpty(
  182402. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  182403. );
  182404. if( p->rc ) break;
  182405. /* If there is a doclist-index, check that it looks right. */
  182406. if( bIdxDlidx ){
  182407. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  182408. int iPrevLeaf = iIdxLeaf;
  182409. int iSegid = pSeg->iSegid;
  182410. int iPg = 0;
  182411. i64 iKey;
  182412. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  182413. fts5DlidxIterEof(p, pDlidx)==0;
  182414. fts5DlidxIterNext(p, pDlidx)
  182415. ){
  182416. /* Check any rowid-less pages that occur before the current leaf. */
  182417. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  182418. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  182419. pLeaf = fts5DataRead(p, iKey);
  182420. if( pLeaf ){
  182421. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  182422. fts5DataRelease(pLeaf);
  182423. }
  182424. }
  182425. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  182426. /* Check that the leaf page indicated by the iterator really does
  182427. ** contain the rowid suggested by the same. */
  182428. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  182429. pLeaf = fts5DataRead(p, iKey);
  182430. if( pLeaf ){
  182431. i64 iRowid;
  182432. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  182433. ASSERT_SZLEAF_OK(pLeaf);
  182434. if( iRowidOff>=pLeaf->szLeaf ){
  182435. p->rc = FTS5_CORRUPT;
  182436. }else{
  182437. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  182438. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  182439. }
  182440. fts5DataRelease(pLeaf);
  182441. }
  182442. }
  182443. iDlidxPrevLeaf = iPg;
  182444. fts5DlidxIterFree(pDlidx);
  182445. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  182446. }else{
  182447. iDlidxPrevLeaf = pSeg->pgnoLast;
  182448. /* TODO: Check there is no doclist index */
  182449. }
  182450. iIdxPrevLeaf = iIdxLeaf;
  182451. }
  182452. rc2 = sqlite3_finalize(pStmt);
  182453. if( p->rc==SQLITE_OK ) p->rc = rc2;
  182454. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  182455. #if 0
  182456. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  182457. p->rc = FTS5_CORRUPT;
  182458. }
  182459. #endif
  182460. }
  182461. /*
  182462. ** Run internal checks to ensure that the FTS index (a) is internally
  182463. ** consistent and (b) contains entries for which the XOR of the checksums
  182464. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  182465. **
  182466. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  182467. ** checksum does not match. Return SQLITE_OK if all checks pass without
  182468. ** error, or some other SQLite error code if another error (e.g. OOM)
  182469. ** occurs.
  182470. */
  182471. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  182472. int eDetail = p->pConfig->eDetail;
  182473. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  182474. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  182475. Fts5Iter *pIter; /* Used to iterate through entire index */
  182476. Fts5Structure *pStruct; /* Index structure */
  182477. #ifdef SQLITE_DEBUG
  182478. /* Used by extra internal tests only run if NDEBUG is not defined */
  182479. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  182480. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  182481. #endif
  182482. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  182483. /* Load the FTS index structure */
  182484. pStruct = fts5StructureRead(p);
  182485. /* Check that the internal nodes of each segment match the leaves */
  182486. if( pStruct ){
  182487. int iLvl, iSeg;
  182488. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  182489. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  182490. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  182491. fts5IndexIntegrityCheckSegment(p, pSeg);
  182492. }
  182493. }
  182494. }
  182495. /* The cksum argument passed to this function is a checksum calculated
  182496. ** based on all expected entries in the FTS index (including prefix index
  182497. ** entries). This block checks that a checksum calculated based on the
  182498. ** actual contents of FTS index is identical.
  182499. **
  182500. ** Two versions of the same checksum are calculated. The first (stack
  182501. ** variable cksum2) based on entries extracted from the full-text index
  182502. ** while doing a linear scan of each individual index in turn.
  182503. **
  182504. ** As each term visited by the linear scans, a separate query for the
  182505. ** same term is performed. cksum3 is calculated based on the entries
  182506. ** extracted by these queries.
  182507. */
  182508. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  182509. fts5MultiIterEof(p, pIter)==0;
  182510. fts5MultiIterNext(p, pIter, 0, 0)
  182511. ){
  182512. int n; /* Size of term in bytes */
  182513. i64 iPos = 0; /* Position read from poslist */
  182514. int iOff = 0; /* Offset within poslist */
  182515. i64 iRowid = fts5MultiIterRowid(pIter);
  182516. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  182517. /* If this is a new term, query for it. Update cksum3 with the results. */
  182518. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  182519. if( eDetail==FTS5_DETAIL_NONE ){
  182520. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  182521. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  182522. }
  182523. }else{
  182524. poslist.n = 0;
  182525. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  182526. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  182527. int iCol = FTS5_POS2COLUMN(iPos);
  182528. int iTokOff = FTS5_POS2OFFSET(iPos);
  182529. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  182530. }
  182531. }
  182532. }
  182533. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  182534. fts5MultiIterFree(pIter);
  182535. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  182536. fts5StructureRelease(pStruct);
  182537. #ifdef SQLITE_DEBUG
  182538. fts5BufferFree(&term);
  182539. #endif
  182540. fts5BufferFree(&poslist);
  182541. return fts5IndexReturn(p);
  182542. }
  182543. /*************************************************************************
  182544. **************************************************************************
  182545. ** Below this point is the implementation of the fts5_decode() scalar
  182546. ** function only.
  182547. */
  182548. /*
  182549. ** Decode a segment-data rowid from the %_data table. This function is
  182550. ** the opposite of macro FTS5_SEGMENT_ROWID().
  182551. */
  182552. static void fts5DecodeRowid(
  182553. i64 iRowid, /* Rowid from %_data table */
  182554. int *piSegid, /* OUT: Segment id */
  182555. int *pbDlidx, /* OUT: Dlidx flag */
  182556. int *piHeight, /* OUT: Height */
  182557. int *piPgno /* OUT: Page number */
  182558. ){
  182559. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  182560. iRowid >>= FTS5_DATA_PAGE_B;
  182561. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  182562. iRowid >>= FTS5_DATA_HEIGHT_B;
  182563. *pbDlidx = (int)(iRowid & 0x0001);
  182564. iRowid >>= FTS5_DATA_DLI_B;
  182565. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  182566. }
  182567. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  182568. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  182569. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  182570. if( iSegid==0 ){
  182571. if( iKey==FTS5_AVERAGES_ROWID ){
  182572. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  182573. }else{
  182574. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  182575. }
  182576. }
  182577. else{
  182578. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  182579. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  182580. );
  182581. }
  182582. }
  182583. static void fts5DebugStructure(
  182584. int *pRc, /* IN/OUT: error code */
  182585. Fts5Buffer *pBuf,
  182586. Fts5Structure *p
  182587. ){
  182588. int iLvl, iSeg; /* Iterate through levels, segments */
  182589. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  182590. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  182591. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  182592. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  182593. );
  182594. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  182595. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  182596. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  182597. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  182598. );
  182599. }
  182600. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  182601. }
  182602. }
  182603. /*
  182604. ** This is part of the fts5_decode() debugging aid.
  182605. **
  182606. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  182607. ** function appends a human-readable representation of the same object
  182608. ** to the buffer passed as the second argument.
  182609. */
  182610. static void fts5DecodeStructure(
  182611. int *pRc, /* IN/OUT: error code */
  182612. Fts5Buffer *pBuf,
  182613. const u8 *pBlob, int nBlob
  182614. ){
  182615. int rc; /* Return code */
  182616. Fts5Structure *p = 0; /* Decoded structure object */
  182617. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  182618. if( rc!=SQLITE_OK ){
  182619. *pRc = rc;
  182620. return;
  182621. }
  182622. fts5DebugStructure(pRc, pBuf, p);
  182623. fts5StructureRelease(p);
  182624. }
  182625. /*
  182626. ** This is part of the fts5_decode() debugging aid.
  182627. **
  182628. ** Arguments pBlob/nBlob contain an "averages" record. This function
  182629. ** appends a human-readable representation of record to the buffer passed
  182630. ** as the second argument.
  182631. */
  182632. static void fts5DecodeAverages(
  182633. int *pRc, /* IN/OUT: error code */
  182634. Fts5Buffer *pBuf,
  182635. const u8 *pBlob, int nBlob
  182636. ){
  182637. int i = 0;
  182638. const char *zSpace = "";
  182639. while( i<nBlob ){
  182640. u64 iVal;
  182641. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  182642. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  182643. zSpace = " ";
  182644. }
  182645. }
  182646. /*
  182647. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  182648. ** each varint and append its string representation to buffer pBuf. Return
  182649. ** after either the input buffer is exhausted or a 0 value is read.
  182650. **
  182651. ** The return value is the number of bytes read from the input buffer.
  182652. */
  182653. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  182654. int iOff = 0;
  182655. while( iOff<n ){
  182656. int iVal;
  182657. iOff += fts5GetVarint32(&a[iOff], iVal);
  182658. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  182659. }
  182660. return iOff;
  182661. }
  182662. /*
  182663. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  182664. ** may or may not finish within the buffer. This function appends a text
  182665. ** representation of the part of the doclist that is present to buffer
  182666. ** pBuf.
  182667. **
  182668. ** The return value is the number of bytes read from the input buffer.
  182669. */
  182670. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  182671. i64 iDocid = 0;
  182672. int iOff = 0;
  182673. if( n>0 ){
  182674. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  182675. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  182676. }
  182677. while( iOff<n ){
  182678. int nPos;
  182679. int bDel;
  182680. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  182681. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  182682. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  182683. if( iOff<n ){
  182684. i64 iDelta;
  182685. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  182686. iDocid += iDelta;
  182687. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  182688. }
  182689. }
  182690. return iOff;
  182691. }
  182692. /*
  182693. ** This function is part of the fts5_decode() debugging function. It is
  182694. ** only ever used with detail=none tables.
  182695. **
  182696. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  182697. ** tables. This function appends a human-readable version of that list to
  182698. ** buffer pBuf.
  182699. **
  182700. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  182701. ** no-op. If an OOM or other error occurs within this function, *pRc is
  182702. ** set to an SQLite error code before returning. The final state of buffer
  182703. ** pBuf is undefined in this case.
  182704. */
  182705. static void fts5DecodeRowidList(
  182706. int *pRc, /* IN/OUT: Error code */
  182707. Fts5Buffer *pBuf, /* Buffer to append text to */
  182708. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  182709. ){
  182710. int i = 0;
  182711. i64 iRowid = 0;
  182712. while( i<nData ){
  182713. const char *zApp = "";
  182714. u64 iVal;
  182715. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  182716. iRowid += iVal;
  182717. if( i<nData && pData[i]==0x00 ){
  182718. i++;
  182719. if( i<nData && pData[i]==0x00 ){
  182720. i++;
  182721. zApp = "+";
  182722. }else{
  182723. zApp = "*";
  182724. }
  182725. }
  182726. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  182727. }
  182728. }
  182729. /*
  182730. ** The implementation of user-defined scalar function fts5_decode().
  182731. */
  182732. static void fts5DecodeFunction(
  182733. sqlite3_context *pCtx, /* Function call context */
  182734. int nArg, /* Number of args (always 2) */
  182735. sqlite3_value **apVal /* Function arguments */
  182736. ){
  182737. i64 iRowid; /* Rowid for record being decoded */
  182738. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  182739. const u8 *aBlob; int n; /* Record to decode */
  182740. u8 *a = 0;
  182741. Fts5Buffer s; /* Build up text to return here */
  182742. int rc = SQLITE_OK; /* Return code */
  182743. int nSpace = 0;
  182744. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  182745. assert( nArg==2 );
  182746. UNUSED_PARAM(nArg);
  182747. memset(&s, 0, sizeof(Fts5Buffer));
  182748. iRowid = sqlite3_value_int64(apVal[0]);
  182749. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  182750. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  182751. ** buffer overreads even if the record is corrupt. */
  182752. n = sqlite3_value_bytes(apVal[1]);
  182753. aBlob = sqlite3_value_blob(apVal[1]);
  182754. nSpace = n + FTS5_DATA_ZERO_PADDING;
  182755. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  182756. if( a==0 ) goto decode_out;
  182757. memcpy(a, aBlob, n);
  182758. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  182759. fts5DebugRowid(&rc, &s, iRowid);
  182760. if( bDlidx ){
  182761. Fts5Data dlidx;
  182762. Fts5DlidxLvl lvl;
  182763. dlidx.p = a;
  182764. dlidx.nn = n;
  182765. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  182766. lvl.pData = &dlidx;
  182767. lvl.iLeafPgno = iPgno;
  182768. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  182769. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  182770. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  182771. );
  182772. }
  182773. }else if( iSegid==0 ){
  182774. if( iRowid==FTS5_AVERAGES_ROWID ){
  182775. fts5DecodeAverages(&rc, &s, a, n);
  182776. }else{
  182777. fts5DecodeStructure(&rc, &s, a, n);
  182778. }
  182779. }else if( eDetailNone ){
  182780. Fts5Buffer term; /* Current term read from page */
  182781. int szLeaf;
  182782. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  182783. int iTermOff;
  182784. int nKeep = 0;
  182785. int iOff;
  182786. memset(&term, 0, sizeof(Fts5Buffer));
  182787. /* Decode any entries that occur before the first term. */
  182788. if( szLeaf<n ){
  182789. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  182790. }else{
  182791. iTermOff = szLeaf;
  182792. }
  182793. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  182794. iOff = iTermOff;
  182795. while( iOff<szLeaf ){
  182796. int nAppend;
  182797. /* Read the term data for the next term*/
  182798. iOff += fts5GetVarint32(&a[iOff], nAppend);
  182799. term.n = nKeep;
  182800. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  182801. sqlite3Fts5BufferAppendPrintf(
  182802. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  182803. );
  182804. iOff += nAppend;
  182805. /* Figure out where the doclist for this term ends */
  182806. if( iPgidxOff<n ){
  182807. int nIncr;
  182808. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  182809. iTermOff += nIncr;
  182810. }else{
  182811. iTermOff = szLeaf;
  182812. }
  182813. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  182814. iOff = iTermOff;
  182815. if( iOff<szLeaf ){
  182816. iOff += fts5GetVarint32(&a[iOff], nKeep);
  182817. }
  182818. }
  182819. fts5BufferFree(&term);
  182820. }else{
  182821. Fts5Buffer term; /* Current term read from page */
  182822. int szLeaf; /* Offset of pgidx in a[] */
  182823. int iPgidxOff;
  182824. int iPgidxPrev = 0; /* Previous value read from pgidx */
  182825. int iTermOff = 0;
  182826. int iRowidOff = 0;
  182827. int iOff;
  182828. int nDoclist;
  182829. memset(&term, 0, sizeof(Fts5Buffer));
  182830. if( n<4 ){
  182831. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  182832. goto decode_out;
  182833. }else{
  182834. iRowidOff = fts5GetU16(&a[0]);
  182835. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  182836. if( iPgidxOff<n ){
  182837. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  182838. }
  182839. }
  182840. /* Decode the position list tail at the start of the page */
  182841. if( iRowidOff!=0 ){
  182842. iOff = iRowidOff;
  182843. }else if( iTermOff!=0 ){
  182844. iOff = iTermOff;
  182845. }else{
  182846. iOff = szLeaf;
  182847. }
  182848. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  182849. /* Decode any more doclist data that appears on the page before the
  182850. ** first term. */
  182851. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  182852. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  182853. while( iPgidxOff<n ){
  182854. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  182855. int nByte; /* Bytes of data */
  182856. int iEnd;
  182857. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  182858. iPgidxPrev += nByte;
  182859. iOff = iPgidxPrev;
  182860. if( iPgidxOff<n ){
  182861. fts5GetVarint32(&a[iPgidxOff], nByte);
  182862. iEnd = iPgidxPrev + nByte;
  182863. }else{
  182864. iEnd = szLeaf;
  182865. }
  182866. if( bFirst==0 ){
  182867. iOff += fts5GetVarint32(&a[iOff], nByte);
  182868. term.n = nByte;
  182869. }
  182870. iOff += fts5GetVarint32(&a[iOff], nByte);
  182871. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  182872. iOff += nByte;
  182873. sqlite3Fts5BufferAppendPrintf(
  182874. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  182875. );
  182876. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  182877. }
  182878. fts5BufferFree(&term);
  182879. }
  182880. decode_out:
  182881. sqlite3_free(a);
  182882. if( rc==SQLITE_OK ){
  182883. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  182884. }else{
  182885. sqlite3_result_error_code(pCtx, rc);
  182886. }
  182887. fts5BufferFree(&s);
  182888. }
  182889. /*
  182890. ** The implementation of user-defined scalar function fts5_rowid().
  182891. */
  182892. static void fts5RowidFunction(
  182893. sqlite3_context *pCtx, /* Function call context */
  182894. int nArg, /* Number of args (always 2) */
  182895. sqlite3_value **apVal /* Function arguments */
  182896. ){
  182897. const char *zArg;
  182898. if( nArg==0 ){
  182899. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  182900. }else{
  182901. zArg = (const char*)sqlite3_value_text(apVal[0]);
  182902. if( 0==sqlite3_stricmp(zArg, "segment") ){
  182903. i64 iRowid;
  182904. int segid, pgno;
  182905. if( nArg!=3 ){
  182906. sqlite3_result_error(pCtx,
  182907. "should be: fts5_rowid('segment', segid, pgno))", -1
  182908. );
  182909. }else{
  182910. segid = sqlite3_value_int(apVal[1]);
  182911. pgno = sqlite3_value_int(apVal[2]);
  182912. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  182913. sqlite3_result_int64(pCtx, iRowid);
  182914. }
  182915. }else{
  182916. sqlite3_result_error(pCtx,
  182917. "first arg to fts5_rowid() must be 'segment'" , -1
  182918. );
  182919. }
  182920. }
  182921. }
  182922. /*
  182923. ** This is called as part of registering the FTS5 module with database
  182924. ** connection db. It registers several user-defined scalar functions useful
  182925. ** with FTS5.
  182926. **
  182927. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  182928. ** SQLite error code is returned instead.
  182929. */
  182930. static int sqlite3Fts5IndexInit(sqlite3 *db){
  182931. int rc = sqlite3_create_function(
  182932. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  182933. );
  182934. if( rc==SQLITE_OK ){
  182935. rc = sqlite3_create_function(
  182936. db, "fts5_decode_none", 2,
  182937. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  182938. );
  182939. }
  182940. if( rc==SQLITE_OK ){
  182941. rc = sqlite3_create_function(
  182942. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  182943. );
  182944. }
  182945. return rc;
  182946. }
  182947. static int sqlite3Fts5IndexReset(Fts5Index *p){
  182948. assert( p->pStruct==0 || p->iStructVersion!=0 );
  182949. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  182950. fts5StructureInvalidate(p);
  182951. }
  182952. return fts5IndexReturn(p);
  182953. }
  182954. /*
  182955. ** 2014 Jun 09
  182956. **
  182957. ** The author disclaims copyright to this source code. In place of
  182958. ** a legal notice, here is a blessing:
  182959. **
  182960. ** May you do good and not evil.
  182961. ** May you find forgiveness for yourself and forgive others.
  182962. ** May you share freely, never taking more than you give.
  182963. **
  182964. ******************************************************************************
  182965. **
  182966. ** This is an SQLite module implementing full-text search.
  182967. */
  182968. /* #include "fts5Int.h" */
  182969. /*
  182970. ** This variable is set to false when running tests for which the on disk
  182971. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  182972. ** assert() conditions in the fts5 code are activated - conditions that are
  182973. ** only true if it is guaranteed that the fts5 database is not corrupt.
  182974. */
  182975. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  182976. typedef struct Fts5Auxdata Fts5Auxdata;
  182977. typedef struct Fts5Auxiliary Fts5Auxiliary;
  182978. typedef struct Fts5Cursor Fts5Cursor;
  182979. typedef struct Fts5Sorter Fts5Sorter;
  182980. typedef struct Fts5Table Fts5Table;
  182981. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  182982. /*
  182983. ** NOTES ON TRANSACTIONS:
  182984. **
  182985. ** SQLite invokes the following virtual table methods as transactions are
  182986. ** opened and closed by the user:
  182987. **
  182988. ** xBegin(): Start of a new transaction.
  182989. ** xSync(): Initial part of two-phase commit.
  182990. ** xCommit(): Final part of two-phase commit.
  182991. ** xRollback(): Rollback the transaction.
  182992. **
  182993. ** Anything that is required as part of a commit that may fail is performed
  182994. ** in the xSync() callback. Current versions of SQLite ignore any errors
  182995. ** returned by xCommit().
  182996. **
  182997. ** And as sub-transactions are opened/closed:
  182998. **
  182999. ** xSavepoint(int S): Open savepoint S.
  183000. ** xRelease(int S): Commit and close savepoint S.
  183001. ** xRollbackTo(int S): Rollback to start of savepoint S.
  183002. **
  183003. ** During a write-transaction the fts5_index.c module may cache some data
  183004. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  183005. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  183006. ** is called.
  183007. **
  183008. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  183009. ** structure is used to record the current transaction state. This information
  183010. ** is not required, but it is used in the assert() statements executed by
  183011. ** function fts5CheckTransactionState() (see below).
  183012. */
  183013. struct Fts5TransactionState {
  183014. int eState; /* 0==closed, 1==open, 2==synced */
  183015. int iSavepoint; /* Number of open savepoints (0 -> none) */
  183016. };
  183017. /*
  183018. ** A single object of this type is allocated when the FTS5 module is
  183019. ** registered with a database handle. It is used to store pointers to
  183020. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  183021. */
  183022. struct Fts5Global {
  183023. fts5_api api; /* User visible part of object (see fts5.h) */
  183024. sqlite3 *db; /* Associated database connection */
  183025. i64 iNextId; /* Used to allocate unique cursor ids */
  183026. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  183027. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  183028. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  183029. Fts5Cursor *pCsr; /* First in list of all open cursors */
  183030. };
  183031. /*
  183032. ** Each auxiliary function registered with the FTS5 module is represented
  183033. ** by an object of the following type. All such objects are stored as part
  183034. ** of the Fts5Global.pAux list.
  183035. */
  183036. struct Fts5Auxiliary {
  183037. Fts5Global *pGlobal; /* Global context for this function */
  183038. char *zFunc; /* Function name (nul-terminated) */
  183039. void *pUserData; /* User-data pointer */
  183040. fts5_extension_function xFunc; /* Callback function */
  183041. void (*xDestroy)(void*); /* Destructor function */
  183042. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  183043. };
  183044. /*
  183045. ** Each tokenizer module registered with the FTS5 module is represented
  183046. ** by an object of the following type. All such objects are stored as part
  183047. ** of the Fts5Global.pTok list.
  183048. */
  183049. struct Fts5TokenizerModule {
  183050. char *zName; /* Name of tokenizer */
  183051. void *pUserData; /* User pointer passed to xCreate() */
  183052. fts5_tokenizer x; /* Tokenizer functions */
  183053. void (*xDestroy)(void*); /* Destructor function */
  183054. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  183055. };
  183056. /*
  183057. ** Virtual-table object.
  183058. */
  183059. struct Fts5Table {
  183060. sqlite3_vtab base; /* Base class used by SQLite core */
  183061. Fts5Config *pConfig; /* Virtual table configuration */
  183062. Fts5Index *pIndex; /* Full-text index */
  183063. Fts5Storage *pStorage; /* Document store */
  183064. Fts5Global *pGlobal; /* Global (connection wide) data */
  183065. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  183066. #ifdef SQLITE_DEBUG
  183067. struct Fts5TransactionState ts;
  183068. #endif
  183069. };
  183070. struct Fts5MatchPhrase {
  183071. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  183072. int nTerm; /* Size of phrase in terms */
  183073. };
  183074. /*
  183075. ** pStmt:
  183076. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  183077. **
  183078. ** aIdx[]:
  183079. ** There is one entry in the aIdx[] array for each phrase in the query,
  183080. ** the value of which is the offset within aPoslist[] following the last
  183081. ** byte of the position list for the corresponding phrase.
  183082. */
  183083. struct Fts5Sorter {
  183084. sqlite3_stmt *pStmt;
  183085. i64 iRowid; /* Current rowid */
  183086. const u8 *aPoslist; /* Position lists for current row */
  183087. int nIdx; /* Number of entries in aIdx[] */
  183088. int aIdx[1]; /* Offsets into aPoslist for current row */
  183089. };
  183090. /*
  183091. ** Virtual-table cursor object.
  183092. **
  183093. ** iSpecial:
  183094. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  183095. ** then this variable contains the result of the query.
  183096. **
  183097. ** iFirstRowid, iLastRowid:
  183098. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  183099. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  183100. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  183101. ** WHERE clause in the user's query might have been:
  183102. **
  183103. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  183104. **
  183105. ** If the cursor iterates in descending order of rowid, iFirstRowid
  183106. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  183107. ** the lower.
  183108. */
  183109. struct Fts5Cursor {
  183110. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  183111. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  183112. int *aColumnSize; /* Values for xColumnSize() */
  183113. i64 iCsrId; /* Cursor id */
  183114. /* Zero from this point onwards on cursor reset */
  183115. int ePlan; /* FTS5_PLAN_XXX value */
  183116. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  183117. i64 iFirstRowid; /* Return no rowids earlier than this */
  183118. i64 iLastRowid; /* Return no rowids later than this */
  183119. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  183120. Fts5Expr *pExpr; /* Expression for MATCH queries */
  183121. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  183122. int csrflags; /* Mask of cursor flags (see below) */
  183123. i64 iSpecial; /* Result of special query */
  183124. /* "rank" function. Populated on demand from vtab.xColumn(). */
  183125. char *zRank; /* Custom rank function */
  183126. char *zRankArgs; /* Custom rank function args */
  183127. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  183128. int nRankArg; /* Number of trailing arguments for rank() */
  183129. sqlite3_value **apRankArg; /* Array of trailing arguments */
  183130. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  183131. /* Auxiliary data storage */
  183132. Fts5Auxiliary *pAux; /* Currently executing extension function */
  183133. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  183134. /* Cache used by auxiliary functions xInst() and xInstCount() */
  183135. Fts5PoslistReader *aInstIter; /* One for each phrase */
  183136. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  183137. int nInstCount; /* Number of phrase instances */
  183138. int *aInst; /* 3 integers per phrase instance */
  183139. };
  183140. /*
  183141. ** Bits that make up the "idxNum" parameter passed indirectly by
  183142. ** xBestIndex() to xFilter().
  183143. */
  183144. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  183145. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  183146. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  183147. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  183148. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  183149. #define FTS5_BI_ORDER_RANK 0x0020
  183150. #define FTS5_BI_ORDER_ROWID 0x0040
  183151. #define FTS5_BI_ORDER_DESC 0x0080
  183152. /*
  183153. ** Values for Fts5Cursor.csrflags
  183154. */
  183155. #define FTS5CSR_EOF 0x01
  183156. #define FTS5CSR_REQUIRE_CONTENT 0x02
  183157. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  183158. #define FTS5CSR_REQUIRE_INST 0x08
  183159. #define FTS5CSR_FREE_ZRANK 0x10
  183160. #define FTS5CSR_REQUIRE_RESEEK 0x20
  183161. #define FTS5CSR_REQUIRE_POSLIST 0x40
  183162. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  183163. #define BitFlagTest(x,y) (((x) & (y))!=0)
  183164. /*
  183165. ** Macros to Set(), Clear() and Test() cursor flags.
  183166. */
  183167. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  183168. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  183169. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  183170. struct Fts5Auxdata {
  183171. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  183172. void *pPtr; /* Pointer value */
  183173. void(*xDelete)(void*); /* Destructor */
  183174. Fts5Auxdata *pNext; /* Next object in linked list */
  183175. };
  183176. #ifdef SQLITE_DEBUG
  183177. #define FTS5_BEGIN 1
  183178. #define FTS5_SYNC 2
  183179. #define FTS5_COMMIT 3
  183180. #define FTS5_ROLLBACK 4
  183181. #define FTS5_SAVEPOINT 5
  183182. #define FTS5_RELEASE 6
  183183. #define FTS5_ROLLBACKTO 7
  183184. static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
  183185. switch( op ){
  183186. case FTS5_BEGIN:
  183187. assert( p->ts.eState==0 );
  183188. p->ts.eState = 1;
  183189. p->ts.iSavepoint = -1;
  183190. break;
  183191. case FTS5_SYNC:
  183192. assert( p->ts.eState==1 );
  183193. p->ts.eState = 2;
  183194. break;
  183195. case FTS5_COMMIT:
  183196. assert( p->ts.eState==2 );
  183197. p->ts.eState = 0;
  183198. break;
  183199. case FTS5_ROLLBACK:
  183200. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  183201. p->ts.eState = 0;
  183202. break;
  183203. case FTS5_SAVEPOINT:
  183204. assert( p->ts.eState==1 );
  183205. assert( iSavepoint>=0 );
  183206. assert( iSavepoint>p->ts.iSavepoint );
  183207. p->ts.iSavepoint = iSavepoint;
  183208. break;
  183209. case FTS5_RELEASE:
  183210. assert( p->ts.eState==1 );
  183211. assert( iSavepoint>=0 );
  183212. assert( iSavepoint<=p->ts.iSavepoint );
  183213. p->ts.iSavepoint = iSavepoint-1;
  183214. break;
  183215. case FTS5_ROLLBACKTO:
  183216. assert( p->ts.eState==1 );
  183217. assert( iSavepoint>=0 );
  183218. assert( iSavepoint<=p->ts.iSavepoint );
  183219. p->ts.iSavepoint = iSavepoint;
  183220. break;
  183221. }
  183222. }
  183223. #else
  183224. # define fts5CheckTransactionState(x,y,z)
  183225. #endif
  183226. /*
  183227. ** Return true if pTab is a contentless table.
  183228. */
  183229. static int fts5IsContentless(Fts5Table *pTab){
  183230. return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
  183231. }
  183232. /*
  183233. ** Delete a virtual table handle allocated by fts5InitVtab().
  183234. */
  183235. static void fts5FreeVtab(Fts5Table *pTab){
  183236. if( pTab ){
  183237. sqlite3Fts5IndexClose(pTab->pIndex);
  183238. sqlite3Fts5StorageClose(pTab->pStorage);
  183239. sqlite3Fts5ConfigFree(pTab->pConfig);
  183240. sqlite3_free(pTab);
  183241. }
  183242. }
  183243. /*
  183244. ** The xDisconnect() virtual table method.
  183245. */
  183246. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  183247. fts5FreeVtab((Fts5Table*)pVtab);
  183248. return SQLITE_OK;
  183249. }
  183250. /*
  183251. ** The xDestroy() virtual table method.
  183252. */
  183253. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  183254. Fts5Table *pTab = (Fts5Table*)pVtab;
  183255. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  183256. if( rc==SQLITE_OK ){
  183257. fts5FreeVtab((Fts5Table*)pVtab);
  183258. }
  183259. return rc;
  183260. }
  183261. /*
  183262. ** This function is the implementation of both the xConnect and xCreate
  183263. ** methods of the FTS3 virtual table.
  183264. **
  183265. ** The argv[] array contains the following:
  183266. **
  183267. ** argv[0] -> module name ("fts5")
  183268. ** argv[1] -> database name
  183269. ** argv[2] -> table name
  183270. ** argv[...] -> "column name" and other module argument fields.
  183271. */
  183272. static int fts5InitVtab(
  183273. int bCreate, /* True for xCreate, false for xConnect */
  183274. sqlite3 *db, /* The SQLite database connection */
  183275. void *pAux, /* Hash table containing tokenizers */
  183276. int argc, /* Number of elements in argv array */
  183277. const char * const *argv, /* xCreate/xConnect argument array */
  183278. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  183279. char **pzErr /* Write any error message here */
  183280. ){
  183281. Fts5Global *pGlobal = (Fts5Global*)pAux;
  183282. const char **azConfig = (const char**)argv;
  183283. int rc = SQLITE_OK; /* Return code */
  183284. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  183285. Fts5Table *pTab = 0; /* New virtual table object */
  183286. /* Allocate the new vtab object and parse the configuration */
  183287. pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
  183288. if( rc==SQLITE_OK ){
  183289. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  183290. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  183291. }
  183292. if( rc==SQLITE_OK ){
  183293. pTab->pConfig = pConfig;
  183294. pTab->pGlobal = pGlobal;
  183295. }
  183296. /* Open the index sub-system */
  183297. if( rc==SQLITE_OK ){
  183298. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
  183299. }
  183300. /* Open the storage sub-system */
  183301. if( rc==SQLITE_OK ){
  183302. rc = sqlite3Fts5StorageOpen(
  183303. pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
  183304. );
  183305. }
  183306. /* Call sqlite3_declare_vtab() */
  183307. if( rc==SQLITE_OK ){
  183308. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  183309. }
  183310. /* Load the initial configuration */
  183311. if( rc==SQLITE_OK ){
  183312. assert( pConfig->pzErrmsg==0 );
  183313. pConfig->pzErrmsg = pzErr;
  183314. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  183315. sqlite3Fts5IndexRollback(pTab->pIndex);
  183316. pConfig->pzErrmsg = 0;
  183317. }
  183318. if( rc!=SQLITE_OK ){
  183319. fts5FreeVtab(pTab);
  183320. pTab = 0;
  183321. }else if( bCreate ){
  183322. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  183323. }
  183324. *ppVTab = (sqlite3_vtab*)pTab;
  183325. return rc;
  183326. }
  183327. /*
  183328. ** The xConnect() and xCreate() methods for the virtual table. All the
  183329. ** work is done in function fts5InitVtab().
  183330. */
  183331. static int fts5ConnectMethod(
  183332. sqlite3 *db, /* Database connection */
  183333. void *pAux, /* Pointer to tokenizer hash table */
  183334. int argc, /* Number of elements in argv array */
  183335. const char * const *argv, /* xCreate/xConnect argument array */
  183336. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  183337. char **pzErr /* OUT: sqlite3_malloc'd error message */
  183338. ){
  183339. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  183340. }
  183341. static int fts5CreateMethod(
  183342. sqlite3 *db, /* Database connection */
  183343. void *pAux, /* Pointer to tokenizer hash table */
  183344. int argc, /* Number of elements in argv array */
  183345. const char * const *argv, /* xCreate/xConnect argument array */
  183346. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  183347. char **pzErr /* OUT: sqlite3_malloc'd error message */
  183348. ){
  183349. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  183350. }
  183351. /*
  183352. ** The different query plans.
  183353. */
  183354. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  183355. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  183356. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  183357. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  183358. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  183359. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  183360. /*
  183361. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  183362. ** extension is currently being used by a version of SQLite too old to
  183363. ** support index-info flags. In that case this function is a no-op.
  183364. */
  183365. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  183366. #if SQLITE_VERSION_NUMBER>=3008012
  183367. #ifndef SQLITE_CORE
  183368. if( sqlite3_libversion_number()>=3008012 )
  183369. #endif
  183370. {
  183371. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  183372. }
  183373. #endif
  183374. }
  183375. /*
  183376. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  183377. ** WHERE constraint, it searches for the following:
  183378. **
  183379. ** 1. A MATCH constraint against the special column.
  183380. ** 2. A MATCH constraint against the "rank" column.
  183381. ** 3. An == constraint against the rowid column.
  183382. ** 4. A < or <= constraint against the rowid column.
  183383. ** 5. A > or >= constraint against the rowid column.
  183384. **
  183385. ** Within the ORDER BY, either:
  183386. **
  183387. ** 5. ORDER BY rank [ASC|DESC]
  183388. ** 6. ORDER BY rowid [ASC|DESC]
  183389. **
  183390. ** Costs are assigned as follows:
  183391. **
  183392. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  183393. ** cost is unconditionally set to 1e50 (a really big number).
  183394. **
  183395. ** a) If a MATCH operator is present, the cost depends on the other
  183396. ** constraints also present. As follows:
  183397. **
  183398. ** * No other constraints: cost=1000.0
  183399. ** * One rowid range constraint: cost=750.0
  183400. ** * Both rowid range constraints: cost=500.0
  183401. ** * An == rowid constraint: cost=100.0
  183402. **
  183403. ** b) Otherwise, if there is no MATCH:
  183404. **
  183405. ** * No other constraints: cost=1000000.0
  183406. ** * One rowid range constraint: cost=750000.0
  183407. ** * Both rowid range constraints: cost=250000.0
  183408. ** * An == rowid constraint: cost=10.0
  183409. **
  183410. ** Costs are not modified by the ORDER BY clause.
  183411. */
  183412. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  183413. Fts5Table *pTab = (Fts5Table*)pVTab;
  183414. Fts5Config *pConfig = pTab->pConfig;
  183415. const int nCol = pConfig->nCol;
  183416. int idxFlags = 0; /* Parameter passed through to xFilter() */
  183417. int bHasMatch;
  183418. int iNext;
  183419. int i;
  183420. struct Constraint {
  183421. int op; /* Mask against sqlite3_index_constraint.op */
  183422. int fts5op; /* FTS5 mask for idxFlags */
  183423. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  183424. int omit; /* True to omit this if found */
  183425. int iConsIndex; /* Index in pInfo->aConstraint[] */
  183426. } aConstraint[] = {
  183427. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  183428. FTS5_BI_MATCH, 1, 1, -1},
  183429. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  183430. FTS5_BI_RANK, 2, 1, -1},
  183431. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  183432. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  183433. FTS5_BI_ROWID_LE, 0, 0, -1},
  183434. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  183435. FTS5_BI_ROWID_GE, 0, 0, -1},
  183436. };
  183437. int aColMap[3];
  183438. aColMap[0] = -1;
  183439. aColMap[1] = nCol;
  183440. aColMap[2] = nCol+1;
  183441. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  183442. for(i=0; i<pInfo->nConstraint; i++){
  183443. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  183444. int iCol = p->iColumn;
  183445. if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
  183446. || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
  183447. ){
  183448. /* A MATCH operator or equivalent */
  183449. if( p->usable ){
  183450. idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
  183451. aConstraint[0].iConsIndex = i;
  183452. }else{
  183453. /* As there exists an unusable MATCH constraint this is an
  183454. ** unusable plan. Set a prohibitively high cost. */
  183455. pInfo->estimatedCost = 1e50;
  183456. return SQLITE_OK;
  183457. }
  183458. }else{
  183459. int j;
  183460. for(j=1; j<ArraySize(aConstraint); j++){
  183461. struct Constraint *pC = &aConstraint[j];
  183462. if( iCol==aColMap[pC->iCol] && p->op & pC->op && p->usable ){
  183463. pC->iConsIndex = i;
  183464. idxFlags |= pC->fts5op;
  183465. }
  183466. }
  183467. }
  183468. }
  183469. /* Set idxFlags flags for the ORDER BY clause */
  183470. if( pInfo->nOrderBy==1 ){
  183471. int iSort = pInfo->aOrderBy[0].iColumn;
  183472. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  183473. idxFlags |= FTS5_BI_ORDER_RANK;
  183474. }else if( iSort==-1 ){
  183475. idxFlags |= FTS5_BI_ORDER_ROWID;
  183476. }
  183477. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  183478. pInfo->orderByConsumed = 1;
  183479. if( pInfo->aOrderBy[0].desc ){
  183480. idxFlags |= FTS5_BI_ORDER_DESC;
  183481. }
  183482. }
  183483. }
  183484. /* Calculate the estimated cost based on the flags set in idxFlags. */
  183485. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  183486. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  183487. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  183488. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  183489. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  183490. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  183491. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  183492. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  183493. }else{
  183494. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  183495. }
  183496. /* Assign argvIndex values to each constraint in use. */
  183497. iNext = 1;
  183498. for(i=0; i<ArraySize(aConstraint); i++){
  183499. struct Constraint *pC = &aConstraint[i];
  183500. if( pC->iConsIndex>=0 ){
  183501. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  183502. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  183503. }
  183504. }
  183505. pInfo->idxNum = idxFlags;
  183506. return SQLITE_OK;
  183507. }
  183508. static int fts5NewTransaction(Fts5Table *pTab){
  183509. Fts5Cursor *pCsr;
  183510. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  183511. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  183512. }
  183513. return sqlite3Fts5StorageReset(pTab->pStorage);
  183514. }
  183515. /*
  183516. ** Implementation of xOpen method.
  183517. */
  183518. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  183519. Fts5Table *pTab = (Fts5Table*)pVTab;
  183520. Fts5Config *pConfig = pTab->pConfig;
  183521. Fts5Cursor *pCsr = 0; /* New cursor object */
  183522. int nByte; /* Bytes of space to allocate */
  183523. int rc; /* Return code */
  183524. rc = fts5NewTransaction(pTab);
  183525. if( rc==SQLITE_OK ){
  183526. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  183527. pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
  183528. if( pCsr ){
  183529. Fts5Global *pGlobal = pTab->pGlobal;
  183530. memset(pCsr, 0, nByte);
  183531. pCsr->aColumnSize = (int*)&pCsr[1];
  183532. pCsr->pNext = pGlobal->pCsr;
  183533. pGlobal->pCsr = pCsr;
  183534. pCsr->iCsrId = ++pGlobal->iNextId;
  183535. }else{
  183536. rc = SQLITE_NOMEM;
  183537. }
  183538. }
  183539. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  183540. return rc;
  183541. }
  183542. static int fts5StmtType(Fts5Cursor *pCsr){
  183543. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  183544. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  183545. }
  183546. return FTS5_STMT_LOOKUP;
  183547. }
  183548. /*
  183549. ** This function is called after the cursor passed as the only argument
  183550. ** is moved to point at a different row. It clears all cached data
  183551. ** specific to the previous row stored by the cursor object.
  183552. */
  183553. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  183554. CsrFlagSet(pCsr,
  183555. FTS5CSR_REQUIRE_CONTENT
  183556. | FTS5CSR_REQUIRE_DOCSIZE
  183557. | FTS5CSR_REQUIRE_INST
  183558. | FTS5CSR_REQUIRE_POSLIST
  183559. );
  183560. }
  183561. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  183562. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  183563. Fts5Auxdata *pData;
  183564. Fts5Auxdata *pNext;
  183565. sqlite3_free(pCsr->aInstIter);
  183566. sqlite3_free(pCsr->aInst);
  183567. if( pCsr->pStmt ){
  183568. int eStmt = fts5StmtType(pCsr);
  183569. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  183570. }
  183571. if( pCsr->pSorter ){
  183572. Fts5Sorter *pSorter = pCsr->pSorter;
  183573. sqlite3_finalize(pSorter->pStmt);
  183574. sqlite3_free(pSorter);
  183575. }
  183576. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  183577. sqlite3Fts5ExprFree(pCsr->pExpr);
  183578. }
  183579. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  183580. pNext = pData->pNext;
  183581. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  183582. sqlite3_free(pData);
  183583. }
  183584. sqlite3_finalize(pCsr->pRankArgStmt);
  183585. sqlite3_free(pCsr->apRankArg);
  183586. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  183587. sqlite3_free(pCsr->zRank);
  183588. sqlite3_free(pCsr->zRankArgs);
  183589. }
  183590. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  183591. }
  183592. /*
  183593. ** Close the cursor. For additional information see the documentation
  183594. ** on the xClose method of the virtual table interface.
  183595. */
  183596. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  183597. if( pCursor ){
  183598. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  183599. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  183600. Fts5Cursor **pp;
  183601. fts5FreeCursorComponents(pCsr);
  183602. /* Remove the cursor from the Fts5Global.pCsr list */
  183603. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  183604. *pp = pCsr->pNext;
  183605. sqlite3_free(pCsr);
  183606. }
  183607. return SQLITE_OK;
  183608. }
  183609. static int fts5SorterNext(Fts5Cursor *pCsr){
  183610. Fts5Sorter *pSorter = pCsr->pSorter;
  183611. int rc;
  183612. rc = sqlite3_step(pSorter->pStmt);
  183613. if( rc==SQLITE_DONE ){
  183614. rc = SQLITE_OK;
  183615. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183616. }else if( rc==SQLITE_ROW ){
  183617. const u8 *a;
  183618. const u8 *aBlob;
  183619. int nBlob;
  183620. int i;
  183621. int iOff = 0;
  183622. rc = SQLITE_OK;
  183623. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  183624. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  183625. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  183626. /* nBlob==0 in detail=none mode. */
  183627. if( nBlob>0 ){
  183628. for(i=0; i<(pSorter->nIdx-1); i++){
  183629. int iVal;
  183630. a += fts5GetVarint32(a, iVal);
  183631. iOff += iVal;
  183632. pSorter->aIdx[i] = iOff;
  183633. }
  183634. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  183635. pSorter->aPoslist = a;
  183636. }
  183637. fts5CsrNewrow(pCsr);
  183638. }
  183639. return rc;
  183640. }
  183641. /*
  183642. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  183643. ** open on table pTab.
  183644. */
  183645. static void fts5TripCursors(Fts5Table *pTab){
  183646. Fts5Cursor *pCsr;
  183647. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  183648. if( pCsr->ePlan==FTS5_PLAN_MATCH
  183649. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  183650. ){
  183651. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  183652. }
  183653. }
  183654. }
  183655. /*
  183656. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  183657. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  183658. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  183659. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  183660. **
  183661. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  183662. ** to 1 before returning. Otherwise, leave it unchanged.
  183663. **
  183664. ** Return SQLITE_OK if successful or if no reseek was required, or an
  183665. ** error code if an error occurred.
  183666. */
  183667. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  183668. int rc = SQLITE_OK;
  183669. assert( *pbSkip==0 );
  183670. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  183671. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  183672. int bDesc = pCsr->bDesc;
  183673. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  183674. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
  183675. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  183676. *pbSkip = 1;
  183677. }
  183678. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  183679. fts5CsrNewrow(pCsr);
  183680. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  183681. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183682. *pbSkip = 1;
  183683. }
  183684. }
  183685. return rc;
  183686. }
  183687. /*
  183688. ** Advance the cursor to the next row in the table that matches the
  183689. ** search criteria.
  183690. **
  183691. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  183692. ** even if we reach end-of-file. The fts5EofMethod() will be called
  183693. ** subsequently to determine whether or not an EOF was hit.
  183694. */
  183695. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  183696. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  183697. int rc;
  183698. assert( (pCsr->ePlan<3)==
  183699. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  183700. );
  183701. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  183702. if( pCsr->ePlan<3 ){
  183703. int bSkip = 0;
  183704. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  183705. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  183706. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  183707. fts5CsrNewrow(pCsr);
  183708. }else{
  183709. switch( pCsr->ePlan ){
  183710. case FTS5_PLAN_SPECIAL: {
  183711. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183712. rc = SQLITE_OK;
  183713. break;
  183714. }
  183715. case FTS5_PLAN_SORTED_MATCH: {
  183716. rc = fts5SorterNext(pCsr);
  183717. break;
  183718. }
  183719. default:
  183720. rc = sqlite3_step(pCsr->pStmt);
  183721. if( rc!=SQLITE_ROW ){
  183722. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183723. rc = sqlite3_reset(pCsr->pStmt);
  183724. }else{
  183725. rc = SQLITE_OK;
  183726. }
  183727. break;
  183728. }
  183729. }
  183730. return rc;
  183731. }
  183732. static int fts5PrepareStatement(
  183733. sqlite3_stmt **ppStmt,
  183734. Fts5Config *pConfig,
  183735. const char *zFmt,
  183736. ...
  183737. ){
  183738. sqlite3_stmt *pRet = 0;
  183739. int rc;
  183740. char *zSql;
  183741. va_list ap;
  183742. va_start(ap, zFmt);
  183743. zSql = sqlite3_vmprintf(zFmt, ap);
  183744. if( zSql==0 ){
  183745. rc = SQLITE_NOMEM;
  183746. }else{
  183747. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
  183748. if( rc!=SQLITE_OK ){
  183749. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  183750. }
  183751. sqlite3_free(zSql);
  183752. }
  183753. va_end(ap);
  183754. *ppStmt = pRet;
  183755. return rc;
  183756. }
  183757. static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  183758. Fts5Config *pConfig = pTab->pConfig;
  183759. Fts5Sorter *pSorter;
  183760. int nPhrase;
  183761. int nByte;
  183762. int rc;
  183763. const char *zRank = pCsr->zRank;
  183764. const char *zRankArgs = pCsr->zRankArgs;
  183765. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  183766. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  183767. pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
  183768. if( pSorter==0 ) return SQLITE_NOMEM;
  183769. memset(pSorter, 0, nByte);
  183770. pSorter->nIdx = nPhrase;
  183771. /* TODO: It would be better to have some system for reusing statement
  183772. ** handles here, rather than preparing a new one for each query. But that
  183773. ** is not possible as SQLite reference counts the virtual table objects.
  183774. ** And since the statement required here reads from this very virtual
  183775. ** table, saving it creates a circular reference.
  183776. **
  183777. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  183778. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  183779. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  183780. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  183781. (zRankArgs ? ", " : ""),
  183782. (zRankArgs ? zRankArgs : ""),
  183783. bDesc ? "DESC" : "ASC"
  183784. );
  183785. pCsr->pSorter = pSorter;
  183786. if( rc==SQLITE_OK ){
  183787. assert( pTab->pSortCsr==0 );
  183788. pTab->pSortCsr = pCsr;
  183789. rc = fts5SorterNext(pCsr);
  183790. pTab->pSortCsr = 0;
  183791. }
  183792. if( rc!=SQLITE_OK ){
  183793. sqlite3_finalize(pSorter->pStmt);
  183794. sqlite3_free(pSorter);
  183795. pCsr->pSorter = 0;
  183796. }
  183797. return rc;
  183798. }
  183799. static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  183800. int rc;
  183801. Fts5Expr *pExpr = pCsr->pExpr;
  183802. rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
  183803. if( sqlite3Fts5ExprEof(pExpr) ){
  183804. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183805. }
  183806. fts5CsrNewrow(pCsr);
  183807. return rc;
  183808. }
  183809. /*
  183810. ** Process a "special" query. A special query is identified as one with a
  183811. ** MATCH expression that begins with a '*' character. The remainder of
  183812. ** the text passed to the MATCH operator are used as the special query
  183813. ** parameters.
  183814. */
  183815. static int fts5SpecialMatch(
  183816. Fts5Table *pTab,
  183817. Fts5Cursor *pCsr,
  183818. const char *zQuery
  183819. ){
  183820. int rc = SQLITE_OK; /* Return code */
  183821. const char *z = zQuery; /* Special query text */
  183822. int n; /* Number of bytes in text at z */
  183823. while( z[0]==' ' ) z++;
  183824. for(n=0; z[n] && z[n]!=' '; n++);
  183825. assert( pTab->base.zErrMsg==0 );
  183826. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  183827. if( 0==sqlite3_strnicmp("reads", z, n) ){
  183828. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
  183829. }
  183830. else if( 0==sqlite3_strnicmp("id", z, n) ){
  183831. pCsr->iSpecial = pCsr->iCsrId;
  183832. }
  183833. else{
  183834. /* An unrecognized directive. Return an error message. */
  183835. pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  183836. rc = SQLITE_ERROR;
  183837. }
  183838. return rc;
  183839. }
  183840. /*
  183841. ** Search for an auxiliary function named zName that can be used with table
  183842. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  183843. ** structure. Otherwise, if no such function exists, return NULL.
  183844. */
  183845. static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
  183846. Fts5Auxiliary *pAux;
  183847. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  183848. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  183849. }
  183850. /* No function of the specified name was found. Return 0. */
  183851. return 0;
  183852. }
  183853. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  183854. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  183855. Fts5Config *pConfig = pTab->pConfig;
  183856. int rc = SQLITE_OK;
  183857. Fts5Auxiliary *pAux = 0;
  183858. const char *zRank = pCsr->zRank;
  183859. const char *zRankArgs = pCsr->zRankArgs;
  183860. if( zRankArgs ){
  183861. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  183862. if( zSql ){
  183863. sqlite3_stmt *pStmt = 0;
  183864. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
  183865. sqlite3_free(zSql);
  183866. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  183867. if( rc==SQLITE_OK ){
  183868. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  183869. int nByte;
  183870. pCsr->nRankArg = sqlite3_column_count(pStmt);
  183871. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  183872. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  183873. if( rc==SQLITE_OK ){
  183874. int i;
  183875. for(i=0; i<pCsr->nRankArg; i++){
  183876. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  183877. }
  183878. }
  183879. pCsr->pRankArgStmt = pStmt;
  183880. }else{
  183881. rc = sqlite3_finalize(pStmt);
  183882. assert( rc!=SQLITE_OK );
  183883. }
  183884. }
  183885. }
  183886. }
  183887. if( rc==SQLITE_OK ){
  183888. pAux = fts5FindAuxiliary(pTab, zRank);
  183889. if( pAux==0 ){
  183890. assert( pTab->base.zErrMsg==0 );
  183891. pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  183892. rc = SQLITE_ERROR;
  183893. }
  183894. }
  183895. pCsr->pRank = pAux;
  183896. return rc;
  183897. }
  183898. static int fts5CursorParseRank(
  183899. Fts5Config *pConfig,
  183900. Fts5Cursor *pCsr,
  183901. sqlite3_value *pRank
  183902. ){
  183903. int rc = SQLITE_OK;
  183904. if( pRank ){
  183905. const char *z = (const char*)sqlite3_value_text(pRank);
  183906. char *zRank = 0;
  183907. char *zRankArgs = 0;
  183908. if( z==0 ){
  183909. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  183910. }else{
  183911. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  183912. }
  183913. if( rc==SQLITE_OK ){
  183914. pCsr->zRank = zRank;
  183915. pCsr->zRankArgs = zRankArgs;
  183916. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  183917. }else if( rc==SQLITE_ERROR ){
  183918. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  183919. "parse error in rank function: %s", z
  183920. );
  183921. }
  183922. }else{
  183923. if( pConfig->zRank ){
  183924. pCsr->zRank = (char*)pConfig->zRank;
  183925. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  183926. }else{
  183927. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  183928. pCsr->zRankArgs = 0;
  183929. }
  183930. }
  183931. return rc;
  183932. }
  183933. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  183934. if( pVal ){
  183935. int eType = sqlite3_value_numeric_type(pVal);
  183936. if( eType==SQLITE_INTEGER ){
  183937. return sqlite3_value_int64(pVal);
  183938. }
  183939. }
  183940. return iDefault;
  183941. }
  183942. /*
  183943. ** This is the xFilter interface for the virtual table. See
  183944. ** the virtual table xFilter method documentation for additional
  183945. ** information.
  183946. **
  183947. ** There are three possible query strategies:
  183948. **
  183949. ** 1. Full-text search using a MATCH operator.
  183950. ** 2. A by-rowid lookup.
  183951. ** 3. A full-table scan.
  183952. */
  183953. static int fts5FilterMethod(
  183954. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  183955. int idxNum, /* Strategy index */
  183956. const char *zUnused, /* Unused */
  183957. int nVal, /* Number of elements in apVal */
  183958. sqlite3_value **apVal /* Arguments for the indexing scheme */
  183959. ){
  183960. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  183961. Fts5Config *pConfig = pTab->pConfig;
  183962. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  183963. int rc = SQLITE_OK; /* Error code */
  183964. int iVal = 0; /* Counter for apVal[] */
  183965. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  183966. int bOrderByRank; /* True if ORDER BY rank */
  183967. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  183968. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  183969. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  183970. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  183971. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  183972. int iCol; /* Column on LHS of MATCH operator */
  183973. char **pzErrmsg = pConfig->pzErrmsg;
  183974. UNUSED_PARAM(zUnused);
  183975. UNUSED_PARAM(nVal);
  183976. if( pCsr->ePlan ){
  183977. fts5FreeCursorComponents(pCsr);
  183978. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  183979. }
  183980. assert( pCsr->pStmt==0 );
  183981. assert( pCsr->pExpr==0 );
  183982. assert( pCsr->csrflags==0 );
  183983. assert( pCsr->pRank==0 );
  183984. assert( pCsr->zRank==0 );
  183985. assert( pCsr->zRankArgs==0 );
  183986. assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
  183987. pConfig->pzErrmsg = &pTab->base.zErrMsg;
  183988. /* Decode the arguments passed through to this function.
  183989. **
  183990. ** Note: The following set of if(...) statements must be in the same
  183991. ** order as the corresponding entries in the struct at the top of
  183992. ** fts5BestIndexMethod(). */
  183993. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  183994. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  183995. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  183996. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  183997. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  183998. iCol = (idxNum>>16);
  183999. assert( iCol>=0 && iCol<=pConfig->nCol );
  184000. assert( iVal==nVal );
  184001. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  184002. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  184003. /* Set the cursor upper and lower rowid limits. Only some strategies
  184004. ** actually use them. This is ok, as the xBestIndex() method leaves the
  184005. ** sqlite3_index_constraint.omit flag clear for range constraints
  184006. ** on the rowid field. */
  184007. if( pRowidEq ){
  184008. pRowidLe = pRowidGe = pRowidEq;
  184009. }
  184010. if( bDesc ){
  184011. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  184012. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  184013. }else{
  184014. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  184015. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  184016. }
  184017. if( pTab->pSortCsr ){
  184018. /* If pSortCsr is non-NULL, then this call is being made as part of
  184019. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  184020. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  184021. ** return results to the user for this query. The current cursor
  184022. ** (pCursor) is used to execute the query issued by function
  184023. ** fts5CursorFirstSorted() above. */
  184024. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  184025. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  184026. assert( pCsr->iLastRowid==LARGEST_INT64 );
  184027. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  184028. pCsr->ePlan = FTS5_PLAN_SOURCE;
  184029. pCsr->pExpr = pTab->pSortCsr->pExpr;
  184030. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  184031. }else if( pMatch ){
  184032. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  184033. if( zExpr==0 ) zExpr = "";
  184034. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  184035. if( rc==SQLITE_OK ){
  184036. if( zExpr[0]=='*' ){
  184037. /* The user has issued a query of the form "MATCH '*...'". This
  184038. ** indicates that the MATCH expression is not a full text query,
  184039. ** but a request for an internal parameter. */
  184040. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  184041. }else{
  184042. char **pzErr = &pTab->base.zErrMsg;
  184043. rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
  184044. if( rc==SQLITE_OK ){
  184045. if( bOrderByRank ){
  184046. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  184047. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  184048. }else{
  184049. pCsr->ePlan = FTS5_PLAN_MATCH;
  184050. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  184051. }
  184052. }
  184053. }
  184054. }
  184055. }else if( pConfig->zContent==0 ){
  184056. *pConfig->pzErrmsg = sqlite3_mprintf(
  184057. "%s: table does not support scanning", pConfig->zName
  184058. );
  184059. rc = SQLITE_ERROR;
  184060. }else{
  184061. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  184062. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  184063. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  184064. rc = sqlite3Fts5StorageStmt(
  184065. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
  184066. );
  184067. if( rc==SQLITE_OK ){
  184068. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  184069. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  184070. }else{
  184071. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  184072. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  184073. }
  184074. rc = fts5NextMethod(pCursor);
  184075. }
  184076. }
  184077. pConfig->pzErrmsg = pzErrmsg;
  184078. return rc;
  184079. }
  184080. /*
  184081. ** This is the xEof method of the virtual table. SQLite calls this
  184082. ** routine to find out if it has reached the end of a result set.
  184083. */
  184084. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  184085. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  184086. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  184087. }
  184088. /*
  184089. ** Return the rowid that the cursor currently points to.
  184090. */
  184091. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  184092. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  184093. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  184094. || pCsr->ePlan==FTS5_PLAN_SOURCE
  184095. );
  184096. if( pCsr->pSorter ){
  184097. return pCsr->pSorter->iRowid;
  184098. }else{
  184099. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  184100. }
  184101. }
  184102. /*
  184103. ** This is the xRowid method. The SQLite core calls this routine to
  184104. ** retrieve the rowid for the current row of the result set. fts5
  184105. ** exposes %_content.rowid as the rowid for the virtual table. The
  184106. ** rowid should be written to *pRowid.
  184107. */
  184108. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  184109. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  184110. int ePlan = pCsr->ePlan;
  184111. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  184112. switch( ePlan ){
  184113. case FTS5_PLAN_SPECIAL:
  184114. *pRowid = 0;
  184115. break;
  184116. case FTS5_PLAN_SOURCE:
  184117. case FTS5_PLAN_MATCH:
  184118. case FTS5_PLAN_SORTED_MATCH:
  184119. *pRowid = fts5CursorRowid(pCsr);
  184120. break;
  184121. default:
  184122. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  184123. break;
  184124. }
  184125. return SQLITE_OK;
  184126. }
  184127. /*
  184128. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  184129. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  184130. **
  184131. ** If argument bErrormsg is true and an error occurs, an error message may
  184132. ** be left in sqlite3_vtab.zErrMsg.
  184133. */
  184134. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  184135. int rc = SQLITE_OK;
  184136. /* If the cursor does not yet have a statement handle, obtain one now. */
  184137. if( pCsr->pStmt==0 ){
  184138. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184139. int eStmt = fts5StmtType(pCsr);
  184140. rc = sqlite3Fts5StorageStmt(
  184141. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
  184142. );
  184143. assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
  184144. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  184145. }
  184146. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  184147. assert( pCsr->pExpr );
  184148. sqlite3_reset(pCsr->pStmt);
  184149. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  184150. rc = sqlite3_step(pCsr->pStmt);
  184151. if( rc==SQLITE_ROW ){
  184152. rc = SQLITE_OK;
  184153. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  184154. }else{
  184155. rc = sqlite3_reset(pCsr->pStmt);
  184156. if( rc==SQLITE_OK ){
  184157. rc = FTS5_CORRUPT;
  184158. }
  184159. }
  184160. }
  184161. return rc;
  184162. }
  184163. static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
  184164. va_list ap; /* ... printf arguments */
  184165. va_start(ap, zFormat);
  184166. assert( p->base.zErrMsg==0 );
  184167. p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  184168. va_end(ap);
  184169. }
  184170. /*
  184171. ** This function is called to handle an FTS INSERT command. In other words,
  184172. ** an INSERT statement of the form:
  184173. **
  184174. ** INSERT INTO fts(fts) VALUES($pCmd)
  184175. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  184176. **
  184177. ** Argument pVal is the value assigned to column "fts" by the INSERT
  184178. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  184179. ** error code if an error occurs.
  184180. **
  184181. ** The commands implemented by this function are documented in the "Special
  184182. ** INSERT Directives" section of the documentation. It should be updated if
  184183. ** more commands are added to this function.
  184184. */
  184185. static int fts5SpecialInsert(
  184186. Fts5Table *pTab, /* Fts5 table object */
  184187. const char *zCmd, /* Text inserted into table-name column */
  184188. sqlite3_value *pVal /* Value inserted into rank column */
  184189. ){
  184190. Fts5Config *pConfig = pTab->pConfig;
  184191. int rc = SQLITE_OK;
  184192. int bError = 0;
  184193. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  184194. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  184195. fts5SetVtabError(pTab,
  184196. "'delete-all' may only be used with a "
  184197. "contentless or external content fts5 table"
  184198. );
  184199. rc = SQLITE_ERROR;
  184200. }else{
  184201. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  184202. }
  184203. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  184204. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  184205. fts5SetVtabError(pTab,
  184206. "'rebuild' may not be used with a contentless fts5 table"
  184207. );
  184208. rc = SQLITE_ERROR;
  184209. }else{
  184210. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  184211. }
  184212. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  184213. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  184214. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  184215. int nMerge = sqlite3_value_int(pVal);
  184216. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  184217. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  184218. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  184219. #ifdef SQLITE_DEBUG
  184220. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  184221. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  184222. #endif
  184223. }else{
  184224. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  184225. if( rc==SQLITE_OK ){
  184226. rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
  184227. }
  184228. if( rc==SQLITE_OK ){
  184229. if( bError ){
  184230. rc = SQLITE_ERROR;
  184231. }else{
  184232. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  184233. }
  184234. }
  184235. }
  184236. return rc;
  184237. }
  184238. static int fts5SpecialDelete(
  184239. Fts5Table *pTab,
  184240. sqlite3_value **apVal
  184241. ){
  184242. int rc = SQLITE_OK;
  184243. int eType1 = sqlite3_value_type(apVal[1]);
  184244. if( eType1==SQLITE_INTEGER ){
  184245. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  184246. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  184247. }
  184248. return rc;
  184249. }
  184250. static void fts5StorageInsert(
  184251. int *pRc,
  184252. Fts5Table *pTab,
  184253. sqlite3_value **apVal,
  184254. i64 *piRowid
  184255. ){
  184256. int rc = *pRc;
  184257. if( rc==SQLITE_OK ){
  184258. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  184259. }
  184260. if( rc==SQLITE_OK ){
  184261. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  184262. }
  184263. *pRc = rc;
  184264. }
  184265. /*
  184266. ** This function is the implementation of the xUpdate callback used by
  184267. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  184268. ** inserted, updated or deleted.
  184269. **
  184270. ** A delete specifies a single argument - the rowid of the row to remove.
  184271. **
  184272. ** Update and insert operations pass:
  184273. **
  184274. ** 1. The "old" rowid, or NULL.
  184275. ** 2. The "new" rowid.
  184276. ** 3. Values for each of the nCol matchable columns.
  184277. ** 4. Values for the two hidden columns (<tablename> and "rank").
  184278. */
  184279. static int fts5UpdateMethod(
  184280. sqlite3_vtab *pVtab, /* Virtual table handle */
  184281. int nArg, /* Size of argument array */
  184282. sqlite3_value **apVal, /* Array of arguments */
  184283. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  184284. ){
  184285. Fts5Table *pTab = (Fts5Table*)pVtab;
  184286. Fts5Config *pConfig = pTab->pConfig;
  184287. int eType0; /* value_type() of apVal[0] */
  184288. int rc = SQLITE_OK; /* Return code */
  184289. /* A transaction must be open when this is called. */
  184290. assert( pTab->ts.eState==1 );
  184291. assert( pVtab->zErrMsg==0 );
  184292. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  184293. assert( nArg==1
  184294. || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  184295. || sqlite3_value_type(apVal[1])==SQLITE_NULL
  184296. );
  184297. assert( pTab->pConfig->pzErrmsg==0 );
  184298. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  184299. /* Put any active cursors into REQUIRE_SEEK state. */
  184300. fts5TripCursors(pTab);
  184301. eType0 = sqlite3_value_type(apVal[0]);
  184302. if( eType0==SQLITE_NULL
  184303. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  184304. ){
  184305. /* A "special" INSERT op. These are handled separately. */
  184306. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  184307. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  184308. && 0==sqlite3_stricmp("delete", z)
  184309. ){
  184310. rc = fts5SpecialDelete(pTab, apVal);
  184311. }else{
  184312. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  184313. }
  184314. }else{
  184315. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  184316. ** any conflict on the rowid value must be detected before any
  184317. ** modifications are made to the database file. There are 4 cases:
  184318. **
  184319. ** 1) DELETE
  184320. ** 2) UPDATE (rowid not modified)
  184321. ** 3) UPDATE (rowid modified)
  184322. ** 4) INSERT
  184323. **
  184324. ** Cases 3 and 4 may violate the rowid constraint.
  184325. */
  184326. int eConflict = SQLITE_ABORT;
  184327. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  184328. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  184329. }
  184330. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  184331. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  184332. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  184333. ** This is not suported. */
  184334. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  184335. pTab->base.zErrMsg = sqlite3_mprintf(
  184336. "cannot %s contentless fts5 table: %s",
  184337. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  184338. );
  184339. rc = SQLITE_ERROR;
  184340. }
  184341. /* DELETE */
  184342. else if( nArg==1 ){
  184343. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  184344. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  184345. }
  184346. /* INSERT */
  184347. else if( eType0!=SQLITE_INTEGER ){
  184348. /* If this is a REPLACE, first remove the current entry (if any) */
  184349. if( eConflict==SQLITE_REPLACE
  184350. && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  184351. ){
  184352. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  184353. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  184354. }
  184355. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  184356. }
  184357. /* UPDATE */
  184358. else{
  184359. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  184360. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  184361. if( iOld!=iNew ){
  184362. if( eConflict==SQLITE_REPLACE ){
  184363. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  184364. if( rc==SQLITE_OK ){
  184365. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  184366. }
  184367. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  184368. }else{
  184369. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  184370. if( rc==SQLITE_OK ){
  184371. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  184372. }
  184373. if( rc==SQLITE_OK ){
  184374. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
  184375. }
  184376. }
  184377. }else{
  184378. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  184379. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  184380. }
  184381. }
  184382. }
  184383. pTab->pConfig->pzErrmsg = 0;
  184384. return rc;
  184385. }
  184386. /*
  184387. ** Implementation of xSync() method.
  184388. */
  184389. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  184390. int rc;
  184391. Fts5Table *pTab = (Fts5Table*)pVtab;
  184392. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  184393. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  184394. fts5TripCursors(pTab);
  184395. rc = sqlite3Fts5StorageSync(pTab->pStorage);
  184396. pTab->pConfig->pzErrmsg = 0;
  184397. return rc;
  184398. }
  184399. /*
  184400. ** Implementation of xBegin() method.
  184401. */
  184402. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  184403. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
  184404. fts5NewTransaction((Fts5Table*)pVtab);
  184405. return SQLITE_OK;
  184406. }
  184407. /*
  184408. ** Implementation of xCommit() method. This is a no-op. The contents of
  184409. ** the pending-terms hash-table have already been flushed into the database
  184410. ** by fts5SyncMethod().
  184411. */
  184412. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  184413. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  184414. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
  184415. return SQLITE_OK;
  184416. }
  184417. /*
  184418. ** Implementation of xRollback(). Discard the contents of the pending-terms
  184419. ** hash-table. Any changes made to the database are reverted by SQLite.
  184420. */
  184421. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  184422. int rc;
  184423. Fts5Table *pTab = (Fts5Table*)pVtab;
  184424. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  184425. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  184426. return rc;
  184427. }
  184428. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  184429. static void *fts5ApiUserData(Fts5Context *pCtx){
  184430. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184431. return pCsr->pAux->pUserData;
  184432. }
  184433. static int fts5ApiColumnCount(Fts5Context *pCtx){
  184434. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184435. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  184436. }
  184437. static int fts5ApiColumnTotalSize(
  184438. Fts5Context *pCtx,
  184439. int iCol,
  184440. sqlite3_int64 *pnToken
  184441. ){
  184442. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184443. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184444. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  184445. }
  184446. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  184447. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184448. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184449. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  184450. }
  184451. static int fts5ApiTokenize(
  184452. Fts5Context *pCtx,
  184453. const char *pText, int nText,
  184454. void *pUserData,
  184455. int (*xToken)(void*, int, const char*, int, int, int)
  184456. ){
  184457. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184458. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184459. return sqlite3Fts5Tokenize(
  184460. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  184461. );
  184462. }
  184463. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  184464. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184465. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  184466. }
  184467. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  184468. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184469. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  184470. }
  184471. static int fts5ApiColumnText(
  184472. Fts5Context *pCtx,
  184473. int iCol,
  184474. const char **pz,
  184475. int *pn
  184476. ){
  184477. int rc = SQLITE_OK;
  184478. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184479. if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
  184480. *pz = 0;
  184481. *pn = 0;
  184482. }else{
  184483. rc = fts5SeekCursor(pCsr, 0);
  184484. if( rc==SQLITE_OK ){
  184485. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  184486. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  184487. }
  184488. }
  184489. return rc;
  184490. }
  184491. static int fts5CsrPoslist(
  184492. Fts5Cursor *pCsr,
  184493. int iPhrase,
  184494. const u8 **pa,
  184495. int *pn
  184496. ){
  184497. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  184498. int rc = SQLITE_OK;
  184499. int bLive = (pCsr->pSorter==0);
  184500. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  184501. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  184502. Fts5PoslistPopulator *aPopulator;
  184503. int i;
  184504. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  184505. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  184506. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  184507. int n; const char *z;
  184508. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  184509. if( rc==SQLITE_OK ){
  184510. rc = sqlite3Fts5ExprPopulatePoslists(
  184511. pConfig, pCsr->pExpr, aPopulator, i, z, n
  184512. );
  184513. }
  184514. }
  184515. sqlite3_free(aPopulator);
  184516. if( pCsr->pSorter ){
  184517. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  184518. }
  184519. }
  184520. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  184521. }
  184522. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  184523. Fts5Sorter *pSorter = pCsr->pSorter;
  184524. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  184525. *pn = pSorter->aIdx[iPhrase] - i1;
  184526. *pa = &pSorter->aPoslist[i1];
  184527. }else{
  184528. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  184529. }
  184530. return rc;
  184531. }
  184532. /*
  184533. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  184534. ** correctly for the current view. Return SQLITE_OK if successful, or an
  184535. ** SQLite error code otherwise.
  184536. */
  184537. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  184538. int rc = SQLITE_OK;
  184539. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  184540. int nIter; /* Number of iterators/phrases */
  184541. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  184542. if( pCsr->aInstIter==0 ){
  184543. int nByte = sizeof(Fts5PoslistReader) * nIter;
  184544. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  184545. }
  184546. aIter = pCsr->aInstIter;
  184547. if( aIter ){
  184548. int nInst = 0; /* Number instances seen so far */
  184549. int i;
  184550. /* Initialize all iterators */
  184551. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  184552. const u8 *a;
  184553. int n;
  184554. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  184555. if( rc==SQLITE_OK ){
  184556. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  184557. }
  184558. }
  184559. if( rc==SQLITE_OK ){
  184560. while( 1 ){
  184561. int *aInst;
  184562. int iBest = -1;
  184563. for(i=0; i<nIter; i++){
  184564. if( (aIter[i].bEof==0)
  184565. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  184566. ){
  184567. iBest = i;
  184568. }
  184569. }
  184570. if( iBest<0 ) break;
  184571. nInst++;
  184572. if( nInst>=pCsr->nInstAlloc ){
  184573. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  184574. aInst = (int*)sqlite3_realloc(
  184575. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  184576. );
  184577. if( aInst ){
  184578. pCsr->aInst = aInst;
  184579. }else{
  184580. rc = SQLITE_NOMEM;
  184581. break;
  184582. }
  184583. }
  184584. aInst = &pCsr->aInst[3 * (nInst-1)];
  184585. aInst[0] = iBest;
  184586. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  184587. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  184588. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  184589. }
  184590. }
  184591. pCsr->nInstCount = nInst;
  184592. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  184593. }
  184594. return rc;
  184595. }
  184596. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  184597. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184598. int rc = SQLITE_OK;
  184599. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  184600. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  184601. *pnInst = pCsr->nInstCount;
  184602. }
  184603. return rc;
  184604. }
  184605. static int fts5ApiInst(
  184606. Fts5Context *pCtx,
  184607. int iIdx,
  184608. int *piPhrase,
  184609. int *piCol,
  184610. int *piOff
  184611. ){
  184612. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184613. int rc = SQLITE_OK;
  184614. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  184615. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  184616. ){
  184617. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  184618. rc = SQLITE_RANGE;
  184619. #if 0
  184620. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  184621. *piPhrase = pCsr->aInst[iIdx*3];
  184622. *piCol = pCsr->aInst[iIdx*3 + 2];
  184623. *piOff = -1;
  184624. #endif
  184625. }else{
  184626. *piPhrase = pCsr->aInst[iIdx*3];
  184627. *piCol = pCsr->aInst[iIdx*3 + 1];
  184628. *piOff = pCsr->aInst[iIdx*3 + 2];
  184629. }
  184630. }
  184631. return rc;
  184632. }
  184633. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  184634. return fts5CursorRowid((Fts5Cursor*)pCtx);
  184635. }
  184636. static int fts5ColumnSizeCb(
  184637. void *pContext, /* Pointer to int */
  184638. int tflags,
  184639. const char *pUnused, /* Buffer containing token */
  184640. int nUnused, /* Size of token in bytes */
  184641. int iUnused1, /* Start offset of token */
  184642. int iUnused2 /* End offset of token */
  184643. ){
  184644. int *pCnt = (int*)pContext;
  184645. UNUSED_PARAM2(pUnused, nUnused);
  184646. UNUSED_PARAM2(iUnused1, iUnused2);
  184647. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  184648. (*pCnt)++;
  184649. }
  184650. return SQLITE_OK;
  184651. }
  184652. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  184653. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184654. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184655. Fts5Config *pConfig = pTab->pConfig;
  184656. int rc = SQLITE_OK;
  184657. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  184658. if( pConfig->bColumnsize ){
  184659. i64 iRowid = fts5CursorRowid(pCsr);
  184660. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  184661. }else if( pConfig->zContent==0 ){
  184662. int i;
  184663. for(i=0; i<pConfig->nCol; i++){
  184664. if( pConfig->abUnindexed[i]==0 ){
  184665. pCsr->aColumnSize[i] = -1;
  184666. }
  184667. }
  184668. }else{
  184669. int i;
  184670. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  184671. if( pConfig->abUnindexed[i]==0 ){
  184672. const char *z; int n;
  184673. void *p = (void*)(&pCsr->aColumnSize[i]);
  184674. pCsr->aColumnSize[i] = 0;
  184675. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  184676. if( rc==SQLITE_OK ){
  184677. rc = sqlite3Fts5Tokenize(
  184678. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  184679. );
  184680. }
  184681. }
  184682. }
  184683. }
  184684. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  184685. }
  184686. if( iCol<0 ){
  184687. int i;
  184688. *pnToken = 0;
  184689. for(i=0; i<pConfig->nCol; i++){
  184690. *pnToken += pCsr->aColumnSize[i];
  184691. }
  184692. }else if( iCol<pConfig->nCol ){
  184693. *pnToken = pCsr->aColumnSize[iCol];
  184694. }else{
  184695. *pnToken = 0;
  184696. rc = SQLITE_RANGE;
  184697. }
  184698. return rc;
  184699. }
  184700. /*
  184701. ** Implementation of the xSetAuxdata() method.
  184702. */
  184703. static int fts5ApiSetAuxdata(
  184704. Fts5Context *pCtx, /* Fts5 context */
  184705. void *pPtr, /* Pointer to save as auxdata */
  184706. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  184707. ){
  184708. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184709. Fts5Auxdata *pData;
  184710. /* Search through the cursors list of Fts5Auxdata objects for one that
  184711. ** corresponds to the currently executing auxiliary function. */
  184712. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  184713. if( pData->pAux==pCsr->pAux ) break;
  184714. }
  184715. if( pData ){
  184716. if( pData->xDelete ){
  184717. pData->xDelete(pData->pPtr);
  184718. }
  184719. }else{
  184720. int rc = SQLITE_OK;
  184721. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  184722. if( pData==0 ){
  184723. if( xDelete ) xDelete(pPtr);
  184724. return rc;
  184725. }
  184726. pData->pAux = pCsr->pAux;
  184727. pData->pNext = pCsr->pAuxdata;
  184728. pCsr->pAuxdata = pData;
  184729. }
  184730. pData->xDelete = xDelete;
  184731. pData->pPtr = pPtr;
  184732. return SQLITE_OK;
  184733. }
  184734. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  184735. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184736. Fts5Auxdata *pData;
  184737. void *pRet = 0;
  184738. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  184739. if( pData->pAux==pCsr->pAux ) break;
  184740. }
  184741. if( pData ){
  184742. pRet = pData->pPtr;
  184743. if( bClear ){
  184744. pData->pPtr = 0;
  184745. pData->xDelete = 0;
  184746. }
  184747. }
  184748. return pRet;
  184749. }
  184750. static void fts5ApiPhraseNext(
  184751. Fts5Context *pUnused,
  184752. Fts5PhraseIter *pIter,
  184753. int *piCol, int *piOff
  184754. ){
  184755. UNUSED_PARAM(pUnused);
  184756. if( pIter->a>=pIter->b ){
  184757. *piCol = -1;
  184758. *piOff = -1;
  184759. }else{
  184760. int iVal;
  184761. pIter->a += fts5GetVarint32(pIter->a, iVal);
  184762. if( iVal==1 ){
  184763. pIter->a += fts5GetVarint32(pIter->a, iVal);
  184764. *piCol = iVal;
  184765. *piOff = 0;
  184766. pIter->a += fts5GetVarint32(pIter->a, iVal);
  184767. }
  184768. *piOff += (iVal-2);
  184769. }
  184770. }
  184771. static int fts5ApiPhraseFirst(
  184772. Fts5Context *pCtx,
  184773. int iPhrase,
  184774. Fts5PhraseIter *pIter,
  184775. int *piCol, int *piOff
  184776. ){
  184777. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184778. int n;
  184779. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  184780. if( rc==SQLITE_OK ){
  184781. pIter->b = &pIter->a[n];
  184782. *piCol = 0;
  184783. *piOff = 0;
  184784. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  184785. }
  184786. return rc;
  184787. }
  184788. static void fts5ApiPhraseNextColumn(
  184789. Fts5Context *pCtx,
  184790. Fts5PhraseIter *pIter,
  184791. int *piCol
  184792. ){
  184793. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184794. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  184795. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  184796. if( pIter->a>=pIter->b ){
  184797. *piCol = -1;
  184798. }else{
  184799. int iIncr;
  184800. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  184801. *piCol += (iIncr-2);
  184802. }
  184803. }else{
  184804. while( 1 ){
  184805. int dummy;
  184806. if( pIter->a>=pIter->b ){
  184807. *piCol = -1;
  184808. return;
  184809. }
  184810. if( pIter->a[0]==0x01 ) break;
  184811. pIter->a += fts5GetVarint32(pIter->a, dummy);
  184812. }
  184813. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  184814. }
  184815. }
  184816. static int fts5ApiPhraseFirstColumn(
  184817. Fts5Context *pCtx,
  184818. int iPhrase,
  184819. Fts5PhraseIter *pIter,
  184820. int *piCol
  184821. ){
  184822. int rc = SQLITE_OK;
  184823. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184824. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  184825. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  184826. Fts5Sorter *pSorter = pCsr->pSorter;
  184827. int n;
  184828. if( pSorter ){
  184829. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  184830. n = pSorter->aIdx[iPhrase] - i1;
  184831. pIter->a = &pSorter->aPoslist[i1];
  184832. }else{
  184833. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  184834. }
  184835. if( rc==SQLITE_OK ){
  184836. pIter->b = &pIter->a[n];
  184837. *piCol = 0;
  184838. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  184839. }
  184840. }else{
  184841. int n;
  184842. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  184843. if( rc==SQLITE_OK ){
  184844. pIter->b = &pIter->a[n];
  184845. if( n<=0 ){
  184846. *piCol = -1;
  184847. }else if( pIter->a[0]==0x01 ){
  184848. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  184849. }else{
  184850. *piCol = 0;
  184851. }
  184852. }
  184853. }
  184854. return rc;
  184855. }
  184856. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  184857. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  184858. );
  184859. static const Fts5ExtensionApi sFts5Api = {
  184860. 2, /* iVersion */
  184861. fts5ApiUserData,
  184862. fts5ApiColumnCount,
  184863. fts5ApiRowCount,
  184864. fts5ApiColumnTotalSize,
  184865. fts5ApiTokenize,
  184866. fts5ApiPhraseCount,
  184867. fts5ApiPhraseSize,
  184868. fts5ApiInstCount,
  184869. fts5ApiInst,
  184870. fts5ApiRowid,
  184871. fts5ApiColumnText,
  184872. fts5ApiColumnSize,
  184873. fts5ApiQueryPhrase,
  184874. fts5ApiSetAuxdata,
  184875. fts5ApiGetAuxdata,
  184876. fts5ApiPhraseFirst,
  184877. fts5ApiPhraseNext,
  184878. fts5ApiPhraseFirstColumn,
  184879. fts5ApiPhraseNextColumn,
  184880. };
  184881. /*
  184882. ** Implementation of API function xQueryPhrase().
  184883. */
  184884. static int fts5ApiQueryPhrase(
  184885. Fts5Context *pCtx,
  184886. int iPhrase,
  184887. void *pUserData,
  184888. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  184889. ){
  184890. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184891. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184892. int rc;
  184893. Fts5Cursor *pNew = 0;
  184894. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  184895. if( rc==SQLITE_OK ){
  184896. pNew->ePlan = FTS5_PLAN_MATCH;
  184897. pNew->iFirstRowid = SMALLEST_INT64;
  184898. pNew->iLastRowid = LARGEST_INT64;
  184899. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  184900. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  184901. }
  184902. if( rc==SQLITE_OK ){
  184903. for(rc = fts5CursorFirst(pTab, pNew, 0);
  184904. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  184905. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  184906. ){
  184907. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  184908. if( rc!=SQLITE_OK ){
  184909. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  184910. break;
  184911. }
  184912. }
  184913. }
  184914. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  184915. return rc;
  184916. }
  184917. static void fts5ApiInvoke(
  184918. Fts5Auxiliary *pAux,
  184919. Fts5Cursor *pCsr,
  184920. sqlite3_context *context,
  184921. int argc,
  184922. sqlite3_value **argv
  184923. ){
  184924. assert( pCsr->pAux==0 );
  184925. pCsr->pAux = pAux;
  184926. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  184927. pCsr->pAux = 0;
  184928. }
  184929. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  184930. Fts5Cursor *pCsr;
  184931. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  184932. if( pCsr->iCsrId==iCsrId ) break;
  184933. }
  184934. return pCsr;
  184935. }
  184936. static void fts5ApiCallback(
  184937. sqlite3_context *context,
  184938. int argc,
  184939. sqlite3_value **argv
  184940. ){
  184941. Fts5Auxiliary *pAux;
  184942. Fts5Cursor *pCsr;
  184943. i64 iCsrId;
  184944. assert( argc>=1 );
  184945. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  184946. iCsrId = sqlite3_value_int64(argv[0]);
  184947. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  184948. if( pCsr==0 ){
  184949. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  184950. sqlite3_result_error(context, zErr, -1);
  184951. sqlite3_free(zErr);
  184952. }else{
  184953. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  184954. }
  184955. }
  184956. /*
  184957. ** Given cursor id iId, return a pointer to the corresponding Fts5Index
  184958. ** object. Or NULL If the cursor id does not exist.
  184959. **
  184960. ** If successful, set *ppConfig to point to the associated config object
  184961. ** before returning.
  184962. */
  184963. static Fts5Index *sqlite3Fts5IndexFromCsrid(
  184964. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  184965. i64 iCsrId, /* Id of cursor to find */
  184966. Fts5Config **ppConfig /* OUT: Configuration object */
  184967. ){
  184968. Fts5Cursor *pCsr;
  184969. Fts5Table *pTab;
  184970. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  184971. pTab = (Fts5Table*)pCsr->base.pVtab;
  184972. *ppConfig = pTab->pConfig;
  184973. return pTab->pIndex;
  184974. }
  184975. /*
  184976. ** Return a "position-list blob" corresponding to the current position of
  184977. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  184978. ** the current position-list for each phrase in the query associated with
  184979. ** cursor pCsr.
  184980. **
  184981. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  184982. ** the number of phrases in the query. Following the varints are the
  184983. ** concatenated position lists for each phrase, in order.
  184984. **
  184985. ** The first varint (if it exists) contains the size of the position list
  184986. ** for phrase 0. The second (same disclaimer) contains the size of position
  184987. ** list 1. And so on. There is no size field for the final position list,
  184988. ** as it can be derived from the total size of the blob.
  184989. */
  184990. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  184991. int i;
  184992. int rc = SQLITE_OK;
  184993. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  184994. Fts5Buffer val;
  184995. memset(&val, 0, sizeof(Fts5Buffer));
  184996. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  184997. case FTS5_DETAIL_FULL:
  184998. /* Append the varints */
  184999. for(i=0; i<(nPhrase-1); i++){
  185000. const u8 *dummy;
  185001. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  185002. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  185003. }
  185004. /* Append the position lists */
  185005. for(i=0; i<nPhrase; i++){
  185006. const u8 *pPoslist;
  185007. int nPoslist;
  185008. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  185009. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  185010. }
  185011. break;
  185012. case FTS5_DETAIL_COLUMNS:
  185013. /* Append the varints */
  185014. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  185015. const u8 *dummy;
  185016. int nByte;
  185017. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  185018. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  185019. }
  185020. /* Append the position lists */
  185021. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  185022. const u8 *pPoslist;
  185023. int nPoslist;
  185024. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  185025. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  185026. }
  185027. break;
  185028. default:
  185029. break;
  185030. }
  185031. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  185032. return rc;
  185033. }
  185034. /*
  185035. ** This is the xColumn method, called by SQLite to request a value from
  185036. ** the row that the supplied cursor currently points to.
  185037. */
  185038. static int fts5ColumnMethod(
  185039. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  185040. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  185041. int iCol /* Index of column to read value from */
  185042. ){
  185043. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  185044. Fts5Config *pConfig = pTab->pConfig;
  185045. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  185046. int rc = SQLITE_OK;
  185047. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  185048. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  185049. if( iCol==pConfig->nCol ){
  185050. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  185051. }
  185052. }else
  185053. if( iCol==pConfig->nCol ){
  185054. /* User is requesting the value of the special column with the same name
  185055. ** as the table. Return the cursor integer id number. This value is only
  185056. ** useful in that it may be passed as the first argument to an FTS5
  185057. ** auxiliary function. */
  185058. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  185059. }else if( iCol==pConfig->nCol+1 ){
  185060. /* The value of the "rank" column. */
  185061. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  185062. fts5PoslistBlob(pCtx, pCsr);
  185063. }else if(
  185064. pCsr->ePlan==FTS5_PLAN_MATCH
  185065. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  185066. ){
  185067. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  185068. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  185069. }
  185070. }
  185071. }else if( !fts5IsContentless(pTab) ){
  185072. rc = fts5SeekCursor(pCsr, 1);
  185073. if( rc==SQLITE_OK ){
  185074. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  185075. }
  185076. }
  185077. return rc;
  185078. }
  185079. /*
  185080. ** This routine implements the xFindFunction method for the FTS3
  185081. ** virtual table.
  185082. */
  185083. static int fts5FindFunctionMethod(
  185084. sqlite3_vtab *pVtab, /* Virtual table handle */
  185085. int nUnused, /* Number of SQL function arguments */
  185086. const char *zName, /* Name of SQL function */
  185087. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  185088. void **ppArg /* OUT: User data for *pxFunc */
  185089. ){
  185090. Fts5Table *pTab = (Fts5Table*)pVtab;
  185091. Fts5Auxiliary *pAux;
  185092. UNUSED_PARAM(nUnused);
  185093. pAux = fts5FindAuxiliary(pTab, zName);
  185094. if( pAux ){
  185095. *pxFunc = fts5ApiCallback;
  185096. *ppArg = (void*)pAux;
  185097. return 1;
  185098. }
  185099. /* No function of the specified name was found. Return 0. */
  185100. return 0;
  185101. }
  185102. /*
  185103. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  185104. */
  185105. static int fts5RenameMethod(
  185106. sqlite3_vtab *pVtab, /* Virtual table handle */
  185107. const char *zName /* New name of table */
  185108. ){
  185109. Fts5Table *pTab = (Fts5Table*)pVtab;
  185110. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  185111. }
  185112. /*
  185113. ** The xSavepoint() method.
  185114. **
  185115. ** Flush the contents of the pending-terms table to disk.
  185116. */
  185117. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  185118. Fts5Table *pTab = (Fts5Table*)pVtab;
  185119. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  185120. fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
  185121. fts5TripCursors(pTab);
  185122. return sqlite3Fts5StorageSync(pTab->pStorage);
  185123. }
  185124. /*
  185125. ** The xRelease() method.
  185126. **
  185127. ** This is a no-op.
  185128. */
  185129. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  185130. Fts5Table *pTab = (Fts5Table*)pVtab;
  185131. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  185132. fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
  185133. fts5TripCursors(pTab);
  185134. return sqlite3Fts5StorageSync(pTab->pStorage);
  185135. }
  185136. /*
  185137. ** The xRollbackTo() method.
  185138. **
  185139. ** Discard the contents of the pending terms table.
  185140. */
  185141. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  185142. Fts5Table *pTab = (Fts5Table*)pVtab;
  185143. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  185144. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  185145. fts5TripCursors(pTab);
  185146. return sqlite3Fts5StorageRollback(pTab->pStorage);
  185147. }
  185148. /*
  185149. ** Register a new auxiliary function with global context pGlobal.
  185150. */
  185151. static int fts5CreateAux(
  185152. fts5_api *pApi, /* Global context (one per db handle) */
  185153. const char *zName, /* Name of new function */
  185154. void *pUserData, /* User data for aux. function */
  185155. fts5_extension_function xFunc, /* Aux. function implementation */
  185156. void(*xDestroy)(void*) /* Destructor for pUserData */
  185157. ){
  185158. Fts5Global *pGlobal = (Fts5Global*)pApi;
  185159. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  185160. if( rc==SQLITE_OK ){
  185161. Fts5Auxiliary *pAux;
  185162. int nName; /* Size of zName in bytes, including \0 */
  185163. int nByte; /* Bytes of space to allocate */
  185164. nName = (int)strlen(zName) + 1;
  185165. nByte = sizeof(Fts5Auxiliary) + nName;
  185166. pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
  185167. if( pAux ){
  185168. memset(pAux, 0, nByte);
  185169. pAux->zFunc = (char*)&pAux[1];
  185170. memcpy(pAux->zFunc, zName, nName);
  185171. pAux->pGlobal = pGlobal;
  185172. pAux->pUserData = pUserData;
  185173. pAux->xFunc = xFunc;
  185174. pAux->xDestroy = xDestroy;
  185175. pAux->pNext = pGlobal->pAux;
  185176. pGlobal->pAux = pAux;
  185177. }else{
  185178. rc = SQLITE_NOMEM;
  185179. }
  185180. }
  185181. return rc;
  185182. }
  185183. /*
  185184. ** Register a new tokenizer. This is the implementation of the
  185185. ** fts5_api.xCreateTokenizer() method.
  185186. */
  185187. static int fts5CreateTokenizer(
  185188. fts5_api *pApi, /* Global context (one per db handle) */
  185189. const char *zName, /* Name of new function */
  185190. void *pUserData, /* User data for aux. function */
  185191. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  185192. void(*xDestroy)(void*) /* Destructor for pUserData */
  185193. ){
  185194. Fts5Global *pGlobal = (Fts5Global*)pApi;
  185195. Fts5TokenizerModule *pNew;
  185196. int nName; /* Size of zName and its \0 terminator */
  185197. int nByte; /* Bytes of space to allocate */
  185198. int rc = SQLITE_OK;
  185199. nName = (int)strlen(zName) + 1;
  185200. nByte = sizeof(Fts5TokenizerModule) + nName;
  185201. pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
  185202. if( pNew ){
  185203. memset(pNew, 0, nByte);
  185204. pNew->zName = (char*)&pNew[1];
  185205. memcpy(pNew->zName, zName, nName);
  185206. pNew->pUserData = pUserData;
  185207. pNew->x = *pTokenizer;
  185208. pNew->xDestroy = xDestroy;
  185209. pNew->pNext = pGlobal->pTok;
  185210. pGlobal->pTok = pNew;
  185211. if( pNew->pNext==0 ){
  185212. pGlobal->pDfltTok = pNew;
  185213. }
  185214. }else{
  185215. rc = SQLITE_NOMEM;
  185216. }
  185217. return rc;
  185218. }
  185219. static Fts5TokenizerModule *fts5LocateTokenizer(
  185220. Fts5Global *pGlobal,
  185221. const char *zName
  185222. ){
  185223. Fts5TokenizerModule *pMod = 0;
  185224. if( zName==0 ){
  185225. pMod = pGlobal->pDfltTok;
  185226. }else{
  185227. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  185228. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  185229. }
  185230. }
  185231. return pMod;
  185232. }
  185233. /*
  185234. ** Find a tokenizer. This is the implementation of the
  185235. ** fts5_api.xFindTokenizer() method.
  185236. */
  185237. static int fts5FindTokenizer(
  185238. fts5_api *pApi, /* Global context (one per db handle) */
  185239. const char *zName, /* Name of new function */
  185240. void **ppUserData,
  185241. fts5_tokenizer *pTokenizer /* Populate this object */
  185242. ){
  185243. int rc = SQLITE_OK;
  185244. Fts5TokenizerModule *pMod;
  185245. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  185246. if( pMod ){
  185247. *pTokenizer = pMod->x;
  185248. *ppUserData = pMod->pUserData;
  185249. }else{
  185250. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  185251. rc = SQLITE_ERROR;
  185252. }
  185253. return rc;
  185254. }
  185255. static int sqlite3Fts5GetTokenizer(
  185256. Fts5Global *pGlobal,
  185257. const char **azArg,
  185258. int nArg,
  185259. Fts5Tokenizer **ppTok,
  185260. fts5_tokenizer **ppTokApi,
  185261. char **pzErr
  185262. ){
  185263. Fts5TokenizerModule *pMod;
  185264. int rc = SQLITE_OK;
  185265. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  185266. if( pMod==0 ){
  185267. assert( nArg>0 );
  185268. rc = SQLITE_ERROR;
  185269. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  185270. }else{
  185271. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  185272. *ppTokApi = &pMod->x;
  185273. if( rc!=SQLITE_OK && pzErr ){
  185274. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  185275. }
  185276. }
  185277. if( rc!=SQLITE_OK ){
  185278. *ppTokApi = 0;
  185279. *ppTok = 0;
  185280. }
  185281. return rc;
  185282. }
  185283. static void fts5ModuleDestroy(void *pCtx){
  185284. Fts5TokenizerModule *pTok, *pNextTok;
  185285. Fts5Auxiliary *pAux, *pNextAux;
  185286. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  185287. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  185288. pNextAux = pAux->pNext;
  185289. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  185290. sqlite3_free(pAux);
  185291. }
  185292. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  185293. pNextTok = pTok->pNext;
  185294. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  185295. sqlite3_free(pTok);
  185296. }
  185297. sqlite3_free(pGlobal);
  185298. }
  185299. static void fts5Fts5Func(
  185300. sqlite3_context *pCtx, /* Function call context */
  185301. int nArg, /* Number of args */
  185302. sqlite3_value **apUnused /* Function arguments */
  185303. ){
  185304. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  185305. char buf[8];
  185306. UNUSED_PARAM2(nArg, apUnused);
  185307. assert( nArg==0 );
  185308. assert( sizeof(buf)>=sizeof(pGlobal) );
  185309. memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
  185310. sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
  185311. }
  185312. /*
  185313. ** Implementation of fts5_source_id() function.
  185314. */
  185315. static void fts5SourceIdFunc(
  185316. sqlite3_context *pCtx, /* Function call context */
  185317. int nArg, /* Number of args */
  185318. sqlite3_value **apUnused /* Function arguments */
  185319. ){
  185320. assert( nArg==0 );
  185321. UNUSED_PARAM2(nArg, apUnused);
  185322. sqlite3_result_text(pCtx, "fts5: 2017-06-08 14:26:16 0ee482a1e0eae22e08edc8978c9733a96603d4509645f348ebf55b579e89636b", -1, SQLITE_TRANSIENT);
  185323. }
  185324. static int fts5Init(sqlite3 *db){
  185325. static const sqlite3_module fts5Mod = {
  185326. /* iVersion */ 2,
  185327. /* xCreate */ fts5CreateMethod,
  185328. /* xConnect */ fts5ConnectMethod,
  185329. /* xBestIndex */ fts5BestIndexMethod,
  185330. /* xDisconnect */ fts5DisconnectMethod,
  185331. /* xDestroy */ fts5DestroyMethod,
  185332. /* xOpen */ fts5OpenMethod,
  185333. /* xClose */ fts5CloseMethod,
  185334. /* xFilter */ fts5FilterMethod,
  185335. /* xNext */ fts5NextMethod,
  185336. /* xEof */ fts5EofMethod,
  185337. /* xColumn */ fts5ColumnMethod,
  185338. /* xRowid */ fts5RowidMethod,
  185339. /* xUpdate */ fts5UpdateMethod,
  185340. /* xBegin */ fts5BeginMethod,
  185341. /* xSync */ fts5SyncMethod,
  185342. /* xCommit */ fts5CommitMethod,
  185343. /* xRollback */ fts5RollbackMethod,
  185344. /* xFindFunction */ fts5FindFunctionMethod,
  185345. /* xRename */ fts5RenameMethod,
  185346. /* xSavepoint */ fts5SavepointMethod,
  185347. /* xRelease */ fts5ReleaseMethod,
  185348. /* xRollbackTo */ fts5RollbackToMethod,
  185349. };
  185350. int rc;
  185351. Fts5Global *pGlobal = 0;
  185352. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  185353. if( pGlobal==0 ){
  185354. rc = SQLITE_NOMEM;
  185355. }else{
  185356. void *p = (void*)pGlobal;
  185357. memset(pGlobal, 0, sizeof(Fts5Global));
  185358. pGlobal->db = db;
  185359. pGlobal->api.iVersion = 2;
  185360. pGlobal->api.xCreateFunction = fts5CreateAux;
  185361. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  185362. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  185363. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  185364. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  185365. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  185366. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  185367. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  185368. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  185369. if( rc==SQLITE_OK ){
  185370. rc = sqlite3_create_function(
  185371. db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  185372. );
  185373. }
  185374. if( rc==SQLITE_OK ){
  185375. rc = sqlite3_create_function(
  185376. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  185377. );
  185378. }
  185379. }
  185380. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  185381. ** fts5_test_mi.c is compiled and linked into the executable. And call
  185382. ** its entry point to enable the matchinfo() demo. */
  185383. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  185384. if( rc==SQLITE_OK ){
  185385. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  185386. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  185387. }
  185388. #endif
  185389. return rc;
  185390. }
  185391. /*
  185392. ** The following functions are used to register the module with SQLite. If
  185393. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  185394. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  185395. **
  185396. ** Or, if this module is being built as a loadable extension,
  185397. ** sqlite3Fts5Init() is omitted and the two standard entry points
  185398. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  185399. */
  185400. #ifndef SQLITE_CORE
  185401. #ifdef _WIN32
  185402. __declspec(dllexport)
  185403. #endif
  185404. SQLITE_API int sqlite3_fts_init(
  185405. sqlite3 *db,
  185406. char **pzErrMsg,
  185407. const sqlite3_api_routines *pApi
  185408. ){
  185409. SQLITE_EXTENSION_INIT2(pApi);
  185410. (void)pzErrMsg; /* Unused parameter */
  185411. return fts5Init(db);
  185412. }
  185413. #ifdef _WIN32
  185414. __declspec(dllexport)
  185415. #endif
  185416. SQLITE_API int sqlite3_fts5_init(
  185417. sqlite3 *db,
  185418. char **pzErrMsg,
  185419. const sqlite3_api_routines *pApi
  185420. ){
  185421. SQLITE_EXTENSION_INIT2(pApi);
  185422. (void)pzErrMsg; /* Unused parameter */
  185423. return fts5Init(db);
  185424. }
  185425. #else
  185426. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  185427. return fts5Init(db);
  185428. }
  185429. #endif
  185430. /*
  185431. ** 2014 May 31
  185432. **
  185433. ** The author disclaims copyright to this source code. In place of
  185434. ** a legal notice, here is a blessing:
  185435. **
  185436. ** May you do good and not evil.
  185437. ** May you find forgiveness for yourself and forgive others.
  185438. ** May you share freely, never taking more than you give.
  185439. **
  185440. ******************************************************************************
  185441. **
  185442. */
  185443. /* #include "fts5Int.h" */
  185444. struct Fts5Storage {
  185445. Fts5Config *pConfig;
  185446. Fts5Index *pIndex;
  185447. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  185448. i64 nTotalRow; /* Total number of rows in FTS table */
  185449. i64 *aTotalSize; /* Total sizes of each column */
  185450. sqlite3_stmt *aStmt[11];
  185451. };
  185452. #if FTS5_STMT_SCAN_ASC!=0
  185453. # error "FTS5_STMT_SCAN_ASC mismatch"
  185454. #endif
  185455. #if FTS5_STMT_SCAN_DESC!=1
  185456. # error "FTS5_STMT_SCAN_DESC mismatch"
  185457. #endif
  185458. #if FTS5_STMT_LOOKUP!=2
  185459. # error "FTS5_STMT_LOOKUP mismatch"
  185460. #endif
  185461. #define FTS5_STMT_INSERT_CONTENT 3
  185462. #define FTS5_STMT_REPLACE_CONTENT 4
  185463. #define FTS5_STMT_DELETE_CONTENT 5
  185464. #define FTS5_STMT_REPLACE_DOCSIZE 6
  185465. #define FTS5_STMT_DELETE_DOCSIZE 7
  185466. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  185467. #define FTS5_STMT_REPLACE_CONFIG 9
  185468. #define FTS5_STMT_SCAN 10
  185469. /*
  185470. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  185471. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  185472. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  185473. ** occurs.
  185474. */
  185475. static int fts5StorageGetStmt(
  185476. Fts5Storage *p, /* Storage handle */
  185477. int eStmt, /* FTS5_STMT_XXX constant */
  185478. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  185479. char **pzErrMsg /* OUT: Error message (if any) */
  185480. ){
  185481. int rc = SQLITE_OK;
  185482. /* If there is no %_docsize table, there should be no requests for
  185483. ** statements to operate on it. */
  185484. assert( p->pConfig->bColumnsize || (
  185485. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  185486. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  185487. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  185488. ));
  185489. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  185490. if( p->aStmt[eStmt]==0 ){
  185491. const char *azStmt[] = {
  185492. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  185493. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  185494. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  185495. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  185496. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  185497. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  185498. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  185499. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  185500. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  185501. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  185502. "SELECT %s FROM %s AS T", /* SCAN */
  185503. };
  185504. Fts5Config *pC = p->pConfig;
  185505. char *zSql = 0;
  185506. switch( eStmt ){
  185507. case FTS5_STMT_SCAN:
  185508. zSql = sqlite3_mprintf(azStmt[eStmt],
  185509. pC->zContentExprlist, pC->zContent
  185510. );
  185511. break;
  185512. case FTS5_STMT_SCAN_ASC:
  185513. case FTS5_STMT_SCAN_DESC:
  185514. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  185515. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  185516. pC->zContentRowid
  185517. );
  185518. break;
  185519. case FTS5_STMT_LOOKUP:
  185520. zSql = sqlite3_mprintf(azStmt[eStmt],
  185521. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  185522. );
  185523. break;
  185524. case FTS5_STMT_INSERT_CONTENT:
  185525. case FTS5_STMT_REPLACE_CONTENT: {
  185526. int nCol = pC->nCol + 1;
  185527. char *zBind;
  185528. int i;
  185529. zBind = sqlite3_malloc(1 + nCol*2);
  185530. if( zBind ){
  185531. for(i=0; i<nCol; i++){
  185532. zBind[i*2] = '?';
  185533. zBind[i*2 + 1] = ',';
  185534. }
  185535. zBind[i*2-1] = '\0';
  185536. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  185537. sqlite3_free(zBind);
  185538. }
  185539. break;
  185540. }
  185541. default:
  185542. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  185543. break;
  185544. }
  185545. if( zSql==0 ){
  185546. rc = SQLITE_NOMEM;
  185547. }else{
  185548. rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
  185549. sqlite3_free(zSql);
  185550. if( rc!=SQLITE_OK && pzErrMsg ){
  185551. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  185552. }
  185553. }
  185554. }
  185555. *ppStmt = p->aStmt[eStmt];
  185556. sqlite3_reset(*ppStmt);
  185557. return rc;
  185558. }
  185559. static int fts5ExecPrintf(
  185560. sqlite3 *db,
  185561. char **pzErr,
  185562. const char *zFormat,
  185563. ...
  185564. ){
  185565. int rc;
  185566. va_list ap; /* ... printf arguments */
  185567. char *zSql;
  185568. va_start(ap, zFormat);
  185569. zSql = sqlite3_vmprintf(zFormat, ap);
  185570. if( zSql==0 ){
  185571. rc = SQLITE_NOMEM;
  185572. }else{
  185573. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  185574. sqlite3_free(zSql);
  185575. }
  185576. va_end(ap);
  185577. return rc;
  185578. }
  185579. /*
  185580. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  185581. ** code otherwise.
  185582. */
  185583. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  185584. int rc = fts5ExecPrintf(pConfig->db, 0,
  185585. "DROP TABLE IF EXISTS %Q.'%q_data';"
  185586. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  185587. "DROP TABLE IF EXISTS %Q.'%q_config';",
  185588. pConfig->zDb, pConfig->zName,
  185589. pConfig->zDb, pConfig->zName,
  185590. pConfig->zDb, pConfig->zName
  185591. );
  185592. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  185593. rc = fts5ExecPrintf(pConfig->db, 0,
  185594. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  185595. pConfig->zDb, pConfig->zName
  185596. );
  185597. }
  185598. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  185599. rc = fts5ExecPrintf(pConfig->db, 0,
  185600. "DROP TABLE IF EXISTS %Q.'%q_content';",
  185601. pConfig->zDb, pConfig->zName
  185602. );
  185603. }
  185604. return rc;
  185605. }
  185606. static void fts5StorageRenameOne(
  185607. Fts5Config *pConfig, /* Current FTS5 configuration */
  185608. int *pRc, /* IN/OUT: Error code */
  185609. const char *zTail, /* Tail of table name e.g. "data", "config" */
  185610. const char *zName /* New name of FTS5 table */
  185611. ){
  185612. if( *pRc==SQLITE_OK ){
  185613. *pRc = fts5ExecPrintf(pConfig->db, 0,
  185614. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  185615. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  185616. );
  185617. }
  185618. }
  185619. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  185620. Fts5Config *pConfig = pStorage->pConfig;
  185621. int rc = sqlite3Fts5StorageSync(pStorage);
  185622. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  185623. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  185624. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  185625. if( pConfig->bColumnsize ){
  185626. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  185627. }
  185628. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  185629. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  185630. }
  185631. return rc;
  185632. }
  185633. /*
  185634. ** Create the shadow table named zPost, with definition zDefn. Return
  185635. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  185636. */
  185637. static int sqlite3Fts5CreateTable(
  185638. Fts5Config *pConfig, /* FTS5 configuration */
  185639. const char *zPost, /* Shadow table to create (e.g. "content") */
  185640. const char *zDefn, /* Columns etc. for shadow table */
  185641. int bWithout, /* True for without rowid */
  185642. char **pzErr /* OUT: Error message */
  185643. ){
  185644. int rc;
  185645. char *zErr = 0;
  185646. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  185647. pConfig->zDb, pConfig->zName, zPost, zDefn,
  185648. #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
  185649. bWithout?" WITHOUT ROWID":
  185650. #endif
  185651. ""
  185652. );
  185653. if( zErr ){
  185654. *pzErr = sqlite3_mprintf(
  185655. "fts5: error creating shadow table %q_%s: %s",
  185656. pConfig->zName, zPost, zErr
  185657. );
  185658. sqlite3_free(zErr);
  185659. }
  185660. return rc;
  185661. }
  185662. /*
  185663. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  185664. ** and initialize the underlying tables
  185665. **
  185666. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  185667. ** Otherwise, set *pp to NULL and return an SQLite error code.
  185668. */
  185669. static int sqlite3Fts5StorageOpen(
  185670. Fts5Config *pConfig,
  185671. Fts5Index *pIndex,
  185672. int bCreate,
  185673. Fts5Storage **pp,
  185674. char **pzErr /* OUT: Error message */
  185675. ){
  185676. int rc = SQLITE_OK;
  185677. Fts5Storage *p; /* New object */
  185678. int nByte; /* Bytes of space to allocate */
  185679. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  185680. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  185681. *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
  185682. if( !p ) return SQLITE_NOMEM;
  185683. memset(p, 0, nByte);
  185684. p->aTotalSize = (i64*)&p[1];
  185685. p->pConfig = pConfig;
  185686. p->pIndex = pIndex;
  185687. if( bCreate ){
  185688. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  185689. int nDefn = 32 + pConfig->nCol*10;
  185690. char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
  185691. if( zDefn==0 ){
  185692. rc = SQLITE_NOMEM;
  185693. }else{
  185694. int i;
  185695. int iOff;
  185696. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  185697. iOff = (int)strlen(zDefn);
  185698. for(i=0; i<pConfig->nCol; i++){
  185699. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  185700. iOff += (int)strlen(&zDefn[iOff]);
  185701. }
  185702. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  185703. }
  185704. sqlite3_free(zDefn);
  185705. }
  185706. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  185707. rc = sqlite3Fts5CreateTable(
  185708. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  185709. );
  185710. }
  185711. if( rc==SQLITE_OK ){
  185712. rc = sqlite3Fts5CreateTable(
  185713. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  185714. );
  185715. }
  185716. if( rc==SQLITE_OK ){
  185717. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  185718. }
  185719. }
  185720. if( rc ){
  185721. sqlite3Fts5StorageClose(p);
  185722. *pp = 0;
  185723. }
  185724. return rc;
  185725. }
  185726. /*
  185727. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  185728. */
  185729. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  185730. int rc = SQLITE_OK;
  185731. if( p ){
  185732. int i;
  185733. /* Finalize all SQL statements */
  185734. for(i=0; i<ArraySize(p->aStmt); i++){
  185735. sqlite3_finalize(p->aStmt[i]);
  185736. }
  185737. sqlite3_free(p);
  185738. }
  185739. return rc;
  185740. }
  185741. typedef struct Fts5InsertCtx Fts5InsertCtx;
  185742. struct Fts5InsertCtx {
  185743. Fts5Storage *pStorage;
  185744. int iCol;
  185745. int szCol; /* Size of column value in tokens */
  185746. };
  185747. /*
  185748. ** Tokenization callback used when inserting tokens into the FTS index.
  185749. */
  185750. static int fts5StorageInsertCallback(
  185751. void *pContext, /* Pointer to Fts5InsertCtx object */
  185752. int tflags,
  185753. const char *pToken, /* Buffer containing token */
  185754. int nToken, /* Size of token in bytes */
  185755. int iUnused1, /* Start offset of token */
  185756. int iUnused2 /* End offset of token */
  185757. ){
  185758. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  185759. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  185760. UNUSED_PARAM2(iUnused1, iUnused2);
  185761. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  185762. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  185763. pCtx->szCol++;
  185764. }
  185765. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  185766. }
  185767. /*
  185768. ** If a row with rowid iDel is present in the %_content table, add the
  185769. ** delete-markers to the FTS index necessary to delete it. Do not actually
  185770. ** remove the %_content row at this time though.
  185771. */
  185772. static int fts5StorageDeleteFromIndex(
  185773. Fts5Storage *p,
  185774. i64 iDel,
  185775. sqlite3_value **apVal
  185776. ){
  185777. Fts5Config *pConfig = p->pConfig;
  185778. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  185779. int rc; /* Return code */
  185780. int rc2; /* sqlite3_reset() return code */
  185781. int iCol;
  185782. Fts5InsertCtx ctx;
  185783. if( apVal==0 ){
  185784. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  185785. if( rc!=SQLITE_OK ) return rc;
  185786. sqlite3_bind_int64(pSeek, 1, iDel);
  185787. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  185788. return sqlite3_reset(pSeek);
  185789. }
  185790. }
  185791. ctx.pStorage = p;
  185792. ctx.iCol = -1;
  185793. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  185794. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  185795. if( pConfig->abUnindexed[iCol-1]==0 ){
  185796. const char *zText;
  185797. int nText;
  185798. if( pSeek ){
  185799. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  185800. nText = sqlite3_column_bytes(pSeek, iCol);
  185801. }else{
  185802. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  185803. nText = sqlite3_value_bytes(apVal[iCol-1]);
  185804. }
  185805. ctx.szCol = 0;
  185806. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  185807. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  185808. );
  185809. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  185810. }
  185811. }
  185812. p->nTotalRow--;
  185813. rc2 = sqlite3_reset(pSeek);
  185814. if( rc==SQLITE_OK ) rc = rc2;
  185815. return rc;
  185816. }
  185817. /*
  185818. ** Insert a record into the %_docsize table. Specifically, do:
  185819. **
  185820. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  185821. **
  185822. ** If there is no %_docsize table (as happens if the columnsize=0 option
  185823. ** is specified when the FTS5 table is created), this function is a no-op.
  185824. */
  185825. static int fts5StorageInsertDocsize(
  185826. Fts5Storage *p, /* Storage module to write to */
  185827. i64 iRowid, /* id value */
  185828. Fts5Buffer *pBuf /* sz value */
  185829. ){
  185830. int rc = SQLITE_OK;
  185831. if( p->pConfig->bColumnsize ){
  185832. sqlite3_stmt *pReplace = 0;
  185833. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  185834. if( rc==SQLITE_OK ){
  185835. sqlite3_bind_int64(pReplace, 1, iRowid);
  185836. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  185837. sqlite3_step(pReplace);
  185838. rc = sqlite3_reset(pReplace);
  185839. }
  185840. }
  185841. return rc;
  185842. }
  185843. /*
  185844. ** Load the contents of the "averages" record from disk into the
  185845. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  185846. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  185847. ** that the contents of aTotalSize[] and nTotalRow are valid until
  185848. ** further notice.
  185849. **
  185850. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  185851. ** occurs.
  185852. */
  185853. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  185854. int rc = SQLITE_OK;
  185855. if( p->bTotalsValid==0 ){
  185856. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  185857. p->bTotalsValid = bCache;
  185858. }
  185859. return rc;
  185860. }
  185861. /*
  185862. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  185863. ** variables in the "averages" record on disk.
  185864. **
  185865. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  185866. ** occurs.
  185867. */
  185868. static int fts5StorageSaveTotals(Fts5Storage *p){
  185869. int nCol = p->pConfig->nCol;
  185870. int i;
  185871. Fts5Buffer buf;
  185872. int rc = SQLITE_OK;
  185873. memset(&buf, 0, sizeof(buf));
  185874. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  185875. for(i=0; i<nCol; i++){
  185876. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  185877. }
  185878. if( rc==SQLITE_OK ){
  185879. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  185880. }
  185881. sqlite3_free(buf.p);
  185882. return rc;
  185883. }
  185884. /*
  185885. ** Remove a row from the FTS table.
  185886. */
  185887. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  185888. Fts5Config *pConfig = p->pConfig;
  185889. int rc;
  185890. sqlite3_stmt *pDel = 0;
  185891. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  185892. rc = fts5StorageLoadTotals(p, 1);
  185893. /* Delete the index records */
  185894. if( rc==SQLITE_OK ){
  185895. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  185896. }
  185897. /* Delete the %_docsize record */
  185898. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  185899. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  185900. if( rc==SQLITE_OK ){
  185901. sqlite3_bind_int64(pDel, 1, iDel);
  185902. sqlite3_step(pDel);
  185903. rc = sqlite3_reset(pDel);
  185904. }
  185905. }
  185906. /* Delete the %_content record */
  185907. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  185908. if( rc==SQLITE_OK ){
  185909. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  185910. }
  185911. if( rc==SQLITE_OK ){
  185912. sqlite3_bind_int64(pDel, 1, iDel);
  185913. sqlite3_step(pDel);
  185914. rc = sqlite3_reset(pDel);
  185915. }
  185916. }
  185917. return rc;
  185918. }
  185919. /*
  185920. ** Delete all entries in the FTS5 index.
  185921. */
  185922. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  185923. Fts5Config *pConfig = p->pConfig;
  185924. int rc;
  185925. /* Delete the contents of the %_data and %_docsize tables. */
  185926. rc = fts5ExecPrintf(pConfig->db, 0,
  185927. "DELETE FROM %Q.'%q_data';"
  185928. "DELETE FROM %Q.'%q_idx';",
  185929. pConfig->zDb, pConfig->zName,
  185930. pConfig->zDb, pConfig->zName
  185931. );
  185932. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  185933. rc = fts5ExecPrintf(pConfig->db, 0,
  185934. "DELETE FROM %Q.'%q_docsize';",
  185935. pConfig->zDb, pConfig->zName
  185936. );
  185937. }
  185938. /* Reinitialize the %_data table. This call creates the initial structure
  185939. ** and averages records. */
  185940. if( rc==SQLITE_OK ){
  185941. rc = sqlite3Fts5IndexReinit(p->pIndex);
  185942. }
  185943. if( rc==SQLITE_OK ){
  185944. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  185945. }
  185946. return rc;
  185947. }
  185948. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  185949. Fts5Buffer buf = {0,0,0};
  185950. Fts5Config *pConfig = p->pConfig;
  185951. sqlite3_stmt *pScan = 0;
  185952. Fts5InsertCtx ctx;
  185953. int rc;
  185954. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  185955. ctx.pStorage = p;
  185956. rc = sqlite3Fts5StorageDeleteAll(p);
  185957. if( rc==SQLITE_OK ){
  185958. rc = fts5StorageLoadTotals(p, 1);
  185959. }
  185960. if( rc==SQLITE_OK ){
  185961. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  185962. }
  185963. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  185964. i64 iRowid = sqlite3_column_int64(pScan, 0);
  185965. sqlite3Fts5BufferZero(&buf);
  185966. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  185967. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  185968. ctx.szCol = 0;
  185969. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  185970. rc = sqlite3Fts5Tokenize(pConfig,
  185971. FTS5_TOKENIZE_DOCUMENT,
  185972. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  185973. sqlite3_column_bytes(pScan, ctx.iCol+1),
  185974. (void*)&ctx,
  185975. fts5StorageInsertCallback
  185976. );
  185977. }
  185978. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  185979. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  185980. }
  185981. p->nTotalRow++;
  185982. if( rc==SQLITE_OK ){
  185983. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  185984. }
  185985. }
  185986. sqlite3_free(buf.p);
  185987. /* Write the averages record */
  185988. if( rc==SQLITE_OK ){
  185989. rc = fts5StorageSaveTotals(p);
  185990. }
  185991. return rc;
  185992. }
  185993. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  185994. return sqlite3Fts5IndexOptimize(p->pIndex);
  185995. }
  185996. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  185997. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  185998. }
  185999. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  186000. return sqlite3Fts5IndexReset(p->pIndex);
  186001. }
  186002. /*
  186003. ** Allocate a new rowid. This is used for "external content" tables when
  186004. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  186005. ** by inserting a dummy row into the %_docsize table. The dummy will be
  186006. ** overwritten later.
  186007. **
  186008. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  186009. ** this case the user is required to provide a rowid explicitly.
  186010. */
  186011. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  186012. int rc = SQLITE_MISMATCH;
  186013. if( p->pConfig->bColumnsize ){
  186014. sqlite3_stmt *pReplace = 0;
  186015. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  186016. if( rc==SQLITE_OK ){
  186017. sqlite3_bind_null(pReplace, 1);
  186018. sqlite3_bind_null(pReplace, 2);
  186019. sqlite3_step(pReplace);
  186020. rc = sqlite3_reset(pReplace);
  186021. }
  186022. if( rc==SQLITE_OK ){
  186023. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  186024. }
  186025. }
  186026. return rc;
  186027. }
  186028. /*
  186029. ** Insert a new row into the FTS content table.
  186030. */
  186031. static int sqlite3Fts5StorageContentInsert(
  186032. Fts5Storage *p,
  186033. sqlite3_value **apVal,
  186034. i64 *piRowid
  186035. ){
  186036. Fts5Config *pConfig = p->pConfig;
  186037. int rc = SQLITE_OK;
  186038. /* Insert the new row into the %_content table. */
  186039. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  186040. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  186041. *piRowid = sqlite3_value_int64(apVal[1]);
  186042. }else{
  186043. rc = fts5StorageNewRowid(p, piRowid);
  186044. }
  186045. }else{
  186046. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  186047. int i; /* Counter variable */
  186048. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  186049. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  186050. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  186051. }
  186052. if( rc==SQLITE_OK ){
  186053. sqlite3_step(pInsert);
  186054. rc = sqlite3_reset(pInsert);
  186055. }
  186056. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  186057. }
  186058. return rc;
  186059. }
  186060. /*
  186061. ** Insert new entries into the FTS index and %_docsize table.
  186062. */
  186063. static int sqlite3Fts5StorageIndexInsert(
  186064. Fts5Storage *p,
  186065. sqlite3_value **apVal,
  186066. i64 iRowid
  186067. ){
  186068. Fts5Config *pConfig = p->pConfig;
  186069. int rc = SQLITE_OK; /* Return code */
  186070. Fts5InsertCtx ctx; /* Tokenization callback context object */
  186071. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  186072. memset(&buf, 0, sizeof(Fts5Buffer));
  186073. ctx.pStorage = p;
  186074. rc = fts5StorageLoadTotals(p, 1);
  186075. if( rc==SQLITE_OK ){
  186076. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  186077. }
  186078. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  186079. ctx.szCol = 0;
  186080. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  186081. rc = sqlite3Fts5Tokenize(pConfig,
  186082. FTS5_TOKENIZE_DOCUMENT,
  186083. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  186084. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  186085. (void*)&ctx,
  186086. fts5StorageInsertCallback
  186087. );
  186088. }
  186089. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  186090. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  186091. }
  186092. p->nTotalRow++;
  186093. /* Write the %_docsize record */
  186094. if( rc==SQLITE_OK ){
  186095. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  186096. }
  186097. sqlite3_free(buf.p);
  186098. return rc;
  186099. }
  186100. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  186101. Fts5Config *pConfig = p->pConfig;
  186102. char *zSql;
  186103. int rc;
  186104. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  186105. pConfig->zDb, pConfig->zName, zSuffix
  186106. );
  186107. if( zSql==0 ){
  186108. rc = SQLITE_NOMEM;
  186109. }else{
  186110. sqlite3_stmt *pCnt = 0;
  186111. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  186112. if( rc==SQLITE_OK ){
  186113. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  186114. *pnRow = sqlite3_column_int64(pCnt, 0);
  186115. }
  186116. rc = sqlite3_finalize(pCnt);
  186117. }
  186118. }
  186119. sqlite3_free(zSql);
  186120. return rc;
  186121. }
  186122. /*
  186123. ** Context object used by sqlite3Fts5StorageIntegrity().
  186124. */
  186125. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  186126. struct Fts5IntegrityCtx {
  186127. i64 iRowid;
  186128. int iCol;
  186129. int szCol;
  186130. u64 cksum;
  186131. Fts5Termset *pTermset;
  186132. Fts5Config *pConfig;
  186133. };
  186134. /*
  186135. ** Tokenization callback used by integrity check.
  186136. */
  186137. static int fts5StorageIntegrityCallback(
  186138. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  186139. int tflags,
  186140. const char *pToken, /* Buffer containing token */
  186141. int nToken, /* Size of token in bytes */
  186142. int iUnused1, /* Start offset of token */
  186143. int iUnused2 /* End offset of token */
  186144. ){
  186145. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  186146. Fts5Termset *pTermset = pCtx->pTermset;
  186147. int bPresent;
  186148. int ii;
  186149. int rc = SQLITE_OK;
  186150. int iPos;
  186151. int iCol;
  186152. UNUSED_PARAM2(iUnused1, iUnused2);
  186153. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  186154. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  186155. pCtx->szCol++;
  186156. }
  186157. switch( pCtx->pConfig->eDetail ){
  186158. case FTS5_DETAIL_FULL:
  186159. iPos = pCtx->szCol-1;
  186160. iCol = pCtx->iCol;
  186161. break;
  186162. case FTS5_DETAIL_COLUMNS:
  186163. iPos = pCtx->iCol;
  186164. iCol = 0;
  186165. break;
  186166. default:
  186167. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  186168. iPos = 0;
  186169. iCol = 0;
  186170. break;
  186171. }
  186172. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  186173. if( rc==SQLITE_OK && bPresent==0 ){
  186174. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  186175. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  186176. );
  186177. }
  186178. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  186179. const int nChar = pCtx->pConfig->aPrefix[ii];
  186180. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  186181. if( nByte ){
  186182. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  186183. if( bPresent==0 ){
  186184. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  186185. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  186186. );
  186187. }
  186188. }
  186189. }
  186190. return rc;
  186191. }
  186192. /*
  186193. ** Check that the contents of the FTS index match that of the %_content
  186194. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  186195. ** some other SQLite error code if an error occurs while attempting to
  186196. ** determine this.
  186197. */
  186198. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  186199. Fts5Config *pConfig = p->pConfig;
  186200. int rc; /* Return code */
  186201. int *aColSize; /* Array of size pConfig->nCol */
  186202. i64 *aTotalSize; /* Array of size pConfig->nCol */
  186203. Fts5IntegrityCtx ctx;
  186204. sqlite3_stmt *pScan;
  186205. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  186206. ctx.pConfig = p->pConfig;
  186207. aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
  186208. if( !aTotalSize ) return SQLITE_NOMEM;
  186209. aColSize = (int*)&aTotalSize[pConfig->nCol];
  186210. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  186211. /* Generate the expected index checksum based on the contents of the
  186212. ** %_content table. This block stores the checksum in ctx.cksum. */
  186213. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  186214. if( rc==SQLITE_OK ){
  186215. int rc2;
  186216. while( SQLITE_ROW==sqlite3_step(pScan) ){
  186217. int i;
  186218. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  186219. ctx.szCol = 0;
  186220. if( pConfig->bColumnsize ){
  186221. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  186222. }
  186223. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  186224. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  186225. }
  186226. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  186227. if( pConfig->abUnindexed[i] ) continue;
  186228. ctx.iCol = i;
  186229. ctx.szCol = 0;
  186230. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  186231. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  186232. }
  186233. if( rc==SQLITE_OK ){
  186234. rc = sqlite3Fts5Tokenize(pConfig,
  186235. FTS5_TOKENIZE_DOCUMENT,
  186236. (const char*)sqlite3_column_text(pScan, i+1),
  186237. sqlite3_column_bytes(pScan, i+1),
  186238. (void*)&ctx,
  186239. fts5StorageIntegrityCallback
  186240. );
  186241. }
  186242. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  186243. rc = FTS5_CORRUPT;
  186244. }
  186245. aTotalSize[i] += ctx.szCol;
  186246. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  186247. sqlite3Fts5TermsetFree(ctx.pTermset);
  186248. ctx.pTermset = 0;
  186249. }
  186250. }
  186251. sqlite3Fts5TermsetFree(ctx.pTermset);
  186252. ctx.pTermset = 0;
  186253. if( rc!=SQLITE_OK ) break;
  186254. }
  186255. rc2 = sqlite3_reset(pScan);
  186256. if( rc==SQLITE_OK ) rc = rc2;
  186257. }
  186258. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  186259. if( rc==SQLITE_OK ){
  186260. int i;
  186261. rc = fts5StorageLoadTotals(p, 0);
  186262. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  186263. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  186264. }
  186265. }
  186266. /* Check that the %_docsize and %_content tables contain the expected
  186267. ** number of rows. */
  186268. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  186269. i64 nRow = 0;
  186270. rc = fts5StorageCount(p, "content", &nRow);
  186271. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  186272. }
  186273. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  186274. i64 nRow = 0;
  186275. rc = fts5StorageCount(p, "docsize", &nRow);
  186276. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  186277. }
  186278. /* Pass the expected checksum down to the FTS index module. It will
  186279. ** verify, amongst other things, that it matches the checksum generated by
  186280. ** inspecting the index itself. */
  186281. if( rc==SQLITE_OK ){
  186282. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  186283. }
  186284. sqlite3_free(aTotalSize);
  186285. return rc;
  186286. }
  186287. /*
  186288. ** Obtain an SQLite statement handle that may be used to read data from the
  186289. ** %_content table.
  186290. */
  186291. static int sqlite3Fts5StorageStmt(
  186292. Fts5Storage *p,
  186293. int eStmt,
  186294. sqlite3_stmt **pp,
  186295. char **pzErrMsg
  186296. ){
  186297. int rc;
  186298. assert( eStmt==FTS5_STMT_SCAN_ASC
  186299. || eStmt==FTS5_STMT_SCAN_DESC
  186300. || eStmt==FTS5_STMT_LOOKUP
  186301. );
  186302. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  186303. if( rc==SQLITE_OK ){
  186304. assert( p->aStmt[eStmt]==*pp );
  186305. p->aStmt[eStmt] = 0;
  186306. }
  186307. return rc;
  186308. }
  186309. /*
  186310. ** Release an SQLite statement handle obtained via an earlier call to
  186311. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  186312. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  186313. */
  186314. static void sqlite3Fts5StorageStmtRelease(
  186315. Fts5Storage *p,
  186316. int eStmt,
  186317. sqlite3_stmt *pStmt
  186318. ){
  186319. assert( eStmt==FTS5_STMT_SCAN_ASC
  186320. || eStmt==FTS5_STMT_SCAN_DESC
  186321. || eStmt==FTS5_STMT_LOOKUP
  186322. );
  186323. if( p->aStmt[eStmt]==0 ){
  186324. sqlite3_reset(pStmt);
  186325. p->aStmt[eStmt] = pStmt;
  186326. }else{
  186327. sqlite3_finalize(pStmt);
  186328. }
  186329. }
  186330. static int fts5StorageDecodeSizeArray(
  186331. int *aCol, int nCol, /* Array to populate */
  186332. const u8 *aBlob, int nBlob /* Record to read varints from */
  186333. ){
  186334. int i;
  186335. int iOff = 0;
  186336. for(i=0; i<nCol; i++){
  186337. if( iOff>=nBlob ) return 1;
  186338. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  186339. }
  186340. return (iOff!=nBlob);
  186341. }
  186342. /*
  186343. ** Argument aCol points to an array of integers containing one entry for
  186344. ** each table column. This function reads the %_docsize record for the
  186345. ** specified rowid and populates aCol[] with the results.
  186346. **
  186347. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  186348. ** otherwise.
  186349. */
  186350. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  186351. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  186352. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  186353. int rc; /* Return Code */
  186354. assert( p->pConfig->bColumnsize );
  186355. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  186356. if( rc==SQLITE_OK ){
  186357. int bCorrupt = 1;
  186358. sqlite3_bind_int64(pLookup, 1, iRowid);
  186359. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  186360. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  186361. int nBlob = sqlite3_column_bytes(pLookup, 0);
  186362. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  186363. bCorrupt = 0;
  186364. }
  186365. }
  186366. rc = sqlite3_reset(pLookup);
  186367. if( bCorrupt && rc==SQLITE_OK ){
  186368. rc = FTS5_CORRUPT;
  186369. }
  186370. }
  186371. return rc;
  186372. }
  186373. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  186374. int rc = fts5StorageLoadTotals(p, 0);
  186375. if( rc==SQLITE_OK ){
  186376. *pnToken = 0;
  186377. if( iCol<0 ){
  186378. int i;
  186379. for(i=0; i<p->pConfig->nCol; i++){
  186380. *pnToken += p->aTotalSize[i];
  186381. }
  186382. }else if( iCol<p->pConfig->nCol ){
  186383. *pnToken = p->aTotalSize[iCol];
  186384. }else{
  186385. rc = SQLITE_RANGE;
  186386. }
  186387. }
  186388. return rc;
  186389. }
  186390. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  186391. int rc = fts5StorageLoadTotals(p, 0);
  186392. if( rc==SQLITE_OK ){
  186393. *pnRow = p->nTotalRow;
  186394. }
  186395. return rc;
  186396. }
  186397. /*
  186398. ** Flush any data currently held in-memory to disk.
  186399. */
  186400. static int sqlite3Fts5StorageSync(Fts5Storage *p){
  186401. int rc = SQLITE_OK;
  186402. i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  186403. if( p->bTotalsValid ){
  186404. rc = fts5StorageSaveTotals(p);
  186405. p->bTotalsValid = 0;
  186406. }
  186407. if( rc==SQLITE_OK ){
  186408. rc = sqlite3Fts5IndexSync(p->pIndex);
  186409. }
  186410. sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
  186411. return rc;
  186412. }
  186413. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  186414. p->bTotalsValid = 0;
  186415. return sqlite3Fts5IndexRollback(p->pIndex);
  186416. }
  186417. static int sqlite3Fts5StorageConfigValue(
  186418. Fts5Storage *p,
  186419. const char *z,
  186420. sqlite3_value *pVal,
  186421. int iVal
  186422. ){
  186423. sqlite3_stmt *pReplace = 0;
  186424. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  186425. if( rc==SQLITE_OK ){
  186426. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  186427. if( pVal ){
  186428. sqlite3_bind_value(pReplace, 2, pVal);
  186429. }else{
  186430. sqlite3_bind_int(pReplace, 2, iVal);
  186431. }
  186432. sqlite3_step(pReplace);
  186433. rc = sqlite3_reset(pReplace);
  186434. }
  186435. if( rc==SQLITE_OK && pVal ){
  186436. int iNew = p->pConfig->iCookie + 1;
  186437. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  186438. if( rc==SQLITE_OK ){
  186439. p->pConfig->iCookie = iNew;
  186440. }
  186441. }
  186442. return rc;
  186443. }
  186444. /*
  186445. ** 2014 May 31
  186446. **
  186447. ** The author disclaims copyright to this source code. In place of
  186448. ** a legal notice, here is a blessing:
  186449. **
  186450. ** May you do good and not evil.
  186451. ** May you find forgiveness for yourself and forgive others.
  186452. ** May you share freely, never taking more than you give.
  186453. **
  186454. ******************************************************************************
  186455. */
  186456. /* #include "fts5Int.h" */
  186457. /**************************************************************************
  186458. ** Start of ascii tokenizer implementation.
  186459. */
  186460. /*
  186461. ** For tokenizers with no "unicode" modifier, the set of token characters
  186462. ** is the same as the set of ASCII range alphanumeric characters.
  186463. */
  186464. static unsigned char aAsciiTokenChar[128] = {
  186465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  186466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  186467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  186468. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  186469. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  186470. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  186471. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  186472. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  186473. };
  186474. typedef struct AsciiTokenizer AsciiTokenizer;
  186475. struct AsciiTokenizer {
  186476. unsigned char aTokenChar[128];
  186477. };
  186478. static void fts5AsciiAddExceptions(
  186479. AsciiTokenizer *p,
  186480. const char *zArg,
  186481. int bTokenChars
  186482. ){
  186483. int i;
  186484. for(i=0; zArg[i]; i++){
  186485. if( (zArg[i] & 0x80)==0 ){
  186486. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  186487. }
  186488. }
  186489. }
  186490. /*
  186491. ** Delete a "ascii" tokenizer.
  186492. */
  186493. static void fts5AsciiDelete(Fts5Tokenizer *p){
  186494. sqlite3_free(p);
  186495. }
  186496. /*
  186497. ** Create an "ascii" tokenizer.
  186498. */
  186499. static int fts5AsciiCreate(
  186500. void *pUnused,
  186501. const char **azArg, int nArg,
  186502. Fts5Tokenizer **ppOut
  186503. ){
  186504. int rc = SQLITE_OK;
  186505. AsciiTokenizer *p = 0;
  186506. UNUSED_PARAM(pUnused);
  186507. if( nArg%2 ){
  186508. rc = SQLITE_ERROR;
  186509. }else{
  186510. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  186511. if( p==0 ){
  186512. rc = SQLITE_NOMEM;
  186513. }else{
  186514. int i;
  186515. memset(p, 0, sizeof(AsciiTokenizer));
  186516. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  186517. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  186518. const char *zArg = azArg[i+1];
  186519. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  186520. fts5AsciiAddExceptions(p, zArg, 1);
  186521. }else
  186522. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  186523. fts5AsciiAddExceptions(p, zArg, 0);
  186524. }else{
  186525. rc = SQLITE_ERROR;
  186526. }
  186527. }
  186528. if( rc!=SQLITE_OK ){
  186529. fts5AsciiDelete((Fts5Tokenizer*)p);
  186530. p = 0;
  186531. }
  186532. }
  186533. }
  186534. *ppOut = (Fts5Tokenizer*)p;
  186535. return rc;
  186536. }
  186537. static void asciiFold(char *aOut, const char *aIn, int nByte){
  186538. int i;
  186539. for(i=0; i<nByte; i++){
  186540. char c = aIn[i];
  186541. if( c>='A' && c<='Z' ) c += 32;
  186542. aOut[i] = c;
  186543. }
  186544. }
  186545. /*
  186546. ** Tokenize some text using the ascii tokenizer.
  186547. */
  186548. static int fts5AsciiTokenize(
  186549. Fts5Tokenizer *pTokenizer,
  186550. void *pCtx,
  186551. int iUnused,
  186552. const char *pText, int nText,
  186553. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  186554. ){
  186555. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  186556. int rc = SQLITE_OK;
  186557. int ie;
  186558. int is = 0;
  186559. char aFold[64];
  186560. int nFold = sizeof(aFold);
  186561. char *pFold = aFold;
  186562. unsigned char *a = p->aTokenChar;
  186563. UNUSED_PARAM(iUnused);
  186564. while( is<nText && rc==SQLITE_OK ){
  186565. int nByte;
  186566. /* Skip any leading divider characters. */
  186567. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  186568. is++;
  186569. }
  186570. if( is==nText ) break;
  186571. /* Count the token characters */
  186572. ie = is+1;
  186573. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  186574. ie++;
  186575. }
  186576. /* Fold to lower case */
  186577. nByte = ie-is;
  186578. if( nByte>nFold ){
  186579. if( pFold!=aFold ) sqlite3_free(pFold);
  186580. pFold = sqlite3_malloc(nByte*2);
  186581. if( pFold==0 ){
  186582. rc = SQLITE_NOMEM;
  186583. break;
  186584. }
  186585. nFold = nByte*2;
  186586. }
  186587. asciiFold(pFold, &pText[is], nByte);
  186588. /* Invoke the token callback */
  186589. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  186590. is = ie+1;
  186591. }
  186592. if( pFold!=aFold ) sqlite3_free(pFold);
  186593. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  186594. return rc;
  186595. }
  186596. /**************************************************************************
  186597. ** Start of unicode61 tokenizer implementation.
  186598. */
  186599. /*
  186600. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  186601. ** from the sqlite3 source file utf.c. If this file is compiled as part
  186602. ** of the amalgamation, they are not required.
  186603. */
  186604. #ifndef SQLITE_AMALGAMATION
  186605. static const unsigned char sqlite3Utf8Trans1[] = {
  186606. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  186607. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  186608. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  186609. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  186610. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  186611. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  186612. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  186613. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  186614. };
  186615. #define READ_UTF8(zIn, zTerm, c) \
  186616. c = *(zIn++); \
  186617. if( c>=0xc0 ){ \
  186618. c = sqlite3Utf8Trans1[c-0xc0]; \
  186619. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  186620. c = (c<<6) + (0x3f & *(zIn++)); \
  186621. } \
  186622. if( c<0x80 \
  186623. || (c&0xFFFFF800)==0xD800 \
  186624. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  186625. }
  186626. #define WRITE_UTF8(zOut, c) { \
  186627. if( c<0x00080 ){ \
  186628. *zOut++ = (unsigned char)(c&0xFF); \
  186629. } \
  186630. else if( c<0x00800 ){ \
  186631. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  186632. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  186633. } \
  186634. else if( c<0x10000 ){ \
  186635. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  186636. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  186637. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  186638. }else{ \
  186639. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  186640. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  186641. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  186642. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  186643. } \
  186644. }
  186645. #endif /* ifndef SQLITE_AMALGAMATION */
  186646. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  186647. struct Unicode61Tokenizer {
  186648. unsigned char aTokenChar[128]; /* ASCII range token characters */
  186649. char *aFold; /* Buffer to fold text into */
  186650. int nFold; /* Size of aFold[] in bytes */
  186651. int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
  186652. int nException;
  186653. int *aiException;
  186654. };
  186655. static int fts5UnicodeAddExceptions(
  186656. Unicode61Tokenizer *p, /* Tokenizer object */
  186657. const char *z, /* Characters to treat as exceptions */
  186658. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  186659. ){
  186660. int rc = SQLITE_OK;
  186661. int n = (int)strlen(z);
  186662. int *aNew;
  186663. if( n>0 ){
  186664. aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
  186665. if( aNew ){
  186666. int nNew = p->nException;
  186667. const unsigned char *zCsr = (const unsigned char*)z;
  186668. const unsigned char *zTerm = (const unsigned char*)&z[n];
  186669. while( zCsr<zTerm ){
  186670. int iCode;
  186671. int bToken;
  186672. READ_UTF8(zCsr, zTerm, iCode);
  186673. if( iCode<128 ){
  186674. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  186675. }else{
  186676. bToken = sqlite3Fts5UnicodeIsalnum(iCode);
  186677. assert( (bToken==0 || bToken==1) );
  186678. assert( (bTokenChars==0 || bTokenChars==1) );
  186679. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  186680. int i;
  186681. for(i=0; i<nNew; i++){
  186682. if( aNew[i]>iCode ) break;
  186683. }
  186684. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  186685. aNew[i] = iCode;
  186686. nNew++;
  186687. }
  186688. }
  186689. }
  186690. p->aiException = aNew;
  186691. p->nException = nNew;
  186692. }else{
  186693. rc = SQLITE_NOMEM;
  186694. }
  186695. }
  186696. return rc;
  186697. }
  186698. /*
  186699. ** Return true if the p->aiException[] array contains the value iCode.
  186700. */
  186701. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  186702. if( p->nException>0 ){
  186703. int *a = p->aiException;
  186704. int iLo = 0;
  186705. int iHi = p->nException-1;
  186706. while( iHi>=iLo ){
  186707. int iTest = (iHi + iLo) / 2;
  186708. if( iCode==a[iTest] ){
  186709. return 1;
  186710. }else if( iCode>a[iTest] ){
  186711. iLo = iTest+1;
  186712. }else{
  186713. iHi = iTest-1;
  186714. }
  186715. }
  186716. }
  186717. return 0;
  186718. }
  186719. /*
  186720. ** Delete a "unicode61" tokenizer.
  186721. */
  186722. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  186723. if( pTok ){
  186724. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  186725. sqlite3_free(p->aiException);
  186726. sqlite3_free(p->aFold);
  186727. sqlite3_free(p);
  186728. }
  186729. return;
  186730. }
  186731. /*
  186732. ** Create a "unicode61" tokenizer.
  186733. */
  186734. static int fts5UnicodeCreate(
  186735. void *pUnused,
  186736. const char **azArg, int nArg,
  186737. Fts5Tokenizer **ppOut
  186738. ){
  186739. int rc = SQLITE_OK; /* Return code */
  186740. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  186741. UNUSED_PARAM(pUnused);
  186742. if( nArg%2 ){
  186743. rc = SQLITE_ERROR;
  186744. }else{
  186745. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  186746. if( p ){
  186747. int i;
  186748. memset(p, 0, sizeof(Unicode61Tokenizer));
  186749. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  186750. p->bRemoveDiacritic = 1;
  186751. p->nFold = 64;
  186752. p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
  186753. if( p->aFold==0 ){
  186754. rc = SQLITE_NOMEM;
  186755. }
  186756. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  186757. const char *zArg = azArg[i+1];
  186758. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  186759. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
  186760. rc = SQLITE_ERROR;
  186761. }
  186762. p->bRemoveDiacritic = (zArg[0]=='1');
  186763. }else
  186764. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  186765. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  186766. }else
  186767. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  186768. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  186769. }else{
  186770. rc = SQLITE_ERROR;
  186771. }
  186772. }
  186773. }else{
  186774. rc = SQLITE_NOMEM;
  186775. }
  186776. if( rc!=SQLITE_OK ){
  186777. fts5UnicodeDelete((Fts5Tokenizer*)p);
  186778. p = 0;
  186779. }
  186780. *ppOut = (Fts5Tokenizer*)p;
  186781. }
  186782. return rc;
  186783. }
  186784. /*
  186785. ** Return true if, for the purposes of tokenizing with the tokenizer
  186786. ** passed as the first argument, codepoint iCode is considered a token
  186787. ** character (not a separator).
  186788. */
  186789. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  186790. assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  186791. return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
  186792. }
  186793. static int fts5UnicodeTokenize(
  186794. Fts5Tokenizer *pTokenizer,
  186795. void *pCtx,
  186796. int iUnused,
  186797. const char *pText, int nText,
  186798. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  186799. ){
  186800. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  186801. int rc = SQLITE_OK;
  186802. unsigned char *a = p->aTokenChar;
  186803. unsigned char *zTerm = (unsigned char*)&pText[nText];
  186804. unsigned char *zCsr = (unsigned char *)pText;
  186805. /* Output buffer */
  186806. char *aFold = p->aFold;
  186807. int nFold = p->nFold;
  186808. const char *pEnd = &aFold[nFold-6];
  186809. UNUSED_PARAM(iUnused);
  186810. /* Each iteration of this loop gobbles up a contiguous run of separators,
  186811. ** then the next token. */
  186812. while( rc==SQLITE_OK ){
  186813. int iCode; /* non-ASCII codepoint read from input */
  186814. char *zOut = aFold;
  186815. int is;
  186816. int ie;
  186817. /* Skip any separator characters. */
  186818. while( 1 ){
  186819. if( zCsr>=zTerm ) goto tokenize_done;
  186820. if( *zCsr & 0x80 ) {
  186821. /* A character outside of the ascii range. Skip past it if it is
  186822. ** a separator character. Or break out of the loop if it is not. */
  186823. is = zCsr - (unsigned char*)pText;
  186824. READ_UTF8(zCsr, zTerm, iCode);
  186825. if( fts5UnicodeIsAlnum(p, iCode) ){
  186826. goto non_ascii_tokenchar;
  186827. }
  186828. }else{
  186829. if( a[*zCsr] ){
  186830. is = zCsr - (unsigned char*)pText;
  186831. goto ascii_tokenchar;
  186832. }
  186833. zCsr++;
  186834. }
  186835. }
  186836. /* Run through the tokenchars. Fold them into the output buffer along
  186837. ** the way. */
  186838. while( zCsr<zTerm ){
  186839. /* Grow the output buffer so that there is sufficient space to fit the
  186840. ** largest possible utf-8 character. */
  186841. if( zOut>pEnd ){
  186842. aFold = sqlite3_malloc(nFold*2);
  186843. if( aFold==0 ){
  186844. rc = SQLITE_NOMEM;
  186845. goto tokenize_done;
  186846. }
  186847. zOut = &aFold[zOut - p->aFold];
  186848. memcpy(aFold, p->aFold, nFold);
  186849. sqlite3_free(p->aFold);
  186850. p->aFold = aFold;
  186851. p->nFold = nFold = nFold*2;
  186852. pEnd = &aFold[nFold-6];
  186853. }
  186854. if( *zCsr & 0x80 ){
  186855. /* An non-ascii-range character. Fold it into the output buffer if
  186856. ** it is a token character, or break out of the loop if it is not. */
  186857. READ_UTF8(zCsr, zTerm, iCode);
  186858. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  186859. non_ascii_tokenchar:
  186860. iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
  186861. if( iCode ) WRITE_UTF8(zOut, iCode);
  186862. }else{
  186863. break;
  186864. }
  186865. }else if( a[*zCsr]==0 ){
  186866. /* An ascii-range separator character. End of token. */
  186867. break;
  186868. }else{
  186869. ascii_tokenchar:
  186870. if( *zCsr>='A' && *zCsr<='Z' ){
  186871. *zOut++ = *zCsr + 32;
  186872. }else{
  186873. *zOut++ = *zCsr;
  186874. }
  186875. zCsr++;
  186876. }
  186877. ie = zCsr - (unsigned char*)pText;
  186878. }
  186879. /* Invoke the token callback */
  186880. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  186881. }
  186882. tokenize_done:
  186883. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  186884. return rc;
  186885. }
  186886. /**************************************************************************
  186887. ** Start of porter stemmer implementation.
  186888. */
  186889. /* Any tokens larger than this (in bytes) are passed through without
  186890. ** stemming. */
  186891. #define FTS5_PORTER_MAX_TOKEN 64
  186892. typedef struct PorterTokenizer PorterTokenizer;
  186893. struct PorterTokenizer {
  186894. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  186895. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  186896. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  186897. };
  186898. /*
  186899. ** Delete a "porter" tokenizer.
  186900. */
  186901. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  186902. if( pTok ){
  186903. PorterTokenizer *p = (PorterTokenizer*)pTok;
  186904. if( p->pTokenizer ){
  186905. p->tokenizer.xDelete(p->pTokenizer);
  186906. }
  186907. sqlite3_free(p);
  186908. }
  186909. }
  186910. /*
  186911. ** Create a "porter" tokenizer.
  186912. */
  186913. static int fts5PorterCreate(
  186914. void *pCtx,
  186915. const char **azArg, int nArg,
  186916. Fts5Tokenizer **ppOut
  186917. ){
  186918. fts5_api *pApi = (fts5_api*)pCtx;
  186919. int rc = SQLITE_OK;
  186920. PorterTokenizer *pRet;
  186921. void *pUserdata = 0;
  186922. const char *zBase = "unicode61";
  186923. if( nArg>0 ){
  186924. zBase = azArg[0];
  186925. }
  186926. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  186927. if( pRet ){
  186928. memset(pRet, 0, sizeof(PorterTokenizer));
  186929. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  186930. }else{
  186931. rc = SQLITE_NOMEM;
  186932. }
  186933. if( rc==SQLITE_OK ){
  186934. int nArg2 = (nArg>0 ? nArg-1 : 0);
  186935. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  186936. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  186937. }
  186938. if( rc!=SQLITE_OK ){
  186939. fts5PorterDelete((Fts5Tokenizer*)pRet);
  186940. pRet = 0;
  186941. }
  186942. *ppOut = (Fts5Tokenizer*)pRet;
  186943. return rc;
  186944. }
  186945. typedef struct PorterContext PorterContext;
  186946. struct PorterContext {
  186947. void *pCtx;
  186948. int (*xToken)(void*, int, const char*, int, int, int);
  186949. char *aBuf;
  186950. };
  186951. typedef struct PorterRule PorterRule;
  186952. struct PorterRule {
  186953. const char *zSuffix;
  186954. int nSuffix;
  186955. int (*xCond)(char *zStem, int nStem);
  186956. const char *zOutput;
  186957. int nOutput;
  186958. };
  186959. #if 0
  186960. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  186961. int ret = -1;
  186962. int nBuf = *pnBuf;
  186963. PorterRule *p;
  186964. for(p=aRule; p->zSuffix; p++){
  186965. assert( strlen(p->zSuffix)==p->nSuffix );
  186966. assert( strlen(p->zOutput)==p->nOutput );
  186967. if( nBuf<p->nSuffix ) continue;
  186968. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  186969. }
  186970. if( p->zSuffix ){
  186971. int nStem = nBuf - p->nSuffix;
  186972. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  186973. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  186974. *pnBuf = nStem + p->nOutput;
  186975. ret = p - aRule;
  186976. }
  186977. }
  186978. return ret;
  186979. }
  186980. #endif
  186981. static int fts5PorterIsVowel(char c, int bYIsVowel){
  186982. return (
  186983. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  186984. );
  186985. }
  186986. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  186987. int i;
  186988. int bCons = bPrevCons;
  186989. /* Scan for a vowel */
  186990. for(i=0; i<nStem; i++){
  186991. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  186992. }
  186993. /* Scan for a consonent */
  186994. for(i++; i<nStem; i++){
  186995. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  186996. }
  186997. return 0;
  186998. }
  186999. /* porter rule condition: (m > 0) */
  187000. static int fts5Porter_MGt0(char *zStem, int nStem){
  187001. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  187002. }
  187003. /* porter rule condition: (m > 1) */
  187004. static int fts5Porter_MGt1(char *zStem, int nStem){
  187005. int n;
  187006. n = fts5PorterGobbleVC(zStem, nStem, 0);
  187007. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  187008. return 1;
  187009. }
  187010. return 0;
  187011. }
  187012. /* porter rule condition: (m = 1) */
  187013. static int fts5Porter_MEq1(char *zStem, int nStem){
  187014. int n;
  187015. n = fts5PorterGobbleVC(zStem, nStem, 0);
  187016. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  187017. return 1;
  187018. }
  187019. return 0;
  187020. }
  187021. /* porter rule condition: (*o) */
  187022. static int fts5Porter_Ostar(char *zStem, int nStem){
  187023. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  187024. return 0;
  187025. }else{
  187026. int i;
  187027. int mask = 0;
  187028. int bCons = 0;
  187029. for(i=0; i<nStem; i++){
  187030. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  187031. assert( bCons==0 || bCons==1 );
  187032. mask = (mask << 1) + bCons;
  187033. }
  187034. return ((mask & 0x0007)==0x0005);
  187035. }
  187036. }
  187037. /* porter rule condition: (m > 1 and (*S or *T)) */
  187038. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  187039. assert( nStem>0 );
  187040. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  187041. && fts5Porter_MGt1(zStem, nStem);
  187042. }
  187043. /* porter rule condition: (*v*) */
  187044. static int fts5Porter_Vowel(char *zStem, int nStem){
  187045. int i;
  187046. for(i=0; i<nStem; i++){
  187047. if( fts5PorterIsVowel(zStem[i], i>0) ){
  187048. return 1;
  187049. }
  187050. }
  187051. return 0;
  187052. }
  187053. /**************************************************************************
  187054. ***************************************************************************
  187055. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  187056. */
  187057. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  187058. int ret = 0;
  187059. int nBuf = *pnBuf;
  187060. switch( aBuf[nBuf-2] ){
  187061. case 'a':
  187062. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  187063. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  187064. *pnBuf = nBuf - 2;
  187065. }
  187066. }
  187067. break;
  187068. case 'c':
  187069. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  187070. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187071. *pnBuf = nBuf - 4;
  187072. }
  187073. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  187074. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187075. *pnBuf = nBuf - 4;
  187076. }
  187077. }
  187078. break;
  187079. case 'e':
  187080. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  187081. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  187082. *pnBuf = nBuf - 2;
  187083. }
  187084. }
  187085. break;
  187086. case 'i':
  187087. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  187088. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  187089. *pnBuf = nBuf - 2;
  187090. }
  187091. }
  187092. break;
  187093. case 'l':
  187094. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  187095. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187096. *pnBuf = nBuf - 4;
  187097. }
  187098. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  187099. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187100. *pnBuf = nBuf - 4;
  187101. }
  187102. }
  187103. break;
  187104. case 'n':
  187105. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  187106. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187107. *pnBuf = nBuf - 3;
  187108. }
  187109. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  187110. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  187111. *pnBuf = nBuf - 5;
  187112. }
  187113. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  187114. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187115. *pnBuf = nBuf - 4;
  187116. }
  187117. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  187118. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187119. *pnBuf = nBuf - 3;
  187120. }
  187121. }
  187122. break;
  187123. case 'o':
  187124. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  187125. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  187126. *pnBuf = nBuf - 3;
  187127. }
  187128. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  187129. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  187130. *pnBuf = nBuf - 2;
  187131. }
  187132. }
  187133. break;
  187134. case 's':
  187135. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  187136. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187137. *pnBuf = nBuf - 3;
  187138. }
  187139. }
  187140. break;
  187141. case 't':
  187142. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  187143. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187144. *pnBuf = nBuf - 3;
  187145. }
  187146. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  187147. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187148. *pnBuf = nBuf - 3;
  187149. }
  187150. }
  187151. break;
  187152. case 'u':
  187153. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  187154. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187155. *pnBuf = nBuf - 3;
  187156. }
  187157. }
  187158. break;
  187159. case 'v':
  187160. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  187161. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187162. *pnBuf = nBuf - 3;
  187163. }
  187164. }
  187165. break;
  187166. case 'z':
  187167. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  187168. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187169. *pnBuf = nBuf - 3;
  187170. }
  187171. }
  187172. break;
  187173. }
  187174. return ret;
  187175. }
  187176. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  187177. int ret = 0;
  187178. int nBuf = *pnBuf;
  187179. switch( aBuf[nBuf-2] ){
  187180. case 'a':
  187181. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  187182. memcpy(&aBuf[nBuf-2], "ate", 3);
  187183. *pnBuf = nBuf - 2 + 3;
  187184. ret = 1;
  187185. }
  187186. break;
  187187. case 'b':
  187188. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  187189. memcpy(&aBuf[nBuf-2], "ble", 3);
  187190. *pnBuf = nBuf - 2 + 3;
  187191. ret = 1;
  187192. }
  187193. break;
  187194. case 'i':
  187195. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  187196. memcpy(&aBuf[nBuf-2], "ize", 3);
  187197. *pnBuf = nBuf - 2 + 3;
  187198. ret = 1;
  187199. }
  187200. break;
  187201. }
  187202. return ret;
  187203. }
  187204. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  187205. int ret = 0;
  187206. int nBuf = *pnBuf;
  187207. switch( aBuf[nBuf-2] ){
  187208. case 'a':
  187209. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  187210. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187211. memcpy(&aBuf[nBuf-7], "ate", 3);
  187212. *pnBuf = nBuf - 7 + 3;
  187213. }
  187214. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  187215. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  187216. memcpy(&aBuf[nBuf-6], "tion", 4);
  187217. *pnBuf = nBuf - 6 + 4;
  187218. }
  187219. }
  187220. break;
  187221. case 'c':
  187222. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  187223. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187224. memcpy(&aBuf[nBuf-4], "ence", 4);
  187225. *pnBuf = nBuf - 4 + 4;
  187226. }
  187227. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  187228. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187229. memcpy(&aBuf[nBuf-4], "ance", 4);
  187230. *pnBuf = nBuf - 4 + 4;
  187231. }
  187232. }
  187233. break;
  187234. case 'e':
  187235. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  187236. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187237. memcpy(&aBuf[nBuf-4], "ize", 3);
  187238. *pnBuf = nBuf - 4 + 3;
  187239. }
  187240. }
  187241. break;
  187242. case 'g':
  187243. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  187244. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187245. memcpy(&aBuf[nBuf-4], "log", 3);
  187246. *pnBuf = nBuf - 4 + 3;
  187247. }
  187248. }
  187249. break;
  187250. case 'l':
  187251. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  187252. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  187253. memcpy(&aBuf[nBuf-3], "ble", 3);
  187254. *pnBuf = nBuf - 3 + 3;
  187255. }
  187256. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  187257. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187258. memcpy(&aBuf[nBuf-4], "al", 2);
  187259. *pnBuf = nBuf - 4 + 2;
  187260. }
  187261. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  187262. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187263. memcpy(&aBuf[nBuf-5], "ent", 3);
  187264. *pnBuf = nBuf - 5 + 3;
  187265. }
  187266. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  187267. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  187268. memcpy(&aBuf[nBuf-3], "e", 1);
  187269. *pnBuf = nBuf - 3 + 1;
  187270. }
  187271. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  187272. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187273. memcpy(&aBuf[nBuf-5], "ous", 3);
  187274. *pnBuf = nBuf - 5 + 3;
  187275. }
  187276. }
  187277. break;
  187278. case 'o':
  187279. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  187280. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187281. memcpy(&aBuf[nBuf-7], "ize", 3);
  187282. *pnBuf = nBuf - 7 + 3;
  187283. }
  187284. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  187285. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187286. memcpy(&aBuf[nBuf-5], "ate", 3);
  187287. *pnBuf = nBuf - 5 + 3;
  187288. }
  187289. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  187290. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187291. memcpy(&aBuf[nBuf-4], "ate", 3);
  187292. *pnBuf = nBuf - 4 + 3;
  187293. }
  187294. }
  187295. break;
  187296. case 's':
  187297. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  187298. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187299. memcpy(&aBuf[nBuf-5], "al", 2);
  187300. *pnBuf = nBuf - 5 + 2;
  187301. }
  187302. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  187303. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187304. memcpy(&aBuf[nBuf-7], "ive", 3);
  187305. *pnBuf = nBuf - 7 + 3;
  187306. }
  187307. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  187308. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187309. memcpy(&aBuf[nBuf-7], "ful", 3);
  187310. *pnBuf = nBuf - 7 + 3;
  187311. }
  187312. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  187313. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187314. memcpy(&aBuf[nBuf-7], "ous", 3);
  187315. *pnBuf = nBuf - 7 + 3;
  187316. }
  187317. }
  187318. break;
  187319. case 't':
  187320. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  187321. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187322. memcpy(&aBuf[nBuf-5], "al", 2);
  187323. *pnBuf = nBuf - 5 + 2;
  187324. }
  187325. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  187326. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187327. memcpy(&aBuf[nBuf-5], "ive", 3);
  187328. *pnBuf = nBuf - 5 + 3;
  187329. }
  187330. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  187331. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  187332. memcpy(&aBuf[nBuf-6], "ble", 3);
  187333. *pnBuf = nBuf - 6 + 3;
  187334. }
  187335. }
  187336. break;
  187337. }
  187338. return ret;
  187339. }
  187340. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  187341. int ret = 0;
  187342. int nBuf = *pnBuf;
  187343. switch( aBuf[nBuf-2] ){
  187344. case 'a':
  187345. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  187346. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187347. memcpy(&aBuf[nBuf-4], "ic", 2);
  187348. *pnBuf = nBuf - 4 + 2;
  187349. }
  187350. }
  187351. break;
  187352. case 's':
  187353. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  187354. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187355. *pnBuf = nBuf - 4;
  187356. }
  187357. }
  187358. break;
  187359. case 't':
  187360. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  187361. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187362. memcpy(&aBuf[nBuf-5], "ic", 2);
  187363. *pnBuf = nBuf - 5 + 2;
  187364. }
  187365. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  187366. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187367. memcpy(&aBuf[nBuf-5], "ic", 2);
  187368. *pnBuf = nBuf - 5 + 2;
  187369. }
  187370. }
  187371. break;
  187372. case 'u':
  187373. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  187374. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  187375. *pnBuf = nBuf - 3;
  187376. }
  187377. }
  187378. break;
  187379. case 'v':
  187380. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  187381. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187382. *pnBuf = nBuf - 5;
  187383. }
  187384. }
  187385. break;
  187386. case 'z':
  187387. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  187388. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187389. memcpy(&aBuf[nBuf-5], "al", 2);
  187390. *pnBuf = nBuf - 5 + 2;
  187391. }
  187392. }
  187393. break;
  187394. }
  187395. return ret;
  187396. }
  187397. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  187398. int ret = 0;
  187399. int nBuf = *pnBuf;
  187400. switch( aBuf[nBuf-2] ){
  187401. case 'e':
  187402. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  187403. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  187404. memcpy(&aBuf[nBuf-3], "ee", 2);
  187405. *pnBuf = nBuf - 3 + 2;
  187406. }
  187407. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  187408. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  187409. *pnBuf = nBuf - 2;
  187410. ret = 1;
  187411. }
  187412. }
  187413. break;
  187414. case 'n':
  187415. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  187416. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  187417. *pnBuf = nBuf - 3;
  187418. ret = 1;
  187419. }
  187420. }
  187421. break;
  187422. }
  187423. return ret;
  187424. }
  187425. /*
  187426. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  187427. ***************************************************************************
  187428. **************************************************************************/
  187429. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  187430. int nBuf = *pnBuf;
  187431. if( aBuf[nBuf-1]=='s' ){
  187432. if( aBuf[nBuf-2]=='e' ){
  187433. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  187434. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  187435. ){
  187436. *pnBuf = nBuf-2;
  187437. }else{
  187438. *pnBuf = nBuf-1;
  187439. }
  187440. }
  187441. else if( aBuf[nBuf-2]!='s' ){
  187442. *pnBuf = nBuf-1;
  187443. }
  187444. }
  187445. }
  187446. static int fts5PorterCb(
  187447. void *pCtx,
  187448. int tflags,
  187449. const char *pToken,
  187450. int nToken,
  187451. int iStart,
  187452. int iEnd
  187453. ){
  187454. PorterContext *p = (PorterContext*)pCtx;
  187455. char *aBuf;
  187456. int nBuf;
  187457. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  187458. aBuf = p->aBuf;
  187459. nBuf = nToken;
  187460. memcpy(aBuf, pToken, nBuf);
  187461. /* Step 1. */
  187462. fts5PorterStep1A(aBuf, &nBuf);
  187463. if( fts5PorterStep1B(aBuf, &nBuf) ){
  187464. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  187465. char c = aBuf[nBuf-1];
  187466. if( fts5PorterIsVowel(c, 0)==0
  187467. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  187468. ){
  187469. nBuf--;
  187470. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  187471. aBuf[nBuf++] = 'e';
  187472. }
  187473. }
  187474. }
  187475. /* Step 1C. */
  187476. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  187477. aBuf[nBuf-1] = 'i';
  187478. }
  187479. /* Steps 2 through 4. */
  187480. fts5PorterStep2(aBuf, &nBuf);
  187481. fts5PorterStep3(aBuf, &nBuf);
  187482. fts5PorterStep4(aBuf, &nBuf);
  187483. /* Step 5a. */
  187484. assert( nBuf>0 );
  187485. if( aBuf[nBuf-1]=='e' ){
  187486. if( fts5Porter_MGt1(aBuf, nBuf-1)
  187487. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  187488. ){
  187489. nBuf--;
  187490. }
  187491. }
  187492. /* Step 5b. */
  187493. if( nBuf>1 && aBuf[nBuf-1]=='l'
  187494. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  187495. ){
  187496. nBuf--;
  187497. }
  187498. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  187499. pass_through:
  187500. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  187501. }
  187502. /*
  187503. ** Tokenize using the porter tokenizer.
  187504. */
  187505. static int fts5PorterTokenize(
  187506. Fts5Tokenizer *pTokenizer,
  187507. void *pCtx,
  187508. int flags,
  187509. const char *pText, int nText,
  187510. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  187511. ){
  187512. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  187513. PorterContext sCtx;
  187514. sCtx.xToken = xToken;
  187515. sCtx.pCtx = pCtx;
  187516. sCtx.aBuf = p->aBuf;
  187517. return p->tokenizer.xTokenize(
  187518. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  187519. );
  187520. }
  187521. /*
  187522. ** Register all built-in tokenizers with FTS5.
  187523. */
  187524. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  187525. struct BuiltinTokenizer {
  187526. const char *zName;
  187527. fts5_tokenizer x;
  187528. } aBuiltin[] = {
  187529. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  187530. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  187531. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  187532. };
  187533. int rc = SQLITE_OK; /* Return code */
  187534. int i; /* To iterate through builtin functions */
  187535. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  187536. rc = pApi->xCreateTokenizer(pApi,
  187537. aBuiltin[i].zName,
  187538. (void*)pApi,
  187539. &aBuiltin[i].x,
  187540. 0
  187541. );
  187542. }
  187543. return rc;
  187544. }
  187545. /*
  187546. ** 2012 May 25
  187547. **
  187548. ** The author disclaims copyright to this source code. In place of
  187549. ** a legal notice, here is a blessing:
  187550. **
  187551. ** May you do good and not evil.
  187552. ** May you find forgiveness for yourself and forgive others.
  187553. ** May you share freely, never taking more than you give.
  187554. **
  187555. ******************************************************************************
  187556. */
  187557. /*
  187558. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  187559. */
  187560. /* #include <assert.h> */
  187561. /*
  187562. ** Return true if the argument corresponds to a unicode codepoint
  187563. ** classified as either a letter or a number. Otherwise false.
  187564. **
  187565. ** The results are undefined if the value passed to this function
  187566. ** is less than zero.
  187567. */
  187568. static int sqlite3Fts5UnicodeIsalnum(int c){
  187569. /* Each unsigned integer in the following array corresponds to a contiguous
  187570. ** range of unicode codepoints that are not either letters or numbers (i.e.
  187571. ** codepoints for which this function should return 0).
  187572. **
  187573. ** The most significant 22 bits in each 32-bit value contain the first
  187574. ** codepoint in the range. The least significant 10 bits are used to store
  187575. ** the size of the range (always at least 1). In other words, the value
  187576. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  187577. ** C. It is not possible to represent a range larger than 1023 codepoints
  187578. ** using this format.
  187579. */
  187580. static const unsigned int aEntry[] = {
  187581. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  187582. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  187583. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  187584. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  187585. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  187586. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  187587. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  187588. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  187589. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  187590. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  187591. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  187592. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  187593. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  187594. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  187595. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  187596. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  187597. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  187598. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  187599. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  187600. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  187601. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  187602. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  187603. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  187604. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  187605. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  187606. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  187607. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  187608. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  187609. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  187610. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  187611. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  187612. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  187613. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  187614. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  187615. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  187616. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  187617. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  187618. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  187619. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  187620. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  187621. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  187622. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  187623. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  187624. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  187625. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  187626. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  187627. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  187628. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  187629. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  187630. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  187631. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  187632. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  187633. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  187634. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  187635. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  187636. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  187637. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  187638. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  187639. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  187640. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  187641. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  187642. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  187643. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  187644. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  187645. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  187646. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  187647. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  187648. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  187649. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  187650. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  187651. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  187652. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  187653. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  187654. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  187655. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  187656. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  187657. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  187658. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  187659. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  187660. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  187661. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  187662. 0x380400F0,
  187663. };
  187664. static const unsigned int aAscii[4] = {
  187665. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  187666. };
  187667. if( (unsigned int)c<128 ){
  187668. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  187669. }else if( (unsigned int)c<(1<<22) ){
  187670. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  187671. int iRes = 0;
  187672. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  187673. int iLo = 0;
  187674. while( iHi>=iLo ){
  187675. int iTest = (iHi + iLo) / 2;
  187676. if( key >= aEntry[iTest] ){
  187677. iRes = iTest;
  187678. iLo = iTest+1;
  187679. }else{
  187680. iHi = iTest-1;
  187681. }
  187682. }
  187683. assert( aEntry[0]<key );
  187684. assert( key>=aEntry[iRes] );
  187685. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  187686. }
  187687. return 1;
  187688. }
  187689. /*
  187690. ** If the argument is a codepoint corresponding to a lowercase letter
  187691. ** in the ASCII range with a diacritic added, return the codepoint
  187692. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  187693. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  187694. ** E"). The resuls of passing a codepoint that corresponds to an
  187695. ** uppercase letter are undefined.
  187696. */
  187697. static int fts5_remove_diacritic(int c){
  187698. unsigned short aDia[] = {
  187699. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  187700. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  187701. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  187702. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  187703. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  187704. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  187705. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  187706. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  187707. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  187708. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  187709. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  187710. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  187711. 62924, 63050, 63082, 63274, 63390,
  187712. };
  187713. char aChar[] = {
  187714. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  187715. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  187716. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  187717. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  187718. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  187719. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  187720. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  187721. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  187722. 'e', 'i', 'o', 'u', 'y',
  187723. };
  187724. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  187725. int iRes = 0;
  187726. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  187727. int iLo = 0;
  187728. while( iHi>=iLo ){
  187729. int iTest = (iHi + iLo) / 2;
  187730. if( key >= aDia[iTest] ){
  187731. iRes = iTest;
  187732. iLo = iTest+1;
  187733. }else{
  187734. iHi = iTest-1;
  187735. }
  187736. }
  187737. assert( key>=aDia[iRes] );
  187738. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  187739. }
  187740. /*
  187741. ** Return true if the argument interpreted as a unicode codepoint
  187742. ** is a diacritical modifier character.
  187743. */
  187744. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  187745. unsigned int mask0 = 0x08029FDF;
  187746. unsigned int mask1 = 0x000361F8;
  187747. if( c<768 || c>817 ) return 0;
  187748. return (c < 768+32) ?
  187749. (mask0 & (1 << (c-768))) :
  187750. (mask1 & (1 << (c-768-32)));
  187751. }
  187752. /*
  187753. ** Interpret the argument as a unicode codepoint. If the codepoint
  187754. ** is an upper case character that has a lower case equivalent,
  187755. ** return the codepoint corresponding to the lower case version.
  187756. ** Otherwise, return a copy of the argument.
  187757. **
  187758. ** The results are undefined if the value passed to this function
  187759. ** is less than zero.
  187760. */
  187761. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
  187762. /* Each entry in the following array defines a rule for folding a range
  187763. ** of codepoints to lower case. The rule applies to a range of nRange
  187764. ** codepoints starting at codepoint iCode.
  187765. **
  187766. ** If the least significant bit in flags is clear, then the rule applies
  187767. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  187768. ** need to be folded). Or, if it is set, then the rule only applies to
  187769. ** every second codepoint in the range, starting with codepoint C.
  187770. **
  187771. ** The 7 most significant bits in flags are an index into the aiOff[]
  187772. ** array. If a specific codepoint C does require folding, then its lower
  187773. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  187774. **
  187775. ** The contents of this array are generated by parsing the CaseFolding.txt
  187776. ** file distributed as part of the "Unicode Character Database". See
  187777. ** http://www.unicode.org for details.
  187778. */
  187779. static const struct TableEntry {
  187780. unsigned short iCode;
  187781. unsigned char flags;
  187782. unsigned char nRange;
  187783. } aEntry[] = {
  187784. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  187785. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  187786. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  187787. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  187788. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  187789. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  187790. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  187791. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  187792. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  187793. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  187794. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  187795. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  187796. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  187797. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  187798. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  187799. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  187800. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  187801. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  187802. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  187803. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  187804. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  187805. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  187806. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  187807. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  187808. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  187809. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  187810. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  187811. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  187812. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  187813. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  187814. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  187815. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  187816. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  187817. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  187818. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  187819. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  187820. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  187821. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  187822. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  187823. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  187824. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  187825. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  187826. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  187827. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  187828. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  187829. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  187830. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  187831. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  187832. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  187833. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  187834. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  187835. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  187836. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  187837. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  187838. {65313, 14, 26},
  187839. };
  187840. static const unsigned short aiOff[] = {
  187841. 1, 2, 8, 15, 16, 26, 28, 32,
  187842. 37, 38, 40, 48, 63, 64, 69, 71,
  187843. 79, 80, 116, 202, 203, 205, 206, 207,
  187844. 209, 210, 211, 213, 214, 217, 218, 219,
  187845. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  187846. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  187847. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  187848. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  187849. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  187850. 65514, 65521, 65527, 65528, 65529,
  187851. };
  187852. int ret = c;
  187853. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  187854. if( c<128 ){
  187855. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  187856. }else if( c<65536 ){
  187857. const struct TableEntry *p;
  187858. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  187859. int iLo = 0;
  187860. int iRes = -1;
  187861. assert( c>aEntry[0].iCode );
  187862. while( iHi>=iLo ){
  187863. int iTest = (iHi + iLo) / 2;
  187864. int cmp = (c - aEntry[iTest].iCode);
  187865. if( cmp>=0 ){
  187866. iRes = iTest;
  187867. iLo = iTest+1;
  187868. }else{
  187869. iHi = iTest-1;
  187870. }
  187871. }
  187872. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  187873. p = &aEntry[iRes];
  187874. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  187875. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  187876. assert( ret>0 );
  187877. }
  187878. if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
  187879. }
  187880. else if( c>=66560 && c<66600 ){
  187881. ret = c + 40;
  187882. }
  187883. return ret;
  187884. }
  187885. /*
  187886. ** 2015 May 30
  187887. **
  187888. ** The author disclaims copyright to this source code. In place of
  187889. ** a legal notice, here is a blessing:
  187890. **
  187891. ** May you do good and not evil.
  187892. ** May you find forgiveness for yourself and forgive others.
  187893. ** May you share freely, never taking more than you give.
  187894. **
  187895. ******************************************************************************
  187896. **
  187897. ** Routines for varint serialization and deserialization.
  187898. */
  187899. /* #include "fts5Int.h" */
  187900. /*
  187901. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  187902. ** Except, this version does handle the single byte case that the core
  187903. ** version depends on being handled before its function is called.
  187904. */
  187905. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  187906. u32 a,b;
  187907. /* The 1-byte case. Overwhelmingly the most common. */
  187908. a = *p;
  187909. /* a: p0 (unmasked) */
  187910. if (!(a&0x80))
  187911. {
  187912. /* Values between 0 and 127 */
  187913. *v = a;
  187914. return 1;
  187915. }
  187916. /* The 2-byte case */
  187917. p++;
  187918. b = *p;
  187919. /* b: p1 (unmasked) */
  187920. if (!(b&0x80))
  187921. {
  187922. /* Values between 128 and 16383 */
  187923. a &= 0x7f;
  187924. a = a<<7;
  187925. *v = a | b;
  187926. return 2;
  187927. }
  187928. /* The 3-byte case */
  187929. p++;
  187930. a = a<<14;
  187931. a |= *p;
  187932. /* a: p0<<14 | p2 (unmasked) */
  187933. if (!(a&0x80))
  187934. {
  187935. /* Values between 16384 and 2097151 */
  187936. a &= (0x7f<<14)|(0x7f);
  187937. b &= 0x7f;
  187938. b = b<<7;
  187939. *v = a | b;
  187940. return 3;
  187941. }
  187942. /* A 32-bit varint is used to store size information in btrees.
  187943. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  187944. ** A 3-byte varint is sufficient, for example, to record the size
  187945. ** of a 1048569-byte BLOB or string.
  187946. **
  187947. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  187948. ** rare larger cases can be handled by the slower 64-bit varint
  187949. ** routine.
  187950. */
  187951. {
  187952. u64 v64;
  187953. u8 n;
  187954. p -= 2;
  187955. n = sqlite3Fts5GetVarint(p, &v64);
  187956. *v = (u32)v64;
  187957. assert( n>3 && n<=9 );
  187958. return n;
  187959. }
  187960. }
  187961. /*
  187962. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  187963. ** are defined here rather than simply putting the constant expressions
  187964. ** inline in order to work around bugs in the RVT compiler.
  187965. **
  187966. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  187967. **
  187968. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  187969. */
  187970. #define SLOT_2_0 0x001fc07f
  187971. #define SLOT_4_2_0 0xf01fc07f
  187972. /*
  187973. ** Read a 64-bit variable-length integer from memory starting at p[0].
  187974. ** Return the number of bytes read. The value is stored in *v.
  187975. */
  187976. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  187977. u32 a,b,s;
  187978. a = *p;
  187979. /* a: p0 (unmasked) */
  187980. if (!(a&0x80))
  187981. {
  187982. *v = a;
  187983. return 1;
  187984. }
  187985. p++;
  187986. b = *p;
  187987. /* b: p1 (unmasked) */
  187988. if (!(b&0x80))
  187989. {
  187990. a &= 0x7f;
  187991. a = a<<7;
  187992. a |= b;
  187993. *v = a;
  187994. return 2;
  187995. }
  187996. /* Verify that constants are precomputed correctly */
  187997. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  187998. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  187999. p++;
  188000. a = a<<14;
  188001. a |= *p;
  188002. /* a: p0<<14 | p2 (unmasked) */
  188003. if (!(a&0x80))
  188004. {
  188005. a &= SLOT_2_0;
  188006. b &= 0x7f;
  188007. b = b<<7;
  188008. a |= b;
  188009. *v = a;
  188010. return 3;
  188011. }
  188012. /* CSE1 from below */
  188013. a &= SLOT_2_0;
  188014. p++;
  188015. b = b<<14;
  188016. b |= *p;
  188017. /* b: p1<<14 | p3 (unmasked) */
  188018. if (!(b&0x80))
  188019. {
  188020. b &= SLOT_2_0;
  188021. /* moved CSE1 up */
  188022. /* a &= (0x7f<<14)|(0x7f); */
  188023. a = a<<7;
  188024. a |= b;
  188025. *v = a;
  188026. return 4;
  188027. }
  188028. /* a: p0<<14 | p2 (masked) */
  188029. /* b: p1<<14 | p3 (unmasked) */
  188030. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  188031. /* moved CSE1 up */
  188032. /* a &= (0x7f<<14)|(0x7f); */
  188033. b &= SLOT_2_0;
  188034. s = a;
  188035. /* s: p0<<14 | p2 (masked) */
  188036. p++;
  188037. a = a<<14;
  188038. a |= *p;
  188039. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  188040. if (!(a&0x80))
  188041. {
  188042. /* we can skip these cause they were (effectively) done above in calc'ing s */
  188043. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  188044. /* b &= (0x7f<<14)|(0x7f); */
  188045. b = b<<7;
  188046. a |= b;
  188047. s = s>>18;
  188048. *v = ((u64)s)<<32 | a;
  188049. return 5;
  188050. }
  188051. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  188052. s = s<<7;
  188053. s |= b;
  188054. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  188055. p++;
  188056. b = b<<14;
  188057. b |= *p;
  188058. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  188059. if (!(b&0x80))
  188060. {
  188061. /* we can skip this cause it was (effectively) done above in calc'ing s */
  188062. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  188063. a &= SLOT_2_0;
  188064. a = a<<7;
  188065. a |= b;
  188066. s = s>>18;
  188067. *v = ((u64)s)<<32 | a;
  188068. return 6;
  188069. }
  188070. p++;
  188071. a = a<<14;
  188072. a |= *p;
  188073. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  188074. if (!(a&0x80))
  188075. {
  188076. a &= SLOT_4_2_0;
  188077. b &= SLOT_2_0;
  188078. b = b<<7;
  188079. a |= b;
  188080. s = s>>11;
  188081. *v = ((u64)s)<<32 | a;
  188082. return 7;
  188083. }
  188084. /* CSE2 from below */
  188085. a &= SLOT_2_0;
  188086. p++;
  188087. b = b<<14;
  188088. b |= *p;
  188089. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  188090. if (!(b&0x80))
  188091. {
  188092. b &= SLOT_4_2_0;
  188093. /* moved CSE2 up */
  188094. /* a &= (0x7f<<14)|(0x7f); */
  188095. a = a<<7;
  188096. a |= b;
  188097. s = s>>4;
  188098. *v = ((u64)s)<<32 | a;
  188099. return 8;
  188100. }
  188101. p++;
  188102. a = a<<15;
  188103. a |= *p;
  188104. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  188105. /* moved CSE2 up */
  188106. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  188107. b &= SLOT_2_0;
  188108. b = b<<8;
  188109. a |= b;
  188110. s = s<<4;
  188111. b = p[-4];
  188112. b &= 0x7f;
  188113. b = b>>3;
  188114. s |= b;
  188115. *v = ((u64)s)<<32 | a;
  188116. return 9;
  188117. }
  188118. /*
  188119. ** The variable-length integer encoding is as follows:
  188120. **
  188121. ** KEY:
  188122. ** A = 0xxxxxxx 7 bits of data and one flag bit
  188123. ** B = 1xxxxxxx 7 bits of data and one flag bit
  188124. ** C = xxxxxxxx 8 bits of data
  188125. **
  188126. ** 7 bits - A
  188127. ** 14 bits - BA
  188128. ** 21 bits - BBA
  188129. ** 28 bits - BBBA
  188130. ** 35 bits - BBBBA
  188131. ** 42 bits - BBBBBA
  188132. ** 49 bits - BBBBBBA
  188133. ** 56 bits - BBBBBBBA
  188134. ** 64 bits - BBBBBBBBC
  188135. */
  188136. #ifdef SQLITE_NOINLINE
  188137. # define FTS5_NOINLINE SQLITE_NOINLINE
  188138. #else
  188139. # define FTS5_NOINLINE
  188140. #endif
  188141. /*
  188142. ** Write a 64-bit variable-length integer to memory starting at p[0].
  188143. ** The length of data write will be between 1 and 9 bytes. The number
  188144. ** of bytes written is returned.
  188145. **
  188146. ** A variable-length integer consists of the lower 7 bits of each byte
  188147. ** for all bytes that have the 8th bit set and one byte with the 8th
  188148. ** bit clear. Except, if we get to the 9th byte, it stores the full
  188149. ** 8 bits and is the last byte.
  188150. */
  188151. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  188152. int i, j, n;
  188153. u8 buf[10];
  188154. if( v & (((u64)0xff000000)<<32) ){
  188155. p[8] = (u8)v;
  188156. v >>= 8;
  188157. for(i=7; i>=0; i--){
  188158. p[i] = (u8)((v & 0x7f) | 0x80);
  188159. v >>= 7;
  188160. }
  188161. return 9;
  188162. }
  188163. n = 0;
  188164. do{
  188165. buf[n++] = (u8)((v & 0x7f) | 0x80);
  188166. v >>= 7;
  188167. }while( v!=0 );
  188168. buf[0] &= 0x7f;
  188169. assert( n<=9 );
  188170. for(i=0, j=n-1; j>=0; j--, i++){
  188171. p[i] = buf[j];
  188172. }
  188173. return n;
  188174. }
  188175. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  188176. if( v<=0x7f ){
  188177. p[0] = v&0x7f;
  188178. return 1;
  188179. }
  188180. if( v<=0x3fff ){
  188181. p[0] = ((v>>7)&0x7f)|0x80;
  188182. p[1] = v&0x7f;
  188183. return 2;
  188184. }
  188185. return fts5PutVarint64(p,v);
  188186. }
  188187. static int sqlite3Fts5GetVarintLen(u32 iVal){
  188188. #if 0
  188189. if( iVal<(1 << 7 ) ) return 1;
  188190. #endif
  188191. assert( iVal>=(1 << 7) );
  188192. if( iVal<(1 << 14) ) return 2;
  188193. if( iVal<(1 << 21) ) return 3;
  188194. if( iVal<(1 << 28) ) return 4;
  188195. return 5;
  188196. }
  188197. /*
  188198. ** 2015 May 08
  188199. **
  188200. ** The author disclaims copyright to this source code. In place of
  188201. ** a legal notice, here is a blessing:
  188202. **
  188203. ** May you do good and not evil.
  188204. ** May you find forgiveness for yourself and forgive others.
  188205. ** May you share freely, never taking more than you give.
  188206. **
  188207. ******************************************************************************
  188208. **
  188209. ** This is an SQLite virtual table module implementing direct access to an
  188210. ** existing FTS5 index. The module may create several different types of
  188211. ** tables:
  188212. **
  188213. ** col:
  188214. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  188215. **
  188216. ** One row for each term/column combination. The value of $doc is set to
  188217. ** the number of fts5 rows that contain at least one instance of term
  188218. ** $term within column $col. Field $cnt is set to the total number of
  188219. ** instances of term $term in column $col (in any row of the fts5 table).
  188220. **
  188221. ** row:
  188222. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  188223. **
  188224. ** One row for each term in the database. The value of $doc is set to
  188225. ** the number of fts5 rows that contain at least one instance of term
  188226. ** $term. Field $cnt is set to the total number of instances of term
  188227. ** $term in the database.
  188228. */
  188229. /* #include "fts5Int.h" */
  188230. typedef struct Fts5VocabTable Fts5VocabTable;
  188231. typedef struct Fts5VocabCursor Fts5VocabCursor;
  188232. struct Fts5VocabTable {
  188233. sqlite3_vtab base;
  188234. char *zFts5Tbl; /* Name of fts5 table */
  188235. char *zFts5Db; /* Db containing fts5 table */
  188236. sqlite3 *db; /* Database handle */
  188237. Fts5Global *pGlobal; /* FTS5 global object for this database */
  188238. int eType; /* FTS5_VOCAB_COL or ROW */
  188239. };
  188240. struct Fts5VocabCursor {
  188241. sqlite3_vtab_cursor base;
  188242. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  188243. Fts5Index *pIndex; /* Associated FTS5 index */
  188244. int bEof; /* True if this cursor is at EOF */
  188245. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  188246. int nLeTerm; /* Size of zLeTerm in bytes */
  188247. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  188248. /* These are used by 'col' tables only */
  188249. Fts5Config *pConfig; /* Fts5 table configuration */
  188250. int iCol;
  188251. i64 *aCnt;
  188252. i64 *aDoc;
  188253. /* Output values used by 'row' and 'col' tables */
  188254. i64 rowid; /* This table's current rowid value */
  188255. Fts5Buffer term; /* Current value of 'term' column */
  188256. };
  188257. #define FTS5_VOCAB_COL 0
  188258. #define FTS5_VOCAB_ROW 1
  188259. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  188260. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  188261. /*
  188262. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  188263. */
  188264. #define FTS5_VOCAB_TERM_EQ 0x01
  188265. #define FTS5_VOCAB_TERM_GE 0x02
  188266. #define FTS5_VOCAB_TERM_LE 0x04
  188267. /*
  188268. ** Translate a string containing an fts5vocab table type to an
  188269. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  188270. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  188271. ** and return SQLITE_ERROR.
  188272. */
  188273. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  188274. int rc = SQLITE_OK;
  188275. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  188276. if( rc==SQLITE_OK ){
  188277. sqlite3Fts5Dequote(zCopy);
  188278. if( sqlite3_stricmp(zCopy, "col")==0 ){
  188279. *peType = FTS5_VOCAB_COL;
  188280. }else
  188281. if( sqlite3_stricmp(zCopy, "row")==0 ){
  188282. *peType = FTS5_VOCAB_ROW;
  188283. }else
  188284. {
  188285. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  188286. rc = SQLITE_ERROR;
  188287. }
  188288. sqlite3_free(zCopy);
  188289. }
  188290. return rc;
  188291. }
  188292. /*
  188293. ** The xDisconnect() virtual table method.
  188294. */
  188295. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  188296. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  188297. sqlite3_free(pTab);
  188298. return SQLITE_OK;
  188299. }
  188300. /*
  188301. ** The xDestroy() virtual table method.
  188302. */
  188303. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  188304. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  188305. sqlite3_free(pTab);
  188306. return SQLITE_OK;
  188307. }
  188308. /*
  188309. ** This function is the implementation of both the xConnect and xCreate
  188310. ** methods of the FTS3 virtual table.
  188311. **
  188312. ** The argv[] array contains the following:
  188313. **
  188314. ** argv[0] -> module name ("fts5vocab")
  188315. ** argv[1] -> database name
  188316. ** argv[2] -> table name
  188317. **
  188318. ** then:
  188319. **
  188320. ** argv[3] -> name of fts5 table
  188321. ** argv[4] -> type of fts5vocab table
  188322. **
  188323. ** or, for tables in the TEMP schema only.
  188324. **
  188325. ** argv[3] -> name of fts5 tables database
  188326. ** argv[4] -> name of fts5 table
  188327. ** argv[5] -> type of fts5vocab table
  188328. */
  188329. static int fts5VocabInitVtab(
  188330. sqlite3 *db, /* The SQLite database connection */
  188331. void *pAux, /* Pointer to Fts5Global object */
  188332. int argc, /* Number of elements in argv array */
  188333. const char * const *argv, /* xCreate/xConnect argument array */
  188334. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  188335. char **pzErr /* Write any error message here */
  188336. ){
  188337. const char *azSchema[] = {
  188338. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  188339. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")"
  188340. };
  188341. Fts5VocabTable *pRet = 0;
  188342. int rc = SQLITE_OK; /* Return code */
  188343. int bDb;
  188344. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  188345. if( argc!=5 && bDb==0 ){
  188346. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  188347. rc = SQLITE_ERROR;
  188348. }else{
  188349. int nByte; /* Bytes of space to allocate */
  188350. const char *zDb = bDb ? argv[3] : argv[1];
  188351. const char *zTab = bDb ? argv[4] : argv[3];
  188352. const char *zType = bDb ? argv[5] : argv[4];
  188353. int nDb = (int)strlen(zDb)+1;
  188354. int nTab = (int)strlen(zTab)+1;
  188355. int eType = 0;
  188356. rc = fts5VocabTableType(zType, pzErr, &eType);
  188357. if( rc==SQLITE_OK ){
  188358. assert( eType>=0 && eType<ArraySize(azSchema) );
  188359. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  188360. }
  188361. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  188362. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  188363. if( pRet ){
  188364. pRet->pGlobal = (Fts5Global*)pAux;
  188365. pRet->eType = eType;
  188366. pRet->db = db;
  188367. pRet->zFts5Tbl = (char*)&pRet[1];
  188368. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  188369. memcpy(pRet->zFts5Tbl, zTab, nTab);
  188370. memcpy(pRet->zFts5Db, zDb, nDb);
  188371. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  188372. sqlite3Fts5Dequote(pRet->zFts5Db);
  188373. }
  188374. }
  188375. *ppVTab = (sqlite3_vtab*)pRet;
  188376. return rc;
  188377. }
  188378. /*
  188379. ** The xConnect() and xCreate() methods for the virtual table. All the
  188380. ** work is done in function fts5VocabInitVtab().
  188381. */
  188382. static int fts5VocabConnectMethod(
  188383. sqlite3 *db, /* Database connection */
  188384. void *pAux, /* Pointer to tokenizer hash table */
  188385. int argc, /* Number of elements in argv array */
  188386. const char * const *argv, /* xCreate/xConnect argument array */
  188387. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  188388. char **pzErr /* OUT: sqlite3_malloc'd error message */
  188389. ){
  188390. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  188391. }
  188392. static int fts5VocabCreateMethod(
  188393. sqlite3 *db, /* Database connection */
  188394. void *pAux, /* Pointer to tokenizer hash table */
  188395. int argc, /* Number of elements in argv array */
  188396. const char * const *argv, /* xCreate/xConnect argument array */
  188397. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  188398. char **pzErr /* OUT: sqlite3_malloc'd error message */
  188399. ){
  188400. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  188401. }
  188402. /*
  188403. ** Implementation of the xBestIndex method.
  188404. */
  188405. static int fts5VocabBestIndexMethod(
  188406. sqlite3_vtab *pUnused,
  188407. sqlite3_index_info *pInfo
  188408. ){
  188409. int i;
  188410. int iTermEq = -1;
  188411. int iTermGe = -1;
  188412. int iTermLe = -1;
  188413. int idxNum = 0;
  188414. int nArg = 0;
  188415. UNUSED_PARAM(pUnused);
  188416. for(i=0; i<pInfo->nConstraint; i++){
  188417. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  188418. if( p->usable==0 ) continue;
  188419. if( p->iColumn==0 ){ /* term column */
  188420. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  188421. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  188422. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  188423. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  188424. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  188425. }
  188426. }
  188427. if( iTermEq>=0 ){
  188428. idxNum |= FTS5_VOCAB_TERM_EQ;
  188429. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  188430. pInfo->estimatedCost = 100;
  188431. }else{
  188432. pInfo->estimatedCost = 1000000;
  188433. if( iTermGe>=0 ){
  188434. idxNum |= FTS5_VOCAB_TERM_GE;
  188435. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  188436. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  188437. }
  188438. if( iTermLe>=0 ){
  188439. idxNum |= FTS5_VOCAB_TERM_LE;
  188440. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  188441. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  188442. }
  188443. }
  188444. /* This virtual table always delivers results in ascending order of
  188445. ** the "term" column (column 0). So if the user has requested this
  188446. ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
  188447. ** sqlite3_index_info.orderByConsumed flag to tell the core the results
  188448. ** are already in sorted order. */
  188449. if( pInfo->nOrderBy==1
  188450. && pInfo->aOrderBy[0].iColumn==0
  188451. && pInfo->aOrderBy[0].desc==0
  188452. ){
  188453. pInfo->orderByConsumed = 1;
  188454. }
  188455. pInfo->idxNum = idxNum;
  188456. return SQLITE_OK;
  188457. }
  188458. /*
  188459. ** Implementation of xOpen method.
  188460. */
  188461. static int fts5VocabOpenMethod(
  188462. sqlite3_vtab *pVTab,
  188463. sqlite3_vtab_cursor **ppCsr
  188464. ){
  188465. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  188466. Fts5Index *pIndex = 0;
  188467. Fts5Config *pConfig = 0;
  188468. Fts5VocabCursor *pCsr = 0;
  188469. int rc = SQLITE_OK;
  188470. sqlite3_stmt *pStmt = 0;
  188471. char *zSql = 0;
  188472. zSql = sqlite3Fts5Mprintf(&rc,
  188473. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  188474. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  188475. );
  188476. if( zSql ){
  188477. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  188478. }
  188479. sqlite3_free(zSql);
  188480. assert( rc==SQLITE_OK || pStmt==0 );
  188481. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  188482. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  188483. i64 iId = sqlite3_column_int64(pStmt, 0);
  188484. pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
  188485. }
  188486. if( rc==SQLITE_OK && pIndex==0 ){
  188487. rc = sqlite3_finalize(pStmt);
  188488. pStmt = 0;
  188489. if( rc==SQLITE_OK ){
  188490. pVTab->zErrMsg = sqlite3_mprintf(
  188491. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  188492. );
  188493. rc = SQLITE_ERROR;
  188494. }
  188495. }
  188496. if( rc==SQLITE_OK ){
  188497. int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
  188498. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  188499. }
  188500. if( pCsr ){
  188501. pCsr->pIndex = pIndex;
  188502. pCsr->pStmt = pStmt;
  188503. pCsr->pConfig = pConfig;
  188504. pCsr->aCnt = (i64*)&pCsr[1];
  188505. pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
  188506. }else{
  188507. sqlite3_finalize(pStmt);
  188508. }
  188509. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  188510. return rc;
  188511. }
  188512. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  188513. pCsr->rowid = 0;
  188514. sqlite3Fts5IterClose(pCsr->pIter);
  188515. pCsr->pIter = 0;
  188516. sqlite3_free(pCsr->zLeTerm);
  188517. pCsr->nLeTerm = -1;
  188518. pCsr->zLeTerm = 0;
  188519. }
  188520. /*
  188521. ** Close the cursor. For additional information see the documentation
  188522. ** on the xClose method of the virtual table interface.
  188523. */
  188524. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  188525. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188526. fts5VocabResetCursor(pCsr);
  188527. sqlite3Fts5BufferFree(&pCsr->term);
  188528. sqlite3_finalize(pCsr->pStmt);
  188529. sqlite3_free(pCsr);
  188530. return SQLITE_OK;
  188531. }
  188532. /*
  188533. ** Advance the cursor to the next row in the table.
  188534. */
  188535. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  188536. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188537. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  188538. int rc = SQLITE_OK;
  188539. int nCol = pCsr->pConfig->nCol;
  188540. pCsr->rowid++;
  188541. if( pTab->eType==FTS5_VOCAB_COL ){
  188542. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  188543. if( pCsr->aDoc[pCsr->iCol] ) break;
  188544. }
  188545. }
  188546. if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
  188547. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  188548. pCsr->bEof = 1;
  188549. }else{
  188550. const char *zTerm;
  188551. int nTerm;
  188552. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  188553. if( pCsr->nLeTerm>=0 ){
  188554. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  188555. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  188556. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  188557. pCsr->bEof = 1;
  188558. return SQLITE_OK;
  188559. }
  188560. }
  188561. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  188562. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  188563. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  188564. pCsr->iCol = 0;
  188565. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  188566. while( rc==SQLITE_OK ){
  188567. const u8 *pPos; int nPos; /* Position list */
  188568. i64 iPos = 0; /* 64-bit position read from poslist */
  188569. int iOff = 0; /* Current offset within position list */
  188570. pPos = pCsr->pIter->pData;
  188571. nPos = pCsr->pIter->nData;
  188572. switch( pCsr->pConfig->eDetail ){
  188573. case FTS5_DETAIL_FULL:
  188574. pPos = pCsr->pIter->pData;
  188575. nPos = pCsr->pIter->nData;
  188576. if( pTab->eType==FTS5_VOCAB_ROW ){
  188577. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  188578. pCsr->aCnt[0]++;
  188579. }
  188580. pCsr->aDoc[0]++;
  188581. }else{
  188582. int iCol = -1;
  188583. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  188584. int ii = FTS5_POS2COLUMN(iPos);
  188585. pCsr->aCnt[ii]++;
  188586. if( iCol!=ii ){
  188587. if( ii>=nCol ){
  188588. rc = FTS5_CORRUPT;
  188589. break;
  188590. }
  188591. pCsr->aDoc[ii]++;
  188592. iCol = ii;
  188593. }
  188594. }
  188595. }
  188596. break;
  188597. case FTS5_DETAIL_COLUMNS:
  188598. if( pTab->eType==FTS5_VOCAB_ROW ){
  188599. pCsr->aDoc[0]++;
  188600. }else{
  188601. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  188602. assert_nc( iPos>=0 && iPos<nCol );
  188603. if( iPos>=nCol ){
  188604. rc = FTS5_CORRUPT;
  188605. break;
  188606. }
  188607. pCsr->aDoc[iPos]++;
  188608. }
  188609. }
  188610. break;
  188611. default:
  188612. assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
  188613. pCsr->aDoc[0]++;
  188614. break;
  188615. }
  188616. if( rc==SQLITE_OK ){
  188617. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  188618. }
  188619. if( rc==SQLITE_OK ){
  188620. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  188621. if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
  188622. break;
  188623. }
  188624. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  188625. }
  188626. }
  188627. }
  188628. }
  188629. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  188630. while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
  188631. assert( pCsr->iCol<pCsr->pConfig->nCol );
  188632. }
  188633. return rc;
  188634. }
  188635. /*
  188636. ** This is the xFilter implementation for the virtual table.
  188637. */
  188638. static int fts5VocabFilterMethod(
  188639. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  188640. int idxNum, /* Strategy index */
  188641. const char *zUnused, /* Unused */
  188642. int nUnused, /* Number of elements in apVal */
  188643. sqlite3_value **apVal /* Arguments for the indexing scheme */
  188644. ){
  188645. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188646. int rc = SQLITE_OK;
  188647. int iVal = 0;
  188648. int f = FTS5INDEX_QUERY_SCAN;
  188649. const char *zTerm = 0;
  188650. int nTerm = 0;
  188651. sqlite3_value *pEq = 0;
  188652. sqlite3_value *pGe = 0;
  188653. sqlite3_value *pLe = 0;
  188654. UNUSED_PARAM2(zUnused, nUnused);
  188655. fts5VocabResetCursor(pCsr);
  188656. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  188657. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  188658. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  188659. if( pEq ){
  188660. zTerm = (const char *)sqlite3_value_text(pEq);
  188661. nTerm = sqlite3_value_bytes(pEq);
  188662. f = 0;
  188663. }else{
  188664. if( pGe ){
  188665. zTerm = (const char *)sqlite3_value_text(pGe);
  188666. nTerm = sqlite3_value_bytes(pGe);
  188667. }
  188668. if( pLe ){
  188669. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  188670. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  188671. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  188672. if( pCsr->zLeTerm==0 ){
  188673. rc = SQLITE_NOMEM;
  188674. }else{
  188675. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  188676. }
  188677. }
  188678. }
  188679. if( rc==SQLITE_OK ){
  188680. rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  188681. }
  188682. if( rc==SQLITE_OK ){
  188683. rc = fts5VocabNextMethod(pCursor);
  188684. }
  188685. return rc;
  188686. }
  188687. /*
  188688. ** This is the xEof method of the virtual table. SQLite calls this
  188689. ** routine to find out if it has reached the end of a result set.
  188690. */
  188691. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  188692. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188693. return pCsr->bEof;
  188694. }
  188695. static int fts5VocabColumnMethod(
  188696. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  188697. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  188698. int iCol /* Index of column to read value from */
  188699. ){
  188700. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188701. int eDetail = pCsr->pConfig->eDetail;
  188702. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  188703. i64 iVal = 0;
  188704. if( iCol==0 ){
  188705. sqlite3_result_text(
  188706. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  188707. );
  188708. }else if( eType==FTS5_VOCAB_COL ){
  188709. assert( iCol==1 || iCol==2 || iCol==3 );
  188710. if( iCol==1 ){
  188711. if( eDetail!=FTS5_DETAIL_NONE ){
  188712. const char *z = pCsr->pConfig->azCol[pCsr->iCol];
  188713. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  188714. }
  188715. }else if( iCol==2 ){
  188716. iVal = pCsr->aDoc[pCsr->iCol];
  188717. }else{
  188718. iVal = pCsr->aCnt[pCsr->iCol];
  188719. }
  188720. }else{
  188721. assert( iCol==1 || iCol==2 );
  188722. if( iCol==1 ){
  188723. iVal = pCsr->aDoc[0];
  188724. }else{
  188725. iVal = pCsr->aCnt[0];
  188726. }
  188727. }
  188728. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  188729. return SQLITE_OK;
  188730. }
  188731. /*
  188732. ** This is the xRowid method. The SQLite core calls this routine to
  188733. ** retrieve the rowid for the current row of the result set. The
  188734. ** rowid should be written to *pRowid.
  188735. */
  188736. static int fts5VocabRowidMethod(
  188737. sqlite3_vtab_cursor *pCursor,
  188738. sqlite_int64 *pRowid
  188739. ){
  188740. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188741. *pRowid = pCsr->rowid;
  188742. return SQLITE_OK;
  188743. }
  188744. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  188745. static const sqlite3_module fts5Vocab = {
  188746. /* iVersion */ 2,
  188747. /* xCreate */ fts5VocabCreateMethod,
  188748. /* xConnect */ fts5VocabConnectMethod,
  188749. /* xBestIndex */ fts5VocabBestIndexMethod,
  188750. /* xDisconnect */ fts5VocabDisconnectMethod,
  188751. /* xDestroy */ fts5VocabDestroyMethod,
  188752. /* xOpen */ fts5VocabOpenMethod,
  188753. /* xClose */ fts5VocabCloseMethod,
  188754. /* xFilter */ fts5VocabFilterMethod,
  188755. /* xNext */ fts5VocabNextMethod,
  188756. /* xEof */ fts5VocabEofMethod,
  188757. /* xColumn */ fts5VocabColumnMethod,
  188758. /* xRowid */ fts5VocabRowidMethod,
  188759. /* xUpdate */ 0,
  188760. /* xBegin */ 0,
  188761. /* xSync */ 0,
  188762. /* xCommit */ 0,
  188763. /* xRollback */ 0,
  188764. /* xFindFunction */ 0,
  188765. /* xRename */ 0,
  188766. /* xSavepoint */ 0,
  188767. /* xRelease */ 0,
  188768. /* xRollbackTo */ 0,
  188769. };
  188770. void *p = (void*)pGlobal;
  188771. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  188772. }
  188773. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  188774. /************** End of fts5.c ************************************************/